4 * This contains a simple multithreaded TCP server manager. It sits around
5 * waiting on the specified port for incoming HTTP connections. When a
6 * connection is established, it calls context_loop() from context_loop.c.
21 #include <sys/types.h>
23 #include <sys/socket.h>
24 #ifdef HAVE_SYS_TIME_H
30 #include <netinet/in.h>
40 #include "webserver.h"
43 int vsnprintf(char *buf, size_t max, const char *fmt, va_list argp);
46 int verbosity = 9; /* Logging level */
47 int msock; /* master listening socket */
48 extern void *context_loop(int);
49 extern void *housekeeping_loop(void);
50 extern pthread_mutex_t SessionListMutex;
51 extern pthread_key_t MyConKey;
54 char *server_cookie = NULL;
57 char *defaulthost = DEFAULT_HOST;
58 char *defaultport = DEFAULT_PORT;
60 pthread_mutex_t AcceptQueue;
63 * This is a generic function to set up a master socket for listening on
64 * a TCP port. The server shuts down if the bind fails.
66 int ig_tcp_server(int port_number, int queue_len)
68 struct sockaddr_in sin;
71 memset(&sin, 0, sizeof(sin));
72 sin.sin_family = AF_INET;
73 sin.sin_addr.s_addr = INADDR_ANY;
75 if (port_number == 0) {
76 lprintf(1, "Cannot start: no port number specified.\n");
79 sin.sin_port = htons((u_short) port_number);
81 s = socket(PF_INET, SOCK_STREAM, (getprotobyname("tcp")->p_proto));
83 lprintf(1, "Can't create a socket: %s\n",
87 /* Set some socket options that make sense. */
89 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
91 if (bind(s, (struct sockaddr *) &sin, sizeof(sin)) < 0) {
92 lprintf(1, "Can't bind: %s\n", strerror(errno));
95 if (listen(s, queue_len) < 0) {
96 lprintf(1, "Can't listen: %s\n", strerror(errno));
104 * Read data from the client socket.
106 * 1 Requested number of bytes has been read.
107 * 0 Request timed out.
108 * -1 Connection is broken, or other error.
110 int client_read_to(int sock, char *buf, int bytes, int timeout)
118 while (len < bytes) {
124 retval = select((sock) + 1,
125 &rfds, NULL, NULL, &tv);
126 if (FD_ISSET(sock, &rfds) == 0) {
129 rlen = read(sock, &buf[len], bytes - len);
131 lprintf(2, "client_read() failed: %s\n",
141 * Read data from the client socket with default timeout.
142 * (This is implemented in terms of client_read_to() and could be
143 * justifiably moved out of sysdep.c)
145 int client_read(int sock, char *buf, int bytes)
147 return (client_read_to(sock, buf, bytes, SLEEPING));
152 * client_gets() ... Get a LF-terminated line of text from the client.
153 * (This is implemented in terms of client_read() and could be
154 * justifiably moved out of sysdep.c)
156 int client_gets(int sock, char *buf)
160 /* Read one character at a time.
163 retval = client_read(sock, &buf[i], 1);
164 if (retval != 1 || buf[i] == '\n' || i == 255)
168 /* If we got a long line, discard characters until the newline.
171 while (buf[i] != '\n' && retval == 1)
172 retval = client_read(sock, &buf[i], 1);
175 * Strip any trailing non-printable characters.
178 while ((strlen(buf) > 0) && (!isprint(buf[strlen(buf) - 1]))) {
179 buf[strlen(buf) - 1] = 0;
186 * Start running as a daemon. Only close stdio if do_close_stdio is set.
188 void start_daemon(int do_close_stdio)
190 if (do_close_stdio) {
195 signal(SIGHUP, SIG_IGN);
196 signal(SIGINT, SIG_IGN);
197 signal(SIGQUIT, SIG_IGN);
202 void spawn_another_worker_thread() {
203 pthread_t SessThread; /* Thread descriptor */
204 pthread_attr_t attr; /* Thread attributes */
206 lprintf(3, "Creating a new thread\n");
208 /* set attributes for the new thread */
209 pthread_attr_init(&attr);
210 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
212 /* now create the thread */
213 if (pthread_create(&SessThread, &attr,
214 (void *(*)(void *)) worker_entry, NULL)
216 lprintf(1, "Can't create thread: %s\n",
222 * Here's where it all begins.
224 int main(int argc, char **argv)
226 pthread_t SessThread; /* Thread descriptor */
227 pthread_attr_t attr; /* Thread attributes */
228 int a, i; /* General-purpose variables */
229 int port = PORT_NUM; /* Port to listen on */
230 char tracefile[PATH_MAX];
232 /* Parse command line */
233 while ((a = getopt(argc, argv, "hp:t:c")) != EOF)
239 strcpy(tracefile, optarg);
240 freopen(tracefile, "w", stdout);
241 freopen(tracefile, "w", stderr);
242 freopen(tracefile, "r", stdin);
245 verbosity = atoi(optarg);
248 server_cookie = malloc(SIZ);
249 if (server_cookie != NULL) {
250 strcpy(server_cookie, "Set-cookie: wcserver=");
252 &server_cookie[strlen(server_cookie)],
254 lprintf(2, "gethostname: %s\n",
261 fprintf(stderr, "usage: webserver [-p localport] "
262 "[-t tracefile] [-c] "
263 "[remotehost [remoteport]]\n");
268 defaulthost = argv[optind];
270 defaultport = argv[optind];
272 /* Tell 'em who's in da house */
273 lprintf(1, SERVER "\n"
274 "Copyright (C) 1996-2002 by the Citadel/UX development team.\n"
275 "This software is distributed under the terms of the GNU General Public\n"
276 "License. If you paid for this software, someone is ripping you off.\n\n");
278 if (chdir(WEBCITDIR) != 0)
282 * Set up a place to put thread-specific data.
283 * We only need a single pointer per thread - it points to the
284 * wcsession struct to which the thread is currently bound.
286 if (pthread_key_create(&MyConKey, NULL) != 0) {
287 lprintf(1, "Can't create TSD key: %s\n", strerror(errno));
291 * Bind the server to our favorite port.
292 * There is no need to check for errors, because ig_tcp_server()
293 * exits if it doesn't succeed.
295 lprintf(2, "Attempting to bind to port %d...\n", port);
296 msock = ig_tcp_server(port, LISTEN_QUEUE_LENGTH);
297 lprintf(2, "Listening on socket %d\n", msock);
298 signal(SIGPIPE, SIG_IGN);
300 pthread_mutex_init(&SessionListMutex, NULL);
301 pthread_mutex_init(&AcceptQueue, NULL);
304 * Start up the housekeeping thread
306 pthread_attr_init(&attr);
307 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
308 pthread_create(&SessThread, &attr,
309 (void *(*)(void *)) housekeeping_loop, NULL);
312 /* Start a few initial worker threads */
313 for (i=0; i<(INITIAL_WORKER_THREADS); ++i) {
314 spawn_another_worker_thread();
317 /* now the original thread can go away. */
324 * Entry point for worker threads
326 void worker_entry(void) {
328 struct sockaddr_in fsin;
332 time_t start_time, stop_time;
335 /* Only one thread can accept at a time */
336 start_time = time(NULL);
337 pthread_mutex_lock(&AcceptQueue);
338 ssock = accept(msock, (struct sockaddr *) &fsin, &alen);
339 pthread_mutex_unlock(&AcceptQueue);
340 stop_time = time(NULL);
342 /* Augment the thread pool if we're not blocking at all */
343 if ( (stop_time - start_time) == 0L) {
344 spawn_another_worker_thread();
348 lprintf(2, "accept() failed: %s\n", strerror(errno));
350 /* Set the SO_REUSEADDR socket option */
352 setsockopt(ssock, SOL_SOCKET, SO_REUSEADDR,
355 /* Perform an HTTP transaction... */
358 /* ...and close the socket. */
359 lingering_close(ssock);
362 } while (!time_to_die);
368 int lprintf(int loglevel, const char *format, ...)
373 va_start(ap, format);
374 vsprintf(buf, format, ap);
377 if (loglevel <= verbosity) {
381 gettimeofday(&tv, NULL);
382 tim = localtime(&(tv.tv_sec));
384 if (WC && WC->wc_session) {
386 "%04d/%02d/%02d %2d:%02d:%02d.%03ld [%ld:%d] %s",
387 tim->tm_year + 1900, tim->tm_mon + 1,
388 tim->tm_mday, tim->tm_hour, tim->tm_min,
389 tim->tm_sec, (long)tv.tv_usec / 1000,
390 pthread_self(), WC->wc_session, buf);
393 "%04d/%02d/%02d %2d:%02d:%02d.%03ld [%ld] %s",
394 tim->tm_year + 1900, tim->tm_mon + 1,
395 tim->tm_mday, tim->tm_hour, tim->tm_min,
396 tim->tm_sec, (long)tv.tv_usec / 1000,
397 pthread_self(), buf);