summaryrefslogtreecommitdiffhomepage
path: root/src/thread.c
blob: b119dbdeb48871a8f06d472e549a1ef833edd8cb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
/* $Id: thread.c,v 1.13 2001-09-08 06:29:04 rjkaes Exp $
 *
 * Handles the creation/destruction of the various threads required for
 * processing incoming connections.
 *
 * Copyright (C) 2000 Robert James Kaes (rjkaes@flarenet.com)
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation; either version 2, or (at your option) any
 * later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 */

#include "tinyproxy.h"

#include "log.h"
#include "reqs.h"
#include "sock.h"
#include "thread.h"

/*
 * This is the stack frame size used by all the threads. We'll start by
 * setting it to 128 KB.
 */
#define THREAD_STACK_SIZE (1024 * 128)

static int listenfd;
static socklen_t addrlen;

/*
 * Stores the internal data needed for each thread (connection)
 */
struct thread_s {
	pthread_t tid;
	enum { T_EMPTY, T_WAITING, T_CONNECTED } status;
	unsigned int connects;
};

/*
 * A pointer to an array of threads. A certain number of threads are
 * created when the program is started.
 */
static struct thread_s *thread_ptr;
static pthread_mutex_t mlock = PTHREAD_MUTEX_INITIALIZER;

/* Used to override the default statck size. */
static pthread_attr_t thread_attr;

static struct thread_config_s {
	unsigned int maxclients, maxrequestsperchild;
	unsigned int maxspareservers, minspareservers, startservers;
} thread_config;

static unsigned int servers_waiting;	/* servers waiting for a connection */
static pthread_mutex_t servers_mutex = PTHREAD_MUTEX_INITIALIZER;

#define SERVER_LOCK()   pthread_mutex_lock(&servers_mutex)
#define SERVER_UNLOCK() pthread_mutex_unlock(&servers_mutex)

#define SERVER_INC() do { \
    SERVER_LOCK(); \
    DEBUG2("INC: servers_waiting: %u", servers_waiting); \
    servers_waiting++; \
    SERVER_UNLOCK(); \
} while (0)

#define SERVER_DEC() do { \
    SERVER_LOCK(); \
    servers_waiting--; \
    DEBUG2("DEC: servers_waiting: %u", servers_waiting); \
    SERVER_UNLOCK(); \
} while (0)

/*
 * Set the configuration values for the various thread related settings.
 */
short int thread_configure(thread_config_t type, unsigned int val)
{
	switch (type) {
	case THREAD_MAXCLIENTS:
		thread_config.maxclients = val;
		break;
	case THREAD_MAXSPARESERVERS:
		thread_config.maxspareservers = val;
		break;
	case THREAD_MINSPARESERVERS:
		thread_config.minspareservers = val;
		break;
	case THREAD_STARTSERVERS:
		thread_config.startservers = val;
		break;
	case THREAD_MAXREQUESTSPERCHILD:
		thread_config.maxrequestsperchild = val;
		break;
	default:
		DEBUG2("Invalid type (%d)", type);
		return -1;
	}

	return 0;
}

/*
 * This is the main (per thread) loop.
 */
static void *thread_main(void *arg)
{
	int connfd;
	struct sockaddr *cliaddr;
	socklen_t clilen;
	struct thread_s *ptr;

	ptr = (struct thread_s *)arg;

	cliaddr = malloc(addrlen);
	if (!cliaddr) {
		log_message(LOG_ERR, "Could not allocate memory in 'thread_main'.");
		return NULL;
	}
	
	while (!config.quit) {
		clilen = addrlen;

		pthread_mutex_lock(&mlock);
		connfd = accept(listenfd, cliaddr, &clilen);
		pthread_mutex_unlock(&mlock);

		ptr->status = T_CONNECTED;

		SERVER_DEC();

		handle_connection(connfd);
		close(connfd);

		if (thread_config.maxrequestsperchild != 0) {
			ptr->connects++;

			DEBUG2("%u connections so far...", ptr->connects);

			if (ptr->connects >= thread_config.maxrequestsperchild) {
				log_message(LOG_NOTICE, "Thread has reached MaxRequestsPerChild (%u > %u). Killing thread.", ptr->connects, thread_config.maxrequestsperchild);

				ptr->status = T_EMPTY;
				
				safefree(cliaddr);

				return NULL;
			}
		}

		SERVER_LOCK();
		if (servers_waiting >= thread_config.maxspareservers) {
			/*
			 * There are too many spare threads, kill ourself
			 * off.
			 */
			SERVER_UNLOCK();

			log_message(LOG_NOTICE, "Waiting servers exceeds MaxSpareServers. Killing thread.");

			ptr->status = T_EMPTY;

			safefree(cliaddr);
			return NULL;
		}
		SERVER_UNLOCK();

		ptr->status = T_WAITING;
		
		SERVER_INC();
	}

	safefree(cliaddr);
	return NULL;
}

/*
 * Create the initial pool of threads.
 */
short int thread_pool_create(void)
{
	unsigned int i;

	/*
	 * Initialize thread_attr to contain a non-default stack size
	 * because the default on some OS's is too small. Also, make sure
	 * we're using a detached creation method so all resources are
	 * reclaimed when the thread exits.
	 */
	pthread_attr_init(&thread_attr);
	pthread_attr_setdetachstate(&thread_attr, PTHREAD_CREATE_DETACHED);
	pthread_attr_setstacksize(&thread_attr, THREAD_STACK_SIZE);

	if (thread_config.maxclients == 0) {
		log_message(LOG_ERR, "'MaxClients' must be greater than zero.");
		return -1;
	}
	if (thread_config.startservers == 0) {
		log_message(LOG_ERR, "'StartServers' must be greater than zero.");
		return -1;
	}

	thread_ptr = calloc((size_t)thread_config.maxclients, sizeof(struct thread_s));
	if (!thread_ptr)
		return -1;

	if (thread_config.startservers > thread_config.maxclients) {
		log_message(LOG_WARNING, "Can not start more than 'MaxClients' servers. Starting %u servers instead.", thread_config.maxclients);
		thread_config.startservers = thread_config.maxclients;
	}

	for (i = 0; i < thread_config.startservers; i++) {
		thread_ptr[i].status = T_WAITING;
		pthread_create(&thread_ptr[i].tid, &thread_attr, &thread_main, &thread_ptr[i]);
	}
	servers_waiting = thread_config.startservers;

	for (i = thread_config.startservers; i < thread_config.maxclients; i++) {
		thread_ptr[i].status = T_EMPTY;
		thread_ptr[i].connects = 0;
	}

	return 0;
}

/*
 * Keep the proper number of servers running. This is the birth of the
 * servers. It monitors this at least once a second.
 */
void thread_main_loop(void)
{
	int i;

	/* If there are not enough spare servers, create more */
	SERVER_LOCK();
	if (servers_waiting < thread_config.minspareservers) {
		SERVER_UNLOCK();

		for (i = 0; i < thread_config.maxclients; i++) {
			if (thread_ptr[i].status == T_EMPTY) {
				pthread_create(&thread_ptr[i].tid, &thread_attr, &thread_main, &thread_ptr[i]);
				thread_ptr[i].status = T_WAITING;
				thread_ptr[i].connects = 0;

				SERVER_INC();

				log_message(LOG_NOTICE, "Waiting servers is less than MinSpareServers. Creating new thread.");

				break;
			}
		}
	}
	SERVER_UNLOCK();
}

int thread_listening_sock(uint16_t port)
{
	listenfd = listen_sock(port, &addrlen);
	return listenfd;
}

void thread_close_sock(void)
{
	close(listenfd);
}