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 ((retval >= 0) && (StrLength(Buf) < bytes))
207 retval = client_read_sslbuffer(Buf, timeout);
209 StrBufAppendBuf(Target, Buf, 0); /// todo: Buf > bytes?
213 lprintf(2, "client_read_ssl() failed\n");
219 if (StrLength(Buf) > 0) {//// todo: what if Buf > bytes?
220 StrBufAppendBuf(Target, Buf, 0);
222 retval = StrBufReadBLOB(Target,
224 (StrLength(Target) > 0),
225 bytes - StrLength(Target),
228 lprintf(2, "client_read() failed: %s\n",
234 write(2, "\033[32m", 5);
235 write(2, buf, bytes);
236 write(2, "\033[30m", 5);
243 * Begin buffering HTTP output so we can transmit it all in one write operation later.
245 void begin_burst(void)
247 if (WC->WBuf == NULL)
248 WC->WBuf = NewStrBufPlain(NULL, 32768);
253 * Finish buffering HTTP output. [Compress using zlib and] output with a Content-Length: header.
257 struct wcsession *WCC = WC;
258 const char *ptr, *eptr;
265 /* Perform gzip compression, if enabled and supported by client */
266 if ((WCC->gzip_ok) && CompressBuffer(WCC->WBuf))
268 hprintf("Content-encoding: gzip\r\n");
270 #endif /* HAVE_ZLIB */
272 hprintf("Content-length: %d\r\n\r\n", StrLength(WCC->WBuf));
274 ptr = ChrPtr(WCC->HBuf);
275 count = StrLength(WCC->HBuf);
280 client_write_ssl(WCC->HBuf);
281 client_write_ssl(WCC->WBuf);
289 write(2, "\033[34m", 5);
290 write(2, ptr, StrLength(WCC->WBuf));
291 write(2, "\033[30m", 5);
293 fdflags = fcntl(WC->http_sock, F_GETFL);
296 if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
298 FD_SET(WCC->http_sock, &wset);
299 if (select(WCC->http_sock + 1, NULL, &wset, NULL, NULL) == -1) {
300 lprintf(2, "client_write: Socket select failed (%s)\n", strerror(errno));
305 if ((res = write(WCC->http_sock,
308 lprintf(2, "client_write: Socket write failed (%s)\n", strerror(errno));
316 ptr = ChrPtr(WCC->WBuf);
317 count = StrLength(WCC->WBuf);
322 write(2, "\033[34m", 5);
323 write(2, ptr, StrLength(WCC->WBuf));
324 write(2, "\033[30m", 5);
328 if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
330 FD_SET(WCC->http_sock, &wset);
331 if (select(WCC->http_sock + 1, NULL, &wset, NULL, NULL) == -1) {
332 lprintf(2, "client_write: Socket select failed (%s)\n", strerror(errno));
337 if ((res = write(WCC->http_sock,
340 lprintf(2, "client_write: Socket write failed (%s)\n", strerror(errno));
348 return StrLength(WCC->WBuf);
354 * Read data from the client socket with default timeout.
355 * (This is implemented in terms of client_read_to() and could be
356 * justifiably moved out of sysdep.c)
358 * sock the socket fd to read from
359 * buf the buffer to write to
360 * bytes Number of bytes to read
362 int client_read(int *sock, StrBuf *Target, StrBuf *buf, int bytes)
364 return (client_read_to(sock, Target, buf, bytes, SLEEPING));
369 * Get a LF-terminated line of text from the client.
370 * (This is implemented in terms of client_read() and could be
371 * justifiably moved out of sysdep.c)
373 * sock socket fd to get client line from
374 * buf buffer to write read data to
375 * bufsiz how many bytes to read
377 * returns the number of bytes read
379 /////int client_getln(int *sock, char *buf, int bufsiz)
383 ///// /* Read one character at a time.*/
384 ///// for (i = 0; *sock > 0; i++) {
385 ///// retval = client_read(sock, &buf[i], 1);
386 ///// if (retval < 0)
388 ///// if (retval != 1 || buf[i] == '\n' || i == (bufsiz-1))
390 ///// if ( (!isspace(buf[i])) && (!isprint(buf[i])) ) {
391 ///// /* Non printable character recieved from client */
396 ///// /* If we got a long line, discard characters until the newline. */
397 ///// if (i == (bufsiz-1))
398 ///// while (buf[i] != '\n' && retval == 1)
399 ///// retval = client_read(sock, &buf[i], 1);
402 ///// * Strip any trailing non-printable characters.
405 ///// while ((i > 0) && (!isprint(buf[i - 1]))) {
408 ///// return (retval);
412 * Shut us down the regular way.
413 * signum is the signal we want to forward
416 void graceful_shutdown_watcher(int signum) {
417 lprintf (1, "bye; shutting down watcher.");
418 kill(current_child, signum);
419 if (signum != SIGHUP)
424 int ClientGetLine(int *sock, StrBuf *Target, StrBuf *CLineBuf)
426 const char *Error, *pch, *pchs;
427 int rlen, len, retval = 0;
430 if (StrLength(CLineBuf) > 0) {
431 pchs = ChrPtr(CLineBuf);
432 pch = strchr(pchs, '\n');
436 if (len > 0 && (*(pch - 1) == '\r') )
438 StrBufSub(Target, CLineBuf, 0, len - rlen);
439 StrBufCutLeft(CLineBuf, len + 1);
444 while ((retval >= 0) &&
445 (pchs = ChrPtr(CLineBuf),
446 pch = strchr(pchs, '\n'),
448 retval = client_read_sslbuffer(CLineBuf, SLEEPING);
449 if ((retval > 0) && (pch != NULL)) {
452 if (len > 0 && (*(pch - 1) == '\r') )
454 StrBufSub(Target, CLineBuf, 0, len - rlen);
455 StrBufCutLeft(CLineBuf, len + 1);
463 return StrBufTCP_read_buffered_line(Target,
474 * Shut us down the regular way.
475 * signum is the signal we want to forward
478 void graceful_shutdown(int signum) {
479 // kill(current_child, signum);
484 lprintf (1, "bye going down gracefull.[%d][%s]\n", signum, wd);
496 * Start running as a daemon.
498 void start_daemon(char *pid_file)
507 /* Close stdin/stdout/stderr and replace them with /dev/null.
508 * We don't just call close() because we don't want these fd's
509 * to be reused for other files.
513 signal(SIGHUP, SIG_IGN);
514 signal(SIGINT, SIG_IGN);
515 signal(SIGQUIT, SIG_IGN);
524 freopen("/dev/null", "r", stdin);
525 freopen("/dev/null", "w", stdout);
526 freopen("/dev/null", "w", stderr);
527 signal(SIGTERM, graceful_shutdown_watcher);
528 signal(SIGHUP, graceful_shutdown_watcher);
531 current_child = fork();
534 if (current_child < 0) {
536 ShutDownLibCitadel ();
540 else if (current_child == 0) { // child process
541 // signal(SIGTERM, graceful_shutdown);
542 signal(SIGHUP, graceful_shutdown);
544 return; /* continue starting webcit. */
547 else { // watcher process
548 // signal(SIGTERM, SIG_IGN);
549 // signal(SIGHUP, SIG_IGN);
551 fp = fopen(pid_file, "w");
553 fprintf(fp, "%d\n", getpid());
557 waitpid(current_child, &status, 0);
562 /* Did the main process exit with an actual exit code? */
563 if (WIFEXITED(status)) {
565 /* Exit code 0 means the watcher should exit */
566 if (WEXITSTATUS(status) == 0) {
570 /* Exit code 101-109 means the watcher should exit */
571 else if ( (WEXITSTATUS(status) >= 101) && (WEXITSTATUS(status) <= 109) ) {
575 /* Any other exit code means we should restart. */
581 /* Any other type of termination (signals, etc.) should also restart. */
586 } while (do_restart);
591 ShutDownLibCitadel ();
592 exit(WEXITSTATUS(status));
596 * Spawn an additional worker thread into the pool.
598 void spawn_another_worker_thread()
600 pthread_t SessThread; /* Thread descriptor */
601 pthread_attr_t attr; /* Thread attributes */
604 lprintf(3, "Creating a new thread\n");
606 /* set attributes for the new thread */
607 pthread_attr_init(&attr);
608 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
611 * Our per-thread stacks need to be bigger than the default size, otherwise
612 * the MIME parser crashes on FreeBSD, and the IMAP service crashes on
615 if ((ret = pthread_attr_setstacksize(&attr, 1024 * 1024))) {
616 lprintf(1, "pthread_attr_setstacksize: %s\n",
618 pthread_attr_destroy(&attr);
621 /* now create the thread */
622 if (pthread_create(&SessThread, &attr,
623 (void *(*)(void *)) worker_entry, NULL)
625 lprintf(1, "Can't create thread: %s\n", strerror(errno));
628 /* free up the attributes */
629 pthread_attr_destroy(&attr);
632 //#define DBG_PRINNT_HOOKS_AT_START
633 #ifdef DBG_PRINNT_HOOKS_AT_START
634 const char foobuf[32];
635 const char *nix(void *vptr) {snprintf(foobuf, 32, "%0x", (long) vptr); return foobuf;}
637 void InitTemplateCache(void);
638 extern int LoadTemplates;
639 extern void LoadZoneFiles(void);
642 * Here's where it all begins.
644 int main(int argc, char **argv)
646 pthread_t SessThread; /* Thread descriptor */
647 pthread_attr_t attr; /* Thread attributes */
648 int a, i; /* General-purpose variables */
649 char tracefile[PATH_MAX];
650 char ip_addr[256]="0.0.0.0";
651 char dirbuffer[PATH_MAX]="";
654 int home_specified=0;
655 char relhome[PATH_MAX]="";
656 char webcitdir[PATH_MAX] = DATADIR;
657 char *pidfile = NULL;
663 #endif /* ENABLE_NLS */
664 char uds_listen_path[PATH_MAX]; /* listen on a unix domain socket? */
666 HandlerHash = NewHash(1, NULL);
667 PreferenceHooks = NewHash(1, NULL);
668 WirelessTemplateCache = NewHash(1, NULL);
669 WirelessLocalTemplateCache = NewHash(1, NULL);
670 LocalTemplateCache = NewHash(1, NULL);
671 TemplateCache = NewHash(1, NULL);
672 GlobalNS = NewHash(1, NULL);
673 Iterators = NewHash(1, NULL);
674 Contitionals = NewHash(1, NULL);
678 #ifdef DBG_PRINNT_HOOKS_AT_START
679 dbg_PrintHash(HandlerHash, nix, NULL);
682 /* Ensure that we are linked to the correct version of libcitadel */
683 if (libcitadel_version_number() < LIBCITADEL_VERSION_NUMBER) {
684 fprintf(stderr, " You are running libcitadel version %d.%02d\n",
685 (libcitadel_version_number() / 100), (libcitadel_version_number() % 100));
686 fprintf(stderr, "WebCit was compiled against version %d.%02d\n",
687 (LIBCITADEL_VERSION_NUMBER / 100), (LIBCITADEL_VERSION_NUMBER % 100));
691 strcpy(uds_listen_path, "");
693 /* Parse command line */
695 while ((a = getopt(argc, argv, "h:i:p:t:T:x:dD:cfs")) != EOF)
697 while ((a = getopt(argc, argv, "h:i:p:t:T:x:dD:cf")) != EOF)
701 hdir = strdup(optarg);
703 if (!relh) safestrncpy(webcitdir, hdir,
706 safestrncpy(relhome, relhome,
708 /* free(hdir); TODO: SHOULD WE DO THIS? */
713 running_as_daemon = 1;
716 pidfile = strdup(optarg);
717 running_as_daemon = 1;
720 safestrncpy(ip_addr, optarg, sizeof ip_addr);
723 http_port = atoi(optarg);
724 if (http_port == 0) {
725 safestrncpy(uds_listen_path, optarg, sizeof uds_listen_path);
729 safestrncpy(tracefile, optarg, sizeof tracefile);
730 freopen(tracefile, "w", stdout);
731 freopen(tracefile, "w", stderr);
732 freopen(tracefile, "r", stdin);
735 LoadTemplates = atoi(optarg);
738 verbosity = atoi(optarg);
744 server_cookie = malloc(256);
745 if (server_cookie != NULL) {
746 safestrncpy(server_cookie,
747 "Set-cookie: wcserver=",
750 (&server_cookie[strlen(server_cookie)],
752 lprintf(2, "gethostname: %s\n",
762 fprintf(stderr, "usage: webcit "
763 "[-i ip_addr] [-p http_port] "
764 "[-t tracefile] [-c] [-f] "
765 "[-T Templatedebuglevel] "
770 "[remotehost [remoteport]]\n");
775 ctdlhost = argv[optind];
777 ctdlport = argv[optind];
780 /* daemonize, if we were asked to */
781 if (running_as_daemon) {
782 start_daemon(pidfile);
785 /// signal(SIGTERM, graceful_shutdown);
786 signal(SIGHUP, graceful_shutdown);
789 /* Tell 'em who's in da house */
790 lprintf(1, PACKAGE_STRING "\n");
791 lprintf(1, "Copyright (C) 1996-2008 by the Citadel development team.\n"
792 "This software is distributed under the terms of the "
793 "GNU General Public License.\n\n"
797 /* initialize the International Bright Young Thing */
799 initialize_locales();
801 locale = setlocale(LC_ALL, "");
803 mo = malloc(strlen(webcitdir) + 20);
804 lprintf(9, "Message catalog directory: %s\n", bindtextdomain("webcit", LOCALEDIR"/locale"));
806 lprintf(9, "Text domain: %s\n", textdomain("webcit"));
807 lprintf(9, "Text domain Charset: %s\n", bind_textdomain_codeset("webcit","UTF8"));
812 /* calculate all our path on a central place */
813 /* where to keep our config */
815 #define COMPUTE_DIRECTORY(SUBDIR) memcpy(dirbuffer,SUBDIR, sizeof dirbuffer);\
816 snprintf(SUBDIR,sizeof SUBDIR, "%s%s%s%s%s%s%s", \
817 (home&!relh)?webcitdir:basedir, \
818 ((basedir!=webcitdir)&(home&!relh))?basedir:"/", \
819 ((basedir!=webcitdir)&(home&!relh))?"/":"", \
821 (relhome[0]!='\0')?"/":"",\
823 (dirbuffer[0]!='\0')?"/":"");
825 COMPUTE_DIRECTORY(socket_dir);
826 basedir=WWWDIR "/static";
827 COMPUTE_DIRECTORY(static_dir);
828 basedir=WWWDIR "/static/icons";
829 COMPUTE_DIRECTORY(static_icon_dir);
830 basedir=WWWDIR "/static.local";
831 COMPUTE_DIRECTORY(static_local_dir);
833 snprintf(file_crpt_file_key,
834 sizeof file_crpt_file_key,
837 snprintf(file_crpt_file_csr,
838 sizeof file_crpt_file_csr,
841 snprintf(file_crpt_file_cer,
842 sizeof file_crpt_file_cer,
846 /* we should go somewhere we can leave our coredump, if enabled... */
847 lprintf(9, "Changing directory to %s\n", socket_dir);
848 if (chdir(webcitdir) != 0) {
851 LoadIconDir(static_icon_dir);
854 initialise_modules();
855 initialize_viewdefs();
858 /* Tell libical to return an error instead of aborting if it sees badly formed iCalendar data. */
859 icalerror_errors_are_fatal = 0;
862 * Set up a place to put thread-specific data.
863 * We only need a single pointer per thread - it points to the
864 * wcsession struct to which the thread is currently bound.
866 if (pthread_key_create(&MyConKey, NULL) != 0) {
867 lprintf(1, "Can't create TSD key: %s\n", strerror(errno));
869 InitialiseSemaphores ();
872 * Set up a place to put thread-specific SSL data.
873 * We don't stick this in the wcsession struct because SSL starts
874 * up before the session is bound, and it gets torn down between
878 if (pthread_key_create(&ThreadSSL, NULL) != 0) {
879 lprintf(1, "Can't create TSD key: %s\n", strerror(errno));
884 * Bind the server to our favorite port.
885 * There is no need to check for errors, because ig_tcp_server()
886 * exits if it doesn't succeed.
889 if (!IsEmptyStr(uds_listen_path)) {
890 lprintf(2, "Attempting to create listener socket at %s...\n", uds_listen_path);
891 msock = ig_uds_server(uds_listen_path, LISTEN_QUEUE_LENGTH);
894 lprintf(2, "Attempting to bind to port %d...\n", http_port);
895 msock = ig_tcp_server(ip_addr, http_port, LISTEN_QUEUE_LENGTH);
898 lprintf(2, "Listening on socket %d\n", msock);
899 signal(SIGPIPE, SIG_IGN);
901 pthread_mutex_init(&SessionListMutex, NULL);
904 * Start up the housekeeping thread
906 pthread_attr_init(&attr);
907 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
908 pthread_create(&SessThread, &attr,
909 (void *(*)(void *)) housekeeping_loop, NULL);
913 * If this is an HTTPS server, fire up SSL
921 /* Start a few initial worker threads */
922 for (i = 0; i < (MIN_WORKER_THREADS); ++i) {
923 spawn_another_worker_thread();
926 /* now the original thread becomes another worker */
928 ShutDownLibCitadel ();
929 DeleteHash(&HandlerHash);
930 DeleteHash(&PreferenceHooks);
935 void ShutDownWebcit(void)
937 DeleteHash(&ZoneHash);
938 free_zone_directory ();
939 icaltimezone_release_zone_tab ();
940 icalmemory_free_ring ();
941 ShutDownLibCitadel ();
942 DeleteHash(&HandlerHash);
943 DeleteHash(&PreferenceHooks);
944 DeleteHash(&GlobalNS);
945 DeleteHash(&WirelessTemplateCache);
946 DeleteHash(&WirelessLocalTemplateCache);
947 DeleteHash(&TemplateCache);
948 DeleteHash(&LocalTemplateCache);
949 DeleteHash(&Iterators);
950 DeleteHash(&Contitionals);
962 * Entry point for worker threads
964 void worker_entry(void)
968 int fail_this_transaction = 0;
971 fd_set readset, tempset;
976 FD_SET(msock, &readset);
979 /* Only one thread can accept at a time */
980 fail_this_transaction = 0;
984 ret = -1; /* just one at once should select... */
985 begin_critical_section(S_SELECT);
988 if (msock > 0) FD_SET(msock, &tempset);
991 if (msock > 0) ret = select(msock+1, &tempset, NULL, NULL, &tv);
992 end_critical_section(S_SELECT);
993 if ((ret < 0) && (errno != EINTR) && (errno != EAGAIN))
994 {// EINTR and EAGAIN are thrown but not of interest.
995 lprintf(2, "accept() failed:%d %s\n",
996 errno, strerror(errno));
998 else if ((ret > 0) && (msock > 0) && FD_ISSET(msock, &tempset))
999 {// Successfully selected, and still not shutting down? Accept!
1000 ssock = accept(msock, NULL, 0);
1003 } while ((msock > 0) && (ssock < 0) && (time_to_die == 0));
1005 if ((msock == -1)||(time_to_die))
1006 {// ok, we're going down.
1009 /* the first to come here will have to do the cleanup.
1010 * make shure its realy just one.
1012 begin_critical_section(S_SHUTDOWN);
1018 end_critical_section(S_SHUTDOWN);
1020 {// we're the one to cleanup the mess.
1021 lprintf(2, "I'm master shutdown: tagging sessions to be killed.\n");
1022 shutdown_sessions();
1023 lprintf(2, "master shutdown: waiting for others\n");
1024 sleeeeeeeeeep(1); // wait so some others might finish...
1025 lprintf(2, "master shutdown: cleaning up sessions\n");
1027 lprintf(2, "master shutdown: cleaning up libical\n");
1031 lprintf(2, "master shutdown exiting!.\n");
1036 if (ssock < 0 ) continue;
1039 if (ssock > 0) close (ssock);
1040 lprintf(2, "inbetween.");
1042 } else { // Got it? do some real work!
1043 /* Set the SO_REUSEADDR socket option */
1045 setsockopt(ssock, SOL_SOCKET, SO_REUSEADDR,
1048 /* If we are an HTTPS server, go crypto now. */
1051 if (starttls(ssock) != 0) {
1052 fail_this_transaction = 1;
1058 if (fail_this_transaction == 0) {
1060 /* Perform an HTTP transaction... */
1061 context_loop(&ssock);
1063 /* Shut down SSL/TLS if required... */
1070 /* ...and close the socket. */
1072 lingering_close(ssock);
1077 } while (!time_to_die);
1079 lprintf (1, "bye\n");
1084 * print log messages
1085 * logs to stderr if loglevel is lower than the verbosity set at startup
1087 * loglevel level of the message
1088 * format the printf like format string
1089 * ... the strings to put into format
1091 int lprintf(int loglevel, const char *format, ...)
1095 if (loglevel <= verbosity) {
1096 va_start(ap, format);
1097 vfprintf(stderr, format, ap);
1106 * print the actual stack frame.
1108 void wc_backtrace(void)
1110 #ifdef HAVE_BACKTRACE
1111 void *stack_frames[50];
1116 size = backtrace(stack_frames, sizeof(stack_frames) / sizeof(void*));
1117 strings = backtrace_symbols(stack_frames, size);
1118 for (i = 0; i < size; i++) {
1119 if (strings != NULL)
1120 lprintf(1, "%s\n", strings[i]);
1122 lprintf(1, "%p\n", stack_frames[i]);