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"
51 int vsnprintf(char *buf, size_t max, const char *fmt, va_list argp);
54 int verbosity = 9; /* Logging level */
55 int msock; /* master listening socket */
56 int is_https = 0; /* Nonzero if I am an HTTPS service */
57 extern void *context_loop(int);
58 extern void *housekeeping_loop(void);
59 extern pthread_mutex_t SessionListMutex;
60 extern pthread_key_t MyConKey;
63 char *server_cookie = NULL;
66 char *ctdlhost = DEFAULT_HOST;
67 char *ctdlport = DEFAULT_PORT;
70 * This is a generic function to set up a master socket for listening on
71 * a TCP port. The server shuts down if the bind fails.
73 int ig_tcp_server(char *ip_addr, int port_number, int queue_len)
75 struct sockaddr_in sin;
78 memset(&sin, 0, sizeof(sin));
79 sin.sin_family = AF_INET;
80 if (ip_addr == NULL) {
81 sin.sin_addr.s_addr = INADDR_ANY;
83 sin.sin_addr.s_addr = inet_addr(ip_addr);
86 if (sin.sin_addr.s_addr == INADDR_NONE) {
87 sin.sin_addr.s_addr = INADDR_ANY;
90 if (port_number == 0) {
91 lprintf(1, "Cannot start: no port number specified.\n");
94 sin.sin_port = htons((u_short) port_number);
96 s = socket(PF_INET, SOCK_STREAM, (getprotobyname("tcp")->p_proto));
98 lprintf(1, "Can't create a socket: %s\n", strerror(errno));
101 /* Set some socket options that make sense. */
103 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
105 if (bind(s, (struct sockaddr *) &sin, sizeof(sin)) < 0) {
106 lprintf(1, "Can't bind: %s\n", strerror(errno));
109 if (listen(s, queue_len) < 0) {
110 lprintf(1, "Can't listen: %s\n", strerror(errno));
118 * Read data from the client socket.
120 * 1 Requested number of bytes has been read.
121 * 0 Request timed out.
122 * -1 Connection is broken, or other error.
124 int client_read_to(int sock, char *buf, int bytes, int timeout)
134 return (client_read_ssl(buf, bytes, timeout));
139 while (len < bytes) {
145 retval = select((sock) + 1, &rfds, NULL, NULL, &tv);
146 if (FD_ISSET(sock, &rfds) == 0) {
150 rlen = read(sock, &buf[len], bytes - len);
153 lprintf(2, "client_read() failed: %s\n",
161 write(2, "\033[32m", 5);
162 write(2, buf, bytes);
163 write(2, "\033[30m", 5);
169 ssize_t client_write(const void *buf, size_t count)
172 if (WC->burst != NULL) {
174 realloc(WC->burst, (WC->burst_len + count + 2));
175 memcpy(&WC->burst[WC->burst_len], buf, count);
176 WC->burst_len += count;
181 client_write_ssl((char *) buf, count);
186 write(2, "\033[34m", 5);
187 write(2, buf, count);
188 write(2, "\033[30m", 5);
190 return (write(WC->http_sock, buf, count));
194 void begin_burst(void)
196 if (WC->burst != NULL) {
201 WC->burst = malloc(SIZ);
206 * compress_gzip() uses the same calling syntax as compress2(), but it
207 * creates a stream compatible with HTTP "Content-encoding: gzip"
210 #define DEF_MEM_LEVEL 8
211 #define OS_CODE 0x03 /* unix */
212 int ZEXPORT compress_gzip(Bytef * dest, uLongf * destLen,
213 const Bytef * source, uLong sourceLen, int level)
215 const int gz_magic[2] = { 0x1f, 0x8b }; /* gzip magic header */
217 /* write gzip header */
218 sprintf((char *) dest, "%c%c%c%c%c%c%c%c%c%c",
219 gz_magic[0], gz_magic[1], Z_DEFLATED,
220 0 /*flags */ , 0, 0, 0, 0 /*time */ , 0 /*xflags */ ,
226 stream.next_in = (Bytef *) source;
227 stream.avail_in = (uInt) sourceLen;
228 stream.next_out = dest + 10L; // after header
229 stream.avail_out = (uInt) * destLen;
230 if ((uLong) stream.avail_out != *destLen)
233 stream.zalloc = (alloc_func) 0;
234 stream.zfree = (free_func) 0;
235 stream.opaque = (voidpf) 0;
237 err = deflateInit2(&stream, level, Z_DEFLATED, -MAX_WBITS,
238 DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
242 err = deflate(&stream, Z_FINISH);
243 if (err != Z_STREAM_END) {
245 return err == Z_OK ? Z_BUF_ERROR : err;
247 *destLen = stream.total_out + 10L;
249 /* write CRC and Length */
250 uLong crc = crc32(0L, source, sourceLen);
252 for (n = 0; n < 4; ++n, ++*destLen) {
253 dest[*destLen] = (int) (crc & 0xff);
256 uLong len = stream.total_in;
257 for (n = 0; n < 4; ++n, ++*destLen) {
258 dest[*destLen] = (int) (len & 0xff);
261 err = deflateEnd(&stream);
271 if (WC->burst == NULL)
274 the_len = WC->burst_len;
275 the_data = WC->burst;
281 /* Handle gzip compression */
283 char *compressed_data = NULL;
284 uLongf compressed_len;
286 compressed_len = (uLongf) ((the_len * 101) / 100) + 100;
287 compressed_data = malloc(compressed_len);
289 if (compress_gzip((Bytef *) compressed_data,
292 (uLongf) the_len, 9) == Z_OK) {
293 wprintf("Content-encoding: gzip\r\n");
295 the_data = compressed_data;
296 the_len = compressed_len;
298 free(compressed_data);
301 #endif /* HAVE_ZLIB */
303 wprintf("Content-length: %d\r\n\r\n", the_len);
304 client_write(the_data, the_len);
312 * Read data from the client socket with default timeout.
313 * (This is implemented in terms of client_read_to() and could be
314 * justifiably moved out of sysdep.c)
316 int client_read(int sock, char *buf, int bytes)
318 return (client_read_to(sock, buf, bytes, SLEEPING));
323 * client_gets() ... Get a LF-terminated line of text from the client.
324 * (This is implemented in terms of client_read() and could be
325 * justifiably moved out of sysdep.c)
327 int client_gets(int sock, char *buf)
331 /* Read one character at a time.
334 retval = client_read(sock, &buf[i], 1);
335 if (retval != 1 || buf[i] == '\n' || i == 255)
339 /* If we got a long line, discard characters until the newline.
342 while (buf[i] != '\n' && retval == 1)
343 retval = client_read(sock, &buf[i], 1);
346 * Strip any trailing non-printable characters.
349 while ((strlen(buf) > 0) && (!isprint(buf[strlen(buf) - 1]))) {
350 buf[strlen(buf) - 1] = 0;
357 * Start running as a daemon. Only close stdio if do_close_stdio is set.
359 void start_daemon(int do_close_stdio)
361 if (do_close_stdio) {
366 signal(SIGHUP, SIG_IGN);
367 signal(SIGINT, SIG_IGN);
368 signal(SIGQUIT, SIG_IGN);
373 void spawn_another_worker_thread()
375 pthread_t SessThread; /* Thread descriptor */
376 pthread_attr_t attr; /* Thread attributes */
379 lprintf(3, "Creating a new thread\n");
381 /* set attributes for the new thread */
382 pthread_attr_init(&attr);
383 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
385 /* Our per-thread stacks need to be bigger than the default size, otherwise
386 * the MIME parser crashes on FreeBSD, and the IMAP service crashes on
389 if ((ret = pthread_attr_setstacksize(&attr, 1024 * 1024))) {
390 lprintf(1, "pthread_attr_setstacksize: %s\n",
392 pthread_attr_destroy(&attr);
395 /* now create the thread */
396 if (pthread_create(&SessThread, &attr,
397 (void *(*)(void *)) worker_entry, NULL)
399 lprintf(1, "Can't create thread: %s\n", strerror(errno));
402 /* free up the attributes */
403 pthread_attr_destroy(&attr);
407 * Here's where it all begins.
409 int main(int argc, char **argv)
411 pthread_t SessThread; /* Thread descriptor */
412 pthread_attr_t attr; /* Thread attributes */
413 int a, i; /* General-purpose variables */
414 int port = PORT_NUM; /* Port to listen on */
415 char tracefile[PATH_MAX];
418 /* Parse command line */
420 while ((a = getopt(argc, argv, "hi:p:t:cs")) != EOF)
422 while ((a = getopt(argc, argv, "hi:p:t:c")) != EOF)
426 strcpy(ip_addr, optarg);
432 strcpy(tracefile, optarg);
433 freopen(tracefile, "w", stdout);
434 freopen(tracefile, "w", stderr);
435 freopen(tracefile, "r", stdin);
438 verbosity = atoi(optarg);
441 server_cookie = malloc(SIZ);
442 if (server_cookie != NULL) {
443 strcpy(server_cookie,
444 "Set-cookie: wcserver=");
446 (&server_cookie[strlen(server_cookie)],
448 lprintf(2, "gethostname: %s\n",
458 fprintf(stderr, "usage: webserver "
459 "[-i ip_addr] [-p http_port] "
460 "[-t tracefile] [-c] "
464 "[remotehost [remoteport]]\n");
469 ctdlhost = argv[optind];
471 ctdlport = argv[optind];
473 /* Tell 'em who's in da house */
474 lprintf(1, SERVER "\n"
475 "Copyright (C) 1996-2005 by the Citadel/UX development team.\n"
476 "This software is distributed under the terms of the GNU General Public\n"
477 "License. If you paid for this software, someone is ripping you off.\n\n");
479 if (chdir(WEBCITDIR) != 0)
483 * Set up a place to put thread-specific data.
484 * We only need a single pointer per thread - it points to the
485 * wcsession struct to which the thread is currently bound.
487 if (pthread_key_create(&MyConKey, NULL) != 0) {
488 lprintf(1, "Can't create TSD key: %s\n", strerror(errno));
492 * Set up a place to put thread-specific SSL data.
493 * We don't stick this in the wcsession struct because SSL starts
494 * up before the session is bound, and it gets torn down between
498 if (pthread_key_create(&ThreadSSL, NULL) != 0) {
499 lprintf(1, "Can't create TSD key: %s\n", strerror(errno));
504 * Bind the server to our favorite port.
505 * There is no need to check for errors, because ig_tcp_server()
506 * exits if it doesn't succeed.
508 lprintf(2, "Attempting to bind to port %d...\n", port);
509 msock = ig_tcp_server(ip_addr, port, LISTEN_QUEUE_LENGTH);
510 lprintf(2, "Listening on socket %d\n", msock);
511 signal(SIGPIPE, SIG_IGN);
513 pthread_mutex_init(&SessionListMutex, NULL);
516 * Start up the housekeeping thread
518 pthread_attr_init(&attr);
519 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
520 pthread_create(&SessThread, &attr,
521 (void *(*)(void *)) housekeeping_loop, NULL);
525 * If this is an HTTPS server, fire up SSL
533 /* Start a few initial worker threads */
534 for (i = 0; i < (MIN_WORKER_THREADS); ++i) {
535 spawn_another_worker_thread();
538 /* now the original thread becomes another worker */
545 * Entry point for worker threads
547 void worker_entry(void)
552 int fail_this_transaction = 0;
555 /* Only one thread can accept at a time */
556 fail_this_transaction = 0;
557 ssock = accept(msock, NULL, 0);
559 lprintf(2, "accept() failed: %s\n",
562 /* Set the SO_REUSEADDR socket option */
564 setsockopt(ssock, SOL_SOCKET, SO_REUSEADDR,
567 /* If we are an HTTPS server, go crypto now. */
570 if (starttls(ssock) != 0) {
571 fail_this_transaction = 1;
577 if (fail_this_transaction == 0) {
578 /* Perform an HTTP transaction... */
580 /* ...and close the socket. */
581 lingering_close(ssock);
586 } while (!time_to_die);
592 int lprintf(int loglevel, const char *format, ...)
596 if (loglevel <= verbosity) {
597 va_start(ap, format);
598 vfprintf(stderr, format, ap);