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 */
42 * Subdirectories from which the client may request static content
44 * (If you add more, remember to increment 'ndirs' below)
46 char *static_content_dirs[] = {
47 "static", /** static templates */
48 "static.local", /** site local static templates */
49 "tiny_mce" /** the JS editor */
55 char *server_cookie = NULL; /**< our Cookie connection to the client */
57 int http_port = PORT_NUM; /**< Port to listen on */
59 char *ctdlhost = DEFAULT_HOST; /**< our name */
60 char *ctdlport = DEFAULT_PORT; /**< our Port */
61 int setup_wizard = 0; /**< should we run the setup wizard? \todo */
62 char wizard_filename[PATH_MAX];/**< where's the setup wizard? */
63 int running_as_daemon = 0; /**< should we deamonize on startup? */
67 * \brief This is a generic function to set up a master socket for listening on
68 * a TCP port. The server shuts down if the bind fails.
69 * \param ip_addr ip to bind to
70 * \param port_number the port to bind to
71 * \param queue_len the size of the input queue ????
73 int ig_tcp_server(char *ip_addr, int port_number, int queue_len)
75 struct sockaddr_in sin;
78 memset(&sin, 0, sizeof(sin));
79 sin.sin_family = AF_INET;
80 if (ip_addr == NULL) {
81 sin.sin_addr.s_addr = INADDR_ANY;
83 sin.sin_addr.s_addr = inet_addr(ip_addr);
86 if (sin.sin_addr.s_addr == INADDR_NONE) {
87 sin.sin_addr.s_addr = INADDR_ANY;
90 if (port_number == 0) {
91 lprintf(1, "Cannot start: no port number specified.\n");
94 sin.sin_port = htons((u_short) port_number);
96 s = socket(PF_INET, SOCK_STREAM, (getprotobyname("tcp")->p_proto));
98 lprintf(1, "Can't create a socket: %s\n", strerror(errno));
101 /** Set some socket options that make sense. */
103 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
105 if (bind(s, (struct sockaddr *) &sin, sizeof(sin)) < 0) {
106 lprintf(1, "Can't bind: %s\n", strerror(errno));
109 if (listen(s, queue_len) < 0) {
110 lprintf(1, "Can't listen: %s\n", strerror(errno));
119 * \brief Create a Unix domain socket and listen on it
120 * \param sockpath file name of the unix domain socket
121 * \param queue_len queue size of the kernel fifo????
123 int ig_uds_server(char *sockpath, int queue_len)
125 struct sockaddr_un addr;
128 int actual_queue_len;
130 actual_queue_len = queue_len;
131 if (actual_queue_len < 5) actual_queue_len = 5;
133 i = unlink(sockpath);
134 if (i != 0) if (errno != ENOENT) {
135 lprintf(1, "citserver: can't unlink %s: %s\n",
136 sockpath, strerror(errno));
140 memset(&addr, 0, sizeof(addr));
141 addr.sun_family = AF_UNIX;
142 safestrncpy(addr.sun_path, sockpath, sizeof addr.sun_path);
144 s = socket(AF_UNIX, SOCK_STREAM, 0);
146 lprintf(1, "citserver: Can't create a socket: %s\n",
151 if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
152 lprintf(1, "citserver: Can't bind: %s\n",
157 if (listen(s, actual_queue_len) < 0) {
158 lprintf(1, "citserver: Can't listen: %s\n",
163 chmod(sockpath, 0777);
171 * \brief Read data from the client socket.
172 * \param sock socket fd to read from ???
173 * \param buf buffer to read into
174 * \param bytes how large is the read buffer?
175 * \param timeout how long should we wait for input?
176 * \return values are\
177 * 1 Requested number of bytes has been read.\
178 * 0 Request timed out.\
179 * -1 Connection is broken, or other error.
181 int client_read_to(int sock, char *buf, int bytes, int timeout)
191 return (client_read_ssl(buf, bytes, timeout));
196 while (len < bytes) {
202 retval = select((sock) + 1, &rfds, NULL, NULL, &tv);
203 if (FD_ISSET(sock, &rfds) == 0) {
207 rlen = read(sock, &buf[len], bytes - len);
210 lprintf(2, "client_read() failed: %s\n",
218 write(2, "\033[32m", 5);
219 write(2, buf, bytes);
220 write(2, "\033[30m", 5);
226 * \brief write data to the client
227 * \param buf data to write to the client
228 * \param count size of buffer
230 ssize_t client_write(const void *buf, size_t count)
235 if (WC->burst != NULL) {
236 if ((WC->burst_len + count) >= WC->burst_alloc) {
237 newalloc = (WC->burst_alloc * 2);
238 if ((WC->burst_len + count) >= newalloc) {
241 newptr = realloc(WC->burst, newalloc);
242 if (newptr != NULL) {
244 WC->burst_alloc = newalloc;
247 if ((WC->burst_len + count) < WC->burst_alloc) {
248 memcpy(&WC->burst[WC->burst_len], buf, count);
249 WC->burst_len += count;
258 client_write_ssl((char *) buf, count);
263 write(2, "\033[34m", 5);
264 write(2, buf, count);
265 write(2, "\033[30m", 5);
267 return (write(WC->http_sock, buf, count));
271 * \brief what burst???
273 void begin_burst(void)
275 if (WC->burst != NULL) {
280 WC->burst_alloc = 32768;
281 WC->burst = malloc(WC->burst_alloc);
286 * \brief uses the same calling syntax as compress2(), but it
287 * creates a stream compatible with HTTP "Content-encoding: gzip"
290 #define DEF_MEM_LEVEL 8 /**< memlevel??? */
291 #define OS_CODE 0x03 /**< unix */
292 int ZEXPORT compress_gzip(Bytef * dest, /**< compressed buffer*/
293 uLongf * destLen, /**< length of the compresed data */
294 const Bytef * source, /**< source to encode */
295 uLong sourceLen, /**< length of the source to encode */
296 int level) /**< what level??? */
298 const int gz_magic[2] = { 0x1f, 0x8b }; /** gzip magic header */
300 /** write gzip header */
301 sprintf((char *) dest, "%c%c%c%c%c%c%c%c%c%c",
302 gz_magic[0], gz_magic[1], Z_DEFLATED,
303 0 /*flags */ , 0, 0, 0, 0 /*time */ , 0 /** xflags */ ,
309 stream.next_in = (Bytef *) source;
310 stream.avail_in = (uInt) sourceLen;
311 stream.next_out = dest + 10L; // after header
312 stream.avail_out = (uInt) * destLen;
313 if ((uLong) stream.avail_out != *destLen)
316 stream.zalloc = (alloc_func) 0;
317 stream.zfree = (free_func) 0;
318 stream.opaque = (voidpf) 0;
320 err = deflateInit2(&stream, level, Z_DEFLATED, -MAX_WBITS,
321 DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
325 err = deflate(&stream, Z_FINISH);
326 if (err != Z_STREAM_END) {
328 return err == Z_OK ? Z_BUF_ERROR : err;
330 *destLen = stream.total_out + 10L;
332 /* write CRC and Length */
333 uLong crc = crc32(0L, source, sourceLen);
335 for (n = 0; n < 4; ++n, ++*destLen) {
336 dest[*destLen] = (int) (crc & 0xff);
339 uLong len = stream.total_in;
340 for (n = 0; n < 4; ++n, ++*destLen) {
341 dest[*destLen] = (int) (len & 0xff);
344 err = deflateEnd(&stream);
350 * \brief what burst???
357 if (WC->burst == NULL)
360 the_len = WC->burst_len;
361 the_data = WC->burst;
368 /* Handle gzip compression */
370 char *compressed_data = NULL;
371 uLongf compressed_len;
373 compressed_len = (uLongf) ((the_len * 101) / 100) + 100;
374 compressed_data = malloc(compressed_len);
376 if (compress_gzip((Bytef *) compressed_data,
379 (uLongf) the_len, Z_BEST_SPEED) == Z_OK) {
380 wprintf("Content-encoding: gzip\r\n");
382 the_data = compressed_data;
383 the_len = compressed_len;
385 free(compressed_data);
388 #endif /* HAVE_ZLIB */
390 wprintf("Content-length: %d\r\n\r\n", the_len);
391 client_write(the_data, the_len);
399 * \brief Read data from the client socket with default timeout.
400 * (This is implemented in terms of client_read_to() and could be
401 * justifiably moved out of sysdep.c)
402 * \param sock the socket fd to read from???
403 * \param buf the buffer to write to
404 * \param bytes how large is the buffer
406 int client_read(int sock, char *buf, int bytes)
408 return (client_read_to(sock, buf, bytes, SLEEPING));
413 * \brief Get a LF-terminated line of text from the client.
414 * (This is implemented in terms of client_read() and could be
415 * justifiably moved out of sysdep.c)
416 * \param sock socket fd to get client line from???
417 * \param buf buffer to write read data to
418 * \param bufsiz how many bytes to read
419 * \return numer of bytes read???
421 int client_getln(int sock, char *buf, int bufsiz)
425 /** Read one character at a time.*/
427 retval = client_read(sock, &buf[i], 1);
428 if (retval != 1 || buf[i] == '\n' || i == (bufsiz-1))
430 if ( (!isspace(buf[i])) && (!isprint(buf[i])) ) {
431 /** Non printable character recieved from client */
436 /** If we got a long line, discard characters until the newline. */
438 while (buf[i] != '\n' && retval == 1)
439 retval = client_read(sock, &buf[i], 1);
442 * Strip any trailing non-printable characters.
445 while ((strlen(buf) > 0) && (!isprint(buf[strlen(buf) - 1]))) {
446 buf[strlen(buf) - 1] = 0;
452 * \brief shut us down the regular way.
453 * param signum the signal we want to forward
456 void graceful_shutdown(int signum) {
457 kill(current_child, signum);
463 * \brief Start running as a daemon.
465 * param do_close_stdio Only close stdio if set.
469 * Start running as a daemon.
471 void start_daemon(char *pid_file)
480 /* Close stdin/stdout/stderr and replace them with /dev/null.
481 * We don't just call close() because we don't want these fd's
482 * to be reused for other files.
486 signal(SIGHUP, SIG_IGN);
487 signal(SIGINT, SIG_IGN);
488 signal(SIGQUIT, SIG_IGN);
497 freopen("/dev/null", "r", stdin);
498 freopen("/dev/null", "w", stdout);
499 freopen("/dev/null", "w", stderr);
502 current_child = fork();
505 if (current_child < 0) {
510 else if (current_child == 0) {
511 signal(SIGTERM, graceful_shutdown);
512 return; /* continue starting citadel. */
516 signal(SIGTERM, SIG_IGN);
518 fp = fopen(pid_file, "w");
520 fprintf(fp, "%d\n", current_child);
524 waitpid(current_child, &status, 0);
529 /* Did the main process exit with an actual exit code? */
530 if (WIFEXITED(status)) {
532 /* Exit code 0 means the watcher should exit */
533 if (WEXITSTATUS(status) == 0) {
537 /* Exit code 101-109 means the watcher should exit */
538 else if ( (WEXITSTATUS(status) >= 101) && (WEXITSTATUS(status) <= 109) ) {
542 /* Any other exit code means we should restart. */
548 /* Any other type of termination (signals, etc.) should also restart. */
553 } while (do_restart);
558 exit(WEXITSTATUS(status));
562 * \brief Spawn an additional worker thread into the pool.
564 void spawn_another_worker_thread()
566 pthread_t SessThread; /**< Thread descriptor */
567 pthread_attr_t attr; /**< Thread attributes */
570 lprintf(3, "Creating a new thread\n");
572 /** set attributes for the new thread */
573 pthread_attr_init(&attr);
574 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
577 * Our per-thread stacks need to be bigger than the default size, otherwise
578 * the MIME parser crashes on FreeBSD, and the IMAP service crashes on
581 if ((ret = pthread_attr_setstacksize(&attr, 1024 * 1024))) {
582 lprintf(1, "pthread_attr_setstacksize: %s\n",
584 pthread_attr_destroy(&attr);
587 /** now create the thread */
588 if (pthread_create(&SessThread, &attr,
589 (void *(*)(void *)) worker_entry, NULL)
591 lprintf(1, "Can't create thread: %s\n", strerror(errno));
594 /** free up the attributes */
595 pthread_attr_destroy(&attr);
599 * \brief Here's where it all begins.
600 * \param argc number of commandline args
601 * \param argv the commandline arguments
603 int main(int argc, char **argv)
605 pthread_t SessThread; /**< Thread descriptor */
606 pthread_attr_t attr; /**< Thread attributes */
607 int a, i; /**< General-purpose variables */
608 char tracefile[PATH_MAX];
610 char dirbuffer[PATH_MAX]="";
613 int home_specified=0;
614 char relhome[PATH_MAX]="";
615 char webcitdir[PATH_MAX] = DATADIR;
616 char *pidfile = NULL;
622 #endif /* ENABLE_NLS */
623 char uds_listen_path[PATH_MAX]; /**< listen on a unix domain socket? */
625 strcpy(uds_listen_path, "");
627 /** Parse command line */
629 while ((a = getopt(argc, argv, "h:i:p:t:x:dD:cfs")) != EOF)
631 while ((a = getopt(argc, argv, "h:i:p:t:x:dD:cf")) != EOF)
635 hdir = strdup(optarg);
637 if (!relh) safestrncpy(webcitdir, hdir,
640 safestrncpy(relhome, relhome,
642 /* free(hdir); TODO: SHOULD WE DO THIS? */
647 running_as_daemon = 1;
650 pidfile = strdup(optarg);
651 running_as_daemon = 1;
654 safestrncpy(ip_addr, optarg, sizeof ip_addr);
657 http_port = atoi(optarg);
658 if (http_port == 0) {
659 safestrncpy(uds_listen_path, optarg, sizeof uds_listen_path);
663 safestrncpy(tracefile, optarg, sizeof tracefile);
664 freopen(tracefile, "w", stdout);
665 freopen(tracefile, "w", stderr);
666 freopen(tracefile, "r", stdin);
669 verbosity = atoi(optarg);
675 server_cookie = malloc(256);
676 if (server_cookie != NULL) {
677 safestrncpy(server_cookie,
678 "Set-cookie: wcserver=",
681 (&server_cookie[strlen(server_cookie)],
683 lprintf(2, "gethostname: %s\n",
693 fprintf(stderr, "usage: webserver "
694 "[-i ip_addr] [-p http_port] "
695 "[-t tracefile] [-c] [-f] "
700 "[remotehost [remoteport]]\n");
705 ctdlhost = argv[optind];
707 ctdlport = argv[optind];
710 /* daemonize, if we were asked to */
711 if (running_as_daemon) {
712 start_daemon(pidfile);
715 /** Tell 'em who's in da house */
716 lprintf(1, SERVER "\n");
717 lprintf(1, "Copyright (C) 1996-2007 by the Citadel development team.\n"
718 "This software is distributed under the terms of the "
719 "GNU General Public License.\n\n"
723 /** initialize the International Bright Young Thing */
725 initialize_locales();
726 locale = setlocale(LC_ALL, "");
727 mo = malloc(strlen(webcitdir) + 20);
728 lprintf(9, "Message catalog directory: %s\n", bindtextdomain("webcit", LOCALEDIR));
730 lprintf(9, "Text domain: %s\n", textdomain("webcit"));
731 lprintf(9, "Text domain Charset: %s\n", bind_textdomain_codeset("webcit","UTF8"));
735 /* calculate all our path on a central place */
736 /* where to keep our config */
738 #define COMPUTE_DIRECTORY(SUBDIR) memcpy(dirbuffer,SUBDIR, sizeof dirbuffer);\
739 snprintf(SUBDIR,sizeof SUBDIR, "%s%s%s%s%s%s%s", \
740 (home&!relh)?webcitdir:basedir, \
741 ((basedir!=webcitdir)&(home&!relh))?basedir:"/", \
742 ((basedir!=webcitdir)&(home&!relh))?"/":"", \
744 (relhome[0]!='\0')?"/":"",\
746 (dirbuffer[0]!='\0')?"/":"");
748 COMPUTE_DIRECTORY(socket_dir);
750 COMPUTE_DIRECTORY(static_dir);
751 /** we should go somewhere we can leave our coredump, if enabled... */
752 lprintf(9, "Changing directory to %s\n", socket_dir);
753 if (chdir(webcitdir) != 0) {
756 initialize_viewdefs();
760 * Set up a place to put thread-specific data.
761 * We only need a single pointer per thread - it points to the
762 * wcsession struct to which the thread is currently bound.
764 if (pthread_key_create(&MyConKey, NULL) != 0) {
765 lprintf(1, "Can't create TSD key: %s\n", strerror(errno));
769 * Set up a place to put thread-specific SSL data.
770 * We don't stick this in the wcsession struct because SSL starts
771 * up before the session is bound, and it gets torn down between
775 if (pthread_key_create(&ThreadSSL, NULL) != 0) {
776 lprintf(1, "Can't create TSD key: %s\n", strerror(errno));
781 * Bind the server to our favorite port.
782 * There is no need to check for errors, because ig_tcp_server()
783 * exits if it doesn't succeed.
786 if (strlen(uds_listen_path) > 0) {
787 lprintf(2, "Attempting to create listener socket at %s...\n", uds_listen_path);
788 msock = ig_uds_server(uds_listen_path, LISTEN_QUEUE_LENGTH);
791 lprintf(2, "Attempting to bind to port %d...\n", http_port);
792 msock = ig_tcp_server(ip_addr, http_port, LISTEN_QUEUE_LENGTH);
795 lprintf(2, "Listening on socket %d\n", msock);
796 signal(SIGPIPE, SIG_IGN);
798 pthread_mutex_init(&SessionListMutex, NULL);
801 * Start up the housekeeping thread
803 pthread_attr_init(&attr);
804 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
805 pthread_create(&SessThread, &attr,
806 (void *(*)(void *)) housekeeping_loop, NULL);
810 * If this is an HTTPS server, fire up SSL
818 /** Start a few initial worker threads */
819 for (i = 0; i < (MIN_WORKER_THREADS); ++i) {
820 spawn_another_worker_thread();
823 /* now the original thread becomes another worker */
830 * Entry point for worker threads
832 void worker_entry(void)
837 int fail_this_transaction = 0;
840 /** Only one thread can accept at a time */
841 fail_this_transaction = 0;
842 ssock = accept(msock, NULL, 0);
844 lprintf(2, "accept() failed: %s\n",
847 /** Set the SO_REUSEADDR socket option */
849 setsockopt(ssock, SOL_SOCKET, SO_REUSEADDR,
852 /** If we are an HTTPS server, go crypto now. */
855 if (starttls(ssock) != 0) {
856 fail_this_transaction = 1;
862 if (fail_this_transaction == 0) {
864 /** Perform an HTTP transaction... */
867 /** Shut down SSL/TLS if required... */
874 /** ...and close the socket. */
875 lingering_close(ssock);
880 } while (!time_to_die);
886 * \brief logprintf. log messages
887 * logs to stderr if loglevel is lower than the verbosity set at startup
888 * \param loglevel level of the message
889 * \param format the printf like format string
890 * \param ... the strings to put into format
892 int lprintf(int loglevel, const char *format, ...)
896 if (loglevel <= verbosity) {
897 va_start(ap, format);
898 vfprintf(stderr, format, ap);
907 * \brief print the actual stack frame.
909 void wc_backtrace(void)
911 #ifdef HAVE_BACKTRACE
912 void *stack_frames[50];
917 size = backtrace(stack_frames, sizeof(stack_frames) / sizeof(void*));
918 strings = backtrace_symbols(stack_frames, size);
919 for (i = 0; i < size; i++) {
921 lprintf(1, "%s\n", strings[i]);
923 lprintf(1, "%p\n", stack_frames[i]);