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"
20 int vsnprintf(char *buf, size_t max, const char *fmt, va_list argp);
23 int verbosity = 9; /**< Logging level */
24 int msock; /**< master listening socket */
25 int is_https = 0; /**< Nonzero if I am an HTTPS service */
26 int follow_xff = 0; /**< Follow X-Forwarded-For: header */
27 int home_specified = 0; /**< did the user specify a homedir? */
28 extern void *context_loop(int);
29 extern void *housekeeping_loop(void);
30 extern pthread_mutex_t SessionListMutex;
31 extern pthread_key_t MyConKey;
33 char socket_dir[PATH_MAX]; /**< where to talk to our citadel server */
34 static const char editor_absolut_dir[PATH_MAX]=EDITORDIR; /**< nailed to what configure gives us. */
35 static char static_dir[PATH_MAX]; /**< calculated on startup */
36 char *static_dirs[]={ /**< needs same sort order as the web mapping */
37 (char*)static_dir, /** our templates on disk */
38 (char*)editor_absolut_dir /** the editor on disk */
40 int ndirs=2; //sizeof(static_content_dirs);//sizeof(char *);
43 * Subdirectories from which the client may request static content
45 char *static_content_dirs[] = {
46 "static", /** static templates */
47 "tiny_mce" /** the JS editor */
52 char *server_cookie = NULL; /**< our Cookie connection to the client */
54 int http_port = PORT_NUM; /**< Port to listen on */
56 char *ctdlhost = DEFAULT_HOST; /**< our name */
57 char *ctdlport = DEFAULT_PORT; /**< our Port */
58 int setup_wizard = 0; /**< should we run the setup wizard? \todo */
59 char wizard_filename[PATH_MAX];/**< where's the setup wizard? */
62 * \brief This is a generic function to set up a master socket for listening on
63 * a TCP port. The server shuts down if the bind fails.
64 * \param ip_addr ip to bind to
65 * \param port_number the port to bind to
66 * \param queue_len the size of the input queue ????
68 int ig_tcp_server(char *ip_addr, int port_number, int queue_len)
70 struct sockaddr_in sin;
73 memset(&sin, 0, sizeof(sin));
74 sin.sin_family = AF_INET;
75 if (ip_addr == NULL) {
76 sin.sin_addr.s_addr = INADDR_ANY;
78 sin.sin_addr.s_addr = inet_addr(ip_addr);
81 if (sin.sin_addr.s_addr == INADDR_NONE) {
82 sin.sin_addr.s_addr = INADDR_ANY;
85 if (port_number == 0) {
86 lprintf(1, "Cannot start: no port number specified.\n");
89 sin.sin_port = htons((u_short) port_number);
91 s = socket(PF_INET, SOCK_STREAM, (getprotobyname("tcp")->p_proto));
93 lprintf(1, "Can't create a socket: %s\n", strerror(errno));
96 /** Set some socket options that make sense. */
98 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
100 if (bind(s, (struct sockaddr *) &sin, sizeof(sin)) < 0) {
101 lprintf(1, "Can't bind: %s\n", strerror(errno));
104 if (listen(s, queue_len) < 0) {
105 lprintf(1, "Can't listen: %s\n", strerror(errno));
114 * \brief Create a Unix domain socket and listen on it
115 * \param sockpath file name of the unix domain socket
116 * \param queue_len queue size of the kernel fifo????
118 int ig_uds_server(char *sockpath, int queue_len)
120 struct sockaddr_un addr;
123 int actual_queue_len;
125 actual_queue_len = queue_len;
126 if (actual_queue_len < 5) actual_queue_len = 5;
128 i = unlink(sockpath);
129 if (i != 0) if (errno != ENOENT) {
130 lprintf(1, "citserver: can't unlink %s: %s\n",
131 sockpath, strerror(errno));
135 memset(&addr, 0, sizeof(addr));
136 addr.sun_family = AF_UNIX;
137 safestrncpy(addr.sun_path, sockpath, sizeof addr.sun_path);
139 s = socket(AF_UNIX, SOCK_STREAM, 0);
141 lprintf(1, "citserver: Can't create a socket: %s\n",
146 if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
147 lprintf(1, "citserver: Can't bind: %s\n",
152 if (listen(s, actual_queue_len) < 0) {
153 lprintf(1, "citserver: Can't listen: %s\n",
158 chmod(sockpath, 0777);
166 * \brief Read data from the client socket.
167 * \param sock socket fd to read from ???
168 * \param buf buffer to read into
169 * \param bytes how large is the read buffer?
170 * \param timeout how long should we wait for input?
171 * \return values are\
172 * 1 Requested number of bytes has been read.\
173 * 0 Request timed out.\
174 * -1 Connection is broken, or other error.
176 int client_read_to(int sock, char *buf, int bytes, int timeout)
186 return (client_read_ssl(buf, bytes, timeout));
191 while (len < bytes) {
197 retval = select((sock) + 1, &rfds, NULL, NULL, &tv);
198 if (FD_ISSET(sock, &rfds) == 0) {
202 rlen = read(sock, &buf[len], bytes - len);
205 lprintf(2, "client_read() failed: %s\n",
213 write(2, "\033[32m", 5);
214 write(2, buf, bytes);
215 write(2, "\033[30m", 5);
221 * \brief write data to the client
222 * \param buf data to write to the client
223 * \param count size of buffer
225 ssize_t client_write(const void *buf, size_t count)
230 if (WC->burst != NULL) {
231 if ((WC->burst_len + count) >= WC->burst_alloc) {
232 newalloc = (WC->burst_alloc * 2);
233 if ((WC->burst_len + count) >= newalloc) {
236 newptr = realloc(WC->burst, newalloc);
237 if (newptr != NULL) {
239 WC->burst_alloc = newalloc;
242 if ((WC->burst_len + count) < WC->burst_alloc) {
243 memcpy(&WC->burst[WC->burst_len], buf, count);
244 WC->burst_len += count;
253 client_write_ssl((char *) buf, count);
258 write(2, "\033[34m", 5);
259 write(2, buf, count);
260 write(2, "\033[30m", 5);
262 return (write(WC->http_sock, buf, count));
266 * \brief what burst???
268 void begin_burst(void)
270 if (WC->burst != NULL) {
275 WC->burst_alloc = 32768;
276 WC->burst = malloc(WC->burst_alloc);
281 * \brief uses the same calling syntax as compress2(), but it
282 * creates a stream compatible with HTTP "Content-encoding: gzip"
285 #define DEF_MEM_LEVEL 8 /**< memlevel??? */
286 #define OS_CODE 0x03 /**< unix */
287 int ZEXPORT compress_gzip(Bytef * dest, /**< compressed buffer*/
288 uLongf * destLen, /**< length of the compresed data */
289 const Bytef * source, /**< source to encode */
290 uLong sourceLen, /**< length of the source to encode */
291 int level) /**< what level??? */
293 const int gz_magic[2] = { 0x1f, 0x8b }; /** gzip magic header */
295 /** write gzip header */
296 sprintf((char *) dest, "%c%c%c%c%c%c%c%c%c%c",
297 gz_magic[0], gz_magic[1], Z_DEFLATED,
298 0 /*flags */ , 0, 0, 0, 0 /*time */ , 0 /** xflags */ ,
304 stream.next_in = (Bytef *) source;
305 stream.avail_in = (uInt) sourceLen;
306 stream.next_out = dest + 10L; // after header
307 stream.avail_out = (uInt) * destLen;
308 if ((uLong) stream.avail_out != *destLen)
311 stream.zalloc = (alloc_func) 0;
312 stream.zfree = (free_func) 0;
313 stream.opaque = (voidpf) 0;
315 err = deflateInit2(&stream, level, Z_DEFLATED, -MAX_WBITS,
316 DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
320 err = deflate(&stream, Z_FINISH);
321 if (err != Z_STREAM_END) {
323 return err == Z_OK ? Z_BUF_ERROR : err;
325 *destLen = stream.total_out + 10L;
327 /* write CRC and Length */
328 uLong crc = crc32(0L, source, sourceLen);
330 for (n = 0; n < 4; ++n, ++*destLen) {
331 dest[*destLen] = (int) (crc & 0xff);
334 uLong len = stream.total_in;
335 for (n = 0; n < 4; ++n, ++*destLen) {
336 dest[*destLen] = (int) (len & 0xff);
339 err = deflateEnd(&stream);
345 * \brief what burst???
352 if (WC->burst == NULL)
355 the_len = WC->burst_len;
356 the_data = WC->burst;
363 /* Handle gzip compression */
365 char *compressed_data = NULL;
366 uLongf compressed_len;
368 compressed_len = (uLongf) ((the_len * 101) / 100) + 100;
369 compressed_data = malloc(compressed_len);
371 if (compress_gzip((Bytef *) compressed_data,
374 (uLongf) the_len, Z_BEST_SPEED) == Z_OK) {
375 wprintf("Content-encoding: gzip\r\n");
377 the_data = compressed_data;
378 the_len = compressed_len;
380 free(compressed_data);
383 #endif /* HAVE_ZLIB */
385 wprintf("Content-length: %d\r\n\r\n", the_len);
386 client_write(the_data, the_len);
394 * \brief Read data from the client socket with default timeout.
395 * (This is implemented in terms of client_read_to() and could be
396 * justifiably moved out of sysdep.c)
397 * \param sock the socket fd to read from???
398 * \param buf the buffer to write to
399 * \param bytes how large is the buffer
401 int client_read(int sock, char *buf, int bytes)
403 return (client_read_to(sock, buf, bytes, SLEEPING));
408 * \brief Get a LF-terminated line of text from the client.
409 * (This is implemented in terms of client_read() and could be
410 * justifiably moved out of sysdep.c)
411 * \param sock socket fd to get client line from???
412 * \param buf buffer to write read data to
413 * \param bufsiz how many bytes to read
414 * \return numer of bytes read???
416 int client_getln(int sock, char *buf, int bufsiz)
420 /** Read one character at a time.*/
422 retval = client_read(sock, &buf[i], 1);
423 if (retval != 1 || buf[i] == '\n' || i == (bufsiz-1))
425 if ( (!isspace(buf[i])) && (!isprint(buf[i])) ) {
426 /** Non printable character recieved from client */
431 /** If we got a long line, discard characters until the newline. */
433 while (buf[i] != '\n' && retval == 1)
434 retval = client_read(sock, &buf[i], 1);
437 * Strip any trailing non-printable characters.
440 while ((strlen(buf) > 0) && (!isprint(buf[strlen(buf) - 1]))) {
441 buf[strlen(buf) - 1] = 0;
448 * \brief Start running as a daemon.
450 * param do_close_stdio Only close stdio if set.
452 void start_daemon(int do_close_stdio)
454 if (do_close_stdio) {
459 signal(SIGHUP, SIG_IGN);
460 signal(SIGINT, SIG_IGN);
461 signal(SIGQUIT, SIG_IGN);
468 * \brief Spawn an additional worker thread into the pool.
470 void spawn_another_worker_thread()
472 pthread_t SessThread; /**< Thread descriptor */
473 pthread_attr_t attr; /**< Thread attributes */
476 lprintf(3, "Creating a new thread\n");
478 /** set attributes for the new thread */
479 pthread_attr_init(&attr);
480 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
483 * Our per-thread stacks need to be bigger than the default size, otherwise
484 * the MIME parser crashes on FreeBSD, and the IMAP service crashes on
487 if ((ret = pthread_attr_setstacksize(&attr, 1024 * 1024))) {
488 lprintf(1, "pthread_attr_setstacksize: %s\n",
490 pthread_attr_destroy(&attr);
493 /** now create the thread */
494 if (pthread_create(&SessThread, &attr,
495 (void *(*)(void *)) worker_entry, NULL)
497 lprintf(1, "Can't create thread: %s\n", strerror(errno));
500 /** free up the attributes */
501 pthread_attr_destroy(&attr);
505 * \brief Here's where it all begins.
506 * \param argc number of commandline args
507 * \param argv the commandline arguments
509 int main(int argc, char **argv)
511 pthread_t SessThread; /**< Thread descriptor */
512 pthread_attr_t attr; /**< Thread attributes */
513 int a, i; /**< General-purpose variables */
514 char tracefile[PATH_MAX];
516 char dirbuffer[PATH_MAX]="";
519 int home_specified=0;
520 char relhome[PATH_MAX]="";
521 char webcitdir[PATH_MAX] = DATADIR;
527 #endif /* ENABLE_NLS */
528 char uds_listen_path[PATH_MAX]; /**< listen on a unix domain socket? */
530 strcpy(uds_listen_path, "");
532 /** Parse command line */
534 while ((a = getopt(argc, argv, "h:i:p:t:x:cfs")) != EOF)
536 while ((a = getopt(argc, argv, "h:i:p:t:x:cf")) != EOF)
540 hdir = strdup(optarg);
542 if (!relh) safestrncpy(webcitdir, hdir,
545 safestrncpy(relhome, relhome,
547 /* free(hdir); TODO: SHOULD WE DO THIS? */
552 safestrncpy(ip_addr, optarg, sizeof ip_addr);
555 http_port = atoi(optarg);
556 if (http_port == 0) {
557 safestrncpy(uds_listen_path, optarg, sizeof uds_listen_path);
561 safestrncpy(tracefile, optarg, sizeof tracefile);
562 freopen(tracefile, "w", stdout);
563 freopen(tracefile, "w", stderr);
564 freopen(tracefile, "r", stdin);
567 verbosity = atoi(optarg);
573 server_cookie = malloc(256);
574 if (server_cookie != NULL) {
575 safestrncpy(server_cookie,
576 "Set-cookie: wcserver=",
579 (&server_cookie[strlen(server_cookie)],
581 lprintf(2, "gethostname: %s\n",
591 fprintf(stderr, "usage: webserver "
592 "[-i ip_addr] [-p http_port] "
593 "[-t tracefile] [-c] [-f] "
597 "[remotehost [remoteport]]\n");
602 ctdlhost = argv[optind];
604 ctdlport = argv[optind];
606 /** Tell 'em who's in da house */
607 lprintf(1, SERVER "\n");
608 lprintf(1, "Copyright (C) 1996-2006 by the Citadel development team.\n"
609 "This software is distributed under the terms of the "
610 "GNU General Public License.\n\n"
614 /** initialize the International Bright Young Thing */
616 initialize_locales();
617 locale = setlocale(LC_ALL, "");
618 mo = malloc(strlen(webcitdir) + 20);
619 lprintf(9, "Message catalog directory: %s\n", bindtextdomain("webcit", LOCALEDIR));
621 lprintf(9, "Text domain: %s\n", textdomain("webcit"));
622 lprintf(9, "Text domain Charset: %s\n", bind_textdomain_codeset("webcit","UTF8"));
626 /* calculate all our path on a central place */
627 /* where to keep our config */
629 #define COMPUTE_DIRECTORY(SUBDIR) memcpy(dirbuffer,SUBDIR, sizeof dirbuffer);\
630 snprintf(SUBDIR,sizeof SUBDIR, "%s%s%s%s%s%s%s", \
631 (home&!relh)?webcitdir:basedir, \
632 ((basedir!=webcitdir)&(home&!relh))?basedir:"/", \
633 ((basedir!=webcitdir)&(home&!relh))?"/":"", \
635 (relhome[0]!='\0')?"/":"",\
637 (dirbuffer[0]!='\0')?"/":"");
639 COMPUTE_DIRECTORY(socket_dir);
641 COMPUTE_DIRECTORY(static_dir);
642 /** we should go somewhere we can leave our coredump, if enabled... */
643 lprintf(9, "Changing directory to %s\n", socket_dir);
644 if (chdir(webcitdir) != 0) {
647 initialize_viewdefs();
651 * Set up a place to put thread-specific data.
652 * We only need a single pointer per thread - it points to the
653 * wcsession struct to which the thread is currently bound.
655 if (pthread_key_create(&MyConKey, NULL) != 0) {
656 lprintf(1, "Can't create TSD key: %s\n", strerror(errno));
660 * Set up a place to put thread-specific SSL data.
661 * We don't stick this in the wcsession struct because SSL starts
662 * up before the session is bound, and it gets torn down between
666 if (pthread_key_create(&ThreadSSL, NULL) != 0) {
667 lprintf(1, "Can't create TSD key: %s\n", strerror(errno));
672 * Bind the server to our favorite port.
673 * There is no need to check for errors, because ig_tcp_server()
674 * exits if it doesn't succeed.
677 if (strlen(uds_listen_path) > 0) {
678 lprintf(2, "Attempting to create listener socket at %s...\n", uds_listen_path);
679 msock = ig_uds_server(uds_listen_path, LISTEN_QUEUE_LENGTH);
682 lprintf(2, "Attempting to bind to port %d...\n", http_port);
683 msock = ig_tcp_server(ip_addr, http_port, LISTEN_QUEUE_LENGTH);
686 lprintf(2, "Listening on socket %d\n", msock);
687 signal(SIGPIPE, SIG_IGN);
689 pthread_mutex_init(&SessionListMutex, NULL);
692 * Start up the housekeeping thread
694 pthread_attr_init(&attr);
695 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
696 pthread_create(&SessThread, &attr,
697 (void *(*)(void *)) housekeeping_loop, NULL);
701 * If this is an HTTPS server, fire up SSL
709 /** Start a few initial worker threads */
710 for (i = 0; i < (MIN_WORKER_THREADS); ++i) {
711 spawn_another_worker_thread();
714 /* now the original thread becomes another worker */
721 * Entry point for worker threads
723 void worker_entry(void)
728 int fail_this_transaction = 0;
731 /** Only one thread can accept at a time */
732 fail_this_transaction = 0;
733 ssock = accept(msock, NULL, 0);
735 lprintf(2, "accept() failed: %s\n",
738 /** Set the SO_REUSEADDR socket option */
740 setsockopt(ssock, SOL_SOCKET, SO_REUSEADDR,
743 /** If we are an HTTPS server, go crypto now. */
746 if (starttls(ssock) != 0) {
747 fail_this_transaction = 1;
753 if (fail_this_transaction == 0) {
754 /** Perform an HTTP transaction... */
756 /** ...and close the socket. */
757 lingering_close(ssock);
762 } while (!time_to_die);
768 * \brief logprintf. log messages
769 * logs to stderr if loglevel is lower than the verbosity set at startup
770 * \param loglevel level of the message
771 * \param format the printf like format string
772 * \param ... the strings to put into format
774 int lprintf(int loglevel, const char *format, ...)
778 if (loglevel <= verbosity) {
779 va_start(ap, format);
780 vfprintf(stderr, format, ap);
789 * \brief print the actual stack frame.
791 void wc_backtrace(void)
793 #ifdef HAVE_BACKTRACE
794 void *stack_frames[50];
799 size = backtrace(stack_frames, sizeof(stack_frames) / sizeof(void*));
800 strings = backtrace_symbols(stack_frames, size);
801 for (i = 0; i < size; i++) {
803 lprintf(1, "%s\n", strings[i]);
805 lprintf(1, "%p\n", stack_frames[i]);