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 */
30 extern void *context_loop(int*);
31 extern void *housekeeping_loop(void);
32 extern pthread_mutex_t SessionListMutex;
33 extern pthread_key_t MyConKey;
36 char ctdl_key_dir[PATH_MAX]=SSL_DIR;
37 char file_crpt_file_key[PATH_MAX]="";
38 char file_crpt_file_csr[PATH_MAX]="";
39 char file_crpt_file_cer[PATH_MAX]="";
41 char socket_dir[PATH_MAX]; /* where to talk to our citadel server */
42 static const char editor_absolut_dir[PATH_MAX]=EDITORDIR; /* nailed to what configure gives us. */
43 static char static_dir[PATH_MAX]; /* calculated on startup */
44 static char static_local_dir[PATH_MAX]; /* calculated on startup */
45 static char static_icon_dir[PATH_MAX]; /* where should we find our mime icons? */
46 char *static_dirs[]={ /* needs same sort order as the web mapping */
47 (char*)static_dir, /* our templates on disk */
48 (char*)static_local_dir, /* user provided templates disk */
49 (char*)editor_absolut_dir, /* the editor on disk */
50 (char*)static_icon_dir /* our icons... */
54 * Subdirectories from which the client may request static content
56 * (If you add more, remember to increment 'ndirs' below)
58 char *static_content_dirs[] = {
59 "static", /* static templates */
60 "static.local", /* site local static templates */
61 "tiny_mce" /* rich text editor */
67 char *server_cookie = NULL; /* our Cookie connection to the client */
68 int http_port = PORT_NUM; /* Port to listen on */
69 char *ctdlhost = DEFAULT_HOST; /* our name */
70 char *ctdlport = DEFAULT_PORT; /* our Port */
71 int setup_wizard = 0; /* should we run the setup wizard? \todo */
72 char wizard_filename[PATH_MAX]; /* where's the setup wizard? */
73 int running_as_daemon = 0; /* should we deamonize on startup? */
77 * This is a generic function to set up a master socket for listening on
78 * a TCP port. The server shuts down if the bind fails.
80 * ip_addr IP address to bind
81 * port_number port number to bind
82 * queue_len number of incoming connections to allow in the queue
84 int ig_tcp_server(char *ip_addr, int port_number, int queue_len)
86 struct sockaddr_in sin;
89 memset(&sin, 0, sizeof(sin));
90 sin.sin_family = AF_INET;
91 if (ip_addr == NULL) {
92 sin.sin_addr.s_addr = INADDR_ANY;
94 sin.sin_addr.s_addr = inet_addr(ip_addr);
97 if (sin.sin_addr.s_addr == INADDR_NONE) {
98 sin.sin_addr.s_addr = INADDR_ANY;
101 if (port_number == 0) {
102 lprintf(1, "Cannot start: no port number specified.\n");
105 sin.sin_port = htons((u_short) port_number);
107 s = socket(PF_INET, SOCK_STREAM, (getprotobyname("tcp")->p_proto));
109 lprintf(1, "Can't create a socket: %s\n", strerror(errno));
112 /* Set some socket options that make sense. */
114 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
116 fcntl(s, F_SETFL, O_NONBLOCK); /* maide: this statement is incorrect
117 there should be a preceding F_GETFL
118 and a bitwise OR with the previous
121 if (bind(s, (struct sockaddr *) &sin, sizeof(sin)) < 0) {
122 lprintf(1, "Can't bind: %s\n", strerror(errno));
125 if (listen(s, queue_len) < 0) {
126 lprintf(1, "Can't listen: %s\n", strerror(errno));
135 * Create a Unix domain socket and listen on it
136 * sockpath - file name of the unix domain socket
137 * queue_len - Number of incoming connections to allow in the queue
139 int ig_uds_server(char *sockpath, int queue_len)
141 struct sockaddr_un addr;
144 int actual_queue_len;
146 actual_queue_len = queue_len;
147 if (actual_queue_len < 5) actual_queue_len = 5;
149 i = unlink(sockpath);
150 if (i != 0) if (errno != ENOENT) {
151 lprintf(1, "webcit: can't unlink %s: %s\n",
152 sockpath, strerror(errno));
156 memset(&addr, 0, sizeof(addr));
157 addr.sun_family = AF_UNIX;
158 safestrncpy(addr.sun_path, sockpath, sizeof addr.sun_path);
160 s = socket(AF_UNIX, SOCK_STREAM, 0);
162 lprintf(1, "webcit: Can't create a socket: %s\n",
167 if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
168 lprintf(1, "webcit: Can't bind: %s\n",
173 if (listen(s, actual_queue_len) < 0) {
174 lprintf(1, "webcit: Can't listen: %s\n",
179 chmod(sockpath, 0777);
187 * Read data from the client socket.
189 * sock socket fd to read from
190 * buf buffer to read into
191 * bytes number of bytes to read
192 * timeout Number of seconds to wait before timing out
194 * Possible return values:
195 * 1 Requested number of bytes has been read.
196 * 0 Request timed out.
197 * -1 Connection is broken, or other error.
199 int client_read_to(int *sock, StrBuf *Target, StrBuf *Buf, int bytes, int timeout)
206 while ((StrLength(Buf) + StrLength(Target) < bytes) &&
208 retval = client_read_sslbuffer(Buf, timeout);
210 StrBufAppendBuf(Target, Buf, 0); /// todo: Buf > bytes?
212 write(2, "\033[32m", 5);
213 write(2, buf, bytes);
214 write(2, "\033[30m", 5);
219 lprintf(2, "client_read_ssl() failed\n");
225 if (StrLength(Buf) > 0) {//// todo: what if Buf > bytes?
226 StrBufAppendBuf(Target, Buf, 0);
228 retval = StrBufReadBLOB(Target,
230 (StrLength(Target) > 0),
231 bytes - StrLength(Target),
234 lprintf(2, "client_read() failed: %s\n",
240 write(2, "\033[32m", 5);
241 write(2, buf, bytes);
242 write(2, "\033[30m", 5);
249 * Begin buffering HTTP output so we can transmit it all in one write operation later.
251 void begin_burst(void)
253 if (WC->WBuf == NULL)
254 WC->WBuf = NewStrBufPlain(NULL, 32768);
259 * Finish buffering HTTP output. [Compress using zlib and] output with a Content-Length: header.
263 struct wcsession *WCC = WC;
264 const char *ptr, *eptr;
271 /* Perform gzip compression, if enabled and supported by client */
272 if ((WCC->gzip_ok) && CompressBuffer(WCC->WBuf))
274 hprintf("Content-encoding: gzip\r\n");
276 #endif /* HAVE_ZLIB */
278 hprintf("Content-length: %d\r\n\r\n", StrLength(WCC->WBuf));
280 ptr = ChrPtr(WCC->HBuf);
281 count = StrLength(WCC->HBuf);
286 client_write_ssl(WCC->HBuf);
287 client_write_ssl(WCC->WBuf);
295 write(2, "\033[34m", 5);
296 write(2, ptr, StrLength(WCC->WBuf));
297 write(2, "\033[30m", 5);
299 fdflags = fcntl(WC->http_sock, F_GETFL);
302 if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
304 FD_SET(WCC->http_sock, &wset);
305 if (select(WCC->http_sock + 1, NULL, &wset, NULL, NULL) == -1) {
306 lprintf(2, "client_write: Socket select failed (%s)\n", strerror(errno));
311 if ((res = write(WCC->http_sock,
314 lprintf(2, "client_write: Socket write failed (%s)\n", strerror(errno));
322 ptr = ChrPtr(WCC->WBuf);
323 count = StrLength(WCC->WBuf);
328 write(2, "\033[34m", 5);
329 write(2, ptr, StrLength(WCC->WBuf));
330 write(2, "\033[30m", 5);
334 if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
336 FD_SET(WCC->http_sock, &wset);
337 if (select(WCC->http_sock + 1, NULL, &wset, NULL, NULL) == -1) {
338 lprintf(2, "client_write: Socket select failed (%s)\n", strerror(errno));
343 if ((res = write(WCC->http_sock,
346 lprintf(2, "client_write: Socket write failed (%s)\n", strerror(errno));
354 return StrLength(WCC->WBuf);
360 * Read data from the client socket with default timeout.
361 * (This is implemented in terms of client_read_to() and could be
362 * justifiably moved out of sysdep.c)
364 * sock the socket fd to read from
365 * buf the buffer to write to
366 * bytes Number of bytes to read
368 int client_read(int *sock, StrBuf *Target, StrBuf *buf, int bytes)
370 return (client_read_to(sock, Target, buf, bytes, SLEEPING));
375 * Get a LF-terminated line of text from the client.
376 * (This is implemented in terms of client_read() and could be
377 * justifiably moved out of sysdep.c)
379 * sock socket fd to get client line from
380 * buf buffer to write read data to
381 * bufsiz how many bytes to read
383 * returns the number of bytes read
385 /////int client_getln(int *sock, char *buf, int bufsiz)
389 ///// /* Read one character at a time.*/
390 ///// for (i = 0; *sock > 0; i++) {
391 ///// retval = client_read(sock, &buf[i], 1);
392 ///// if (retval < 0)
394 ///// if (retval != 1 || buf[i] == '\n' || i == (bufsiz-1))
396 ///// if ( (!isspace(buf[i])) && (!isprint(buf[i])) ) {
397 ///// /* Non printable character recieved from client */
402 ///// /* If we got a long line, discard characters until the newline. */
403 ///// if (i == (bufsiz-1))
404 ///// while (buf[i] != '\n' && retval == 1)
405 ///// retval = client_read(sock, &buf[i], 1);
408 ///// * Strip any trailing non-printable characters.
411 ///// while ((i > 0) && (!isprint(buf[i - 1]))) {
414 ///// return (retval);
418 * Shut us down the regular way.
419 * signum is the signal we want to forward
422 void graceful_shutdown_watcher(int signum) {
423 lprintf (1, "bye; shutting down watcher.");
424 kill(current_child, signum);
425 if (signum != SIGHUP)
430 int ClientGetLine(int *sock, StrBuf *Target, StrBuf *CLineBuf)
432 const char *Error, *pch, *pchs;
433 int rlen, len, retval = 0;
436 if (StrLength(CLineBuf) > 0) {
437 pchs = ChrPtr(CLineBuf);
438 pch = strchr(pchs, '\n');
442 if (len > 0 && (*(pch - 1) == '\r') )
444 StrBufSub(Target, CLineBuf, 0, len - rlen);
445 StrBufCutLeft(CLineBuf, len + 1);
450 while ((retval >= 0) &&
451 (pchs = ChrPtr(CLineBuf),
452 pch = strchr(pchs, '\n'),
454 retval = client_read_sslbuffer(CLineBuf, SLEEPING);
455 if ((retval > 0) && (pch != NULL)) {
458 if (len > 0 && (*(pch - 1) == '\r') )
460 StrBufSub(Target, CLineBuf, 0, len - rlen);
461 StrBufCutLeft(CLineBuf, len + 1);
469 return StrBufTCP_read_buffered_line(Target,
480 * Shut us down the regular way.
481 * signum is the signal we want to forward
484 void graceful_shutdown(int signum) {
485 // kill(current_child, signum);
490 lprintf (1, "bye going down gracefull.[%d][%s]\n", signum, wd);
502 * Start running as a daemon.
504 void start_daemon(char *pid_file)
513 /* Close stdin/stdout/stderr and replace them with /dev/null.
514 * We don't just call close() because we don't want these fd's
515 * to be reused for other files.
519 signal(SIGHUP, SIG_IGN);
520 signal(SIGINT, SIG_IGN);
521 signal(SIGQUIT, SIG_IGN);
530 freopen("/dev/null", "r", stdin);
531 freopen("/dev/null", "w", stdout);
532 freopen("/dev/null", "w", stderr);
533 signal(SIGTERM, graceful_shutdown_watcher);
534 signal(SIGHUP, graceful_shutdown_watcher);
537 current_child = fork();
540 if (current_child < 0) {
542 ShutDownLibCitadel ();
546 else if (current_child == 0) { // child process
547 // signal(SIGTERM, graceful_shutdown);
548 signal(SIGHUP, graceful_shutdown);
550 return; /* continue starting webcit. */
553 else { // watcher process
554 // signal(SIGTERM, SIG_IGN);
555 // signal(SIGHUP, SIG_IGN);
557 fp = fopen(pid_file, "w");
559 fprintf(fp, "%d\n", getpid());
563 waitpid(current_child, &status, 0);
568 /* Did the main process exit with an actual exit code? */
569 if (WIFEXITED(status)) {
571 /* Exit code 0 means the watcher should exit */
572 if (WEXITSTATUS(status) == 0) {
576 /* Exit code 101-109 means the watcher should exit */
577 else if ( (WEXITSTATUS(status) >= 101) && (WEXITSTATUS(status) <= 109) ) {
581 /* Any other exit code means we should restart. */
587 /* Any other type of termination (signals, etc.) should also restart. */
592 } while (do_restart);
597 ShutDownLibCitadel ();
598 exit(WEXITSTATUS(status));
602 * Spawn an additional worker thread into the pool.
604 void spawn_another_worker_thread()
606 pthread_t SessThread; /* Thread descriptor */
607 pthread_attr_t attr; /* Thread attributes */
610 lprintf(3, "Creating a new thread\n");
612 /* set attributes for the new thread */
613 pthread_attr_init(&attr);
614 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
617 * Our per-thread stacks need to be bigger than the default size, otherwise
618 * the MIME parser crashes on FreeBSD, and the IMAP service crashes on
621 if ((ret = pthread_attr_setstacksize(&attr, 1024 * 1024))) {
622 lprintf(1, "pthread_attr_setstacksize: %s\n",
624 pthread_attr_destroy(&attr);
627 /* now create the thread */
628 if (pthread_create(&SessThread, &attr,
629 (void *(*)(void *)) worker_entry, NULL)
631 lprintf(1, "Can't create thread: %s\n", strerror(errno));
634 /* free up the attributes */
635 pthread_attr_destroy(&attr);
638 //#define DBG_PRINNT_HOOKS_AT_START
639 #ifdef DBG_PRINNT_HOOKS_AT_START
640 const char foobuf[32];
641 const char *nix(void *vptr) {snprintf(foobuf, 32, "%0x", (long) vptr); return foobuf;}
643 void InitTemplateCache(void);
644 extern int LoadTemplates;
645 extern void LoadZoneFiles(void);
648 * Here's where it all begins.
650 int main(int argc, char **argv)
652 pthread_t SessThread; /* Thread descriptor */
653 pthread_attr_t attr; /* Thread attributes */
654 int a, i; /* General-purpose variables */
655 char tracefile[PATH_MAX];
656 char ip_addr[256]="0.0.0.0";
657 char dirbuffer[PATH_MAX]="";
660 int home_specified=0;
661 char relhome[PATH_MAX]="";
662 char webcitdir[PATH_MAX] = DATADIR;
663 char *pidfile = NULL;
669 #endif /* ENABLE_NLS */
670 char uds_listen_path[PATH_MAX]; /* listen on a unix domain socket? */
672 HandlerHash = NewHash(1, NULL);
673 PreferenceHooks = NewHash(1, NULL);
674 WirelessTemplateCache = NewHash(1, NULL);
675 WirelessLocalTemplateCache = NewHash(1, NULL);
676 LocalTemplateCache = NewHash(1, NULL);
677 TemplateCache = NewHash(1, NULL);
678 GlobalNS = NewHash(1, NULL);
679 Iterators = NewHash(1, NULL);
680 Contitionals = NewHash(1, NULL);
684 #ifdef DBG_PRINNT_HOOKS_AT_START
685 dbg_PrintHash(HandlerHash, nix, NULL);
688 /* Ensure that we are linked to the correct version of libcitadel */
689 if (libcitadel_version_number() < LIBCITADEL_VERSION_NUMBER) {
690 fprintf(stderr, " You are running libcitadel version %d.%02d\n",
691 (libcitadel_version_number() / 100), (libcitadel_version_number() % 100));
692 fprintf(stderr, "WebCit was compiled against version %d.%02d\n",
693 (LIBCITADEL_VERSION_NUMBER / 100), (LIBCITADEL_VERSION_NUMBER % 100));
697 strcpy(uds_listen_path, "");
699 /* Parse command line */
701 while ((a = getopt(argc, argv, "h:i:p:t:T:x:dD:cfs")) != EOF)
703 while ((a = getopt(argc, argv, "h:i:p:t:T:x:dD:cf")) != EOF)
707 hdir = strdup(optarg);
709 if (!relh) safestrncpy(webcitdir, hdir,
712 safestrncpy(relhome, relhome,
714 /* free(hdir); TODO: SHOULD WE DO THIS? */
719 running_as_daemon = 1;
722 pidfile = strdup(optarg);
723 running_as_daemon = 1;
726 safestrncpy(ip_addr, optarg, sizeof ip_addr);
729 http_port = atoi(optarg);
730 if (http_port == 0) {
731 safestrncpy(uds_listen_path, optarg, sizeof uds_listen_path);
735 safestrncpy(tracefile, optarg, sizeof tracefile);
736 freopen(tracefile, "w", stdout);
737 freopen(tracefile, "w", stderr);
738 freopen(tracefile, "r", stdin);
741 LoadTemplates = atoi(optarg);
744 verbosity = atoi(optarg);
750 server_cookie = malloc(256);
751 if (server_cookie != NULL) {
752 safestrncpy(server_cookie,
753 "Set-cookie: wcserver=",
756 (&server_cookie[strlen(server_cookie)],
758 lprintf(2, "gethostname: %s\n",
768 fprintf(stderr, "usage: webcit "
769 "[-i ip_addr] [-p http_port] "
770 "[-t tracefile] [-c] [-f] "
771 "[-T Templatedebuglevel] "
776 "[remotehost [remoteport]]\n");
781 ctdlhost = argv[optind];
783 ctdlport = argv[optind];
786 /* daemonize, if we were asked to */
787 if (running_as_daemon) {
788 start_daemon(pidfile);
791 /// signal(SIGTERM, graceful_shutdown);
792 signal(SIGHUP, graceful_shutdown);
795 /* Tell 'em who's in da house */
796 lprintf(1, PACKAGE_STRING "\n");
797 lprintf(1, "Copyright (C) 1996-2008 by the Citadel development team.\n"
798 "This software is distributed under the terms of the "
799 "GNU General Public License.\n\n"
803 /* initialize the International Bright Young Thing */
805 initialize_locales();
807 locale = setlocale(LC_ALL, "");
809 mo = malloc(strlen(webcitdir) + 20);
810 lprintf(9, "Message catalog directory: %s\n", bindtextdomain("webcit", LOCALEDIR"/locale"));
812 lprintf(9, "Text domain: %s\n", textdomain("webcit"));
813 lprintf(9, "Text domain Charset: %s\n", bind_textdomain_codeset("webcit","UTF8"));
818 /* calculate all our path on a central place */
819 /* where to keep our config */
821 #define COMPUTE_DIRECTORY(SUBDIR) memcpy(dirbuffer,SUBDIR, sizeof dirbuffer);\
822 snprintf(SUBDIR,sizeof SUBDIR, "%s%s%s%s%s%s%s", \
823 (home&!relh)?webcitdir:basedir, \
824 ((basedir!=webcitdir)&(home&!relh))?basedir:"/", \
825 ((basedir!=webcitdir)&(home&!relh))?"/":"", \
827 (relhome[0]!='\0')?"/":"",\
829 (dirbuffer[0]!='\0')?"/":"");
831 COMPUTE_DIRECTORY(socket_dir);
832 basedir=WWWDIR "/static";
833 COMPUTE_DIRECTORY(static_dir);
834 basedir=WWWDIR "/static/icons";
835 COMPUTE_DIRECTORY(static_icon_dir);
836 basedir=WWWDIR "/static.local";
837 COMPUTE_DIRECTORY(static_local_dir);
839 snprintf(file_crpt_file_key,
840 sizeof file_crpt_file_key,
843 snprintf(file_crpt_file_csr,
844 sizeof file_crpt_file_csr,
847 snprintf(file_crpt_file_cer,
848 sizeof file_crpt_file_cer,
852 /* we should go somewhere we can leave our coredump, if enabled... */
853 lprintf(9, "Changing directory to %s\n", socket_dir);
854 if (chdir(webcitdir) != 0) {
857 LoadIconDir(static_icon_dir);
860 initialise_modules();
861 initialize_viewdefs();
864 /* Tell libical to return an error instead of aborting if it sees badly formed iCalendar data. */
865 icalerror_errors_are_fatal = 0;
868 * Set up a place to put thread-specific data.
869 * We only need a single pointer per thread - it points to the
870 * wcsession struct to which the thread is currently bound.
872 if (pthread_key_create(&MyConKey, NULL) != 0) {
873 lprintf(1, "Can't create TSD key: %s\n", strerror(errno));
875 InitialiseSemaphores ();
878 * Set up a place to put thread-specific SSL data.
879 * We don't stick this in the wcsession struct because SSL starts
880 * up before the session is bound, and it gets torn down between
884 if (pthread_key_create(&ThreadSSL, NULL) != 0) {
885 lprintf(1, "Can't create TSD key: %s\n", strerror(errno));
890 * Bind the server to our favorite port.
891 * There is no need to check for errors, because ig_tcp_server()
892 * exits if it doesn't succeed.
895 if (!IsEmptyStr(uds_listen_path)) {
896 lprintf(2, "Attempting to create listener socket at %s...\n", uds_listen_path);
897 msock = ig_uds_server(uds_listen_path, LISTEN_QUEUE_LENGTH);
900 lprintf(2, "Attempting to bind to port %d...\n", http_port);
901 msock = ig_tcp_server(ip_addr, http_port, LISTEN_QUEUE_LENGTH);
904 lprintf(2, "Listening on socket %d\n", msock);
905 signal(SIGPIPE, SIG_IGN);
907 pthread_mutex_init(&SessionListMutex, NULL);
910 * Start up the housekeeping thread
912 pthread_attr_init(&attr);
913 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
914 pthread_create(&SessThread, &attr,
915 (void *(*)(void *)) housekeeping_loop, NULL);
919 * If this is an HTTPS server, fire up SSL
927 /* Start a few initial worker threads */
928 for (i = 0; i < (MIN_WORKER_THREADS); ++i) {
929 spawn_another_worker_thread();
932 /* now the original thread becomes another worker */
934 ShutDownLibCitadel ();
935 DeleteHash(&HandlerHash);
936 DeleteHash(&PreferenceHooks);
941 void ShutDownWebcit(void)
943 DeleteHash(&ZoneHash);
944 free_zone_directory ();
945 icaltimezone_release_zone_tab ();
946 icalmemory_free_ring ();
947 ShutDownLibCitadel ();
948 DeleteHash(&HandlerHash);
949 DeleteHash(&PreferenceHooks);
950 DeleteHash(&GlobalNS);
951 DeleteHash(&WirelessTemplateCache);
952 DeleteHash(&WirelessLocalTemplateCache);
953 DeleteHash(&TemplateCache);
954 DeleteHash(&LocalTemplateCache);
955 DeleteHash(&Iterators);
956 DeleteHash(&Contitionals);
968 * Entry point for worker threads
970 void worker_entry(void)
974 int fail_this_transaction = 0;
977 fd_set readset, tempset;
982 FD_SET(msock, &readset);
985 /* Only one thread can accept at a time */
986 fail_this_transaction = 0;
990 ret = -1; /* just one at once should select... */
991 begin_critical_section(S_SELECT);
994 if (msock > 0) FD_SET(msock, &tempset);
997 if (msock > 0) ret = select(msock+1, &tempset, NULL, NULL, &tv);
998 end_critical_section(S_SELECT);
999 if ((ret < 0) && (errno != EINTR) && (errno != EAGAIN))
1000 {// EINTR and EAGAIN are thrown but not of interest.
1001 lprintf(2, "accept() failed:%d %s\n",
1002 errno, strerror(errno));
1004 else if ((ret > 0) && (msock > 0) && FD_ISSET(msock, &tempset))
1005 {// Successfully selected, and still not shutting down? Accept!
1006 ssock = accept(msock, NULL, 0);
1009 } while ((msock > 0) && (ssock < 0) && (time_to_die == 0));
1011 if ((msock == -1)||(time_to_die))
1012 {// ok, we're going down.
1015 /* the first to come here will have to do the cleanup.
1016 * make shure its realy just one.
1018 begin_critical_section(S_SHUTDOWN);
1024 end_critical_section(S_SHUTDOWN);
1026 {// we're the one to cleanup the mess.
1027 lprintf(2, "I'm master shutdown: tagging sessions to be killed.\n");
1028 shutdown_sessions();
1029 lprintf(2, "master shutdown: waiting for others\n");
1030 sleeeeeeeeeep(1); // wait so some others might finish...
1031 lprintf(2, "master shutdown: cleaning up sessions\n");
1033 lprintf(2, "master shutdown: cleaning up libical\n");
1037 lprintf(2, "master shutdown exiting!.\n");
1042 if (ssock < 0 ) continue;
1045 if (ssock > 0) close (ssock);
1046 lprintf(2, "inbetween.");
1048 } else { // Got it? do some real work!
1049 /* Set the SO_REUSEADDR socket option */
1051 setsockopt(ssock, SOL_SOCKET, SO_REUSEADDR,
1054 /* If we are an HTTPS server, go crypto now. */
1057 if (starttls(ssock) != 0) {
1058 fail_this_transaction = 1;
1064 if (fail_this_transaction == 0) {
1066 /* Perform an HTTP transaction... */
1067 context_loop(&ssock);
1069 /* Shut down SSL/TLS if required... */
1076 /* ...and close the socket. */
1078 lingering_close(ssock);
1083 } while (!time_to_die);
1085 lprintf (1, "bye\n");
1090 * print log messages
1091 * logs to stderr if loglevel is lower than the verbosity set at startup
1093 * loglevel level of the message
1094 * format the printf like format string
1095 * ... the strings to put into format
1097 int lprintf(int loglevel, const char *format, ...)
1101 if (loglevel <= verbosity) {
1102 va_start(ap, format);
1103 vfprintf(stderr, format, ap);
1112 * print the actual stack frame.
1114 void wc_backtrace(void)
1116 #ifdef HAVE_BACKTRACE
1117 void *stack_frames[50];
1122 size = backtrace(stack_frames, sizeof(stack_frames) / sizeof(void*));
1123 strings = backtrace_symbols(stack_frames, size);
1124 for (i = 0; i < size; i++) {
1125 if (strings != NULL)
1126 lprintf(1, "%s\n", strings[i]);
1128 lprintf(1, "%p\n", stack_frames[i]);