4 * This contains a simple multithreaded TCP server manager. It sits around
5 * waiting on the specified port for incoming HTTP connections. When a
6 * connection is established, it calls context_loop() from context_loop.c.
8 * Copyright (c) 1996-2008 by the citadel.org developers.
9 * This program is released under the terms of the GNU General Public License v3.
14 #include "webserver.h"
19 #include "modules_init.h"
21 int vsnprintf(char *buf, size_t max, const char *fmt, va_list argp);
24 int verbosity = 9; /* Logging level */
25 int msock; /* master listening socket */
26 int is_https = 0; /* Nonzero if I am an HTTPS service */
27 int follow_xff = 0; /* Follow X-Forwarded-For: header */
28 int home_specified = 0; /* did the user specify a homedir? */
29 int time_to_die = 0; /* Nonzero if server is shutting down */
31 extern void *context_loop(int*);
32 extern void *housekeeping_loop(void);
33 extern pthread_mutex_t SessionListMutex;
34 extern pthread_key_t MyConKey;
37 char ctdl_key_dir[PATH_MAX]=SSL_DIR;
38 char file_crpt_file_key[PATH_MAX]="";
39 char file_crpt_file_csr[PATH_MAX]="";
40 char file_crpt_file_cer[PATH_MAX]="";
42 char socket_dir[PATH_MAX]; /* where to talk to our citadel server */
43 static const char editor_absolut_dir[PATH_MAX]=EDITORDIR; /* nailed to what configure gives us. */
44 static char static_dir[PATH_MAX]; /* calculated on startup */
45 static char static_local_dir[PATH_MAX]; /* calculated on startup */
46 static char static_icon_dir[PATH_MAX]; /* where should we find our mime icons? */
47 char *static_dirs[]={ /* needs same sort order as the web mapping */
48 (char*)static_dir, /* our templates on disk */
49 (char*)static_local_dir, /* user provided templates disk */
50 (char*)editor_absolut_dir, /* the editor on disk */
51 (char*)static_icon_dir /* our icons... */
55 * Subdirectories from which the client may request static content
57 * (If you add more, remember to increment 'ndirs' below)
59 char *static_content_dirs[] = {
60 "static", /* static templates */
61 "static.local", /* site local static templates */
62 "tiny_mce" /* rich text editor */
68 char *server_cookie = NULL; /* our Cookie connection to the client */
69 int http_port = PORT_NUM; /* Port to listen on */
70 char *ctdlhost = DEFAULT_HOST; /* our name */
71 char *ctdlport = DEFAULT_PORT; /* our Port */
72 int setup_wizard = 0; /* should we run the setup wizard? \todo */
73 char wizard_filename[PATH_MAX]; /* where's the setup wizard? */
74 int running_as_daemon = 0; /* should we deamonize on startup? */
78 * This is a generic function to set up a master socket for listening on
79 * a TCP port. The server shuts down if the bind fails.
81 * ip_addr IP address to bind
82 * port_number port number to bind
83 * queue_len number of incoming connections to allow in the queue
85 int ig_tcp_server(char *ip_addr, int port_number, int queue_len)
87 struct sockaddr_in sin;
90 memset(&sin, 0, sizeof(sin));
91 sin.sin_family = AF_INET;
92 if (ip_addr == NULL) {
93 sin.sin_addr.s_addr = INADDR_ANY;
95 sin.sin_addr.s_addr = inet_addr(ip_addr);
98 if (sin.sin_addr.s_addr == INADDR_NONE) {
99 sin.sin_addr.s_addr = INADDR_ANY;
102 if (port_number == 0) {
103 lprintf(1, "Cannot start: no port number specified.\n");
106 sin.sin_port = htons((u_short) port_number);
108 s = socket(PF_INET, SOCK_STREAM, (getprotobyname("tcp")->p_proto));
110 lprintf(1, "Can't create a socket: %s\n", strerror(errno));
113 /* Set some socket options that make sense. */
115 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
118 fcntl(s, F_SETFL, O_NONBLOCK); /* maide: this statement is incorrect
119 there should be a preceding F_GETFL
120 and a bitwise OR with the previous
124 if (bind(s, (struct sockaddr *) &sin, sizeof(sin)) < 0) {
125 lprintf(1, "Can't bind: %s\n", strerror(errno));
128 if (listen(s, queue_len) < 0) {
129 lprintf(1, "Can't listen: %s\n", strerror(errno));
138 * Create a Unix domain socket and listen on it
139 * sockpath - file name of the unix domain socket
140 * queue_len - Number of incoming connections to allow in the queue
142 int ig_uds_server(char *sockpath, int queue_len)
144 struct sockaddr_un addr;
147 int actual_queue_len;
149 actual_queue_len = queue_len;
150 if (actual_queue_len < 5) actual_queue_len = 5;
152 i = unlink(sockpath);
153 if ((i != 0) && (errno != ENOENT)) {
154 lprintf(1, "webcit: can't unlink %s: %s\n",
155 sockpath, strerror(errno));
159 memset(&addr, 0, sizeof(addr));
160 addr.sun_family = AF_UNIX;
161 safestrncpy(addr.sun_path, sockpath, sizeof addr.sun_path);
163 s = socket(AF_UNIX, SOCK_STREAM, 0);
165 lprintf(1, "webcit: Can't create a socket: %s\n",
170 if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
171 lprintf(1, "webcit: Can't bind: %s\n",
176 if (listen(s, actual_queue_len) < 0) {
177 lprintf(1, "webcit: Can't listen: %s\n",
182 chmod(sockpath, 0777);
190 * Read data from the client socket.
192 * sock socket fd to read from
193 * buf buffer to read into
194 * bytes number of bytes to read
195 * timeout Number of seconds to wait before timing out
197 * Possible return values:
198 * 1 Requested number of bytes has been read.
199 * 0 Request timed out.
200 * -1 Connection is broken, or other error.
202 int client_read_to(int *sock, StrBuf *Target, StrBuf *Buf, int bytes, int timeout)
209 while ((StrLength(Buf) + StrLength(Target) < bytes) &&
211 retval = client_read_sslbuffer(Buf, timeout);
213 StrBufAppendBuf(Target, Buf, 0); /// todo: Buf > bytes?
215 write(2, "\033[32m", 5);
216 write(2, buf, bytes);
217 write(2, "\033[30m", 5);
222 lprintf(2, "client_read_ssl() failed\n");
228 if (StrLength(Buf) > 0) {//// todo: what if Buf > bytes?
229 StrBufAppendBuf(Target, Buf, 0);
231 retval = StrBufReadBLOB(Target,
233 (StrLength(Target) > 0),
234 bytes - StrLength(Target),
237 lprintf(2, "client_read() failed: %s\n",
243 write(2, "\033[32m", 5);
244 write(2, buf, bytes);
245 write(2, "\033[30m", 5);
252 * Begin buffering HTTP output so we can transmit it all in one write operation later.
254 void begin_burst(void)
256 if (WC->WBuf == NULL)
257 WC->WBuf = NewStrBufPlain(NULL, 32768);
262 * Finish buffering HTTP output. [Compress using zlib and] output with a Content-Length: header.
267 const char *ptr, *eptr;
274 /* Perform gzip compression, if enabled and supported by client */
275 if (!DisableGzip && (WCC->gzip_ok) && CompressBuffer(WCC->WBuf))
277 hprintf("Content-encoding: gzip\r\n");
279 #endif /* HAVE_ZLIB */
281 hprintf("Content-length: %d\r\n\r\n", StrLength(WCC->WBuf));
283 ptr = ChrPtr(WCC->HBuf);
284 count = StrLength(WCC->HBuf);
289 client_write_ssl(WCC->HBuf);
290 client_write_ssl(WCC->WBuf);
298 write(2, "\033[34m", 5);
299 write(2, ptr, StrLength(WCC->WBuf));
300 write(2, "\033[30m", 5);
302 fdflags = fcntl(WC->http_sock, F_GETFL);
305 if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
307 FD_SET(WCC->http_sock, &wset);
308 if (select(WCC->http_sock + 1, NULL, &wset, NULL, NULL) == -1) {
309 lprintf(2, "client_write: Socket select failed (%s)\n", strerror(errno));
314 if ((res = write(WCC->http_sock,
317 lprintf(2, "client_write: Socket write failed (%s)\n", strerror(errno));
325 ptr = ChrPtr(WCC->WBuf);
326 count = StrLength(WCC->WBuf);
331 write(2, "\033[34m", 5);
332 write(2, ptr, StrLength(WCC->WBuf));
333 write(2, "\033[30m", 5);
337 if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
339 FD_SET(WCC->http_sock, &wset);
340 if (select(WCC->http_sock + 1, NULL, &wset, NULL, NULL) == -1) {
341 lprintf(2, "client_write: Socket select failed (%s)\n", strerror(errno));
346 if ((res = write(WCC->http_sock,
349 lprintf(2, "client_write: Socket write failed (%s)\n", strerror(errno));
357 return StrLength(WCC->WBuf);
363 * Read data from the client socket with default timeout.
364 * (This is implemented in terms of client_read_to() and could be
365 * justifiably moved out of sysdep.c)
367 * sock the socket fd to read from
368 * buf the buffer to write to
369 * bytes Number of bytes to read
371 int client_read(int *sock, StrBuf *Target, StrBuf *buf, int bytes)
373 return (client_read_to(sock, Target, buf, bytes, SLEEPING));
378 * Get a LF-terminated line of text from the client.
379 * (This is implemented in terms of client_read() and could be
380 * justifiably moved out of sysdep.c)
382 * sock socket fd to get client line from
383 * buf buffer to write read data to
384 * bufsiz how many bytes to read
386 * returns the number of bytes read
388 /////int client_getln(int *sock, char *buf, int bufsiz)
392 ///// /* Read one character at a time.*/
393 ///// for (i = 0; *sock > 0; i++) {
394 ///// retval = client_read(sock, &buf[i], 1);
395 ///// if (retval < 0)
397 ///// if (retval != 1 || buf[i] == '\n' || i == (bufsiz-1))
399 ///// if ( (!isspace(buf[i])) && (!isprint(buf[i])) ) {
400 ///// /* Non printable character recieved from client */
405 ///// /* If we got a long line, discard characters until the newline. */
406 ///// if (i == (bufsiz-1))
407 ///// while (buf[i] != '\n' && retval == 1)
408 ///// retval = client_read(sock, &buf[i], 1);
411 ///// * Strip any trailing non-printable characters.
414 ///// while ((i > 0) && (!isprint(buf[i - 1]))) {
417 ///// return (retval);
421 * Shut us down the regular way.
422 * signum is the signal we want to forward
425 void graceful_shutdown_watcher(int signum) {
426 lprintf (1, "bye; shutting down watcher.");
427 kill(current_child, signum);
428 if (signum != SIGHUP)
433 int ClientGetLine(int *sock, StrBuf *Target, StrBuf *CLineBuf)
435 const char *Error, *pch, *pchs;
436 int rlen, len, retval = 0;
440 if (StrLength(CLineBuf) > 0) {
441 pchs = ChrPtr(CLineBuf);
442 pch = strchr(pchs, '\n');
446 if (len > 0 && (*(pch - 1) == '\r') )
448 StrBufSub(Target, CLineBuf, 0, len - rlen);
449 StrBufCutLeft(CLineBuf, len + 1);
454 while (retval == 0) {
456 pchs = ChrPtr(CLineBuf);
458 pch = strchr(pchs, '\n');
460 retval = client_read_sslbuffer(CLineBuf, SLEEPING);
461 pchs = ChrPtr(CLineBuf);
462 pch = strchr(pchs, '\n');
471 if ((retval > 0) && (pch != NULL)) {
474 if (len > 0 && (*(pch - 1) == '\r') )
476 StrBufSub(Target, CLineBuf, 0, len - rlen);
477 StrBufCutLeft(CLineBuf, len + 1);
485 return StrBufTCP_read_buffered_line(Target,
496 * Shut us down the regular way.
497 * signum is the signal we want to forward
500 void graceful_shutdown(int signum) {
501 // kill(current_child, signum);
506 lprintf (1, "bye going down gracefull.[%d][%s]\n", signum, wd);
518 * Start running as a daemon.
520 void start_daemon(char *pid_file)
529 /* Close stdin/stdout/stderr and replace them with /dev/null.
530 * We don't just call close() because we don't want these fd's
531 * to be reused for other files.
535 signal(SIGHUP, SIG_IGN);
536 signal(SIGINT, SIG_IGN);
537 signal(SIGQUIT, SIG_IGN);
546 freopen("/dev/null", "r", stdin);
547 freopen("/dev/null", "w", stdout);
548 freopen("/dev/null", "w", stderr);
549 signal(SIGTERM, graceful_shutdown_watcher);
550 signal(SIGHUP, graceful_shutdown_watcher);
553 current_child = fork();
556 if (current_child < 0) {
558 ShutDownLibCitadel ();
562 else if (current_child == 0) { // child process
563 // signal(SIGTERM, graceful_shutdown);
564 signal(SIGHUP, graceful_shutdown);
566 return; /* continue starting webcit. */
569 else { // watcher process
570 // signal(SIGTERM, SIG_IGN);
571 // signal(SIGHUP, SIG_IGN);
573 fp = fopen(pid_file, "w");
575 fprintf(fp, "%d\n", getpid());
579 waitpid(current_child, &status, 0);
584 /* Did the main process exit with an actual exit code? */
585 if (WIFEXITED(status)) {
587 /* Exit code 0 means the watcher should exit */
588 if (WEXITSTATUS(status) == 0) {
592 /* Exit code 101-109 means the watcher should exit */
593 else if ( (WEXITSTATUS(status) >= 101) && (WEXITSTATUS(status) <= 109) ) {
597 /* Any other exit code means we should restart. */
603 /* Any other type of termination (signals, etc.) should also restart. */
608 } while (do_restart);
613 ShutDownLibCitadel ();
614 exit(WEXITSTATUS(status));
618 * Spawn an additional worker thread into the pool.
620 void spawn_another_worker_thread()
622 pthread_t SessThread; /* Thread descriptor */
623 pthread_attr_t attr; /* Thread attributes */
626 lprintf(3, "Creating a new thread\n");
628 /* set attributes for the new thread */
629 pthread_attr_init(&attr);
630 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
633 * Our per-thread stacks need to be bigger than the default size, otherwise
634 * the MIME parser crashes on FreeBSD, and the IMAP service crashes on
637 if ((ret = pthread_attr_setstacksize(&attr, 1024 * 1024))) {
638 lprintf(1, "pthread_attr_setstacksize: %s\n",
640 pthread_attr_destroy(&attr);
643 /* now create the thread */
644 if (pthread_create(&SessThread, &attr,
645 (void *(*)(void *)) worker_entry, NULL)
647 lprintf(1, "Can't create thread: %s\n", strerror(errno));
650 /* free up the attributes */
651 pthread_attr_destroy(&attr);
654 //#define DBG_PRINNT_HOOKS_AT_START
655 #ifdef DBG_PRINNT_HOOKS_AT_START
656 const char foobuf[32];
657 const char *nix(void *vptr) {snprintf(foobuf, 32, "%0x", (long) vptr); return foobuf;}
659 void InitTemplateCache(void);
660 extern int LoadTemplates;
661 extern void LoadZoneFiles(void);
662 StrBuf *csslocal = NULL;
664 * Here's where it all begins.
666 int main(int argc, char **argv)
668 pthread_t SessThread; /* Thread descriptor */
669 pthread_attr_t attr; /* Thread attributes */
670 int a, i; /* General-purpose variables */
671 char tracefile[PATH_MAX];
672 char ip_addr[256]="0.0.0.0";
673 char dirbuffer[PATH_MAX]="";
676 int home_specified=0;
677 char relhome[PATH_MAX]="";
678 char webcitdir[PATH_MAX] = DATADIR;
679 char *pidfile = NULL;
685 #endif /* ENABLE_NLS */
686 char uds_listen_path[PATH_MAX]; /* listen on a unix domain socket? */
688 HandlerHash = NewHash(1, NULL);
689 PreferenceHooks = NewHash(1, NULL);
690 WirelessTemplateCache = NewHash(1, NULL);
691 WirelessLocalTemplateCache = NewHash(1, NULL);
692 LocalTemplateCache = NewHash(1, NULL);
693 TemplateCache = NewHash(1, NULL);
694 GlobalNS = NewHash(1, NULL);
695 Iterators = NewHash(1, NULL);
696 Conditionals = NewHash(1, NULL);
697 MsgHeaderHandler = NewHash(1, NULL);
698 MimeRenderHandler = NewHash(1, NULL);
699 SortHash = NewHash(1, NULL);
702 StrBuf *foo=NewStrBufPlain("", -1);
703 StrBuf *bar = NewStrBufPlain("A", -1);
705 StrBufExtract_token(bar, foo, 0, '|');
706 StrBufExtract_token(bar, foo, 1, '|');
707 StrBufExtract_token(bar, foo, 2, '|');
708 StrBufExtract_token(bar, foo, 3, '|');
709 StrBufExtract_token(bar, foo, 4, '|');
710 StrBufExtract_token(bar, foo, 5, '|');
711 StrBufExtract_token(bar, foo, 6, '|');
713 #ifdef DBG_PRINNT_HOOKS_AT_START
714 dbg_PrintHash(HandlerHash, nix, NULL);
717 /* Ensure that we are linked to the correct version of libcitadel */
718 if (libcitadel_version_number() < LIBCITADEL_VERSION_NUMBER) {
719 fprintf(stderr, " You are running libcitadel version %d.%02d\n",
720 (libcitadel_version_number() / 100), (libcitadel_version_number() % 100));
721 fprintf(stderr, "WebCit was compiled against version %d.%02d\n",
722 (LIBCITADEL_VERSION_NUMBER / 100), (LIBCITADEL_VERSION_NUMBER % 100));
726 strcpy(uds_listen_path, "");
728 /* Parse command line */
730 while ((a = getopt(argc, argv, "h:i:p:t:T:x:dD:cfsZ")) != EOF)
732 while ((a = getopt(argc, argv, "h:i:p:t:T:x:dD:cfZ")) != EOF)
736 hdir = strdup(optarg);
738 if (!relh) safestrncpy(webcitdir, hdir,
741 safestrncpy(relhome, relhome,
743 /* free(hdir); TODO: SHOULD WE DO THIS? */
748 running_as_daemon = 1;
751 pidfile = strdup(optarg);
752 running_as_daemon = 1;
755 safestrncpy(ip_addr, optarg, sizeof ip_addr);
758 http_port = atoi(optarg);
759 if (http_port == 0) {
760 safestrncpy(uds_listen_path, optarg, sizeof uds_listen_path);
764 safestrncpy(tracefile, optarg, sizeof tracefile);
765 freopen(tracefile, "w", stdout);
766 freopen(tracefile, "w", stderr);
767 freopen(tracefile, "r", stdin);
770 LoadTemplates = atoi(optarg);
776 verbosity = atoi(optarg);
782 server_cookie = malloc(256);
783 if (server_cookie != NULL) {
784 safestrncpy(server_cookie,
785 "Set-cookie: wcserver=",
788 (&server_cookie[strlen(server_cookie)],
790 lprintf(2, "gethostname: %s\n",
800 fprintf(stderr, "usage: webcit "
801 "[-i ip_addr] [-p http_port] "
802 "[-t tracefile] [-c] [-f] "
803 "[-T Templatedebuglevel] "
808 "[remotehost [remoteport]]\n");
813 ctdlhost = argv[optind];
815 ctdlport = argv[optind];
818 /* daemonize, if we were asked to */
819 if (running_as_daemon) {
820 start_daemon(pidfile);
823 /// signal(SIGTERM, graceful_shutdown);
824 signal(SIGHUP, graceful_shutdown);
827 /* Tell 'em who's in da house */
828 lprintf(1, PACKAGE_STRING "\n");
829 lprintf(1, "Copyright (C) 1996-2008 by the Citadel development team.\n"
830 "This software is distributed under the terms of the "
831 "GNU General Public License.\n\n"
835 /* initialize the International Bright Young Thing */
837 initialize_locales();
839 locale = setlocale(LC_ALL, "");
841 mo = malloc(strlen(webcitdir) + 20);
842 lprintf(9, "Message catalog directory: %s\n", bindtextdomain("webcit", LOCALEDIR"/locale"));
844 lprintf(9, "Text domain: %s\n", textdomain("webcit"));
845 lprintf(9, "Text domain Charset: %s\n", bind_textdomain_codeset("webcit","UTF8"));
850 /* calculate all our path on a central place */
851 /* where to keep our config */
853 #define COMPUTE_DIRECTORY(SUBDIR) memcpy(dirbuffer,SUBDIR, sizeof dirbuffer);\
854 snprintf(SUBDIR,sizeof SUBDIR, "%s%s%s%s%s%s%s", \
855 (home&!relh)?webcitdir:basedir, \
856 ((basedir!=webcitdir)&(home&!relh))?basedir:"/", \
857 ((basedir!=webcitdir)&(home&!relh))?"/":"", \
859 (relhome[0]!='\0')?"/":"",\
861 (dirbuffer[0]!='\0')?"/":"");
863 COMPUTE_DIRECTORY(socket_dir);
864 basedir=WWWDIR "/static";
865 COMPUTE_DIRECTORY(static_dir);
866 basedir=WWWDIR "/static/icons";
867 COMPUTE_DIRECTORY(static_icon_dir);
868 basedir=WWWDIR "/static.local";
869 COMPUTE_DIRECTORY(static_local_dir);
871 snprintf(file_crpt_file_key,
872 sizeof file_crpt_file_key,
875 snprintf(file_crpt_file_csr,
876 sizeof file_crpt_file_csr,
879 snprintf(file_crpt_file_cer,
880 sizeof file_crpt_file_cer,
884 /* we should go somewhere we can leave our coredump, if enabled... */
885 lprintf(9, "Changing directory to %s\n", socket_dir);
886 if (chdir(webcitdir) != 0) {
889 LoadIconDir(static_icon_dir);
891 initialise_modules();
892 initialize_viewdefs();
897 if (!access("static.local/webcit.css", R_OK)) {
898 csslocal = NewStrBufPlain(HKEY("<link href=\"static.local/webcit.css\" rel=\"stylesheet\" type=\"text/css\">"));
901 /* Tell libical to return an error instead of aborting if it sees badly formed iCalendar data. */
902 icalerror_errors_are_fatal = 0;
904 /* Use our own prefix on tzid's generated from system tzdata */
905 icaltimezone_set_tzid_prefix("/citadel.org/");
908 * Set up a place to put thread-specific data.
909 * We only need a single pointer per thread - it points to the
910 * wcsession struct to which the thread is currently bound.
912 if (pthread_key_create(&MyConKey, NULL) != 0) {
913 lprintf(1, "Can't create TSD key: %s\n", strerror(errno));
915 InitialiseSemaphores ();
918 * Set up a place to put thread-specific SSL data.
919 * We don't stick this in the wcsession struct because SSL starts
920 * up before the session is bound, and it gets torn down between
924 if (pthread_key_create(&ThreadSSL, NULL) != 0) {
925 lprintf(1, "Can't create TSD key: %s\n", strerror(errno));
930 * Bind the server to our favorite port.
931 * There is no need to check for errors, because ig_tcp_server()
932 * exits if it doesn't succeed.
935 if (!IsEmptyStr(uds_listen_path)) {
936 lprintf(2, "Attempting to create listener socket at %s...\n", uds_listen_path);
937 msock = ig_uds_server(uds_listen_path, LISTEN_QUEUE_LENGTH);
940 lprintf(2, "Attempting to bind to port %d...\n", http_port);
941 msock = ig_tcp_server(ip_addr, http_port, LISTEN_QUEUE_LENGTH);
944 lprintf(2, "Listening on socket %d\n", msock);
945 signal(SIGPIPE, SIG_IGN);
947 pthread_mutex_init(&SessionListMutex, NULL);
950 * Start up the housekeeping thread
952 pthread_attr_init(&attr);
953 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
954 pthread_create(&SessThread, &attr,
955 (void *(*)(void *)) housekeeping_loop, NULL);
959 * If this is an HTTPS server, fire up SSL
967 /* Start a few initial worker threads */
968 for (i = 0; i < (MIN_WORKER_THREADS); ++i) {
969 spawn_another_worker_thread();
972 /* now the original thread becomes another worker */
974 ShutDownLibCitadel ();
975 DeleteHash(&HandlerHash);
976 DeleteHash(&PreferenceHooks);
981 void ShutDownWebcit(void)
983 DeleteHash(&ZoneHash);
984 free_zone_directory ();
985 icaltimezone_release_zone_tab ();
986 icalmemory_free_ring ();
987 ShutDownLibCitadel ();
988 DeleteHash(&HandlerHash);
989 DeleteHash(&PreferenceHooks);
990 DeleteHash(&GlobalNS);
991 DeleteHash(&WirelessTemplateCache);
992 DeleteHash(&WirelessLocalTemplateCache);
993 DeleteHash(&TemplateCache);
994 DeleteHash(&LocalTemplateCache);
995 DeleteHash(&Iterators);
996 DeleteHash(&MimeRenderHandler);
997 DeleteHash(&Conditionals);
998 DeleteHash(&MsgHeaderHandler);
999 DeleteHash(&SortHash);
1011 * Entry point for worker threads
1013 void worker_entry(void)
1017 int fail_this_transaction = 0;
1020 fd_set readset, tempset;
1025 FD_SET(msock, &readset);
1028 /* Only one thread can accept at a time */
1029 fail_this_transaction = 0;
1033 ret = -1; /* just one at once should select... */
1034 begin_critical_section(S_SELECT);
1037 if (msock > 0) FD_SET(msock, &tempset);
1040 if (msock > 0) ret = select(msock+1, &tempset, NULL, NULL, &tv);
1041 end_critical_section(S_SELECT);
1042 if ((ret < 0) && (errno != EINTR) && (errno != EAGAIN))
1043 {// EINTR and EAGAIN are thrown but not of interest.
1044 lprintf(2, "accept() failed:%d %s\n",
1045 errno, strerror(errno));
1047 else if ((ret > 0) && (msock > 0) && FD_ISSET(msock, &tempset))
1048 {// Successfully selected, and still not shutting down? Accept!
1049 ssock = accept(msock, NULL, 0);
1052 } while ((msock > 0) && (ssock < 0) && (time_to_die == 0));
1054 if ((msock == -1)||(time_to_die))
1055 {// ok, we're going down.
1058 /* the first to come here will have to do the cleanup.
1059 * make shure its realy just one.
1061 begin_critical_section(S_SHUTDOWN);
1067 end_critical_section(S_SHUTDOWN);
1069 {// we're the one to cleanup the mess.
1070 lprintf(2, "I'm master shutdown: tagging sessions to be killed.\n");
1071 shutdown_sessions();
1072 lprintf(2, "master shutdown: waiting for others\n");
1073 sleeeeeeeeeep(1); // wait so some others might finish...
1074 lprintf(2, "master shutdown: cleaning up sessions\n");
1076 lprintf(2, "master shutdown: cleaning up libical\n");
1080 lprintf(2, "master shutdown exiting!.\n");
1085 if (ssock < 0 ) continue;
1088 if (ssock > 0) close (ssock);
1089 lprintf(2, "inbetween.");
1091 } else { // Got it? do some real work!
1092 /* Set the SO_REUSEADDR socket option */
1094 setsockopt(ssock, SOL_SOCKET, SO_REUSEADDR,
1097 /* If we are an HTTPS server, go crypto now. */
1100 if (starttls(ssock) != 0) {
1101 fail_this_transaction = 1;
1107 if (fail_this_transaction == 0) {
1109 /* Perform an HTTP transaction... */
1110 context_loop(&ssock);
1112 /* Shut down SSL/TLS if required... */
1119 /* ...and close the socket. */
1121 lingering_close(ssock);
1126 } while (!time_to_die);
1128 lprintf (1, "bye\n");
1133 * print log messages
1134 * logs to stderr if loglevel is lower than the verbosity set at startup
1136 * loglevel level of the message
1137 * format the printf like format string
1138 * ... the strings to put into format
1140 int lprintf(int loglevel, const char *format, ...)
1144 if (loglevel <= verbosity) {
1145 va_start(ap, format);
1146 vfprintf(stderr, format, ap);
1155 * print the actual stack frame.
1157 void wc_backtrace(void)
1159 #ifdef HAVE_BACKTRACE
1160 void *stack_frames[50];
1165 size = backtrace(stack_frames, sizeof(stack_frames) / sizeof(void*));
1166 strings = backtrace_symbols(stack_frames, size);
1167 for (i = 0; i < size; i++) {
1168 if (strings != NULL)
1169 lprintf(1, "%s\n", strings[i]);
1171 lprintf(1, "%p\n", stack_frames[i]);