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;
66 * This is a generic function to set up a master socket for listening on
67 * a TCP port. The server shuts down if the bind fails.
69 int ig_tcp_server(char *ip_addr, int port_number, int queue_len)
71 struct sockaddr_in sin;
74 memset(&sin, 0, sizeof(sin));
75 sin.sin_family = AF_INET;
76 if (ip_addr == NULL) {
77 sin.sin_addr.s_addr = INADDR_ANY;
79 sin.sin_addr.s_addr = inet_addr(ip_addr);
82 if (sin.sin_addr.s_addr == INADDR_NONE) {
83 sin.sin_addr.s_addr = INADDR_ANY;
86 if (port_number == 0) {
87 lprintf(1, "Cannot start: no port number specified.\n");
90 sin.sin_port = htons((u_short) port_number);
92 s = socket(PF_INET, SOCK_STREAM, (getprotobyname("tcp")->p_proto));
94 lprintf(1, "Can't create a socket: %s\n", strerror(errno));
97 /* Set some socket options that make sense. */
99 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
101 if (bind(s, (struct sockaddr *) &sin, sizeof(sin)) < 0) {
102 lprintf(1, "Can't bind: %s\n", strerror(errno));
105 if (listen(s, queue_len) < 0) {
106 lprintf(1, "Can't listen: %s\n", strerror(errno));
114 * Read data from the client socket.
116 * 1 Requested number of bytes has been read.
117 * 0 Request timed out.
118 * -1 Connection is broken, or other error.
120 int client_read_to(int sock, char *buf, int bytes, int timeout)
130 return (client_read_ssl(buf, bytes, timeout));
135 while (len < bytes) {
141 retval = select((sock) + 1, &rfds, NULL, NULL, &tv);
142 if (FD_ISSET(sock, &rfds) == 0) {
146 rlen = read(sock, &buf[len], bytes - len);
149 lprintf(2, "client_read() failed: %s\n",
157 write(2, "\033[32m", 5);
158 write(2, buf, bytes);
159 write(2, "\033[30m", 5);
165 ssize_t client_write(const void *buf, size_t count)
168 if (WC->burst != NULL) {
170 realloc(WC->burst, (WC->burst_len + count + 2));
171 memcpy(&WC->burst[WC->burst_len], buf, count);
172 WC->burst_len += count;
177 client_write_ssl((char *) buf, count);
182 write(2, "\033[34m", 5);
183 write(2, buf, count);
184 write(2, "\033[30m", 5);
186 return (write(WC->http_sock, buf, count));
190 void begin_burst(void)
192 if (WC->burst != NULL) {
197 WC->burst = malloc(SIZ);
202 * compress_gzip() uses the same calling syntax as compress2(), but it
203 * creates a stream compatible with HTTP "Content-encoding: gzip"
206 #define DEF_MEM_LEVEL 8
207 #define OS_CODE 0x03 /* unix */
208 int ZEXPORT compress_gzip(Bytef * dest, uLongf * destLen,
209 const Bytef * source, uLong sourceLen, int level)
211 const int gz_magic[2] = { 0x1f, 0x8b }; /* gzip magic header */
213 /* write gzip header */
214 sprintf((char *) dest, "%c%c%c%c%c%c%c%c%c%c",
215 gz_magic[0], gz_magic[1], Z_DEFLATED,
216 0 /*flags */ , 0, 0, 0, 0 /*time */ , 0 /*xflags */ ,
222 stream.next_in = (Bytef *) source;
223 stream.avail_in = (uInt) sourceLen;
224 stream.next_out = dest + 10L; // after header
225 stream.avail_out = (uInt) * destLen;
226 if ((uLong) stream.avail_out != *destLen)
229 stream.zalloc = (alloc_func) 0;
230 stream.zfree = (free_func) 0;
231 stream.opaque = (voidpf) 0;
233 err = deflateInit2(&stream, level, Z_DEFLATED, -MAX_WBITS,
234 DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
238 err = deflate(&stream, Z_FINISH);
239 if (err != Z_STREAM_END) {
241 return err == Z_OK ? Z_BUF_ERROR : err;
243 *destLen = stream.total_out + 10L;
245 /* write CRC and Length */
246 uLong crc = crc32(0L, source, sourceLen);
248 for (n = 0; n < 4; ++n, ++*destLen) {
249 dest[*destLen] = (int) (crc & 0xff);
252 uLong len = stream.total_in;
253 for (n = 0; n < 4; ++n, ++*destLen) {
254 dest[*destLen] = (int) (len & 0xff);
257 err = deflateEnd(&stream);
267 if (WC->burst == NULL)
270 the_len = WC->burst_len;
271 the_data = WC->burst;
277 /* Handle gzip compression */
279 char *compressed_data = NULL;
280 uLongf compressed_len;
282 compressed_len = (uLongf) ((the_len * 101) / 100) + 100;
283 compressed_data = malloc(compressed_len);
285 if (compress_gzip((Bytef *) compressed_data,
288 (uLongf) the_len, Z_BEST_SPEED) == Z_OK) {
289 wprintf("Content-encoding: gzip\r\n");
291 the_data = compressed_data;
292 the_len = compressed_len;
294 free(compressed_data);
297 #endif /* HAVE_ZLIB */
299 wprintf("Content-length: %d\r\n\r\n", the_len);
300 client_write(the_data, the_len);
308 * Read data from the client socket with default timeout.
309 * (This is implemented in terms of client_read_to() and could be
310 * justifiably moved out of sysdep.c)
312 int client_read(int sock, char *buf, int bytes)
314 return (client_read_to(sock, buf, bytes, SLEEPING));
319 * client_gets() ... Get a LF-terminated line of text from the client.
320 * (This is implemented in terms of client_read() and could be
321 * justifiably moved out of sysdep.c)
323 int client_gets(int sock, char *buf)
327 /* Read one character at a time.
330 retval = client_read(sock, &buf[i], 1);
331 if (retval != 1 || buf[i] == '\n' || i == 255)
335 /* If we got a long line, discard characters until the newline.
338 while (buf[i] != '\n' && retval == 1)
339 retval = client_read(sock, &buf[i], 1);
342 * Strip any trailing non-printable characters.
345 while ((strlen(buf) > 0) && (!isprint(buf[strlen(buf) - 1]))) {
346 buf[strlen(buf) - 1] = 0;
353 * Start running as a daemon. Only close stdio if do_close_stdio is set.
355 void start_daemon(int do_close_stdio)
357 if (do_close_stdio) {
362 signal(SIGHUP, SIG_IGN);
363 signal(SIGINT, SIG_IGN);
364 signal(SIGQUIT, SIG_IGN);
369 void spawn_another_worker_thread()
371 pthread_t SessThread; /* Thread descriptor */
372 pthread_attr_t attr; /* Thread attributes */
375 lprintf(3, "Creating a new thread\n");
377 /* set attributes for the new thread */
378 pthread_attr_init(&attr);
379 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
381 /* Our per-thread stacks need to be bigger than the default size, otherwise
382 * the MIME parser crashes on FreeBSD, and the IMAP service crashes on
385 if ((ret = pthread_attr_setstacksize(&attr, 1024 * 1024))) {
386 lprintf(1, "pthread_attr_setstacksize: %s\n",
388 pthread_attr_destroy(&attr);
391 /* now create the thread */
392 if (pthread_create(&SessThread, &attr,
393 (void *(*)(void *)) worker_entry, NULL)
395 lprintf(1, "Can't create thread: %s\n", strerror(errno));
398 /* free up the attributes */
399 pthread_attr_destroy(&attr);
403 * Here's where it all begins.
405 int main(int argc, char **argv)
407 pthread_t SessThread; /* Thread descriptor */
408 pthread_attr_t attr; /* Thread attributes */
409 int a, i; /* General-purpose variables */
410 int port = PORT_NUM; /* Port to listen on */
411 char tracefile[PATH_MAX];
414 /* Parse command line */
416 while ((a = getopt(argc, argv, "hi:p:t:x:cs")) != EOF)
418 while ((a = getopt(argc, argv, "hi:p:t:x:c")) != EOF)
422 strcpy(ip_addr, optarg);
428 strcpy(tracefile, optarg);
429 freopen(tracefile, "w", stdout);
430 freopen(tracefile, "w", stderr);
431 freopen(tracefile, "r", stdin);
434 verbosity = atoi(optarg);
437 server_cookie = malloc(SIZ);
438 if (server_cookie != NULL) {
439 strcpy(server_cookie,
440 "Set-cookie: wcserver=");
442 (&server_cookie[strlen(server_cookie)],
444 lprintf(2, "gethostname: %s\n",
454 fprintf(stderr, "usage: webserver "
455 "[-i ip_addr] [-p http_port] "
456 "[-t tracefile] [-c] "
460 "[remotehost [remoteport]]\n");
465 ctdlhost = argv[optind];
467 ctdlport = argv[optind];
469 /* Tell 'em who's in da house */
470 lprintf(1, SERVER "\n"
471 "Copyright (C) 1996-2005 by the Citadel/UX development team.\n"
472 "This software is distributed under the terms of the GNU General Public\n"
473 "License. If you paid for this software, someone is ripping you off.\n\n");
475 if (chdir(WEBCITDIR) != 0)
479 * Set up a place to put thread-specific data.
480 * We only need a single pointer per thread - it points to the
481 * wcsession struct to which the thread is currently bound.
483 if (pthread_key_create(&MyConKey, NULL) != 0) {
484 lprintf(1, "Can't create TSD key: %s\n", strerror(errno));
488 * Set up a place to put thread-specific SSL data.
489 * We don't stick this in the wcsession struct because SSL starts
490 * up before the session is bound, and it gets torn down between
494 if (pthread_key_create(&ThreadSSL, NULL) != 0) {
495 lprintf(1, "Can't create TSD key: %s\n", strerror(errno));
500 * Bind the server to our favorite port.
501 * There is no need to check for errors, because ig_tcp_server()
502 * exits if it doesn't succeed.
504 lprintf(2, "Attempting to bind to port %d...\n", port);
505 msock = ig_tcp_server(ip_addr, port, LISTEN_QUEUE_LENGTH);
506 lprintf(2, "Listening on socket %d\n", msock);
507 signal(SIGPIPE, SIG_IGN);
509 pthread_mutex_init(&SessionListMutex, NULL);
512 * Start up the housekeeping thread
514 pthread_attr_init(&attr);
515 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
516 pthread_create(&SessThread, &attr,
517 (void *(*)(void *)) housekeeping_loop, NULL);
521 * If this is an HTTPS server, fire up SSL
529 /* Start a few initial worker threads */
530 for (i = 0; i < (MIN_WORKER_THREADS); ++i) {
531 spawn_another_worker_thread();
534 /* now the original thread becomes another worker */
541 * Entry point for worker threads
543 void worker_entry(void)
548 int fail_this_transaction = 0;
551 /* Only one thread can accept at a time */
552 fail_this_transaction = 0;
553 ssock = accept(msock, NULL, 0);
555 lprintf(2, "accept() failed: %s\n",
558 /* Set the SO_REUSEADDR socket option */
560 setsockopt(ssock, SOL_SOCKET, SO_REUSEADDR,
563 /* If we are an HTTPS server, go crypto now. */
566 if (starttls(ssock) != 0) {
567 fail_this_transaction = 1;
573 if (fail_this_transaction == 0) {
574 /* Perform an HTTP transaction... */
576 /* ...and close the socket. */
577 lingering_close(ssock);
582 } while (!time_to_die);
588 int lprintf(int loglevel, const char *format, ...)
592 if (loglevel <= verbosity) {
593 va_start(ap, format);
594 vfprintf(stderr, format, ap);