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 int time_to_die = 0; /**< shold we shut down? */
29 extern void *context_loop(int);
30 extern void *housekeeping_loop(void);
31 extern pthread_mutex_t SessionListMutex;
32 extern pthread_key_t MyConKey;
35 char ctdl_key_dir[PATH_MAX]=SSL_DIR;
36 char file_crpt_file_key[PATH_MAX]="";
37 char file_crpt_file_csr[PATH_MAX]="";
38 char file_crpt_file_cer[PATH_MAX]="";
40 char socket_dir[PATH_MAX]; /**< where to talk to our citadel server */
41 static const char editor_absolut_dir[PATH_MAX]=EDITORDIR; /**< nailed to what configure gives us. */
42 static char static_dir[PATH_MAX]; /**< calculated on startup */
43 static char static_local_dir[PATH_MAX]; /**< calculated on startup */
44 char *static_dirs[]={ /**< needs same sort order as the web mapping */
45 (char*)static_dir, /** our templates on disk */
46 (char*)static_local_dir, /** user provided templates disk */
47 (char*)editor_absolut_dir /** the editor on disk */
51 * Subdirectories from which the client may request static content
53 * (If you add more, remember to increment 'ndirs' below)
55 char *static_content_dirs[] = {
56 "static", /** static templates */
57 "static.local", /** site local static templates */
58 "tiny_mce" /** the JS editor */
64 char *server_cookie = NULL; /**< our Cookie connection to the client */
66 int http_port = PORT_NUM; /**< Port to listen on */
68 char *ctdlhost = DEFAULT_HOST; /**< our name */
69 char *ctdlport = DEFAULT_PORT; /**< our Port */
70 int setup_wizard = 0; /**< should we run the setup wizard? \todo */
71 char wizard_filename[PATH_MAX];/**< where's the setup wizard? */
72 int running_as_daemon = 0; /**< should we deamonize on startup? */
76 * \brief This is a generic function to set up a master socket for listening on
77 * a TCP port. The server shuts down if the bind fails.
78 * \param ip_addr ip to bind to
79 * \param port_number the port to bind to
80 * \param queue_len the size of the input queue ????
82 int ig_tcp_server(char *ip_addr, int port_number, int queue_len)
84 struct sockaddr_in sin;
87 memset(&sin, 0, sizeof(sin));
88 sin.sin_family = AF_INET;
89 if (ip_addr == NULL) {
90 sin.sin_addr.s_addr = INADDR_ANY;
92 sin.sin_addr.s_addr = inet_addr(ip_addr);
95 if (sin.sin_addr.s_addr == INADDR_NONE) {
96 sin.sin_addr.s_addr = INADDR_ANY;
99 if (port_number == 0) {
100 lprintf(1, "Cannot start: no port number specified.\n");
103 sin.sin_port = htons((u_short) port_number);
105 s = socket(PF_INET, SOCK_STREAM, (getprotobyname("tcp")->p_proto));
107 lprintf(1, "Can't create a socket: %s\n", strerror(errno));
110 /** Set some socket options that make sense. */
112 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
114 if (bind(s, (struct sockaddr *) &sin, sizeof(sin)) < 0) {
115 lprintf(1, "Can't bind: %s\n", strerror(errno));
118 if (listen(s, queue_len) < 0) {
119 lprintf(1, "Can't listen: %s\n", strerror(errno));
128 * \brief Create a Unix domain socket and listen on it
129 * \param sockpath file name of the unix domain socket
130 * \param queue_len queue size of the kernel fifo????
132 int ig_uds_server(char *sockpath, int queue_len)
134 struct sockaddr_un addr;
137 int actual_queue_len;
139 actual_queue_len = queue_len;
140 if (actual_queue_len < 5) actual_queue_len = 5;
142 i = unlink(sockpath);
143 if (i != 0) if (errno != ENOENT) {
144 lprintf(1, "citserver: can't unlink %s: %s\n",
145 sockpath, strerror(errno));
149 memset(&addr, 0, sizeof(addr));
150 addr.sun_family = AF_UNIX;
151 safestrncpy(addr.sun_path, sockpath, sizeof addr.sun_path);
153 s = socket(AF_UNIX, SOCK_STREAM, 0);
155 lprintf(1, "citserver: Can't create a socket: %s\n",
160 if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
161 lprintf(1, "citserver: Can't bind: %s\n",
166 if (listen(s, actual_queue_len) < 0) {
167 lprintf(1, "citserver: Can't listen: %s\n",
172 chmod(sockpath, 0777);
180 * \brief Read data from the client socket.
181 * \param sock socket fd to read from ???
182 * \param buf buffer to read into
183 * \param bytes how large is the read buffer?
184 * \param timeout how long should we wait for input?
185 * \return values are\
186 * 1 Requested number of bytes has been read.\
187 * 0 Request timed out.\
188 * -1 Connection is broken, or other error.
190 int client_read_to(int sock, char *buf, int bytes, int timeout)
200 return (client_read_ssl(buf, bytes, timeout));
205 while (len < bytes) {
211 retval = select((sock) + 1, &rfds, NULL, NULL, &tv);
212 if (FD_ISSET(sock, &rfds) == 0) {
216 rlen = read(sock, &buf[len], bytes - len);
219 lprintf(2, "client_read() failed: %s\n",
227 write(2, "\033[32m", 5);
228 write(2, buf, bytes);
229 write(2, "\033[30m", 5);
235 * \brief write data to the client
236 * \param buf data to write to the client
237 * \param count size of buffer
239 ssize_t client_write(const void *buf, size_t count)
244 if (WC->burst != NULL) {
245 if ((WC->burst_len + count) >= WC->burst_alloc) {
246 newalloc = (WC->burst_alloc * 2);
247 if ((WC->burst_len + count) >= newalloc) {
250 newptr = realloc(WC->burst, newalloc);
251 if (newptr != NULL) {
253 WC->burst_alloc = newalloc;
256 if ((WC->burst_len + count) < WC->burst_alloc) {
257 memcpy(&WC->burst[WC->burst_len], buf, count);
258 WC->burst_len += count;
267 client_write_ssl((char *) buf, count);
272 write(2, "\033[34m", 5);
273 write(2, buf, count);
274 write(2, "\033[30m", 5);
276 return (write(WC->http_sock, buf, count));
280 * \brief what burst???
282 void begin_burst(void)
284 if (WC->burst != NULL) {
289 WC->burst_alloc = 32768;
290 WC->burst = malloc(WC->burst_alloc);
295 * \brief uses the same calling syntax as compress2(), but it
296 * creates a stream compatible with HTTP "Content-encoding: gzip"
299 #define DEF_MEM_LEVEL 8 /**< memlevel??? */
300 #define OS_CODE 0x03 /**< unix */
301 int ZEXPORT compress_gzip(Bytef * dest, /**< compressed buffer*/
302 uLongf * destLen, /**< length of the compresed data */
303 const Bytef * source, /**< source to encode */
304 uLong sourceLen, /**< length of the source to encode */
305 int level) /**< what level??? */
307 const int gz_magic[2] = { 0x1f, 0x8b }; /** gzip magic header */
309 /** write gzip header */
310 sprintf((char *) dest, "%c%c%c%c%c%c%c%c%c%c",
311 gz_magic[0], gz_magic[1], Z_DEFLATED,
312 0 /*flags */ , 0, 0, 0, 0 /*time */ , 0 /** xflags */ ,
318 stream.next_in = (Bytef *) source;
319 stream.avail_in = (uInt) sourceLen;
320 stream.next_out = dest + 10L; // after header
321 stream.avail_out = (uInt) * destLen;
322 if ((uLong) stream.avail_out != *destLen)
325 stream.zalloc = (alloc_func) 0;
326 stream.zfree = (free_func) 0;
327 stream.opaque = (voidpf) 0;
329 err = deflateInit2(&stream, level, Z_DEFLATED, -MAX_WBITS,
330 DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
334 err = deflate(&stream, Z_FINISH);
335 if (err != Z_STREAM_END) {
337 return err == Z_OK ? Z_BUF_ERROR : err;
339 *destLen = stream.total_out + 10L;
341 /* write CRC and Length */
342 uLong crc = crc32(0L, source, sourceLen);
344 for (n = 0; n < 4; ++n, ++*destLen) {
345 dest[*destLen] = (int) (crc & 0xff);
348 uLong len = stream.total_in;
349 for (n = 0; n < 4; ++n, ++*destLen) {
350 dest[*destLen] = (int) (len & 0xff);
353 err = deflateEnd(&stream);
359 * \brief what burst???
366 if (WC->burst == NULL)
369 the_len = WC->burst_len;
370 the_data = WC->burst;
377 /* Handle gzip compression */
379 char *compressed_data = NULL;
380 uLongf compressed_len;
382 compressed_len = (uLongf) ((the_len * 101) / 100) + 100;
383 compressed_data = malloc(compressed_len);
385 if (compress_gzip((Bytef *) compressed_data,
388 (uLongf) the_len, Z_BEST_SPEED) == Z_OK) {
389 wprintf("Content-encoding: gzip\r\n");
391 the_data = compressed_data;
392 the_len = compressed_len;
394 free(compressed_data);
397 #endif /* HAVE_ZLIB */
399 wprintf("Content-length: %d\r\n\r\n", the_len);
400 client_write(the_data, the_len);
408 * \brief Read data from the client socket with default timeout.
409 * (This is implemented in terms of client_read_to() and could be
410 * justifiably moved out of sysdep.c)
411 * \param sock the socket fd to read from???
412 * \param buf the buffer to write to
413 * \param bytes how large is the buffer
415 int client_read(int sock, char *buf, int bytes)
417 return (client_read_to(sock, buf, bytes, SLEEPING));
422 * \brief Get a LF-terminated line of text from the client.
423 * (This is implemented in terms of client_read() and could be
424 * justifiably moved out of sysdep.c)
425 * \param sock socket fd to get client line from???
426 * \param buf buffer to write read data to
427 * \param bufsiz how many bytes to read
428 * \return numer of bytes read???
430 int client_getln(int sock, char *buf, int bufsiz)
434 /** Read one character at a time.*/
436 retval = client_read(sock, &buf[i], 1);
437 if (retval != 1 || buf[i] == '\n' || i == (bufsiz-1))
439 if ( (!isspace(buf[i])) && (!isprint(buf[i])) ) {
440 /** Non printable character recieved from client */
445 /** If we got a long line, discard characters until the newline. */
447 while (buf[i] != '\n' && retval == 1)
448 retval = client_read(sock, &buf[i], 1);
451 * Strip any trailing non-printable characters.
454 while ((i > 0) && (!isprint(buf[i - 1]))) {
461 * \brief shut us down the regular way.
462 * param signum the signal we want to forward
465 void graceful_shutdown_watcher(int signum) {
466 lprintf (1, "bye; shutting down watcher.");
467 kill(current_child, signum);
472 * \brief shut us down the regular way.
473 * param signum the signal we want to forward
476 void graceful_shutdown(int signum) {
477 // kill(current_child, signum);
480 lprintf (1, "bye going down gracefull.[%s]\n", wd);
487 * \brief Start running as a daemon.
489 * param do_close_stdio Only close stdio if set.
493 * Start running as a daemon.
495 void start_daemon(char *pid_file)
504 /* Close stdin/stdout/stderr and replace them with /dev/null.
505 * We don't just call close() because we don't want these fd's
506 * to be reused for other files.
510 signal(SIGHUP, SIG_IGN);
511 signal(SIGINT, SIG_IGN);
512 signal(SIGQUIT, SIG_IGN);
521 freopen("/dev/null", "r", stdin);
522 freopen("/dev/null", "w", stdout);
523 freopen("/dev/null", "w", stderr);
524 signal(SIGTERM, graceful_shutdown_watcher);
527 current_child = fork();
530 if (current_child < 0) {
535 else if (current_child == 0) {
536 signal(SIGTERM, graceful_shutdown);
537 return; /* continue starting webcit. */
541 signal(SIGTERM, SIG_IGN);
543 fp = fopen(pid_file, "w");
545 fprintf(fp, "%d\n", current_child);
549 waitpid(current_child, &status, 0);
554 /* Did the main process exit with an actual exit code? */
555 if (WIFEXITED(status)) {
557 /* Exit code 0 means the watcher should exit */
558 if (WEXITSTATUS(status) == 0) {
562 /* Exit code 101-109 means the watcher should exit */
563 else if ( (WEXITSTATUS(status) >= 101) && (WEXITSTATUS(status) <= 109) ) {
567 /* Any other exit code means we should restart. */
573 /* Any other type of termination (signals, etc.) should also restart. */
578 } while (do_restart);
583 exit(WEXITSTATUS(status));
587 * \brief Spawn an additional worker thread into the pool.
589 void spawn_another_worker_thread()
591 pthread_t SessThread; /**< Thread descriptor */
592 pthread_attr_t attr; /**< Thread attributes */
595 lprintf(3, "Creating a new thread\n");
597 /** set attributes for the new thread */
598 pthread_attr_init(&attr);
599 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
602 * Our per-thread stacks need to be bigger than the default size, otherwise
603 * the MIME parser crashes on FreeBSD, and the IMAP service crashes on
606 if ((ret = pthread_attr_setstacksize(&attr, 1024 * 1024))) {
607 lprintf(1, "pthread_attr_setstacksize: %s\n",
609 pthread_attr_destroy(&attr);
612 /** now create the thread */
613 if (pthread_create(&SessThread, &attr,
614 (void *(*)(void *)) worker_entry, NULL)
616 lprintf(1, "Can't create thread: %s\n", strerror(errno));
619 /** free up the attributes */
620 pthread_attr_destroy(&attr);
624 * \brief Here's where it all begins.
625 * \param argc number of commandline args
626 * \param argv the commandline arguments
628 int main(int argc, char **argv)
630 pthread_t SessThread; /**< Thread descriptor */
631 pthread_attr_t attr; /**< Thread attributes */
632 int a, i; /**< General-purpose variables */
633 char tracefile[PATH_MAX];
634 char ip_addr[256]="0.0.0.0";
635 char dirbuffer[PATH_MAX]="";
638 int home_specified=0;
639 char relhome[PATH_MAX]="";
640 char webcitdir[PATH_MAX] = DATADIR;
641 char *pidfile = NULL;
647 #endif /* ENABLE_NLS */
648 char uds_listen_path[PATH_MAX]; /**< listen on a unix domain socket? */
650 strcpy(uds_listen_path, "");
652 /** Parse command line */
654 while ((a = getopt(argc, argv, "h:i:p:t:x:dD:cfs")) != EOF)
656 while ((a = getopt(argc, argv, "h:i:p:t:x:dD:cf")) != EOF)
660 hdir = strdup(optarg);
662 if (!relh) safestrncpy(webcitdir, hdir,
665 safestrncpy(relhome, relhome,
667 /* free(hdir); TODO: SHOULD WE DO THIS? */
672 running_as_daemon = 1;
675 pidfile = strdup(optarg);
676 running_as_daemon = 1;
679 safestrncpy(ip_addr, optarg, sizeof ip_addr);
682 http_port = atoi(optarg);
683 if (http_port == 0) {
684 safestrncpy(uds_listen_path, optarg, sizeof uds_listen_path);
688 safestrncpy(tracefile, optarg, sizeof tracefile);
689 freopen(tracefile, "w", stdout);
690 freopen(tracefile, "w", stderr);
691 freopen(tracefile, "r", stdin);
694 verbosity = atoi(optarg);
700 server_cookie = malloc(256);
701 if (server_cookie != NULL) {
702 safestrncpy(server_cookie,
703 "Set-cookie: wcserver=",
706 (&server_cookie[strlen(server_cookie)],
708 lprintf(2, "gethostname: %s\n",
718 fprintf(stderr, "usage: webserver "
719 "[-i ip_addr] [-p http_port] "
720 "[-t tracefile] [-c] [-f] "
725 "[remotehost [remoteport]]\n");
730 ctdlhost = argv[optind];
732 ctdlport = argv[optind];
735 /* daemonize, if we were asked to */
736 if (running_as_daemon) {
737 start_daemon(pidfile);
740 signal(SIGTERM, graceful_shutdown);
743 /** Tell 'em who's in da house */
744 lprintf(1, SERVER "\n");
745 lprintf(1, "Copyright (C) 1996-2007 by the Citadel development team.\n"
746 "This software is distributed under the terms of the "
747 "GNU General Public License.\n\n"
751 /** initialize the International Bright Young Thing */
753 initialize_locales();
754 locale = setlocale(LC_ALL, "");
755 mo = malloc(strlen(webcitdir) + 20);
756 lprintf(9, "Message catalog directory: %s\n", bindtextdomain("webcit", LOCALEDIR"/locale"));
758 lprintf(9, "Text domain: %s\n", textdomain("webcit"));
759 lprintf(9, "Text domain Charset: %s\n", bind_textdomain_codeset("webcit","UTF8"));
763 /* calculate all our path on a central place */
764 /* where to keep our config */
766 #define COMPUTE_DIRECTORY(SUBDIR) memcpy(dirbuffer,SUBDIR, sizeof dirbuffer);\
767 snprintf(SUBDIR,sizeof SUBDIR, "%s%s%s%s%s%s%s", \
768 (home&!relh)?webcitdir:basedir, \
769 ((basedir!=webcitdir)&(home&!relh))?basedir:"/", \
770 ((basedir!=webcitdir)&(home&!relh))?"/":"", \
772 (relhome[0]!='\0')?"/":"",\
774 (dirbuffer[0]!='\0')?"/":"");
776 COMPUTE_DIRECTORY(socket_dir);
777 basedir=WWWDIR "/static";
778 COMPUTE_DIRECTORY(static_dir);
779 basedir=WWWDIR "/static.local";
780 COMPUTE_DIRECTORY(static_local_dir);
782 snprintf(file_crpt_file_key,
783 sizeof file_crpt_file_key,
786 snprintf(file_crpt_file_csr,
787 sizeof file_crpt_file_csr,
790 snprintf(file_crpt_file_cer,
791 sizeof file_crpt_file_cer,
795 /** we should go somewhere we can leave our coredump, if enabled... */
796 lprintf(9, "Changing directory to %s\n", socket_dir);
797 if (chdir(webcitdir) != 0) {
800 initialize_viewdefs();
804 * Set up a place to put thread-specific data.
805 * We only need a single pointer per thread - it points to the
806 * wcsession struct to which the thread is currently bound.
808 if (pthread_key_create(&MyConKey, NULL) != 0) {
809 lprintf(1, "Can't create TSD key: %s\n", strerror(errno));
813 * Set up a place to put thread-specific SSL data.
814 * We don't stick this in the wcsession struct because SSL starts
815 * up before the session is bound, and it gets torn down between
819 if (pthread_key_create(&ThreadSSL, NULL) != 0) {
820 lprintf(1, "Can't create TSD key: %s\n", strerror(errno));
825 * Bind the server to our favorite port.
826 * There is no need to check for errors, because ig_tcp_server()
827 * exits if it doesn't succeed.
830 if (!IsEmptyStr(uds_listen_path)) {
831 lprintf(2, "Attempting to create listener socket at %s...\n", uds_listen_path);
832 msock = ig_uds_server(uds_listen_path, LISTEN_QUEUE_LENGTH);
835 lprintf(2, "Attempting to bind to port %d...\n", http_port);
836 msock = ig_tcp_server(ip_addr, http_port, LISTEN_QUEUE_LENGTH);
839 lprintf(2, "Listening on socket %d\n", msock);
840 signal(SIGPIPE, SIG_IGN);
842 pthread_mutex_init(&SessionListMutex, NULL);
845 * Start up the housekeeping thread
847 pthread_attr_init(&attr);
848 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
849 pthread_create(&SessThread, &attr,
850 (void *(*)(void *)) housekeeping_loop, NULL);
854 * If this is an HTTPS server, fire up SSL
862 /** Start a few initial worker threads */
863 for (i = 0; i < (MIN_WORKER_THREADS); ++i) {
864 spawn_another_worker_thread();
867 /* now the original thread becomes another worker */
874 * Entry point for worker threads
876 void worker_entry(void)
880 int fail_this_transaction = 0;
883 /** Only one thread can accept at a time */
884 fail_this_transaction = 0;
885 ssock = accept(msock, NULL, 0);
887 lprintf(2, "accept() failed: %s\n",
890 /** Set the SO_REUSEADDR socket option */
892 setsockopt(ssock, SOL_SOCKET, SO_REUSEADDR,
895 /** If we are an HTTPS server, go crypto now. */
898 if (starttls(ssock) != 0) {
899 fail_this_transaction = 1;
905 if (fail_this_transaction == 0) {
907 /** Perform an HTTP transaction... */
910 /** Shut down SSL/TLS if required... */
917 /** ...and close the socket. */
918 lingering_close(ssock);
923 } while (!time_to_die);
930 * \brief logprintf. log messages
931 * logs to stderr if loglevel is lower than the verbosity set at startup
932 * \param loglevel level of the message
933 * \param format the printf like format string
934 * \param ... the strings to put into format
936 int lprintf(int loglevel, const char *format, ...)
940 if (loglevel <= verbosity) {
941 va_start(ap, format);
942 vfprintf(stderr, format, ap);
951 * \brief print the actual stack frame.
953 void wc_backtrace(void)
955 #ifdef HAVE_BACKTRACE
956 void *stack_frames[50];
961 size = backtrace(stack_frames, sizeof(stack_frames) / sizeof(void*));
962 strings = backtrace_symbols(stack_frames, size);
963 for (i = 0; i < size; i++) {
965 lprintf(1, "%s\n", strings[i]);
967 lprintf(1, "%p\n", stack_frames[i]);