5 * \defgroup Webserver This contains a simple multithreaded TCP server manager. It sits around
6 * waiting on the specified port for incoming HTTP connections. When a
7 * connection is established, it calls context_loop() from context_loop.c.
8 * \ingroup WebcitHttpServer
13 #include "webserver.h"
16 int vsnprintf(char *buf, size_t max, const char *fmt, va_list argp);
19 int verbosity = 9; /**< Logging level */
20 int msock; /**< master listening socket */
21 int is_https = 0; /**< Nonzero if I am an HTTPS service */
22 int follow_xff = 0; /**< Follow X-Forwarded-For: header */
23 extern void *context_loop(int);
24 extern void *housekeeping_loop(void);
25 extern pthread_mutex_t SessionListMutex;
26 extern pthread_key_t MyConKey;
29 char *server_cookie = NULL; /**< our Cookie connection to the client */
31 int http_port = PORT_NUM; /**< Port to listen on */
33 char *ctdlhost = DEFAULT_HOST; /**< our name */
34 char *ctdlport = DEFAULT_PORT; /**< our Port */
35 int setup_wizard = 0; /**< should we run the setup wizard? \todo */
36 char wizard_filename[PATH_MAX];/**< where's the setup wizard? */
39 * \brief This is a generic function to set up a master socket for listening on
40 * a TCP port. The server shuts down if the bind fails.
41 * \param ip_addr ip to bind to
42 * \param port_number the port to bind to
43 * \param queue_len the size of the input queue ????
45 int ig_tcp_server(char *ip_addr, int port_number, int queue_len)
47 struct sockaddr_in sin;
50 memset(&sin, 0, sizeof(sin));
51 sin.sin_family = AF_INET;
52 if (ip_addr == NULL) {
53 sin.sin_addr.s_addr = INADDR_ANY;
55 sin.sin_addr.s_addr = inet_addr(ip_addr);
58 if (sin.sin_addr.s_addr == INADDR_NONE) {
59 sin.sin_addr.s_addr = INADDR_ANY;
62 if (port_number == 0) {
63 lprintf(1, "Cannot start: no port number specified.\n");
66 sin.sin_port = htons((u_short) port_number);
68 s = socket(PF_INET, SOCK_STREAM, (getprotobyname("tcp")->p_proto));
70 lprintf(1, "Can't create a socket: %s\n", strerror(errno));
73 /** Set some socket options that make sense. */
75 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
77 if (bind(s, (struct sockaddr *) &sin, sizeof(sin)) < 0) {
78 lprintf(1, "Can't bind: %s\n", strerror(errno));
81 if (listen(s, queue_len) < 0) {
82 lprintf(1, "Can't listen: %s\n", strerror(errno));
91 * \brief Create a Unix domain socket and listen on it
92 * \param sockpath file name of the unix domain socket
93 * \param queue_len queue size of the kernel fifo????
95 int ig_uds_server(char *sockpath, int queue_len)
97 struct sockaddr_un addr;
100 int actual_queue_len;
102 actual_queue_len = queue_len;
103 if (actual_queue_len < 5) actual_queue_len = 5;
105 i = unlink(sockpath);
106 if (i != 0) if (errno != ENOENT) {
107 lprintf(1, "citserver: can't unlink %s: %s\n",
108 sockpath, strerror(errno));
112 memset(&addr, 0, sizeof(addr));
113 addr.sun_family = AF_UNIX;
114 safestrncpy(addr.sun_path, sockpath, sizeof addr.sun_path);
116 s = socket(AF_UNIX, SOCK_STREAM, 0);
118 lprintf(1, "citserver: Can't create a socket: %s\n",
123 if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
124 lprintf(1, "citserver: Can't bind: %s\n",
129 if (listen(s, actual_queue_len) < 0) {
130 lprintf(1, "citserver: Can't listen: %s\n",
135 chmod(sockpath, 0777);
143 * \brief Read data from the client socket.
144 * \param sock socket fd to read from ???
145 * \param buf buffer to read into
146 * \param bytes how large is the read buffer?
147 * \param timeout how long should we wait for input?
148 * \return values are\
149 * 1 Requested number of bytes has been read.\
150 * 0 Request timed out.\
151 * -1 Connection is broken, or other error.
153 int client_read_to(int sock, char *buf, int bytes, int timeout)
163 return (client_read_ssl(buf, bytes, timeout));
168 while (len < bytes) {
174 retval = select((sock) + 1, &rfds, NULL, NULL, &tv);
175 if (FD_ISSET(sock, &rfds) == 0) {
179 rlen = read(sock, &buf[len], bytes - len);
182 lprintf(2, "client_read() failed: %s\n",
190 write(2, "\033[32m", 5);
191 write(2, buf, bytes);
192 write(2, "\033[30m", 5);
198 * \brief write data to the client
199 * \param buf data to write to the client
200 * \param count size of buffer
202 ssize_t client_write(const void *buf, size_t count)
207 if (WC->burst != NULL) {
208 if ((WC->burst_len + count) >= WC->burst_alloc) {
209 newalloc = (WC->burst_alloc * 2);
210 if ((WC->burst_len + count) >= newalloc) {
213 newptr = realloc(WC->burst, newalloc);
214 if (newptr != NULL) {
216 WC->burst_alloc = newalloc;
219 if ((WC->burst_len + count) < WC->burst_alloc) {
220 memcpy(&WC->burst[WC->burst_len], buf, count);
221 WC->burst_len += count;
230 client_write_ssl((char *) buf, count);
235 write(2, "\033[34m", 5);
236 write(2, buf, count);
237 write(2, "\033[30m", 5);
239 return (write(WC->http_sock, buf, count));
243 * \brief what burst???
245 void begin_burst(void)
247 if (WC->burst != NULL) {
252 WC->burst_alloc = 32768;
253 WC->burst = malloc(WC->burst_alloc);
258 * \brief uses the same calling syntax as compress2(), but it
259 * creates a stream compatible with HTTP "Content-encoding: gzip"
262 #define DEF_MEM_LEVEL 8 /**< memlevel??? */
263 #define OS_CODE 0x03 /**< unix */
264 int ZEXPORT compress_gzip(Bytef * dest, /**< compressed buffer*/
265 uLongf * destLen, /**< length of the compresed data */
266 const Bytef * source, /**< source to encode */
267 uLong sourceLen, /**< length of the source to encode */
268 int level) /**< what level??? */
270 const int gz_magic[2] = { 0x1f, 0x8b }; /** gzip magic header */
272 /** write gzip header */
273 sprintf((char *) dest, "%c%c%c%c%c%c%c%c%c%c",
274 gz_magic[0], gz_magic[1], Z_DEFLATED,
275 0 /*flags */ , 0, 0, 0, 0 /*time */ , 0 /** xflags */ ,
281 stream.next_in = (Bytef *) source;
282 stream.avail_in = (uInt) sourceLen;
283 stream.next_out = dest + 10L; // after header
284 stream.avail_out = (uInt) * destLen;
285 if ((uLong) stream.avail_out != *destLen)
288 stream.zalloc = (alloc_func) 0;
289 stream.zfree = (free_func) 0;
290 stream.opaque = (voidpf) 0;
292 err = deflateInit2(&stream, level, Z_DEFLATED, -MAX_WBITS,
293 DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
297 err = deflate(&stream, Z_FINISH);
298 if (err != Z_STREAM_END) {
300 return err == Z_OK ? Z_BUF_ERROR : err;
302 *destLen = stream.total_out + 10L;
304 /* write CRC and Length */
305 uLong crc = crc32(0L, source, sourceLen);
307 for (n = 0; n < 4; ++n, ++*destLen) {
308 dest[*destLen] = (int) (crc & 0xff);
311 uLong len = stream.total_in;
312 for (n = 0; n < 4; ++n, ++*destLen) {
313 dest[*destLen] = (int) (len & 0xff);
316 err = deflateEnd(&stream);
322 * \brief what burst???
329 if (WC->burst == NULL)
332 the_len = WC->burst_len;
333 the_data = WC->burst;
340 /* Handle gzip compression */
342 char *compressed_data = NULL;
343 uLongf compressed_len;
345 compressed_len = (uLongf) ((the_len * 101) / 100) + 100;
346 compressed_data = malloc(compressed_len);
348 if (compress_gzip((Bytef *) compressed_data,
351 (uLongf) the_len, Z_BEST_SPEED) == Z_OK) {
352 wprintf("Content-encoding: gzip\r\n");
354 the_data = compressed_data;
355 the_len = compressed_len;
357 free(compressed_data);
360 #endif /* HAVE_ZLIB */
362 wprintf("Content-length: %d\r\n\r\n", the_len);
363 client_write(the_data, the_len);
371 * \brief Read data from the client socket with default timeout.
372 * (This is implemented in terms of client_read_to() and could be
373 * justifiably moved out of sysdep.c)
374 * \param sock the socket fd to read from???
375 * \param buf the buffer to write to
376 * \param bytes how large is the buffer
378 int client_read(int sock, char *buf, int bytes)
380 return (client_read_to(sock, buf, bytes, SLEEPING));
385 * \brief Get a LF-terminated line of text from the client.
386 * (This is implemented in terms of client_read() and could be
387 * justifiably moved out of sysdep.c)
388 * \param sock socket fd to get client line from???
389 * \param buf buffer to write read data to
390 * \param bufsiz how many bytes to read
391 * \return numer of bytes read???
393 int client_getln(int sock, char *buf, int bufsiz)
397 /** Read one character at a time.*/
399 retval = client_read(sock, &buf[i], 1);
400 if (retval != 1 || buf[i] == '\n' || i == (bufsiz-1))
402 if ( (!isspace(buf[i])) && (!isprint(buf[i])) ) {
403 /** Non printable character recieved from client */
408 /** If we got a long line, discard characters until the newline. */
410 while (buf[i] != '\n' && retval == 1)
411 retval = client_read(sock, &buf[i], 1);
414 * Strip any trailing non-printable characters.
417 while ((strlen(buf) > 0) && (!isprint(buf[strlen(buf) - 1]))) {
418 buf[strlen(buf) - 1] = 0;
425 * \brief Start running as a daemon.
427 * param do_close_stdio Only close stdio if set.
429 void start_daemon(int do_close_stdio)
431 if (do_close_stdio) {
436 signal(SIGHUP, SIG_IGN);
437 signal(SIGINT, SIG_IGN);
438 signal(SIGQUIT, SIG_IGN);
445 * \brief Spawn an additional worker thread into the pool.
447 void spawn_another_worker_thread()
449 pthread_t SessThread; /**< Thread descriptor */
450 pthread_attr_t attr; /**< Thread attributes */
453 lprintf(3, "Creating a new thread\n");
455 /** set attributes for the new thread */
456 pthread_attr_init(&attr);
457 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
460 * Our per-thread stacks need to be bigger than the default size, otherwise
461 * the MIME parser crashes on FreeBSD, and the IMAP service crashes on
464 if ((ret = pthread_attr_setstacksize(&attr, 1024 * 1024))) {
465 lprintf(1, "pthread_attr_setstacksize: %s\n",
467 pthread_attr_destroy(&attr);
470 /** now create the thread */
471 if (pthread_create(&SessThread, &attr,
472 (void *(*)(void *)) worker_entry, NULL)
474 lprintf(1, "Can't create thread: %s\n", strerror(errno));
477 /** free up the attributes */
478 pthread_attr_destroy(&attr);
482 * \brief Here's where it all begins.
483 * \param argc number of commandline args
484 * \param argv the commandline arguments
486 int main(int argc, char **argv)
488 pthread_t SessThread; /**< Thread descriptor */
489 pthread_attr_t attr; /**< Thread attributes */
490 int a, i; /**< General-purpose variables */
491 char tracefile[PATH_MAX];
493 char *webcitdir = WEBCITDIR;
497 #endif /* ENABLE_NLS */
498 char uds_listen_path[PATH_MAX]; /**< listen on a unix domain socket? */
500 strcpy(uds_listen_path, "");
502 /** Parse command line */
504 while ((a = getopt(argc, argv, "h:i:p:t:x:cfs")) != EOF)
506 while ((a = getopt(argc, argv, "h:i:p:t:x:cf")) != EOF)
510 webcitdir = strdup(optarg);
513 safestrncpy(ip_addr, optarg, sizeof ip_addr);
516 http_port = atoi(optarg);
517 if (http_port == 0) {
518 safestrncpy(uds_listen_path, optarg, sizeof uds_listen_path);
522 safestrncpy(tracefile, optarg, sizeof tracefile);
523 freopen(tracefile, "w", stdout);
524 freopen(tracefile, "w", stderr);
525 freopen(tracefile, "r", stdin);
528 verbosity = atoi(optarg);
534 server_cookie = malloc(256);
535 if (server_cookie != NULL) {
536 safestrncpy(server_cookie,
537 "Set-cookie: wcserver=",
540 (&server_cookie[strlen(server_cookie)],
542 lprintf(2, "gethostname: %s\n",
552 fprintf(stderr, "usage: webserver "
553 "[-i ip_addr] [-p http_port] "
554 "[-t tracefile] [-c] [-f] "
558 "[remotehost [remoteport]]\n");
563 ctdlhost = argv[optind];
565 ctdlport = argv[optind];
567 /** Tell 'em who's in da house */
568 lprintf(1, SERVER "\n");
569 lprintf(1, "Copyright (C) 1996-2006 by the Citadel development team.\n"
570 "This software is distributed under the terms of the "
571 "GNU General Public License.\n\n"
574 lprintf(9, "Changing directory to %s\n", webcitdir);
575 if (chdir(webcitdir) != 0) {
579 /** initialize the International Bright Young Thing */
582 initialize_locales();
584 locale = setlocale(LC_ALL, "");
586 mo = malloc(strlen(webcitdir) + 20);
587 sprintf(mo, "%s/locale", webcitdir);
588 lprintf(9, "Message catalog directory: %s\n",
589 bindtextdomain("webcit", mo)
592 lprintf(9, "Text domain: %s\n",
595 lprintf(9, "Text domain Charset: %s\n",
596 bind_textdomain_codeset("webcit","UTF8")
600 initialize_viewdefs();
604 * Set up a place to put thread-specific data.
605 * We only need a single pointer per thread - it points to the
606 * wcsession struct to which the thread is currently bound.
608 if (pthread_key_create(&MyConKey, NULL) != 0) {
609 lprintf(1, "Can't create TSD key: %s\n", strerror(errno));
613 * Set up a place to put thread-specific SSL data.
614 * We don't stick this in the wcsession struct because SSL starts
615 * up before the session is bound, and it gets torn down between
619 if (pthread_key_create(&ThreadSSL, NULL) != 0) {
620 lprintf(1, "Can't create TSD key: %s\n", strerror(errno));
625 * Bind the server to our favorite port.
626 * There is no need to check for errors, because ig_tcp_server()
627 * exits if it doesn't succeed.
630 if (strlen(uds_listen_path) > 0) {
631 lprintf(2, "Attempting to create listener socket at %s...\n", uds_listen_path);
632 msock = ig_uds_server(uds_listen_path, LISTEN_QUEUE_LENGTH);
635 lprintf(2, "Attempting to bind to port %d...\n", http_port);
636 msock = ig_tcp_server(ip_addr, http_port, LISTEN_QUEUE_LENGTH);
639 lprintf(2, "Listening on socket %d\n", msock);
640 signal(SIGPIPE, SIG_IGN);
642 pthread_mutex_init(&SessionListMutex, NULL);
645 * Start up the housekeeping thread
647 pthread_attr_init(&attr);
648 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
649 pthread_create(&SessThread, &attr,
650 (void *(*)(void *)) housekeeping_loop, NULL);
654 * If this is an HTTPS server, fire up SSL
662 /** Start a few initial worker threads */
663 for (i = 0; i < (MIN_WORKER_THREADS); ++i) {
664 spawn_another_worker_thread();
667 /* now the original thread becomes another worker */
674 * Entry point for worker threads
676 void worker_entry(void)
681 int fail_this_transaction = 0;
684 /** Only one thread can accept at a time */
685 fail_this_transaction = 0;
686 ssock = accept(msock, NULL, 0);
688 lprintf(2, "accept() failed: %s\n",
691 /** Set the SO_REUSEADDR socket option */
693 setsockopt(ssock, SOL_SOCKET, SO_REUSEADDR,
696 /** If we are an HTTPS server, go crypto now. */
699 if (starttls(ssock) != 0) {
700 fail_this_transaction = 1;
706 if (fail_this_transaction == 0) {
707 /** Perform an HTTP transaction... */
709 /** ...and close the socket. */
710 lingering_close(ssock);
715 } while (!time_to_die);
721 * \brief logprintf. log messages
722 * logs to stderr if loglevel is lower than the verbosity set at startup
723 * \param loglevel level of the message
724 * \param format the printf like format string
725 * \param ... the strings to put into format
727 int lprintf(int loglevel, const char *format, ...)
731 if (loglevel <= verbosity) {
732 va_start(ap, format);
733 vfprintf(stderr, format, ap);
742 * \brief print the actual stack frame.
744 void wc_backtrace(void)
746 #ifdef HAVE_BACKTRACE
747 void *stack_frames[50];
752 size = backtrace(stack_frames, sizeof(stack_frames) / sizeof(void*));
753 strings = backtrace_symbols(stack_frames, size);
754 for (i = 0; i < size; i++) {
756 lprintf(1, "%s\n", strings[i]);
758 lprintf(1, "%p\n", stack_frames[i]);