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;
34 char socket_dir[PATH_MAX]; /**< where to talk to our citadel server */
35 static const char editor_absolut_dir[PATH_MAX]=EDITORDIR; /**< nailed to what configure gives us. */
36 static char static_dir[PATH_MAX]; /**< calculated on startup */
37 static char static_local_dir[PATH_MAX]; /**< calculated on startup */
38 char *static_dirs[]={ /**< needs same sort order as the web mapping */
39 (char*)static_dir, /** our templates on disk */
40 (char*)static_local_dir, /** user provided templates disk */
41 (char*)editor_absolut_dir /** the editor on disk */
45 * Subdirectories from which the client may request static content
47 * (If you add more, remember to increment 'ndirs' below)
49 char *static_content_dirs[] = {
50 "static", /** static templates */
51 "static.local", /** site local static templates */
52 "tiny_mce" /** the JS editor */
58 char *server_cookie = NULL; /**< our Cookie connection to the client */
60 int http_port = PORT_NUM; /**< Port to listen on */
62 char *ctdlhost = DEFAULT_HOST; /**< our name */
63 char *ctdlport = DEFAULT_PORT; /**< our Port */
64 int setup_wizard = 0; /**< should we run the setup wizard? \todo */
65 char wizard_filename[PATH_MAX];/**< where's the setup wizard? */
66 int running_as_daemon = 0; /**< should we deamonize on startup? */
70 * \brief This is a generic function to set up a master socket for listening on
71 * a TCP port. The server shuts down if the bind fails.
72 * \param ip_addr ip to bind to
73 * \param port_number the port to bind to
74 * \param queue_len the size of the input queue ????
76 int ig_tcp_server(char *ip_addr, int port_number, int queue_len)
78 struct sockaddr_in sin;
81 memset(&sin, 0, sizeof(sin));
82 sin.sin_family = AF_INET;
83 if (ip_addr == NULL) {
84 sin.sin_addr.s_addr = INADDR_ANY;
86 sin.sin_addr.s_addr = inet_addr(ip_addr);
89 if (sin.sin_addr.s_addr == INADDR_NONE) {
90 sin.sin_addr.s_addr = INADDR_ANY;
93 if (port_number == 0) {
94 lprintf(1, "Cannot start: no port number specified.\n");
97 sin.sin_port = htons((u_short) port_number);
99 s = socket(PF_INET, SOCK_STREAM, (getprotobyname("tcp")->p_proto));
101 lprintf(1, "Can't create a socket: %s\n", strerror(errno));
104 /** Set some socket options that make sense. */
106 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
108 if (bind(s, (struct sockaddr *) &sin, sizeof(sin)) < 0) {
109 lprintf(1, "Can't bind: %s\n", strerror(errno));
112 if (listen(s, queue_len) < 0) {
113 lprintf(1, "Can't listen: %s\n", strerror(errno));
122 * \brief Create a Unix domain socket and listen on it
123 * \param sockpath file name of the unix domain socket
124 * \param queue_len queue size of the kernel fifo????
126 int ig_uds_server(char *sockpath, int queue_len)
128 struct sockaddr_un addr;
131 int actual_queue_len;
133 actual_queue_len = queue_len;
134 if (actual_queue_len < 5) actual_queue_len = 5;
136 i = unlink(sockpath);
137 if (i != 0) if (errno != ENOENT) {
138 lprintf(1, "citserver: can't unlink %s: %s\n",
139 sockpath, strerror(errno));
143 memset(&addr, 0, sizeof(addr));
144 addr.sun_family = AF_UNIX;
145 safestrncpy(addr.sun_path, sockpath, sizeof addr.sun_path);
147 s = socket(AF_UNIX, SOCK_STREAM, 0);
149 lprintf(1, "citserver: Can't create a socket: %s\n",
154 if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
155 lprintf(1, "citserver: Can't bind: %s\n",
160 if (listen(s, actual_queue_len) < 0) {
161 lprintf(1, "citserver: Can't listen: %s\n",
166 chmod(sockpath, 0777);
174 * \brief Read data from the client socket.
175 * \param sock socket fd to read from ???
176 * \param buf buffer to read into
177 * \param bytes how large is the read buffer?
178 * \param timeout how long should we wait for input?
179 * \return values are\
180 * 1 Requested number of bytes has been read.\
181 * 0 Request timed out.\
182 * -1 Connection is broken, or other error.
184 int client_read_to(int sock, char *buf, int bytes, int timeout)
194 return (client_read_ssl(buf, bytes, timeout));
199 while (len < bytes) {
205 retval = select((sock) + 1, &rfds, NULL, NULL, &tv);
206 if (FD_ISSET(sock, &rfds) == 0) {
210 rlen = read(sock, &buf[len], bytes - len);
213 lprintf(2, "client_read() failed: %s\n",
221 write(2, "\033[32m", 5);
222 write(2, buf, bytes);
223 write(2, "\033[30m", 5);
229 * \brief write data to the client
230 * \param buf data to write to the client
231 * \param count size of buffer
233 ssize_t client_write(const void *buf, size_t count)
238 if (WC->burst != NULL) {
239 if ((WC->burst_len + count) >= WC->burst_alloc) {
240 newalloc = (WC->burst_alloc * 2);
241 if ((WC->burst_len + count) >= newalloc) {
244 newptr = realloc(WC->burst, newalloc);
245 if (newptr != NULL) {
247 WC->burst_alloc = newalloc;
250 if ((WC->burst_len + count) < WC->burst_alloc) {
251 memcpy(&WC->burst[WC->burst_len], buf, count);
252 WC->burst_len += count;
261 client_write_ssl((char *) buf, count);
266 write(2, "\033[34m", 5);
267 write(2, buf, count);
268 write(2, "\033[30m", 5);
270 return (write(WC->http_sock, buf, count));
274 * \brief what burst???
276 void begin_burst(void)
278 if (WC->burst != NULL) {
283 WC->burst_alloc = 32768;
284 WC->burst = malloc(WC->burst_alloc);
289 * \brief uses the same calling syntax as compress2(), but it
290 * creates a stream compatible with HTTP "Content-encoding: gzip"
293 #define DEF_MEM_LEVEL 8 /**< memlevel??? */
294 #define OS_CODE 0x03 /**< unix */
295 int ZEXPORT compress_gzip(Bytef * dest, /**< compressed buffer*/
296 uLongf * destLen, /**< length of the compresed data */
297 const Bytef * source, /**< source to encode */
298 uLong sourceLen, /**< length of the source to encode */
299 int level) /**< what level??? */
301 const int gz_magic[2] = { 0x1f, 0x8b }; /** gzip magic header */
303 /** write gzip header */
304 sprintf((char *) dest, "%c%c%c%c%c%c%c%c%c%c",
305 gz_magic[0], gz_magic[1], Z_DEFLATED,
306 0 /*flags */ , 0, 0, 0, 0 /*time */ , 0 /** xflags */ ,
312 stream.next_in = (Bytef *) source;
313 stream.avail_in = (uInt) sourceLen;
314 stream.next_out = dest + 10L; // after header
315 stream.avail_out = (uInt) * destLen;
316 if ((uLong) stream.avail_out != *destLen)
319 stream.zalloc = (alloc_func) 0;
320 stream.zfree = (free_func) 0;
321 stream.opaque = (voidpf) 0;
323 err = deflateInit2(&stream, level, Z_DEFLATED, -MAX_WBITS,
324 DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
328 err = deflate(&stream, Z_FINISH);
329 if (err != Z_STREAM_END) {
331 return err == Z_OK ? Z_BUF_ERROR : err;
333 *destLen = stream.total_out + 10L;
335 /* write CRC and Length */
336 uLong crc = crc32(0L, source, sourceLen);
338 for (n = 0; n < 4; ++n, ++*destLen) {
339 dest[*destLen] = (int) (crc & 0xff);
342 uLong len = stream.total_in;
343 for (n = 0; n < 4; ++n, ++*destLen) {
344 dest[*destLen] = (int) (len & 0xff);
347 err = deflateEnd(&stream);
353 * \brief what burst???
360 if (WC->burst == NULL)
363 the_len = WC->burst_len;
364 the_data = WC->burst;
371 /* Handle gzip compression */
373 char *compressed_data = NULL;
374 uLongf compressed_len;
376 compressed_len = (uLongf) ((the_len * 101) / 100) + 100;
377 compressed_data = malloc(compressed_len);
379 if (compress_gzip((Bytef *) compressed_data,
382 (uLongf) the_len, Z_BEST_SPEED) == Z_OK) {
383 wprintf("Content-encoding: gzip\r\n");
385 the_data = compressed_data;
386 the_len = compressed_len;
388 free(compressed_data);
391 #endif /* HAVE_ZLIB */
393 wprintf("Content-length: %d\r\n\r\n", the_len);
394 client_write(the_data, the_len);
402 * \brief Read data from the client socket with default timeout.
403 * (This is implemented in terms of client_read_to() and could be
404 * justifiably moved out of sysdep.c)
405 * \param sock the socket fd to read from???
406 * \param buf the buffer to write to
407 * \param bytes how large is the buffer
409 int client_read(int sock, char *buf, int bytes)
411 return (client_read_to(sock, buf, bytes, SLEEPING));
416 * \brief Get a LF-terminated line of text from the client.
417 * (This is implemented in terms of client_read() and could be
418 * justifiably moved out of sysdep.c)
419 * \param sock socket fd to get client line from???
420 * \param buf buffer to write read data to
421 * \param bufsiz how many bytes to read
422 * \return numer of bytes read???
424 int client_getln(int sock, char *buf, int bufsiz)
428 /** Read one character at a time.*/
430 retval = client_read(sock, &buf[i], 1);
431 if (retval != 1 || buf[i] == '\n' || i == (bufsiz-1))
433 if ( (!isspace(buf[i])) && (!isprint(buf[i])) ) {
434 /** Non printable character recieved from client */
439 /** If we got a long line, discard characters until the newline. */
441 while (buf[i] != '\n' && retval == 1)
442 retval = client_read(sock, &buf[i], 1);
445 * Strip any trailing non-printable characters.
448 while ((i > 0) && (!isprint(buf[i - 1]))) {
455 * \brief shut us down the regular way.
456 * param signum the signal we want to forward
459 void graceful_shutdown_watcher(int signum) {
460 lprintf (1, "bye; shutting down watcher.");
461 kill(current_child, signum);
466 * \brief shut us down the regular way.
467 * param signum the signal we want to forward
470 void graceful_shutdown(int signum) {
471 // kill(current_child, signum);
472 lprintf (1, "bye going down gracefull.");
479 * \brief Start running as a daemon.
481 * param do_close_stdio Only close stdio if set.
485 * Start running as a daemon.
487 void start_daemon(char *pid_file)
496 /* Close stdin/stdout/stderr and replace them with /dev/null.
497 * We don't just call close() because we don't want these fd's
498 * to be reused for other files.
502 signal(SIGHUP, SIG_IGN);
503 signal(SIGINT, SIG_IGN);
504 signal(SIGQUIT, SIG_IGN);
513 freopen("/dev/null", "r", stdin);
514 freopen("/dev/null", "w", stdout);
515 freopen("/dev/null", "w", stderr);
516 signal(SIGTERM, graceful_shutdown_watcher);
519 current_child = fork();
522 if (current_child < 0) {
527 else if (current_child == 0) {
528 signal(SIGTERM, graceful_shutdown);
529 return; /* continue starting webcit. */
533 signal(SIGTERM, SIG_IGN);
535 fp = fopen(pid_file, "w");
537 fprintf(fp, "%d\n", current_child);
541 waitpid(current_child, &status, 0);
546 /* Did the main process exit with an actual exit code? */
547 if (WIFEXITED(status)) {
549 /* Exit code 0 means the watcher should exit */
550 if (WEXITSTATUS(status) == 0) {
554 /* Exit code 101-109 means the watcher should exit */
555 else if ( (WEXITSTATUS(status) >= 101) && (WEXITSTATUS(status) <= 109) ) {
559 /* Any other exit code means we should restart. */
565 /* Any other type of termination (signals, etc.) should also restart. */
570 } while (do_restart);
575 exit(WEXITSTATUS(status));
579 * \brief Spawn an additional worker thread into the pool.
581 void spawn_another_worker_thread()
583 pthread_t SessThread; /**< Thread descriptor */
584 pthread_attr_t attr; /**< Thread attributes */
587 lprintf(3, "Creating a new thread\n");
589 /** set attributes for the new thread */
590 pthread_attr_init(&attr);
591 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
594 * Our per-thread stacks need to be bigger than the default size, otherwise
595 * the MIME parser crashes on FreeBSD, and the IMAP service crashes on
598 if ((ret = pthread_attr_setstacksize(&attr, 1024 * 1024))) {
599 lprintf(1, "pthread_attr_setstacksize: %s\n",
601 pthread_attr_destroy(&attr);
604 /** now create the thread */
605 if (pthread_create(&SessThread, &attr,
606 (void *(*)(void *)) worker_entry, NULL)
608 lprintf(1, "Can't create thread: %s\n", strerror(errno));
611 /** free up the attributes */
612 pthread_attr_destroy(&attr);
616 * \brief Here's where it all begins.
617 * \param argc number of commandline args
618 * \param argv the commandline arguments
620 int main(int argc, char **argv)
622 pthread_t SessThread; /**< Thread descriptor */
623 pthread_attr_t attr; /**< Thread attributes */
624 int a, i; /**< General-purpose variables */
625 char tracefile[PATH_MAX];
626 char ip_addr[256]="0.0.0.0";
627 char dirbuffer[PATH_MAX]="";
630 int home_specified=0;
631 char relhome[PATH_MAX]="";
632 char webcitdir[PATH_MAX] = DATADIR;
633 char *pidfile = NULL;
639 #endif /* ENABLE_NLS */
640 char uds_listen_path[PATH_MAX]; /**< listen on a unix domain socket? */
642 strcpy(uds_listen_path, "");
644 /** Parse command line */
646 while ((a = getopt(argc, argv, "h:i:p:t:x:dD:cfs")) != EOF)
648 while ((a = getopt(argc, argv, "h:i:p:t:x:dD:cf")) != EOF)
652 hdir = strdup(optarg);
654 if (!relh) safestrncpy(webcitdir, hdir,
657 safestrncpy(relhome, relhome,
659 /* free(hdir); TODO: SHOULD WE DO THIS? */
664 running_as_daemon = 1;
667 pidfile = strdup(optarg);
668 running_as_daemon = 1;
671 safestrncpy(ip_addr, optarg, sizeof ip_addr);
674 http_port = atoi(optarg);
675 if (http_port == 0) {
676 safestrncpy(uds_listen_path, optarg, sizeof uds_listen_path);
680 safestrncpy(tracefile, optarg, sizeof tracefile);
681 freopen(tracefile, "w", stdout);
682 freopen(tracefile, "w", stderr);
683 freopen(tracefile, "r", stdin);
686 verbosity = atoi(optarg);
692 server_cookie = malloc(256);
693 if (server_cookie != NULL) {
694 safestrncpy(server_cookie,
695 "Set-cookie: wcserver=",
698 (&server_cookie[strlen(server_cookie)],
700 lprintf(2, "gethostname: %s\n",
710 fprintf(stderr, "usage: webserver "
711 "[-i ip_addr] [-p http_port] "
712 "[-t tracefile] [-c] [-f] "
717 "[remotehost [remoteport]]\n");
722 ctdlhost = argv[optind];
724 ctdlport = argv[optind];
727 /* daemonize, if we were asked to */
728 if (running_as_daemon) {
729 start_daemon(pidfile);
732 signal(SIGTERM, graceful_shutdown);
735 /** Tell 'em who's in da house */
736 lprintf(1, SERVER "\n");
737 lprintf(1, "Copyright (C) 1996-2007 by the Citadel development team.\n"
738 "This software is distributed under the terms of the "
739 "GNU General Public License.\n\n"
743 /** initialize the International Bright Young Thing */
745 initialize_locales();
746 locale = setlocale(LC_ALL, "");
747 mo = malloc(strlen(webcitdir) + 20);
748 lprintf(9, "Message catalog directory: %s\n", bindtextdomain("webcit", LOCALEDIR"/locale"));
750 lprintf(9, "Text domain: %s\n", textdomain("webcit"));
751 lprintf(9, "Text domain Charset: %s\n", bind_textdomain_codeset("webcit","UTF8"));
755 /* calculate all our path on a central place */
756 /* where to keep our config */
758 #define COMPUTE_DIRECTORY(SUBDIR) memcpy(dirbuffer,SUBDIR, sizeof dirbuffer);\
759 snprintf(SUBDIR,sizeof SUBDIR, "%s%s%s%s%s%s%s", \
760 (home&!relh)?webcitdir:basedir, \
761 ((basedir!=webcitdir)&(home&!relh))?basedir:"/", \
762 ((basedir!=webcitdir)&(home&!relh))?"/":"", \
764 (relhome[0]!='\0')?"/":"",\
766 (dirbuffer[0]!='\0')?"/":"");
768 COMPUTE_DIRECTORY(socket_dir);
769 basedir=DATADIR "/static";
770 COMPUTE_DIRECTORY(static_dir);
771 basedir=DATADIR "/static.local";
772 COMPUTE_DIRECTORY(static_local_dir);
773 /** we should go somewhere we can leave our coredump, if enabled... */
774 lprintf(9, "Changing directory to %s\n", socket_dir);
775 if (chdir(webcitdir) != 0) {
778 initialize_viewdefs();
782 * Set up a place to put thread-specific data.
783 * We only need a single pointer per thread - it points to the
784 * wcsession struct to which the thread is currently bound.
786 if (pthread_key_create(&MyConKey, NULL) != 0) {
787 lprintf(1, "Can't create TSD key: %s\n", strerror(errno));
791 * Set up a place to put thread-specific SSL data.
792 * We don't stick this in the wcsession struct because SSL starts
793 * up before the session is bound, and it gets torn down between
797 if (pthread_key_create(&ThreadSSL, NULL) != 0) {
798 lprintf(1, "Can't create TSD key: %s\n", strerror(errno));
803 * Bind the server to our favorite port.
804 * There is no need to check for errors, because ig_tcp_server()
805 * exits if it doesn't succeed.
808 if (!IsEmptyStr(uds_listen_path)) {
809 lprintf(2, "Attempting to create listener socket at %s...\n", uds_listen_path);
810 msock = ig_uds_server(uds_listen_path, LISTEN_QUEUE_LENGTH);
813 lprintf(2, "Attempting to bind to port %d...\n", http_port);
814 msock = ig_tcp_server(ip_addr, http_port, LISTEN_QUEUE_LENGTH);
817 lprintf(2, "Listening on socket %d\n", msock);
818 signal(SIGPIPE, SIG_IGN);
820 pthread_mutex_init(&SessionListMutex, NULL);
823 * Start up the housekeeping thread
825 pthread_attr_init(&attr);
826 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
827 pthread_create(&SessThread, &attr,
828 (void *(*)(void *)) housekeeping_loop, NULL);
832 * If this is an HTTPS server, fire up SSL
840 /** Start a few initial worker threads */
841 for (i = 0; i < (MIN_WORKER_THREADS); ++i) {
842 spawn_another_worker_thread();
845 /* now the original thread becomes another worker */
852 * Entry point for worker threads
854 void worker_entry(void)
858 int fail_this_transaction = 0;
861 /** Only one thread can accept at a time */
862 fail_this_transaction = 0;
863 ssock = accept(msock, NULL, 0);
865 lprintf(2, "accept() failed: %s\n",
868 /** Set the SO_REUSEADDR socket option */
870 setsockopt(ssock, SOL_SOCKET, SO_REUSEADDR,
873 /** If we are an HTTPS server, go crypto now. */
876 if (starttls(ssock) != 0) {
877 fail_this_transaction = 1;
883 if (fail_this_transaction == 0) {
885 /** Perform an HTTP transaction... */
888 /** Shut down SSL/TLS if required... */
895 /** ...and close the socket. */
896 lingering_close(ssock);
901 } while (!time_to_die);
908 * \brief logprintf. log messages
909 * logs to stderr if loglevel is lower than the verbosity set at startup
910 * \param loglevel level of the message
911 * \param format the printf like format string
912 * \param ... the strings to put into format
914 int lprintf(int loglevel, const char *format, ...)
918 if (loglevel <= verbosity) {
919 va_start(ap, format);
920 vfprintf(stderr, format, ap);
929 * \brief print the actual stack frame.
931 void wc_backtrace(void)
933 #ifdef HAVE_BACKTRACE
934 void *stack_frames[50];
939 size = backtrace(stack_frames, sizeof(stack_frames) / sizeof(void*));
940 strings = backtrace_symbols(stack_frames, size);
941 for (i = 0; i < size; i++) {
943 lprintf(1, "%s\n", strings[i]);
945 lprintf(1, "%p\n", stack_frames[i]);