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.
11 * Uncomment to dump an HTTP trace to stderr
12 #define HTTP_TRACING 1
25 #include <sys/types.h>
27 #include <sys/socket.h>
28 #ifdef HAVE_SYS_TIME_H
34 #include <netinet/in.h>
35 #include <arpa/inet.h>
44 #include "webserver.h"
47 int vsnprintf(char *buf, size_t max, const char *fmt, va_list argp);
50 int verbosity = 9; /* Logging level */
51 int msock; /* master listening socket */
52 int is_https = 0; /* Nonzero if I am an HTTPS service */
53 extern void *context_loop(int);
54 extern void *housekeeping_loop(void);
55 extern pthread_mutex_t SessionListMutex;
56 extern pthread_key_t MyConKey;
59 char *server_cookie = NULL;
62 char *ctdlhost = DEFAULT_HOST;
63 char *ctdlport = DEFAULT_PORT;
65 char wizard_filename[PATH_MAX];
68 * This is a generic function to set up a master socket for listening on
69 * a TCP port. The server shuts down if the bind fails.
71 int ig_tcp_server(char *ip_addr, int port_number, int queue_len)
73 struct sockaddr_in sin;
76 memset(&sin, 0, sizeof(sin));
77 sin.sin_family = AF_INET;
78 if (ip_addr == NULL) {
79 sin.sin_addr.s_addr = INADDR_ANY;
81 sin.sin_addr.s_addr = inet_addr(ip_addr);
84 if (sin.sin_addr.s_addr == INADDR_NONE) {
85 sin.sin_addr.s_addr = INADDR_ANY;
88 if (port_number == 0) {
89 lprintf(1, "Cannot start: no port number specified.\n");
92 sin.sin_port = htons((u_short) port_number);
94 s = socket(PF_INET, SOCK_STREAM, (getprotobyname("tcp")->p_proto));
96 lprintf(1, "Can't create a socket: %s\n", strerror(errno));
99 /* Set some socket options that make sense. */
101 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
103 if (bind(s, (struct sockaddr *) &sin, sizeof(sin)) < 0) {
104 lprintf(1, "Can't bind: %s\n", strerror(errno));
107 if (listen(s, queue_len) < 0) {
108 lprintf(1, "Can't listen: %s\n", strerror(errno));
116 * Read data from the client socket.
118 * 1 Requested number of bytes has been read.
119 * 0 Request timed out.
120 * -1 Connection is broken, or other error.
122 int client_read_to(int sock, char *buf, int bytes, int timeout)
132 return (client_read_ssl(buf, bytes, timeout));
137 while (len < bytes) {
143 retval = select((sock) + 1, &rfds, NULL, NULL, &tv);
144 if (FD_ISSET(sock, &rfds) == 0) {
148 rlen = read(sock, &buf[len], bytes - len);
151 lprintf(2, "client_read() failed: %s\n",
159 write(2, "\033[32m", 5);
160 write(2, buf, bytes);
161 write(2, "\033[30m", 5);
167 ssize_t client_write(const void *buf, size_t count)
170 if (WC->burst != NULL) {
172 realloc(WC->burst, (WC->burst_len + count + 2));
173 memcpy(&WC->burst[WC->burst_len], buf, count);
174 WC->burst_len += count;
179 client_write_ssl((char *) buf, count);
184 write(2, "\033[34m", 5);
185 write(2, buf, count);
186 write(2, "\033[30m", 5);
188 return (write(WC->http_sock, buf, count));
192 void begin_burst(void)
194 if (WC->burst != NULL) {
199 WC->burst = malloc(SIZ);
204 * compress_gzip() uses the same calling syntax as compress2(), but it
205 * creates a stream compatible with HTTP "Content-encoding: gzip"
208 #define DEF_MEM_LEVEL 8
209 #define OS_CODE 0x03 /* unix */
210 int ZEXPORT compress_gzip(Bytef * dest, uLongf * destLen,
211 const Bytef * source, uLong sourceLen, int level)
213 const int gz_magic[2] = { 0x1f, 0x8b }; /* gzip magic header */
215 /* write gzip header */
216 sprintf((char *) dest, "%c%c%c%c%c%c%c%c%c%c",
217 gz_magic[0], gz_magic[1], Z_DEFLATED,
218 0 /*flags */ , 0, 0, 0, 0 /*time */ , 0 /*xflags */ ,
224 stream.next_in = (Bytef *) source;
225 stream.avail_in = (uInt) sourceLen;
226 stream.next_out = dest + 10L; // after header
227 stream.avail_out = (uInt) * destLen;
228 if ((uLong) stream.avail_out != *destLen)
231 stream.zalloc = (alloc_func) 0;
232 stream.zfree = (free_func) 0;
233 stream.opaque = (voidpf) 0;
235 err = deflateInit2(&stream, level, Z_DEFLATED, -MAX_WBITS,
236 DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
240 err = deflate(&stream, Z_FINISH);
241 if (err != Z_STREAM_END) {
243 return err == Z_OK ? Z_BUF_ERROR : err;
245 *destLen = stream.total_out + 10L;
247 /* write CRC and Length */
248 uLong crc = crc32(0L, source, sourceLen);
250 for (n = 0; n < 4; ++n, ++*destLen) {
251 dest[*destLen] = (int) (crc & 0xff);
254 uLong len = stream.total_in;
255 for (n = 0; n < 4; ++n, ++*destLen) {
256 dest[*destLen] = (int) (len & 0xff);
259 err = deflateEnd(&stream);
269 if (WC->burst == NULL)
272 the_len = WC->burst_len;
273 the_data = WC->burst;
279 /* Handle gzip compression */
281 char *compressed_data = NULL;
282 uLongf compressed_len;
284 compressed_len = (uLongf) ((the_len * 101) / 100) + 100;
285 compressed_data = malloc(compressed_len);
287 if (compress_gzip((Bytef *) compressed_data,
290 (uLongf) the_len, Z_BEST_SPEED) == Z_OK) {
291 wprintf("Content-encoding: gzip\r\n");
293 the_data = compressed_data;
294 the_len = compressed_len;
296 free(compressed_data);
299 #endif /* HAVE_ZLIB */
301 wprintf("Content-length: %d\r\n\r\n", the_len);
302 client_write(the_data, the_len);
310 * Read data from the client socket with default timeout.
311 * (This is implemented in terms of client_read_to() and could be
312 * justifiably moved out of sysdep.c)
314 int client_read(int sock, char *buf, int bytes)
316 return (client_read_to(sock, buf, bytes, SLEEPING));
321 * client_gets() ... Get a LF-terminated line of text from the client.
322 * (This is implemented in terms of client_read() and could be
323 * justifiably moved out of sysdep.c)
325 int client_gets(int sock, char *buf)
329 /* Read one character at a time.
332 retval = client_read(sock, &buf[i], 1);
333 if (retval != 1 || buf[i] == '\n' || i == 255)
337 /* If we got a long line, discard characters until the newline.
340 while (buf[i] != '\n' && retval == 1)
341 retval = client_read(sock, &buf[i], 1);
344 * Strip any trailing non-printable characters.
347 while ((strlen(buf) > 0) && (!isprint(buf[strlen(buf) - 1]))) {
348 buf[strlen(buf) - 1] = 0;
355 * Start running as a daemon. Only close stdio if do_close_stdio is set.
357 void start_daemon(int do_close_stdio)
359 if (do_close_stdio) {
364 signal(SIGHUP, SIG_IGN);
365 signal(SIGINT, SIG_IGN);
366 signal(SIGQUIT, SIG_IGN);
371 void spawn_another_worker_thread()
373 pthread_t SessThread; /* Thread descriptor */
374 pthread_attr_t attr; /* Thread attributes */
377 lprintf(3, "Creating a new thread\n");
379 /* set attributes for the new thread */
380 pthread_attr_init(&attr);
381 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
383 /* Our per-thread stacks need to be bigger than the default size, otherwise
384 * the MIME parser crashes on FreeBSD, and the IMAP service crashes on
387 if ((ret = pthread_attr_setstacksize(&attr, 1024 * 1024))) {
388 lprintf(1, "pthread_attr_setstacksize: %s\n",
390 pthread_attr_destroy(&attr);
393 /* now create the thread */
394 if (pthread_create(&SessThread, &attr,
395 (void *(*)(void *)) worker_entry, NULL)
397 lprintf(1, "Can't create thread: %s\n", strerror(errno));
400 /* free up the attributes */
401 pthread_attr_destroy(&attr);
405 * Here's where it all begins.
407 int main(int argc, char **argv)
409 pthread_t SessThread; /* Thread descriptor */
410 pthread_attr_t attr; /* Thread attributes */
411 int a, i; /* General-purpose variables */
412 int port = PORT_NUM; /* Port to listen on */
413 char tracefile[PATH_MAX];
416 /* Parse command line */
418 while ((a = getopt(argc, argv, "hi:p:t:x:cs")) != EOF)
420 while ((a = getopt(argc, argv, "hi:p:t:x:c")) != EOF)
424 safestrncpy(ip_addr, optarg, sizeof ip_addr);
430 safestrncpy(tracefile, optarg, sizeof tracefile);
431 freopen(tracefile, "w", stdout);
432 freopen(tracefile, "w", stderr);
433 freopen(tracefile, "r", stdin);
436 verbosity = atoi(optarg);
439 server_cookie = malloc(256);
440 if (server_cookie != NULL) {
441 safestrncpy(server_cookie,
442 "Set-cookie: wcserver=",
445 (&server_cookie[strlen(server_cookie)],
447 lprintf(2, "gethostname: %s\n",
457 fprintf(stderr, "usage: webserver "
458 "[-i ip_addr] [-p http_port] "
459 "[-t tracefile] [-c] "
463 "[remotehost [remoteport]]\n");
468 ctdlhost = argv[optind];
470 ctdlport = argv[optind];
472 /* Tell 'em who's in da house */
473 lprintf(1, SERVER "\n"
474 "Copyright (C) 1996-2005 by the Citadel/UX development team.\n"
475 "This software is distributed under the terms of the GNU General Public\n"
476 "License. If you paid for this software, someone is ripping you off.\n\n");
478 if (chdir(WEBCITDIR) != 0)
482 * Set up a place to put thread-specific data.
483 * We only need a single pointer per thread - it points to the
484 * wcsession struct to which the thread is currently bound.
486 if (pthread_key_create(&MyConKey, NULL) != 0) {
487 lprintf(1, "Can't create TSD key: %s\n", strerror(errno));
491 * Set up a place to put thread-specific SSL data.
492 * We don't stick this in the wcsession struct because SSL starts
493 * up before the session is bound, and it gets torn down between
497 if (pthread_key_create(&ThreadSSL, NULL) != 0) {
498 lprintf(1, "Can't create TSD key: %s\n", strerror(errno));
503 * Bind the server to our favorite port.
504 * There is no need to check for errors, because ig_tcp_server()
505 * exits if it doesn't succeed.
507 lprintf(2, "Attempting to bind to port %d...\n", port);
508 msock = ig_tcp_server(ip_addr, port, LISTEN_QUEUE_LENGTH);
509 lprintf(2, "Listening on socket %d\n", msock);
510 signal(SIGPIPE, SIG_IGN);
512 pthread_mutex_init(&SessionListMutex, NULL);
515 * Start up the housekeeping thread
517 pthread_attr_init(&attr);
518 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
519 pthread_create(&SessThread, &attr,
520 (void *(*)(void *)) housekeeping_loop, NULL);
524 * If this is an HTTPS server, fire up SSL
532 /* Start a few initial worker threads */
533 for (i = 0; i < (MIN_WORKER_THREADS); ++i) {
534 spawn_another_worker_thread();
537 /* now the original thread becomes another worker */
544 * Entry point for worker threads
546 void worker_entry(void)
551 int fail_this_transaction = 0;
554 /* Only one thread can accept at a time */
555 fail_this_transaction = 0;
556 ssock = accept(msock, NULL, 0);
558 lprintf(2, "accept() failed: %s\n",
561 /* Set the SO_REUSEADDR socket option */
563 setsockopt(ssock, SOL_SOCKET, SO_REUSEADDR,
566 /* If we are an HTTPS server, go crypto now. */
569 if (starttls(ssock) != 0) {
570 fail_this_transaction = 1;
576 if (fail_this_transaction == 0) {
577 /* Perform an HTTP transaction... */
579 /* ...and close the socket. */
580 lingering_close(ssock);
585 } while (!time_to_die);
591 int lprintf(int loglevel, const char *format, ...)
595 if (loglevel <= verbosity) {
596 va_start(ap, format);
597 vfprintf(stderr, format, ap);