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));
117 fcntl(s, F_SETFL, O_NONBLOCK); /* maide: this statement is incorrect
118 there should be a preceding F_GETFL
119 and a bitwise OR with the previous
123 if (bind(s, (struct sockaddr *) &sin, sizeof(sin)) < 0) {
124 lprintf(1, "Can't bind: %s\n", strerror(errno));
127 if (listen(s, queue_len) < 0) {
128 lprintf(1, "Can't listen: %s\n", strerror(errno));
137 * Create a Unix domain socket and listen on it
138 * sockpath - file name of the unix domain socket
139 * queue_len - Number of incoming connections to allow in the queue
141 int ig_uds_server(char *sockpath, int queue_len)
143 struct sockaddr_un addr;
146 int actual_queue_len;
148 actual_queue_len = queue_len;
149 if (actual_queue_len < 5) actual_queue_len = 5;
151 i = unlink(sockpath);
152 if ((i != 0) && (errno != ENOENT)) {
153 lprintf(1, "webcit: can't unlink %s: %s\n",
154 sockpath, strerror(errno));
158 memset(&addr, 0, sizeof(addr));
159 addr.sun_family = AF_UNIX;
160 safestrncpy(addr.sun_path, sockpath, sizeof addr.sun_path);
162 s = socket(AF_UNIX, SOCK_STREAM, 0);
164 lprintf(1, "webcit: Can't create a socket: %s\n",
169 if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
170 lprintf(1, "webcit: Can't bind: %s\n",
175 if (listen(s, actual_queue_len) < 0) {
176 lprintf(1, "webcit: Can't listen: %s\n",
181 chmod(sockpath, 0777);
189 * Read data from the client socket.
191 * sock socket fd to read from
192 * buf buffer to read into
193 * bytes number of bytes to read
194 * timeout Number of seconds to wait before timing out
196 * Possible return values:
197 * 1 Requested number of bytes has been read.
198 * 0 Request timed out.
199 * -1 Connection is broken, or other error.
201 int client_read_to(int *sock, StrBuf *Target, StrBuf *Buf, int bytes, int timeout)
208 while ((StrLength(Buf) + StrLength(Target) < bytes) &&
210 retval = client_read_sslbuffer(Buf, timeout);
212 StrBufAppendBuf(Target, Buf, 0); /// todo: Buf > bytes?
214 write(2, "\033[32m", 5);
215 write(2, buf, bytes);
216 write(2, "\033[30m", 5);
221 lprintf(2, "client_read_ssl() failed\n");
227 if (StrLength(Buf) > 0) {//// todo: what if Buf > bytes?
228 StrBufAppendBuf(Target, Buf, 0);
230 retval = StrBufReadBLOB(Target,
232 (StrLength(Target) > 0),
233 bytes - StrLength(Target),
236 lprintf(2, "client_read() failed: %s\n",
242 write(2, "\033[32m", 5);
243 write(2, buf, bytes);
244 write(2, "\033[30m", 5);
251 * Begin buffering HTTP output so we can transmit it all in one write operation later.
253 void begin_burst(void)
255 if (WC->WBuf == NULL)
256 WC->WBuf = NewStrBufPlain(NULL, 32768);
261 * Finish buffering HTTP output. [Compress using zlib and] output with a Content-Length: header.
265 struct wcsession *WCC = WC;
266 const char *ptr, *eptr;
273 /* Perform gzip compression, if enabled and supported by client */
274 if ((WCC->gzip_ok) && CompressBuffer(WCC->WBuf))
276 hprintf("Content-encoding: gzip\r\n");
278 #endif /* HAVE_ZLIB */
280 hprintf("Content-length: %d\r\n\r\n", StrLength(WCC->WBuf));
282 ptr = ChrPtr(WCC->HBuf);
283 count = StrLength(WCC->HBuf);
288 client_write_ssl(WCC->HBuf);
289 client_write_ssl(WCC->WBuf);
297 write(2, "\033[34m", 5);
298 write(2, ptr, StrLength(WCC->WBuf));
299 write(2, "\033[30m", 5);
301 fdflags = fcntl(WC->http_sock, F_GETFL);
304 if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
306 FD_SET(WCC->http_sock, &wset);
307 if (select(WCC->http_sock + 1, NULL, &wset, NULL, NULL) == -1) {
308 lprintf(2, "client_write: Socket select failed (%s)\n", strerror(errno));
313 if ((res = write(WCC->http_sock,
316 lprintf(2, "client_write: Socket write failed (%s)\n", strerror(errno));
324 ptr = ChrPtr(WCC->WBuf);
325 count = StrLength(WCC->WBuf);
330 write(2, "\033[34m", 5);
331 write(2, ptr, StrLength(WCC->WBuf));
332 write(2, "\033[30m", 5);
336 if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
338 FD_SET(WCC->http_sock, &wset);
339 if (select(WCC->http_sock + 1, NULL, &wset, NULL, NULL) == -1) {
340 lprintf(2, "client_write: Socket select failed (%s)\n", strerror(errno));
345 if ((res = write(WCC->http_sock,
348 lprintf(2, "client_write: Socket write failed (%s)\n", strerror(errno));
356 return StrLength(WCC->WBuf);
362 * Read data from the client socket with default timeout.
363 * (This is implemented in terms of client_read_to() and could be
364 * justifiably moved out of sysdep.c)
366 * sock the socket fd to read from
367 * buf the buffer to write to
368 * bytes Number of bytes to read
370 int client_read(int *sock, StrBuf *Target, StrBuf *buf, int bytes)
372 return (client_read_to(sock, Target, buf, bytes, SLEEPING));
377 * Get a LF-terminated line of text from the client.
378 * (This is implemented in terms of client_read() and could be
379 * justifiably moved out of sysdep.c)
381 * sock socket fd to get client line from
382 * buf buffer to write read data to
383 * bufsiz how many bytes to read
385 * returns the number of bytes read
387 /////int client_getln(int *sock, char *buf, int bufsiz)
391 ///// /* Read one character at a time.*/
392 ///// for (i = 0; *sock > 0; i++) {
393 ///// retval = client_read(sock, &buf[i], 1);
394 ///// if (retval < 0)
396 ///// if (retval != 1 || buf[i] == '\n' || i == (bufsiz-1))
398 ///// if ( (!isspace(buf[i])) && (!isprint(buf[i])) ) {
399 ///// /* Non printable character recieved from client */
404 ///// /* If we got a long line, discard characters until the newline. */
405 ///// if (i == (bufsiz-1))
406 ///// while (buf[i] != '\n' && retval == 1)
407 ///// retval = client_read(sock, &buf[i], 1);
410 ///// * Strip any trailing non-printable characters.
413 ///// while ((i > 0) && (!isprint(buf[i - 1]))) {
416 ///// return (retval);
420 * Shut us down the regular way.
421 * signum is the signal we want to forward
424 void graceful_shutdown_watcher(int signum) {
425 lprintf (1, "bye; shutting down watcher.");
426 kill(current_child, signum);
427 if (signum != SIGHUP)
432 int ClientGetLine(int *sock, StrBuf *Target, StrBuf *CLineBuf)
434 const char *Error, *pch, *pchs;
435 int rlen, len, retval = 0;
439 if (StrLength(CLineBuf) > 0) {
440 pchs = ChrPtr(CLineBuf);
441 pch = strchr(pchs, '\n');
445 if (len > 0 && (*(pch - 1) == '\r') )
447 StrBufSub(Target, CLineBuf, 0, len - rlen);
448 StrBufCutLeft(CLineBuf, len + 1);
453 while (retval == 0) {
455 pchs = ChrPtr(CLineBuf);
457 pch = strchr(pchs, '\n');
459 retval = client_read_sslbuffer(CLineBuf, SLEEPING);
460 pchs = ChrPtr(CLineBuf);
461 pch = strchr(pchs, '\n');
470 if ((retval > 0) && (pch != NULL)) {
473 if (len > 0 && (*(pch - 1) == '\r') )
475 StrBufSub(Target, CLineBuf, 0, len - rlen);
476 StrBufCutLeft(CLineBuf, len + 1);
484 return StrBufTCP_read_buffered_line(Target,
495 * Shut us down the regular way.
496 * signum is the signal we want to forward
499 void graceful_shutdown(int signum) {
500 // kill(current_child, signum);
505 lprintf (1, "bye going down gracefull.[%d][%s]\n", signum, wd);
517 * Start running as a daemon.
519 void start_daemon(char *pid_file)
528 /* Close stdin/stdout/stderr and replace them with /dev/null.
529 * We don't just call close() because we don't want these fd's
530 * to be reused for other files.
534 signal(SIGHUP, SIG_IGN);
535 signal(SIGINT, SIG_IGN);
536 signal(SIGQUIT, SIG_IGN);
545 freopen("/dev/null", "r", stdin);
546 freopen("/dev/null", "w", stdout);
547 freopen("/dev/null", "w", stderr);
548 signal(SIGTERM, graceful_shutdown_watcher);
549 signal(SIGHUP, graceful_shutdown_watcher);
552 current_child = fork();
555 if (current_child < 0) {
557 ShutDownLibCitadel ();
561 else if (current_child == 0) { // child process
562 // signal(SIGTERM, graceful_shutdown);
563 signal(SIGHUP, graceful_shutdown);
565 return; /* continue starting webcit. */
568 else { // watcher process
569 // signal(SIGTERM, SIG_IGN);
570 // signal(SIGHUP, SIG_IGN);
572 fp = fopen(pid_file, "w");
574 fprintf(fp, "%d\n", getpid());
578 waitpid(current_child, &status, 0);
583 /* Did the main process exit with an actual exit code? */
584 if (WIFEXITED(status)) {
586 /* Exit code 0 means the watcher should exit */
587 if (WEXITSTATUS(status) == 0) {
591 /* Exit code 101-109 means the watcher should exit */
592 else if ( (WEXITSTATUS(status) >= 101) && (WEXITSTATUS(status) <= 109) ) {
596 /* Any other exit code means we should restart. */
602 /* Any other type of termination (signals, etc.) should also restart. */
607 } while (do_restart);
612 ShutDownLibCitadel ();
613 exit(WEXITSTATUS(status));
617 * Spawn an additional worker thread into the pool.
619 void spawn_another_worker_thread()
621 pthread_t SessThread; /* Thread descriptor */
622 pthread_attr_t attr; /* Thread attributes */
625 lprintf(3, "Creating a new thread\n");
627 /* set attributes for the new thread */
628 pthread_attr_init(&attr);
629 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
632 * Our per-thread stacks need to be bigger than the default size, otherwise
633 * the MIME parser crashes on FreeBSD, and the IMAP service crashes on
636 if ((ret = pthread_attr_setstacksize(&attr, 1024 * 1024))) {
637 lprintf(1, "pthread_attr_setstacksize: %s\n",
639 pthread_attr_destroy(&attr);
642 /* now create the thread */
643 if (pthread_create(&SessThread, &attr,
644 (void *(*)(void *)) worker_entry, NULL)
646 lprintf(1, "Can't create thread: %s\n", strerror(errno));
649 /* free up the attributes */
650 pthread_attr_destroy(&attr);
653 //#define DBG_PRINNT_HOOKS_AT_START
654 #ifdef DBG_PRINNT_HOOKS_AT_START
655 const char foobuf[32];
656 const char *nix(void *vptr) {snprintf(foobuf, 32, "%0x", (long) vptr); return foobuf;}
658 void InitTemplateCache(void);
659 extern int LoadTemplates;
660 extern void LoadZoneFiles(void);
663 * Here's where it all begins.
665 int main(int argc, char **argv)
667 pthread_t SessThread; /* Thread descriptor */
668 pthread_attr_t attr; /* Thread attributes */
669 int a, i; /* General-purpose variables */
670 char tracefile[PATH_MAX];
671 char ip_addr[256]="0.0.0.0";
672 char dirbuffer[PATH_MAX]="";
675 int home_specified=0;
676 char relhome[PATH_MAX]="";
677 char webcitdir[PATH_MAX] = DATADIR;
678 char *pidfile = NULL;
684 #endif /* ENABLE_NLS */
685 char uds_listen_path[PATH_MAX]; /* listen on a unix domain socket? */
687 HandlerHash = NewHash(1, NULL);
688 PreferenceHooks = NewHash(1, NULL);
689 WirelessTemplateCache = NewHash(1, NULL);
690 WirelessLocalTemplateCache = NewHash(1, NULL);
691 LocalTemplateCache = NewHash(1, NULL);
692 TemplateCache = NewHash(1, NULL);
693 GlobalNS = NewHash(1, NULL);
694 Iterators = NewHash(1, NULL);
695 Contitionals = NewHash(1, NULL);
696 MsgHeaderHandler = NewHash(1, NULL);
697 MimeRenderHandler = NewHash(1, NULL);
702 #ifdef DBG_PRINNT_HOOKS_AT_START
703 dbg_PrintHash(HandlerHash, nix, NULL);
706 /* Ensure that we are linked to the correct version of libcitadel */
707 if (libcitadel_version_number() < LIBCITADEL_VERSION_NUMBER) {
708 fprintf(stderr, " You are running libcitadel version %d.%02d\n",
709 (libcitadel_version_number() / 100), (libcitadel_version_number() % 100));
710 fprintf(stderr, "WebCit was compiled against version %d.%02d\n",
711 (LIBCITADEL_VERSION_NUMBER / 100), (LIBCITADEL_VERSION_NUMBER % 100));
715 strcpy(uds_listen_path, "");
717 /* Parse command line */
719 while ((a = getopt(argc, argv, "h:i:p:t:T:x:dD:cfs")) != EOF)
721 while ((a = getopt(argc, argv, "h:i:p:t:T:x:dD:cf")) != EOF)
725 hdir = strdup(optarg);
727 if (!relh) safestrncpy(webcitdir, hdir,
730 safestrncpy(relhome, relhome,
732 /* free(hdir); TODO: SHOULD WE DO THIS? */
737 running_as_daemon = 1;
740 pidfile = strdup(optarg);
741 running_as_daemon = 1;
744 safestrncpy(ip_addr, optarg, sizeof ip_addr);
747 http_port = atoi(optarg);
748 if (http_port == 0) {
749 safestrncpy(uds_listen_path, optarg, sizeof uds_listen_path);
753 safestrncpy(tracefile, optarg, sizeof tracefile);
754 freopen(tracefile, "w", stdout);
755 freopen(tracefile, "w", stderr);
756 freopen(tracefile, "r", stdin);
759 LoadTemplates = atoi(optarg);
762 verbosity = atoi(optarg);
768 server_cookie = malloc(256);
769 if (server_cookie != NULL) {
770 safestrncpy(server_cookie,
771 "Set-cookie: wcserver=",
774 (&server_cookie[strlen(server_cookie)],
776 lprintf(2, "gethostname: %s\n",
786 fprintf(stderr, "usage: webcit "
787 "[-i ip_addr] [-p http_port] "
788 "[-t tracefile] [-c] [-f] "
789 "[-T Templatedebuglevel] "
794 "[remotehost [remoteport]]\n");
799 ctdlhost = argv[optind];
801 ctdlport = argv[optind];
804 /* daemonize, if we were asked to */
805 if (running_as_daemon) {
806 start_daemon(pidfile);
809 /// signal(SIGTERM, graceful_shutdown);
810 signal(SIGHUP, graceful_shutdown);
813 /* Tell 'em who's in da house */
814 lprintf(1, PACKAGE_STRING "\n");
815 lprintf(1, "Copyright (C) 1996-2008 by the Citadel development team.\n"
816 "This software is distributed under the terms of the "
817 "GNU General Public License.\n\n"
821 /* initialize the International Bright Young Thing */
823 initialize_locales();
825 locale = setlocale(LC_ALL, "");
827 mo = malloc(strlen(webcitdir) + 20);
828 lprintf(9, "Message catalog directory: %s\n", bindtextdomain("webcit", LOCALEDIR"/locale"));
830 lprintf(9, "Text domain: %s\n", textdomain("webcit"));
831 lprintf(9, "Text domain Charset: %s\n", bind_textdomain_codeset("webcit","UTF8"));
836 /* calculate all our path on a central place */
837 /* where to keep our config */
839 #define COMPUTE_DIRECTORY(SUBDIR) memcpy(dirbuffer,SUBDIR, sizeof dirbuffer);\
840 snprintf(SUBDIR,sizeof SUBDIR, "%s%s%s%s%s%s%s", \
841 (home&!relh)?webcitdir:basedir, \
842 ((basedir!=webcitdir)&(home&!relh))?basedir:"/", \
843 ((basedir!=webcitdir)&(home&!relh))?"/":"", \
845 (relhome[0]!='\0')?"/":"",\
847 (dirbuffer[0]!='\0')?"/":"");
849 COMPUTE_DIRECTORY(socket_dir);
850 basedir=WWWDIR "/static";
851 COMPUTE_DIRECTORY(static_dir);
852 basedir=WWWDIR "/static/icons";
853 COMPUTE_DIRECTORY(static_icon_dir);
854 basedir=WWWDIR "/static.local";
855 COMPUTE_DIRECTORY(static_local_dir);
857 snprintf(file_crpt_file_key,
858 sizeof file_crpt_file_key,
861 snprintf(file_crpt_file_csr,
862 sizeof file_crpt_file_csr,
865 snprintf(file_crpt_file_cer,
866 sizeof file_crpt_file_cer,
870 /* we should go somewhere we can leave our coredump, if enabled... */
871 lprintf(9, "Changing directory to %s\n", socket_dir);
872 if (chdir(webcitdir) != 0) {
875 LoadIconDir(static_icon_dir);
878 initialise_modules();
879 initialize_viewdefs();
882 /* Tell libical to return an error instead of aborting if it sees badly formed iCalendar data. */
883 icalerror_errors_are_fatal = 0;
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(&Contitionals);
976 DeleteHash(&MsgHeaderHandler);
988 * Entry point for worker threads
990 void worker_entry(void)
994 int fail_this_transaction = 0;
997 fd_set readset, tempset;
1002 FD_SET(msock, &readset);
1005 /* Only one thread can accept at a time */
1006 fail_this_transaction = 0;
1010 ret = -1; /* just one at once should select... */
1011 begin_critical_section(S_SELECT);
1014 if (msock > 0) FD_SET(msock, &tempset);
1017 if (msock > 0) ret = select(msock+1, &tempset, NULL, NULL, &tv);
1018 end_critical_section(S_SELECT);
1019 if ((ret < 0) && (errno != EINTR) && (errno != EAGAIN))
1020 {// EINTR and EAGAIN are thrown but not of interest.
1021 lprintf(2, "accept() failed:%d %s\n",
1022 errno, strerror(errno));
1024 else if ((ret > 0) && (msock > 0) && FD_ISSET(msock, &tempset))
1025 {// Successfully selected, and still not shutting down? Accept!
1026 ssock = accept(msock, NULL, 0);
1029 } while ((msock > 0) && (ssock < 0) && (time_to_die == 0));
1031 if ((msock == -1)||(time_to_die))
1032 {// ok, we're going down.
1035 /* the first to come here will have to do the cleanup.
1036 * make shure its realy just one.
1038 begin_critical_section(S_SHUTDOWN);
1044 end_critical_section(S_SHUTDOWN);
1046 {// we're the one to cleanup the mess.
1047 lprintf(2, "I'm master shutdown: tagging sessions to be killed.\n");
1048 shutdown_sessions();
1049 lprintf(2, "master shutdown: waiting for others\n");
1050 sleeeeeeeeeep(1); // wait so some others might finish...
1051 lprintf(2, "master shutdown: cleaning up sessions\n");
1053 lprintf(2, "master shutdown: cleaning up libical\n");
1057 lprintf(2, "master shutdown exiting!.\n");
1062 if (ssock < 0 ) continue;
1065 if (ssock > 0) close (ssock);
1066 lprintf(2, "inbetween.");
1068 } else { // Got it? do some real work!
1069 /* Set the SO_REUSEADDR socket option */
1071 setsockopt(ssock, SOL_SOCKET, SO_REUSEADDR,
1074 /* If we are an HTTPS server, go crypto now. */
1077 if (starttls(ssock) != 0) {
1078 fail_this_transaction = 1;
1084 if (fail_this_transaction == 0) {
1086 /* Perform an HTTP transaction... */
1087 context_loop(&ssock);
1089 /* Shut down SSL/TLS if required... */
1096 /* ...and close the socket. */
1098 lingering_close(ssock);
1103 } while (!time_to_die);
1105 lprintf (1, "bye\n");
1110 * print log messages
1111 * logs to stderr if loglevel is lower than the verbosity set at startup
1113 * loglevel level of the message
1114 * format the printf like format string
1115 * ... the strings to put into format
1117 int lprintf(int loglevel, const char *format, ...)
1121 if (loglevel <= verbosity) {
1122 va_start(ap, format);
1123 vfprintf(stderr, format, ap);
1132 * print the actual stack frame.
1134 void wc_backtrace(void)
1136 #ifdef HAVE_BACKTRACE
1137 void *stack_frames[50];
1142 size = backtrace(stack_frames, sizeof(stack_frames) / sizeof(void*));
1143 strings = backtrace_symbols(stack_frames, size);
1144 for (i = 0; i < size; i++) {
1145 if (strings != NULL)
1146 lprintf(1, "%s\n", strings[i]);
1148 lprintf(1, "%p\n", stack_frames[i]);