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-2009 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);
263 * Finish buffering HTTP output. [Compress using zlib and] output with a Content-Length: header.
268 const char *ptr, *eptr;
275 /* Perform gzip compression, if enabled and supported by client */
276 if (!DisableGzip && (WCC->gzip_ok) && CompressBuffer(WCC->WBuf))
278 hprintf("Content-encoding: gzip\r\n");
280 //#endif /* HAVE_ZLIB */
282 hprintf("Content-length: %d\r\n\r\n", StrLength(WCC->WBuf));
284 ptr = ChrPtr(WCC->HBuf);
285 count = StrLength(WCC->HBuf);
290 client_write_ssl(WCC->HBuf);
291 client_write_ssl(WCC->WBuf);
299 write(2, "\033[34m", 5);
300 write(2, ptr, StrLength(WCC->WBuf));
301 write(2, "\033[30m", 5);
303 fdflags = fcntl(WC->http_sock, F_GETFL);
306 if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
308 FD_SET(WCC->http_sock, &wset);
309 if (select(WCC->http_sock + 1, NULL, &wset, NULL, NULL) == -1) {
310 lprintf(2, "client_write: Socket select failed (%s)\n", strerror(errno));
315 if ((res = write(WCC->http_sock,
318 lprintf(2, "client_write: Socket write failed (%s)\n", strerror(errno));
326 ptr = ChrPtr(WCC->WBuf);
327 count = StrLength(WCC->WBuf);
332 write(2, "\033[34m", 5);
333 write(2, ptr, StrLength(WCC->WBuf));
334 write(2, "\033[30m", 5);
338 if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
340 FD_SET(WCC->http_sock, &wset);
341 if (select(WCC->http_sock + 1, NULL, &wset, NULL, NULL) == -1) {
342 lprintf(2, "client_write: Socket select failed (%s)\n", strerror(errno));
347 if ((res = write(WCC->http_sock,
350 lprintf(2, "client_write: Socket write failed (%s)\n", strerror(errno));
358 return StrLength(WCC->WBuf);
364 * Read data from the client socket with default timeout.
365 * (This is implemented in terms of client_read_to() and could be
366 * justifiably moved out of sysdep.c)
368 * sock the socket fd to read from
369 * buf the buffer to write to
370 * bytes Number of bytes to read
372 int client_read(int *sock, StrBuf *Target, StrBuf *buf, int bytes)
374 return (client_read_to(sock, Target, buf, bytes, SLEEPING));
380 * Shut us down the regular way.
381 * signum is the signal we want to forward
384 void graceful_shutdown_watcher(int signum) {
385 lprintf (1, "bye; shutting down watcher.");
386 kill(current_child, signum);
387 if (signum != SIGHUP)
392 int ClientGetLine(int *sock, StrBuf *Target, StrBuf *CLineBuf, const char **Pos)
394 const char *Error, *pch, *pchs;
395 int rlen, len, retval = 0;
399 if (StrLength(CLineBuf) > 0) {
400 pchs = ChrPtr(CLineBuf);
401 pch = strchr(pchs, '\n');
405 if (len > 0 && (*(pch - 1) == '\r') )
407 StrBufSub(Target, CLineBuf, 0, len - rlen);
408 StrBufCutLeft(CLineBuf, len + 1);
413 while (retval == 0) {
415 pchs = ChrPtr(CLineBuf);
417 pch = strchr(pchs, '\n');
419 retval = client_read_sslbuffer(CLineBuf, SLEEPING);
420 pchs = ChrPtr(CLineBuf);
421 pch = strchr(pchs, '\n');
430 if ((retval > 0) && (pch != NULL)) {
433 if (len > 0 && (*(pch - 1) == '\r') )
435 StrBufSub(Target, CLineBuf, 0, len - rlen);
436 StrBufCutLeft(CLineBuf, len + 1);
444 return StrBufTCP_read_buffered_line_fast(Target,
456 * Shut us down the regular way.
457 * signum is the signal we want to forward
460 void graceful_shutdown(int signum) {
465 lprintf (1, "bye going down gracefull.[%d][%s]\n", signum, wd);
477 * Start running as a daemon.
479 void start_daemon(char *pid_file)
488 /* Close stdin/stdout/stderr and replace them with /dev/null.
489 * We don't just call close() because we don't want these fd's
490 * to be reused for other files.
494 signal(SIGHUP, SIG_IGN);
495 signal(SIGINT, SIG_IGN);
496 signal(SIGQUIT, SIG_IGN);
505 freopen("/dev/null", "r", stdin);
506 freopen("/dev/null", "w", stdout);
507 freopen("/dev/null", "w", stderr);
508 signal(SIGTERM, graceful_shutdown_watcher);
509 signal(SIGHUP, graceful_shutdown_watcher);
512 current_child = fork();
515 if (current_child < 0) {
517 ShutDownLibCitadel ();
521 else if (current_child == 0) { /* child process */
522 signal(SIGHUP, graceful_shutdown);
524 return; /* continue starting webcit. */
526 else { /* watcher process */
528 fp = fopen(pid_file, "w");
530 fprintf(fp, "%d\n", getpid());
534 waitpid(current_child, &status, 0);
539 /* Did the main process exit with an actual exit code? */
540 if (WIFEXITED(status)) {
542 /* Exit code 0 means the watcher should exit */
543 if (WEXITSTATUS(status) == 0) {
547 /* Exit code 101-109 means the watcher should exit */
548 else if ( (WEXITSTATUS(status) >= 101) && (WEXITSTATUS(status) <= 109) ) {
552 /* Any other exit code means we should restart. */
558 /* Any other type of termination (signals, etc.) should also restart. */
563 } while (do_restart);
568 ShutDownLibCitadel ();
569 exit(WEXITSTATUS(status));
573 * Spawn an additional worker thread into the pool.
575 void spawn_another_worker_thread()
577 pthread_t SessThread; /* Thread descriptor */
578 pthread_attr_t attr; /* Thread attributes */
581 lprintf(3, "Creating a new thread\n");
583 /* set attributes for the new thread */
584 pthread_attr_init(&attr);
585 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
588 * Our per-thread stacks need to be bigger than the default size, otherwise
589 * the MIME parser crashes on FreeBSD, and the IMAP service crashes on
592 if ((ret = pthread_attr_setstacksize(&attr, 1024 * 1024))) {
593 lprintf(1, "pthread_attr_setstacksize: %s\n",
595 pthread_attr_destroy(&attr);
598 /* now create the thread */
599 if (pthread_create(&SessThread, &attr,
600 (void *(*)(void *)) worker_entry, NULL)
602 lprintf(1, "Can't create thread: %s\n", strerror(errno));
605 /* free up the attributes */
606 pthread_attr_destroy(&attr);
609 /* #define DBG_PRINNT_HOOKS_AT_START */
610 #ifdef DBG_PRINNT_HOOKS_AT_START
611 const char foobuf[32];
612 const char *nix(void *vptr) {snprintf(foobuf, 32, "%0x", (long) vptr); return foobuf;}
614 extern int dbg_analyze_msg;
615 extern int dbg_bactrace_template_errors;
616 extern int DumpTemplateI18NStrings;
617 extern StrBuf *I18nDump;
618 void InitTemplateCache(void);
619 extern int LoadTemplates;
620 extern void LoadZoneFiles(void);
621 StrBuf *csslocal = NULL;
623 * Here's where it all begins.
625 int main(int argc, char **argv)
627 pthread_t SessThread; /* Thread descriptor */
628 pthread_attr_t attr; /* Thread attributes */
629 int a, i; /* General-purpose variables */
630 char tracefile[PATH_MAX];
631 char ip_addr[256]="0.0.0.0";
632 char dirbuffer[PATH_MAX]="";
635 int home_specified=0;
636 char relhome[PATH_MAX]="";
637 char webcitdir[PATH_MAX] = DATADIR;
638 char *pidfile = NULL;
644 #endif /* ENABLE_NLS */
645 char uds_listen_path[PATH_MAX]; /* listen on a unix domain socket? */
646 const char *I18nDumpFile = NULL;
648 WildFireInitBacktrace(argv[0], 2);
650 HandlerHash = NewHash(1, NULL);
651 PreferenceHooks = NewHash(1, NULL);
652 WirelessTemplateCache = NewHash(1, NULL);
653 WirelessLocalTemplateCache = NewHash(1, NULL);
654 LocalTemplateCache = NewHash(1, NULL);
655 TemplateCache = NewHash(1, NULL);
656 GlobalNS = NewHash(1, NULL);
657 Iterators = NewHash(1, NULL);
658 Conditionals = NewHash(1, NULL);
659 MsgHeaderHandler = NewHash(1, NULL);
660 MimeRenderHandler = NewHash(1, NULL);
661 SortHash = NewHash(1, NULL);
665 #ifdef DBG_PRINNT_HOOKS_AT_START
666 dbg_PrintHash(HandlerHash, nix, NULL);
669 /* Ensure that we are linked to the correct version of libcitadel */
670 if (libcitadel_version_number() < LIBCITADEL_VERSION_NUMBER) {
671 fprintf(stderr, " You are running libcitadel version %d.%02d\n",
672 (libcitadel_version_number() / 100), (libcitadel_version_number() % 100));
673 fprintf(stderr, "WebCit was compiled against version %d.%02d\n",
674 (LIBCITADEL_VERSION_NUMBER / 100), (LIBCITADEL_VERSION_NUMBER % 100));
678 strcpy(uds_listen_path, "");
680 /* Parse command line */
682 while ((a = getopt(argc, argv, "h:i:p:t:T:x:dD:G:cfsZ")) != EOF)
684 while ((a = getopt(argc, argv, "h:i:p:t:T:x:dD:G:cfZ")) != EOF)
688 hdir = strdup(optarg);
690 if (!relh) safestrncpy(webcitdir, hdir,
693 safestrncpy(relhome, relhome,
695 /* free(hdir); TODO: SHOULD WE DO THIS? */
700 running_as_daemon = 1;
703 pidfile = strdup(optarg);
704 running_as_daemon = 1;
707 safestrncpy(ip_addr, optarg, sizeof ip_addr);
710 http_port = atoi(optarg);
711 if (http_port == 0) {
712 safestrncpy(uds_listen_path, optarg, sizeof uds_listen_path);
716 safestrncpy(tracefile, optarg, sizeof tracefile);
717 freopen(tracefile, "w", stdout);
718 freopen(tracefile, "w", stderr);
719 freopen(tracefile, "r", stdin);
722 LoadTemplates = atoi(optarg);
723 dbg_analyze_msg = (LoadTemplates && (1<<1)) != 0;
724 dbg_bactrace_template_errors = (LoadTemplates && (1<<2)) != 0;
730 verbosity = atoi(optarg);
736 server_cookie = malloc(256);
737 if (server_cookie != NULL) {
738 safestrncpy(server_cookie,
739 "Set-cookie: wcserver=",
742 (&server_cookie[strlen(server_cookie)],
744 lprintf(2, "gethostname: %s\n",
754 DumpTemplateI18NStrings = 1;
755 I18nDump = NewStrBufPlain(HKEY("int templatestrings(void)\n{\n"));
756 I18nDumpFile = optarg;
759 fprintf(stderr, "usage: webcit "
760 "[-i ip_addr] [-p http_port] "
761 "[-t tracefile] [-c] [-f] "
762 "[-T Templatedebuglevel] "
763 "[-d] [-Z] [-G i18ndumpfile] "
767 "[remotehost [remoteport]]\n");
772 ctdlhost = argv[optind];
774 ctdlport = argv[optind];
777 /* daemonize, if we were asked to */
778 if (!DumpTemplateI18NStrings && running_as_daemon) {
779 start_daemon(pidfile);
782 signal(SIGHUP, graceful_shutdown);
785 /* Tell 'em who's in da house */
786 lprintf(1, PACKAGE_STRING "\n");
787 lprintf(1, "Copyright (C) 1996-2009 by the Citadel development team.\n"
788 "This software is distributed under the terms of the "
789 "GNU General Public License.\n\n"
793 /* initialize the International Bright Young Thing */
795 initialize_locales();
798 locale = setlocale(LC_ALL, "");
800 mo = malloc(strlen(webcitdir) + 20);
801 lprintf(9, "Message catalog directory: %s\n", bindtextdomain("webcit", LOCALEDIR"/locale"));
803 lprintf(9, "Text domain: %s\n", textdomain("webcit"));
804 lprintf(9, "Text domain Charset: %s\n", bind_textdomain_codeset("webcit","UTF8"));
808 /* calculate all our path on a central place */
809 /* where to keep our config */
811 #define COMPUTE_DIRECTORY(SUBDIR) memcpy(dirbuffer,SUBDIR, sizeof dirbuffer);\
812 snprintf(SUBDIR,sizeof SUBDIR, "%s%s%s%s%s%s%s", \
813 (home&!relh)?webcitdir:basedir, \
814 ((basedir!=webcitdir)&(home&!relh))?basedir:"/", \
815 ((basedir!=webcitdir)&(home&!relh))?"/":"", \
817 (relhome[0]!='\0')?"/":"",\
819 (dirbuffer[0]!='\0')?"/":"");
821 COMPUTE_DIRECTORY(socket_dir);
822 basedir=WWWDIR "/static";
823 COMPUTE_DIRECTORY(static_dir);
824 basedir=WWWDIR "/static/icons";
825 COMPUTE_DIRECTORY(static_icon_dir);
826 basedir=WWWDIR "/static.local";
827 COMPUTE_DIRECTORY(static_local_dir);
829 snprintf(file_crpt_file_key,
830 sizeof file_crpt_file_key,
833 snprintf(file_crpt_file_csr,
834 sizeof file_crpt_file_csr,
837 snprintf(file_crpt_file_cer,
838 sizeof file_crpt_file_cer,
842 /* we should go somewhere we can leave our coredump, if enabled... */
843 lprintf(9, "Changing directory to %s\n", socket_dir);
844 if (chdir(webcitdir) != 0) {
847 LoadIconDir(static_icon_dir);
849 initialise_modules();
850 initialize_viewdefs();
854 if (DumpTemplateI18NStrings) {
856 StrBufAppendBufPlain(I18nDump, HKEY("}\n"), 0);
857 if (StrLength(I18nDump) < 50) {
858 lprintf(1, "********************************************************************************\n");
859 lprintf(1, "* No strings found in templates! are you shure they're there? *\n");
860 lprintf(1, "********************************************************************************\n");
863 fd = fopen(I18nDumpFile, "w");
865 lprintf(1, "********************************************************************************\n");
866 lprintf(1, "* unable to open I18N dumpfile [%s] *\n", I18nDumpFile);
867 lprintf(1, "********************************************************************************\n");
870 fwrite(ChrPtr(I18nDump), 1, StrLength(I18nDump), fd);
875 if (!access("static.local/webcit.css", R_OK)) {
876 csslocal = NewStrBufPlain(HKEY("<link href=\"static.local/webcit.css\" rel=\"stylesheet\" type=\"text/css\">"));
879 /* Tell libical to return an error instead of aborting if it sees badly formed iCalendar data. */
880 icalerror_errors_are_fatal = 0;
882 /* Use our own prefix on tzid's generated from system tzdata */
883 icaltimezone_set_tzid_prefix("/citadel.org/");
886 * Set up a place to put thread-specific data.
887 * We only need a single pointer per thread - it points to the
888 * wcsession struct to which the thread is currently bound.
890 if (pthread_key_create(&MyConKey, NULL) != 0) {
891 lprintf(1, "Can't create TSD key: %s\n", strerror(errno));
893 InitialiseSemaphores ();
896 * Set up a place to put thread-specific SSL data.
897 * We don't stick this in the wcsession struct because SSL starts
898 * up before the session is bound, and it gets torn down between
902 if (pthread_key_create(&ThreadSSL, NULL) != 0) {
903 lprintf(1, "Can't create TSD key: %s\n", strerror(errno));
908 * Bind the server to our favorite port.
909 * There is no need to check for errors, because ig_tcp_server()
910 * exits if it doesn't succeed.
913 if (!IsEmptyStr(uds_listen_path)) {
914 lprintf(2, "Attempting to create listener socket at %s...\n", uds_listen_path);
915 msock = ig_uds_server(uds_listen_path, LISTEN_QUEUE_LENGTH);
918 lprintf(2, "Attempting to bind to port %d...\n", http_port);
919 msock = ig_tcp_server(ip_addr, http_port, LISTEN_QUEUE_LENGTH);
922 lprintf(2, "Listening on socket %d\n", msock);
923 signal(SIGPIPE, SIG_IGN);
925 pthread_mutex_init(&SessionListMutex, NULL);
928 * Start up the housekeeping thread
930 pthread_attr_init(&attr);
931 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
932 pthread_create(&SessThread, &attr,
933 (void *(*)(void *)) housekeeping_loop, NULL);
937 * If this is an HTTPS server, fire up SSL
945 /* Start a few initial worker threads */
946 for (i = 0; i < (MIN_WORKER_THREADS); ++i) {
947 spawn_another_worker_thread();
950 /* now the original thread becomes another worker */
952 ShutDownLibCitadel ();
953 DeleteHash(&HandlerHash);
954 DeleteHash(&PreferenceHooks);
959 void ShutDownWebcit(void)
961 DeleteHash(&ZoneHash);
962 free_zone_directory ();
963 icaltimezone_release_zone_tab ();
964 icalmemory_free_ring ();
965 ShutDownLibCitadel ();
966 DeleteHash(&HandlerHash);
967 DeleteHash(&PreferenceHooks);
968 DeleteHash(&GlobalNS);
969 DeleteHash(&WirelessTemplateCache);
970 DeleteHash(&WirelessLocalTemplateCache);
971 DeleteHash(&TemplateCache);
972 DeleteHash(&LocalTemplateCache);
973 DeleteHash(&Iterators);
974 DeleteHash(&MimeRenderHandler);
975 DeleteHash(&Conditionals);
976 DeleteHash(&MsgHeaderHandler);
977 DeleteHash(&SortHash);
989 * Entry point for worker threads
991 void worker_entry(void)
995 int fail_this_transaction = 0;
998 fd_set readset, tempset;
1003 FD_SET(msock, &readset);
1006 /* Only one thread can accept at a time */
1007 fail_this_transaction = 0;
1011 ret = -1; /* just one at once should select... */
1012 begin_critical_section(S_SELECT);
1015 if (msock > 0) FD_SET(msock, &tempset);
1018 if (msock > 0) ret = select(msock+1, &tempset, NULL, NULL, &tv);
1019 end_critical_section(S_SELECT);
1020 if ((ret < 0) && (errno != EINTR) && (errno != EAGAIN))
1021 {/* EINTR and EAGAIN are thrown but not of interest. */
1022 lprintf(2, "accept() failed:%d %s\n",
1023 errno, strerror(errno));
1025 else if ((ret > 0) && (msock > 0) && FD_ISSET(msock, &tempset))
1026 {/* Successfully selected, and still not shutting down? Accept! */
1027 ssock = accept(msock, NULL, 0);
1030 } while ((msock > 0) && (ssock < 0) && (time_to_die == 0));
1032 if ((msock == -1)||(time_to_die))
1033 {/* ok, we're going down. */
1036 /* the first to come here will have to do the cleanup.
1037 * make shure its realy just one.
1039 begin_critical_section(S_SHUTDOWN);
1045 end_critical_section(S_SHUTDOWN);
1047 {/* we're the one to cleanup the mess. */
1048 lprintf(2, "I'm master shutdown: tagging sessions to be killed.\n");
1049 shutdown_sessions();
1050 lprintf(2, "master shutdown: waiting for others\n");
1051 sleeeeeeeeeep(1); /* wait so some others might finish... */
1052 lprintf(2, "master shutdown: cleaning up sessions\n");
1054 lprintf(2, "master shutdown: cleaning up libical\n");
1058 lprintf(2, "master shutdown exiting!.\n");
1063 if (ssock < 0 ) continue;
1066 if (ssock > 0) close (ssock);
1067 lprintf(2, "inbetween.");
1069 } else { /* Got it? do some real work! */
1070 /* Set the SO_REUSEADDR socket option */
1072 setsockopt(ssock, SOL_SOCKET, SO_REUSEADDR,
1075 /* If we are an HTTPS server, go crypto now. */
1078 if (starttls(ssock) != 0) {
1079 fail_this_transaction = 1;
1085 if (fail_this_transaction == 0) {
1087 /* Perform an HTTP transaction... */
1088 context_loop(&ssock);
1090 /* Shut down SSL/TLS if required... */
1097 /* ...and close the socket. */
1099 lingering_close(ssock);
1104 } while (!time_to_die);
1106 lprintf (1, "bye\n");
1111 * print log messages
1112 * logs to stderr if loglevel is lower than the verbosity set at startup
1114 * loglevel level of the message
1115 * format the printf like format string
1116 * ... the strings to put into format
1118 int lprintf(int loglevel, const char *format, ...)
1122 if (loglevel <= verbosity) {
1123 va_start(ap, format);
1124 vfprintf(stderr, format, ap);
1133 * print the actual stack frame.
1135 void wc_backtrace(void)
1137 #ifdef HAVE_BACKTRACE
1138 void *stack_frames[50];
1143 size = backtrace(stack_frames, sizeof(stack_frames) / sizeof(void*));
1144 strings = backtrace_symbols(stack_frames, size);
1145 for (i = 0; i < size; i++) {
1146 if (strings != NULL)
1147 lprintf(1, "%s\n", strings[i]);
1149 lprintf(1, "%p\n", stack_frames[i]);