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)
205 if (WC->burst != NULL) {
207 realloc(WC->burst, (WC->burst_len + count + 2));
208 memcpy(&WC->burst[WC->burst_len], buf, count);
209 WC->burst_len += count;
214 client_write_ssl((char *) buf, count);
219 write(2, "\033[34m", 5);
220 write(2, buf, count);
221 write(2, "\033[30m", 5);
223 return (write(WC->http_sock, buf, count));
227 * \brief what burst???
229 void begin_burst(void)
231 if (WC->burst != NULL) {
236 WC->burst = malloc(SIZ);
241 * \brief uses the same calling syntax as compress2(), but it
242 * creates a stream compatible with HTTP "Content-encoding: gzip"
245 #define DEF_MEM_LEVEL 8 /**< memlevel??? */
246 #define OS_CODE 0x03 /**< unix */
247 int ZEXPORT compress_gzip(Bytef * dest, /**< compressed buffer*/
248 uLongf * destLen, /**< length of the compresed data */
249 const Bytef * source, /**< source to encode */
250 uLong sourceLen, /**< length of the source to encode */
251 int level) /**< what level??? */
253 const int gz_magic[2] = { 0x1f, 0x8b }; /** gzip magic header */
255 /** write gzip header */
256 sprintf((char *) dest, "%c%c%c%c%c%c%c%c%c%c",
257 gz_magic[0], gz_magic[1], Z_DEFLATED,
258 0 /*flags */ , 0, 0, 0, 0 /*time */ , 0 /** xflags */ ,
264 stream.next_in = (Bytef *) source;
265 stream.avail_in = (uInt) sourceLen;
266 stream.next_out = dest + 10L; // after header
267 stream.avail_out = (uInt) * destLen;
268 if ((uLong) stream.avail_out != *destLen)
271 stream.zalloc = (alloc_func) 0;
272 stream.zfree = (free_func) 0;
273 stream.opaque = (voidpf) 0;
275 err = deflateInit2(&stream, level, Z_DEFLATED, -MAX_WBITS,
276 DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
280 err = deflate(&stream, Z_FINISH);
281 if (err != Z_STREAM_END) {
283 return err == Z_OK ? Z_BUF_ERROR : err;
285 *destLen = stream.total_out + 10L;
287 /* write CRC and Length */
288 uLong crc = crc32(0L, source, sourceLen);
290 for (n = 0; n < 4; ++n, ++*destLen) {
291 dest[*destLen] = (int) (crc & 0xff);
294 uLong len = stream.total_in;
295 for (n = 0; n < 4; ++n, ++*destLen) {
296 dest[*destLen] = (int) (len & 0xff);
299 err = deflateEnd(&stream);
305 * \brief what burst???
312 if (WC->burst == NULL)
315 the_len = WC->burst_len;
316 the_data = WC->burst;
322 /* Handle gzip compression */
324 char *compressed_data = NULL;
325 uLongf compressed_len;
327 compressed_len = (uLongf) ((the_len * 101) / 100) + 100;
328 compressed_data = malloc(compressed_len);
330 if (compress_gzip((Bytef *) compressed_data,
333 (uLongf) the_len, Z_BEST_SPEED) == Z_OK) {
334 wprintf("Content-encoding: gzip\r\n");
336 the_data = compressed_data;
337 the_len = compressed_len;
339 free(compressed_data);
342 #endif /* HAVE_ZLIB */
344 wprintf("Content-length: %d\r\n\r\n", the_len);
345 client_write(the_data, the_len);
353 * \brief Read data from the client socket with default timeout.
354 * (This is implemented in terms of client_read_to() and could be
355 * justifiably moved out of sysdep.c)
356 * \param sock the socket fd to read from???
357 * \param buf the buffer to write to
358 * \param bytes how large is the buffer
360 int client_read(int sock, char *buf, int bytes)
362 return (client_read_to(sock, buf, bytes, SLEEPING));
367 * \brief Get a LF-terminated line of text from the client.
368 * (This is implemented in terms of client_read() and could be
369 * justifiably moved out of sysdep.c)
370 * \param sock socket fd to get client line from???
371 * \param buf buffer to write read data to
372 * \param bufsiz how many bytes to read
373 * \return numer of bytes read???
375 int client_getln(int sock, char *buf, int bufsiz)
379 /** Read one character at a time.*/
381 retval = client_read(sock, &buf[i], 1);
382 if (retval != 1 || buf[i] == '\n' || i == (bufsiz-1))
384 if ( (!isspace(buf[i])) && (!isprint(buf[i])) ) {
385 lprintf(2, "Non printable character recieved from client\n");
391 /** If we got a long line, discard characters until the newline. */
393 while (buf[i] != '\n' && retval == 1)
394 retval = client_read(sock, &buf[i], 1);
397 * Strip any trailing non-printable characters.
400 while ((strlen(buf) > 0) && (!isprint(buf[strlen(buf) - 1]))) {
401 buf[strlen(buf) - 1] = 0;
408 * \brief Start running as a daemon.
409 * param do_close_stdio Only close stdio if set.
411 void start_daemon(int do_close_stdio)
413 if (do_close_stdio) {
418 signal(SIGHUP, SIG_IGN);
419 signal(SIGINT, SIG_IGN);
420 signal(SIGQUIT, SIG_IGN);
425 void spawn_another_worker_thread()
427 pthread_t SessThread; /**< Thread descriptor */
428 pthread_attr_t attr; /**< Thread attributes */
431 lprintf(3, "Creating a new thread\n");
433 /** set attributes for the new thread */
434 pthread_attr_init(&attr);
435 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
438 * Our per-thread stacks need to be bigger than the default size, otherwise
439 * the MIME parser crashes on FreeBSD, and the IMAP service crashes on
442 if ((ret = pthread_attr_setstacksize(&attr, 1024 * 1024))) {
443 lprintf(1, "pthread_attr_setstacksize: %s\n",
445 pthread_attr_destroy(&attr);
448 /** now create the thread */
449 if (pthread_create(&SessThread, &attr,
450 (void *(*)(void *)) worker_entry, NULL)
452 lprintf(1, "Can't create thread: %s\n", strerror(errno));
455 /** free up the attributes */
456 pthread_attr_destroy(&attr);
460 * \brief Here's where it all begins.
461 * \param argc number of commandline args
462 * \param argv the commandline arguments
464 int main(int argc, char **argv)
466 pthread_t SessThread; /**< Thread descriptor */
467 pthread_attr_t attr; /**< Thread attributes */
468 int a, i; /**< General-purpose variables */
469 char tracefile[PATH_MAX];
471 char *webcitdir = WEBCITDIR;
475 #endif /* ENABLE_NLS */
476 char uds_listen_path[PATH_MAX]; /**< listen on a unix domain socket? */
478 strcpy(uds_listen_path, "");
480 /** Parse command line */
482 while ((a = getopt(argc, argv, "h:i:p:t:x:cfs")) != EOF)
484 while ((a = getopt(argc, argv, "h:i:p:t:x:cf")) != EOF)
488 webcitdir = strdup(optarg);
491 safestrncpy(ip_addr, optarg, sizeof ip_addr);
494 http_port = atoi(optarg);
495 if (http_port == 0) {
496 safestrncpy(uds_listen_path, optarg, sizeof uds_listen_path);
500 safestrncpy(tracefile, optarg, sizeof tracefile);
501 freopen(tracefile, "w", stdout);
502 freopen(tracefile, "w", stderr);
503 freopen(tracefile, "r", stdin);
506 verbosity = atoi(optarg);
512 server_cookie = malloc(256);
513 if (server_cookie != NULL) {
514 safestrncpy(server_cookie,
515 "Set-cookie: wcserver=",
518 (&server_cookie[strlen(server_cookie)],
520 lprintf(2, "gethostname: %s\n",
530 fprintf(stderr, "usage: webserver "
531 "[-i ip_addr] [-p http_port] "
532 "[-t tracefile] [-c] [-f] "
536 "[remotehost [remoteport]]\n");
541 ctdlhost = argv[optind];
543 ctdlport = argv[optind];
545 /** Tell 'em who's in da house */
546 lprintf(1, SERVER "\n");
547 lprintf(1, "Copyright (C) 1996-2006 by the Citadel development team.\n"
548 "This software is distributed under the terms of the "
549 "GNU General Public License.\n\n"
552 lprintf(9, "Changing directory to %s\n", webcitdir);
553 if (chdir(webcitdir) != 0) {
557 /** initialize the International Bright Young Thing */
560 initialize_locales();
562 locale = setlocale(LC_ALL, "");
564 mo = malloc(strlen(webcitdir) + 20);
565 sprintf(mo, "%s/locale", webcitdir);
566 lprintf(9, "Message catalog directory: %s\n",
567 bindtextdomain("webcit", mo)
570 lprintf(9, "Text domain: %s\n",
573 lprintf(9, "Text domain Charset: %s\n",
574 bind_textdomain_codeset("webcit","UTF8")
578 initialize_viewdefs();
582 * Set up a place to put thread-specific data.
583 * We only need a single pointer per thread - it points to the
584 * wcsession struct to which the thread is currently bound.
586 if (pthread_key_create(&MyConKey, NULL) != 0) {
587 lprintf(1, "Can't create TSD key: %s\n", strerror(errno));
591 * Set up a place to put thread-specific SSL data.
592 * We don't stick this in the wcsession struct because SSL starts
593 * up before the session is bound, and it gets torn down between
597 if (pthread_key_create(&ThreadSSL, NULL) != 0) {
598 lprintf(1, "Can't create TSD key: %s\n", strerror(errno));
603 * Bind the server to our favorite port.
604 * There is no need to check for errors, because ig_tcp_server()
605 * exits if it doesn't succeed.
608 if (strlen(uds_listen_path) > 0) {
609 lprintf(2, "Attempting to create listener socket at %s...\n", uds_listen_path);
610 msock = ig_uds_server(uds_listen_path, LISTEN_QUEUE_LENGTH);
613 lprintf(2, "Attempting to bind to port %d...\n", http_port);
614 msock = ig_tcp_server(ip_addr, http_port, LISTEN_QUEUE_LENGTH);
617 lprintf(2, "Listening on socket %d\n", msock);
618 signal(SIGPIPE, SIG_IGN);
620 pthread_mutex_init(&SessionListMutex, NULL);
623 * Start up the housekeeping thread
625 pthread_attr_init(&attr);
626 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
627 pthread_create(&SessThread, &attr,
628 (void *(*)(void *)) housekeeping_loop, NULL);
632 * If this is an HTTPS server, fire up SSL
640 /** Start a few initial worker threads */
641 for (i = 0; i < (MIN_WORKER_THREADS); ++i) {
642 spawn_another_worker_thread();
645 /* now the original thread becomes another worker */
652 * Entry point for worker threads
654 void worker_entry(void)
659 int fail_this_transaction = 0;
662 /** Only one thread can accept at a time */
663 fail_this_transaction = 0;
664 ssock = accept(msock, NULL, 0);
666 lprintf(2, "accept() failed: %s\n",
669 /** Set the SO_REUSEADDR socket option */
671 setsockopt(ssock, SOL_SOCKET, SO_REUSEADDR,
674 /** If we are an HTTPS server, go crypto now. */
677 if (starttls(ssock) != 0) {
678 fail_this_transaction = 1;
684 if (fail_this_transaction == 0) {
685 /** Perform an HTTP transaction... */
687 /** ...and close the socket. */
688 lingering_close(ssock);
693 } while (!time_to_die);
699 * \brief logprintf. log messages
700 * logs to stderr if loglevel is lower than the verbosity set at startup
701 * \param loglevel level of the message
702 * \param format the printf like format string
703 * \param ... the strings to put into format
705 int lprintf(int loglevel, const char *format, ...)
709 if (loglevel <= verbosity) {
710 va_start(ap, format);
711 vfprintf(stderr, format, ap);