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*)static_dir, /** our templates on disk */
39 (char*)editor_absolut_dir /** the editor on disk */
43 * Subdirectories from which the client may request static content
45 * (If you add more, remember to increment 'ndirs' below)
47 char *static_content_dirs[] = {
48 "static", /** static templates */
49 "static.local", /** site local static templates */
50 "tiny_mce" /** the JS editor */
56 char *server_cookie = NULL; /**< our Cookie connection to the client */
58 int http_port = PORT_NUM; /**< Port to listen on */
60 char *ctdlhost = DEFAULT_HOST; /**< our name */
61 char *ctdlport = DEFAULT_PORT; /**< our Port */
62 int setup_wizard = 0; /**< should we run the setup wizard? \todo */
63 char wizard_filename[PATH_MAX];/**< where's the setup wizard? */
64 int running_as_daemon = 0; /**< should we deamonize on startup? */
68 * \brief This is a generic function to set up a master socket for listening on
69 * a TCP port. The server shuts down if the bind fails.
70 * \param ip_addr ip to bind to
71 * \param port_number the port to bind to
72 * \param queue_len the size of the input queue ????
74 int ig_tcp_server(char *ip_addr, int port_number, int queue_len)
76 struct sockaddr_in sin;
79 memset(&sin, 0, sizeof(sin));
80 sin.sin_family = AF_INET;
81 if (ip_addr == NULL) {
82 sin.sin_addr.s_addr = INADDR_ANY;
84 sin.sin_addr.s_addr = inet_addr(ip_addr);
87 if (sin.sin_addr.s_addr == INADDR_NONE) {
88 sin.sin_addr.s_addr = INADDR_ANY;
91 if (port_number == 0) {
92 lprintf(1, "Cannot start: no port number specified.\n");
95 sin.sin_port = htons((u_short) port_number);
97 s = socket(PF_INET, SOCK_STREAM, (getprotobyname("tcp")->p_proto));
99 lprintf(1, "Can't create a socket: %s\n", strerror(errno));
102 /** Set some socket options that make sense. */
104 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
106 if (bind(s, (struct sockaddr *) &sin, sizeof(sin)) < 0) {
107 lprintf(1, "Can't bind: %s\n", strerror(errno));
110 if (listen(s, queue_len) < 0) {
111 lprintf(1, "Can't listen: %s\n", strerror(errno));
120 * \brief Create a Unix domain socket and listen on it
121 * \param sockpath file name of the unix domain socket
122 * \param queue_len queue size of the kernel fifo????
124 int ig_uds_server(char *sockpath, int queue_len)
126 struct sockaddr_un addr;
129 int actual_queue_len;
131 actual_queue_len = queue_len;
132 if (actual_queue_len < 5) actual_queue_len = 5;
134 i = unlink(sockpath);
135 if (i != 0) if (errno != ENOENT) {
136 lprintf(1, "citserver: can't unlink %s: %s\n",
137 sockpath, strerror(errno));
141 memset(&addr, 0, sizeof(addr));
142 addr.sun_family = AF_UNIX;
143 safestrncpy(addr.sun_path, sockpath, sizeof addr.sun_path);
145 s = socket(AF_UNIX, SOCK_STREAM, 0);
147 lprintf(1, "citserver: Can't create a socket: %s\n",
152 if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
153 lprintf(1, "citserver: Can't bind: %s\n",
158 if (listen(s, actual_queue_len) < 0) {
159 lprintf(1, "citserver: Can't listen: %s\n",
164 chmod(sockpath, 0777);
172 * \brief Read data from the client socket.
173 * \param sock socket fd to read from ???
174 * \param buf buffer to read into
175 * \param bytes how large is the read buffer?
176 * \param timeout how long should we wait for input?
177 * \return values are\
178 * 1 Requested number of bytes has been read.\
179 * 0 Request timed out.\
180 * -1 Connection is broken, or other error.
182 int client_read_to(int sock, char *buf, int bytes, int timeout)
192 return (client_read_ssl(buf, bytes, timeout));
197 while (len < bytes) {
203 retval = select((sock) + 1, &rfds, NULL, NULL, &tv);
204 if (FD_ISSET(sock, &rfds) == 0) {
208 rlen = read(sock, &buf[len], bytes - len);
211 lprintf(2, "client_read() failed: %s\n",
219 write(2, "\033[32m", 5);
220 write(2, buf, bytes);
221 write(2, "\033[30m", 5);
227 * \brief write data to the client
228 * \param buf data to write to the client
229 * \param count size of buffer
231 ssize_t client_write(const void *buf, size_t count)
236 if (WC->burst != NULL) {
237 if ((WC->burst_len + count) >= WC->burst_alloc) {
238 newalloc = (WC->burst_alloc * 2);
239 if ((WC->burst_len + count) >= newalloc) {
242 newptr = realloc(WC->burst, newalloc);
243 if (newptr != NULL) {
245 WC->burst_alloc = newalloc;
248 if ((WC->burst_len + count) < WC->burst_alloc) {
249 memcpy(&WC->burst[WC->burst_len], buf, count);
250 WC->burst_len += count;
259 client_write_ssl((char *) buf, count);
264 write(2, "\033[34m", 5);
265 write(2, buf, count);
266 write(2, "\033[30m", 5);
268 return (write(WC->http_sock, buf, count));
272 * \brief what burst???
274 void begin_burst(void)
276 if (WC->burst != NULL) {
281 WC->burst_alloc = 32768;
282 WC->burst = malloc(WC->burst_alloc);
287 * \brief uses the same calling syntax as compress2(), but it
288 * creates a stream compatible with HTTP "Content-encoding: gzip"
291 #define DEF_MEM_LEVEL 8 /**< memlevel??? */
292 #define OS_CODE 0x03 /**< unix */
293 int ZEXPORT compress_gzip(Bytef * dest, /**< compressed buffer*/
294 uLongf * destLen, /**< length of the compresed data */
295 const Bytef * source, /**< source to encode */
296 uLong sourceLen, /**< length of the source to encode */
297 int level) /**< what level??? */
299 const int gz_magic[2] = { 0x1f, 0x8b }; /** gzip magic header */
301 /** write gzip header */
302 sprintf((char *) dest, "%c%c%c%c%c%c%c%c%c%c",
303 gz_magic[0], gz_magic[1], Z_DEFLATED,
304 0 /*flags */ , 0, 0, 0, 0 /*time */ , 0 /** xflags */ ,
310 stream.next_in = (Bytef *) source;
311 stream.avail_in = (uInt) sourceLen;
312 stream.next_out = dest + 10L; // after header
313 stream.avail_out = (uInt) * destLen;
314 if ((uLong) stream.avail_out != *destLen)
317 stream.zalloc = (alloc_func) 0;
318 stream.zfree = (free_func) 0;
319 stream.opaque = (voidpf) 0;
321 err = deflateInit2(&stream, level, Z_DEFLATED, -MAX_WBITS,
322 DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
326 err = deflate(&stream, Z_FINISH);
327 if (err != Z_STREAM_END) {
329 return err == Z_OK ? Z_BUF_ERROR : err;
331 *destLen = stream.total_out + 10L;
333 /* write CRC and Length */
334 uLong crc = crc32(0L, source, sourceLen);
336 for (n = 0; n < 4; ++n, ++*destLen) {
337 dest[*destLen] = (int) (crc & 0xff);
340 uLong len = stream.total_in;
341 for (n = 0; n < 4; ++n, ++*destLen) {
342 dest[*destLen] = (int) (len & 0xff);
345 err = deflateEnd(&stream);
351 * \brief what burst???
358 if (WC->burst == NULL)
361 the_len = WC->burst_len;
362 the_data = WC->burst;
369 /* Handle gzip compression */
371 char *compressed_data = NULL;
372 uLongf compressed_len;
374 compressed_len = (uLongf) ((the_len * 101) / 100) + 100;
375 compressed_data = malloc(compressed_len);
377 if (compress_gzip((Bytef *) compressed_data,
380 (uLongf) the_len, Z_BEST_SPEED) == Z_OK) {
381 wprintf("Content-encoding: gzip\r\n");
383 the_data = compressed_data;
384 the_len = compressed_len;
386 free(compressed_data);
389 #endif /* HAVE_ZLIB */
391 wprintf("Content-length: %d\r\n\r\n", the_len);
392 client_write(the_data, the_len);
400 * \brief Read data from the client socket with default timeout.
401 * (This is implemented in terms of client_read_to() and could be
402 * justifiably moved out of sysdep.c)
403 * \param sock the socket fd to read from???
404 * \param buf the buffer to write to
405 * \param bytes how large is the buffer
407 int client_read(int sock, char *buf, int bytes)
409 return (client_read_to(sock, buf, bytes, SLEEPING));
414 * \brief Get a LF-terminated line of text from the client.
415 * (This is implemented in terms of client_read() and could be
416 * justifiably moved out of sysdep.c)
417 * \param sock socket fd to get client line from???
418 * \param buf buffer to write read data to
419 * \param bufsiz how many bytes to read
420 * \return numer of bytes read???
422 int client_getln(int sock, char *buf, int bufsiz)
426 /** Read one character at a time.*/
428 retval = client_read(sock, &buf[i], 1);
429 if (retval != 1 || buf[i] == '\n' || i == (bufsiz-1))
431 if ( (!isspace(buf[i])) && (!isprint(buf[i])) ) {
432 /** Non printable character recieved from client */
437 /** If we got a long line, discard characters until the newline. */
439 while (buf[i] != '\n' && retval == 1)
440 retval = client_read(sock, &buf[i], 1);
443 * Strip any trailing non-printable characters.
446 while ((strlen(buf) > 0) && (!isprint(buf[strlen(buf) - 1]))) {
447 buf[strlen(buf) - 1] = 0;
453 * \brief shut us down the regular way.
454 * param signum the signal we want to forward
457 void graceful_shutdown(int signum) {
458 kill(current_child, signum);
464 * \brief Start running as a daemon.
466 * param do_close_stdio Only close stdio if set.
470 * Start running as a daemon.
472 void start_daemon(char *pid_file)
481 /* Close stdin/stdout/stderr and replace them with /dev/null.
482 * We don't just call close() because we don't want these fd's
483 * to be reused for other files.
487 signal(SIGHUP, SIG_IGN);
488 signal(SIGINT, SIG_IGN);
489 signal(SIGQUIT, SIG_IGN);
498 freopen("/dev/null", "r", stdin);
499 freopen("/dev/null", "w", stdout);
500 freopen("/dev/null", "w", stderr);
503 current_child = fork();
506 if (current_child < 0) {
511 else if (current_child == 0) {
512 signal(SIGTERM, graceful_shutdown);
513 return; /* continue starting citadel. */
517 signal(SIGTERM, SIG_IGN);
519 fp = fopen(pid_file, "w");
521 fprintf(fp, "%d\n", current_child);
525 waitpid(current_child, &status, 0);
530 /* Did the main process exit with an actual exit code? */
531 if (WIFEXITED(status)) {
533 /* Exit code 0 means the watcher should exit */
534 if (WEXITSTATUS(status) == 0) {
538 /* Exit code 101-109 means the watcher should exit */
539 else if ( (WEXITSTATUS(status) >= 101) && (WEXITSTATUS(status) <= 109) ) {
543 /* Any other exit code means we should restart. */
549 /* Any other type of termination (signals, etc.) should also restart. */
554 } while (do_restart);
559 exit(WEXITSTATUS(status));
563 * \brief Spawn an additional worker thread into the pool.
565 void spawn_another_worker_thread()
567 pthread_t SessThread; /**< Thread descriptor */
568 pthread_attr_t attr; /**< Thread attributes */
571 lprintf(3, "Creating a new thread\n");
573 /** set attributes for the new thread */
574 pthread_attr_init(&attr);
575 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
578 * Our per-thread stacks need to be bigger than the default size, otherwise
579 * the MIME parser crashes on FreeBSD, and the IMAP service crashes on
582 if ((ret = pthread_attr_setstacksize(&attr, 1024 * 1024))) {
583 lprintf(1, "pthread_attr_setstacksize: %s\n",
585 pthread_attr_destroy(&attr);
588 /** now create the thread */
589 if (pthread_create(&SessThread, &attr,
590 (void *(*)(void *)) worker_entry, NULL)
592 lprintf(1, "Can't create thread: %s\n", strerror(errno));
595 /** free up the attributes */
596 pthread_attr_destroy(&attr);
600 * \brief Here's where it all begins.
601 * \param argc number of commandline args
602 * \param argv the commandline arguments
604 int main(int argc, char **argv)
606 pthread_t SessThread; /**< Thread descriptor */
607 pthread_attr_t attr; /**< Thread attributes */
608 int a, i; /**< General-purpose variables */
609 char tracefile[PATH_MAX];
611 char dirbuffer[PATH_MAX]="";
614 int home_specified=0;
615 char relhome[PATH_MAX]="";
616 char webcitdir[PATH_MAX] = DATADIR;
617 char *pidfile = NULL;
623 #endif /* ENABLE_NLS */
624 char uds_listen_path[PATH_MAX]; /**< listen on a unix domain socket? */
626 strcpy(uds_listen_path, "");
628 /** Parse command line */
630 while ((a = getopt(argc, argv, "h:i:p:t:x:dD:cfs")) != EOF)
632 while ((a = getopt(argc, argv, "h:i:p:t:x:dD:cf")) != EOF)
636 hdir = strdup(optarg);
638 if (!relh) safestrncpy(webcitdir, hdir,
641 safestrncpy(relhome, relhome,
643 /* free(hdir); TODO: SHOULD WE DO THIS? */
648 running_as_daemon = 1;
651 pidfile = strdup(optarg);
652 running_as_daemon = 1;
655 safestrncpy(ip_addr, optarg, sizeof ip_addr);
658 http_port = atoi(optarg);
659 if (http_port == 0) {
660 safestrncpy(uds_listen_path, optarg, sizeof uds_listen_path);
664 safestrncpy(tracefile, optarg, sizeof tracefile);
665 freopen(tracefile, "w", stdout);
666 freopen(tracefile, "w", stderr);
667 freopen(tracefile, "r", stdin);
670 verbosity = atoi(optarg);
676 server_cookie = malloc(256);
677 if (server_cookie != NULL) {
678 safestrncpy(server_cookie,
679 "Set-cookie: wcserver=",
682 (&server_cookie[strlen(server_cookie)],
684 lprintf(2, "gethostname: %s\n",
694 fprintf(stderr, "usage: webserver "
695 "[-i ip_addr] [-p http_port] "
696 "[-t tracefile] [-c] [-f] "
701 "[remotehost [remoteport]]\n");
706 ctdlhost = argv[optind];
708 ctdlport = argv[optind];
711 /* daemonize, if we were asked to */
712 if (running_as_daemon) {
713 start_daemon(pidfile);
716 /** Tell 'em who's in da house */
717 lprintf(1, SERVER "\n");
718 lprintf(1, "Copyright (C) 1996-2007 by the Citadel development team.\n"
719 "This software is distributed under the terms of the "
720 "GNU General Public License.\n\n"
724 /** initialize the International Bright Young Thing */
726 initialize_locales();
727 locale = setlocale(LC_ALL, "");
728 mo = malloc(strlen(webcitdir) + 20);
729 lprintf(9, "Message catalog directory: %s\n", bindtextdomain("webcit", LOCALEDIR"/locale"));
731 lprintf(9, "Text domain: %s\n", textdomain("webcit"));
732 lprintf(9, "Text domain Charset: %s\n", bind_textdomain_codeset("webcit","UTF8"));
736 /* calculate all our path on a central place */
737 /* where to keep our config */
739 #define COMPUTE_DIRECTORY(SUBDIR) memcpy(dirbuffer,SUBDIR, sizeof dirbuffer);\
740 snprintf(SUBDIR,sizeof SUBDIR, "%s%s%s%s%s%s%s", \
741 (home&!relh)?webcitdir:basedir, \
742 ((basedir!=webcitdir)&(home&!relh))?basedir:"/", \
743 ((basedir!=webcitdir)&(home&!relh))?"/":"", \
745 (relhome[0]!='\0')?"/":"",\
747 (dirbuffer[0]!='\0')?"/":"");
749 COMPUTE_DIRECTORY(socket_dir);
751 COMPUTE_DIRECTORY(static_dir);
752 /** we should go somewhere we can leave our coredump, if enabled... */
753 lprintf(9, "Changing directory to %s\n", socket_dir);
754 if (chdir(webcitdir) != 0) {
757 initialize_viewdefs();
761 * Set up a place to put thread-specific data.
762 * We only need a single pointer per thread - it points to the
763 * wcsession struct to which the thread is currently bound.
765 if (pthread_key_create(&MyConKey, NULL) != 0) {
766 lprintf(1, "Can't create TSD key: %s\n", strerror(errno));
770 * Set up a place to put thread-specific SSL data.
771 * We don't stick this in the wcsession struct because SSL starts
772 * up before the session is bound, and it gets torn down between
776 if (pthread_key_create(&ThreadSSL, NULL) != 0) {
777 lprintf(1, "Can't create TSD key: %s\n", strerror(errno));
782 * Bind the server to our favorite port.
783 * There is no need to check for errors, because ig_tcp_server()
784 * exits if it doesn't succeed.
787 if (strlen(uds_listen_path) > 0) {
788 lprintf(2, "Attempting to create listener socket at %s...\n", uds_listen_path);
789 msock = ig_uds_server(uds_listen_path, LISTEN_QUEUE_LENGTH);
792 lprintf(2, "Attempting to bind to port %d...\n", http_port);
793 msock = ig_tcp_server(ip_addr, http_port, LISTEN_QUEUE_LENGTH);
796 lprintf(2, "Listening on socket %d\n", msock);
797 signal(SIGPIPE, SIG_IGN);
799 pthread_mutex_init(&SessionListMutex, NULL);
802 * Start up the housekeeping thread
804 pthread_attr_init(&attr);
805 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
806 pthread_create(&SessThread, &attr,
807 (void *(*)(void *)) housekeeping_loop, NULL);
811 * If this is an HTTPS server, fire up SSL
819 /** Start a few initial worker threads */
820 for (i = 0; i < (MIN_WORKER_THREADS); ++i) {
821 spawn_another_worker_thread();
824 /* now the original thread becomes another worker */
831 * Entry point for worker threads
833 void worker_entry(void)
838 int fail_this_transaction = 0;
841 /** Only one thread can accept at a time */
842 fail_this_transaction = 0;
843 ssock = accept(msock, NULL, 0);
845 lprintf(2, "accept() failed: %s\n",
848 /** Set the SO_REUSEADDR socket option */
850 setsockopt(ssock, SOL_SOCKET, SO_REUSEADDR,
853 /** If we are an HTTPS server, go crypto now. */
856 if (starttls(ssock) != 0) {
857 fail_this_transaction = 1;
863 if (fail_this_transaction == 0) {
865 /** Perform an HTTP transaction... */
868 /** Shut down SSL/TLS if required... */
875 /** ...and close the socket. */
876 lingering_close(ssock);
881 } while (!time_to_die);
887 * \brief logprintf. log messages
888 * logs to stderr if loglevel is lower than the verbosity set at startup
889 * \param loglevel level of the message
890 * \param format the printf like format string
891 * \param ... the strings to put into format
893 int lprintf(int loglevel, const char *format, ...)
897 if (loglevel <= verbosity) {
898 va_start(ap, format);
899 vfprintf(stderr, format, ap);
908 * \brief print the actual stack frame.
910 void wc_backtrace(void)
912 #ifdef HAVE_BACKTRACE
913 void *stack_frames[50];
918 size = backtrace(stack_frames, sizeof(stack_frames) / sizeof(void*));
919 strings = backtrace_symbols(stack_frames, size);
920 for (i = 0; i < size; i++) {
922 lprintf(1, "%s\n", strings[i]);
924 lprintf(1, "%p\n", stack_frames[i]);