* #if out the printing of the handler hash at system start; if s.b. needs it for...
[citadel.git] / webcit / webserver.c
1 /*
2  * $Id$
3  *
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.
7  *
8  */
9
10 #include "webcit.h"
11 #include "webserver.h"
12
13 #if HAVE_BACKTRACE
14 #include <execinfo.h>
15 #endif
16 #include "modules_init.h"
17 #ifndef HAVE_SNPRINTF
18 int vsnprintf(char *buf, size_t max, const char *fmt, va_list argp);
19 #endif
20
21 int verbosity = 9;              /* Logging level */
22 int msock;                      /* master listening socket */
23 int is_https = 0;               /* Nonzero if I am an HTTPS service */
24 int follow_xff = 0;             /* Follow X-Forwarded-For: header */
25 int home_specified = 0;         /* did the user specify a homedir? */
26 int time_to_die = 0;            /* Nonzero if server is shutting down */
27 extern void *context_loop(int);
28 extern void *housekeeping_loop(void);
29 extern pthread_mutex_t SessionListMutex;
30 extern pthread_key_t MyConKey;
31
32
33 char ctdl_key_dir[PATH_MAX]=SSL_DIR;
34 char file_crpt_file_key[PATH_MAX]="";
35 char file_crpt_file_csr[PATH_MAX]="";
36 char file_crpt_file_cer[PATH_MAX]="";
37
38 char socket_dir[PATH_MAX];                      /* where to talk to our citadel server */
39 static const char editor_absolut_dir[PATH_MAX]=EDITORDIR;       /* nailed to what configure gives us. */
40 static char static_dir[PATH_MAX];               /* calculated on startup */
41 static char static_local_dir[PATH_MAX];         /* calculated on startup */
42 static char static_icon_dir[PATH_MAX];          /* where should we find our mime icons? */
43 char  *static_dirs[]={                          /* needs same sort order as the web mapping */
44         (char*)static_dir,                      /* our templates on disk */
45         (char*)static_local_dir,                /* user provided templates disk */
46         (char*)editor_absolut_dir,              /* the editor on disk */
47         (char*)static_icon_dir                  /* our icons... */
48 };
49
50 /*
51  * Subdirectories from which the client may request static content
52  *
53  * (If you add more, remember to increment 'ndirs' below)
54  */
55 char *static_content_dirs[] = {
56         "static",                     /* static templates */
57         "static.local",               /* site local static templates */
58         "tiny_mce"                    /* rich text editor */
59 };
60
61 int ndirs=3;
62
63
64 char *server_cookie = NULL;     /* our Cookie connection to the client */
65 int http_port = PORT_NUM;       /* Port to listen on */
66 char *ctdlhost = DEFAULT_HOST;  /* our name */
67 char *ctdlport = DEFAULT_PORT;  /* our Port */
68 int setup_wizard = 0;           /* should we run the setup wizard? \todo */
69 char wizard_filename[PATH_MAX]; /* where's the setup wizard? */
70 int running_as_daemon = 0;      /* should we deamonize on startup? */
71
72
73 /* 
74  * This is a generic function to set up a master socket for listening on
75  * a TCP port.  The server shuts down if the bind fails.
76  *
77  * ip_addr      IP address to bind
78  * port_number  port number to bind
79  * queue_len    number of incoming connections to allow in the queue
80  */
81 int ig_tcp_server(char *ip_addr, int port_number, int queue_len)
82 {
83         struct sockaddr_in sin;
84         int s, i;
85
86         memset(&sin, 0, sizeof(sin));
87         sin.sin_family = AF_INET;
88         if (ip_addr == NULL) {
89                 sin.sin_addr.s_addr = INADDR_ANY;
90         } else {
91                 sin.sin_addr.s_addr = inet_addr(ip_addr);
92         }
93
94         if (sin.sin_addr.s_addr == INADDR_NONE) {
95                 sin.sin_addr.s_addr = INADDR_ANY;
96         }
97
98         if (port_number == 0) {
99                 lprintf(1, "Cannot start: no port number specified.\n");
100                 exit(WC_EXIT_BIND);
101         }
102         sin.sin_port = htons((u_short) port_number);
103
104         s = socket(PF_INET, SOCK_STREAM, (getprotobyname("tcp")->p_proto));
105         if (s < 0) {
106                 lprintf(1, "Can't create a socket: %s\n", strerror(errno));
107                 exit(WC_EXIT_BIND);
108         }
109         /* Set some socket options that make sense. */
110         i = 1;
111         setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
112
113         fcntl(s, F_SETFL, O_NONBLOCK); /* maide: this statement is incorrect
114                                           there should be a preceding F_GETFL
115                                           and a bitwise OR with the previous
116                                           fd flags */
117         
118         if (bind(s, (struct sockaddr *) &sin, sizeof(sin)) < 0) {
119                 lprintf(1, "Can't bind: %s\n", strerror(errno));
120                 exit(WC_EXIT_BIND);
121         }
122         if (listen(s, queue_len) < 0) {
123                 lprintf(1, "Can't listen: %s\n", strerror(errno));
124                 exit(WC_EXIT_BIND);
125         }
126         return (s);
127 }
128
129
130
131 /*
132  * Create a Unix domain socket and listen on it
133  * sockpath - file name of the unix domain socket
134  * queue_len - Number of incoming connections to allow in the queue
135  */
136 int ig_uds_server(char *sockpath, int queue_len)
137 {
138         struct sockaddr_un addr;
139         int s;
140         int i;
141         int actual_queue_len;
142
143         actual_queue_len = queue_len;
144         if (actual_queue_len < 5) actual_queue_len = 5;
145
146         i = unlink(sockpath);
147         if (i != 0) if (errno != ENOENT) {
148                 lprintf(1, "webcit: can't unlink %s: %s\n",
149                         sockpath, strerror(errno));
150                 exit(WC_EXIT_BIND);
151         }
152
153         memset(&addr, 0, sizeof(addr));
154         addr.sun_family = AF_UNIX;
155         safestrncpy(addr.sun_path, sockpath, sizeof addr.sun_path);
156
157         s = socket(AF_UNIX, SOCK_STREAM, 0);
158         if (s < 0) {
159                 lprintf(1, "webcit: Can't create a socket: %s\n",
160                         strerror(errno));
161                 exit(WC_EXIT_BIND);
162         }
163
164         if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
165                 lprintf(1, "webcit: Can't bind: %s\n",
166                         strerror(errno));
167                 exit(WC_EXIT_BIND);
168         }
169
170         if (listen(s, actual_queue_len) < 0) {
171                 lprintf(1, "webcit: Can't listen: %s\n",
172                         strerror(errno));
173                 exit(WC_EXIT_BIND);
174         }
175
176         chmod(sockpath, 0777);
177         return(s);
178 }
179
180
181
182
183 /*
184  * Read data from the client socket.
185  *
186  * sock         socket fd to read from
187  * buf          buffer to read into 
188  * bytes        number of bytes to read
189  * timeout      Number of seconds to wait before timing out
190  *
191  * Possible return values:
192  *      1       Requested number of bytes has been read.
193  *      0       Request timed out.
194  *      -1      Connection is broken, or other error.
195  */
196 int client_read_to(int sock, char *buf, int bytes, int timeout)
197 {
198         int len, rlen;
199         fd_set rfds;
200         struct timeval tv;
201         int retval;
202
203
204 #ifdef HAVE_OPENSSL
205         if (is_https) {
206                 return (client_read_ssl(buf, bytes, timeout));
207         }
208 #endif
209
210         len = 0;
211         while (len < bytes) {
212                 FD_ZERO(&rfds);
213                 FD_SET(sock, &rfds);
214                 tv.tv_sec = timeout;
215                 tv.tv_usec = 0;
216
217                 retval = select((sock) + 1, &rfds, NULL, NULL, &tv);
218                 if (FD_ISSET(sock, &rfds) == 0) {
219                         return (0);
220                 }
221
222                 rlen = read(sock, &buf[len], bytes - len);
223
224                 if (rlen < 1) {
225                         lprintf(2, "client_read() failed: %s\n",
226                                 strerror(errno));
227                         return (-1);
228                 }
229                 len = len + rlen;
230         }
231
232 #ifdef HTTP_TRACING
233         write(2, "\033[32m", 5);
234         write(2, buf, bytes);
235         write(2, "\033[30m", 5);
236 #endif
237         return (1);
238 }
239
240 /*
241  * \brief Begin buffering HTTP output so we can transmit it all in one write operation later.
242  */
243 void begin_burst(void)
244 {
245         WC->WBuf = NewStrBufPlain(NULL, 32768);
246 }
247
248
249 /*
250  * \brief Finish buffering HTTP output.  [Compress using zlib and] output with a Content-Length: header.
251  */
252 long end_burst(void)
253 {
254         struct wcsession *WCC = WC;
255         const char *ptr, *eptr;
256         long count;
257         ssize_t res;
258         fd_set wset;
259         int fdflags;
260
261 #ifdef HAVE_ZLIB
262         /* Perform gzip compression, if enabled and supported by client */
263         if ((WCC->gzip_ok) && CompressBuffer(WCC->WBuf))
264         {
265                 hprintf("Content-encoding: gzip\r\n");
266         }
267 #endif  /* HAVE_ZLIB */
268
269         hprintf("Content-length: %d\r\n\r\n", StrLength(WCC->WBuf));
270
271         ptr = ChrPtr(WCC->HBuf);
272         count = StrLength(WCC->HBuf);
273         eptr = ptr + count;
274
275 #ifdef HAVE_OPENSSL
276         if (is_https) {
277                 client_write_ssl(ptr, StrLength(WCC->HBuf));
278                 return (count);
279         }
280 #endif
281
282         
283 #ifdef HTTP_TRACING
284         
285         write(2, "\033[34m", 5);
286         write(2, ptr, StrLength(WCC->WBuf));
287         write(2, "\033[30m", 5);
288 #endif
289         fdflags = fcntl(WC->http_sock, F_GETFL);
290
291         while (ptr < eptr) {
292                 if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
293                         FD_ZERO(&wset);
294                         FD_SET(WCC->http_sock, &wset);
295                         if (select(WCC->http_sock + 1, NULL, &wset, NULL, NULL) == -1) {
296                                 lprintf(2, "client_write: Socket select failed (%s)\n", strerror(errno));
297                                 return -1;
298                         }
299                 }
300
301                 if ((res = write(WCC->http_sock, 
302                                  ptr,
303                                  count)) == -1) {
304                         lprintf(2, "client_write: Socket write failed (%s)\n", strerror(errno));
305                         return res;
306                 }
307                 count -= res;
308                 ptr += res;
309         }
310
311         ptr = ChrPtr(WCC->WBuf);
312         count = StrLength(WCC->WBuf);
313         eptr = ptr + count;
314
315 #ifdef HAVE_OPENSSL
316         if (is_https) {
317                 client_write_ssl(ptr, StrLength(WCC->HBuf));
318                 return (count);
319         }
320 #endif
321
322 #ifdef HTTP_TRACING
323         
324         write(2, "\033[34m", 5);
325         write(2, ptr, StrLength(WCC->WBuf));
326         write(2, "\033[30m", 5);
327 #endif
328
329         while (ptr < eptr) {
330                 if ((fdflags & O_NONBLOCK) == O_NONBLOCK) {
331                         FD_ZERO(&wset);
332                         FD_SET(WCC->http_sock, &wset);
333                         if (select(WCC->http_sock + 1, NULL, &wset, NULL, NULL) == -1) {
334                                 lprintf(2, "client_write: Socket select failed (%s)\n", strerror(errno));
335                                 return -1;
336                         }
337                 }
338
339                 if ((res = write(WCC->http_sock, 
340                                  ptr,
341                                  count)) == -1) {
342                         lprintf(2, "client_write: Socket write failed (%s)\n", strerror(errno));
343                         return res;
344                 }
345                 count -= res;
346                 ptr += res;
347         }
348
349         return StrLength(WCC->WBuf);
350 }
351
352
353
354 /*
355  * \brief Read data from the client socket with default timeout.
356  * (This is implemented in terms of client_read_to() and could be
357  * justifiably moved out of sysdep.c)
358  * \param sock the socket fd to read from
359  * \param buf the buffer to write to
360  * \param bytes Number of bytes to read
361  */
362 int client_read(int sock, char *buf, int bytes)
363 {
364         return (client_read_to(sock, buf, bytes, SLEEPING));
365 }
366
367
368 /*
369  * \brief 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)
372  * \param sock socket fd to get client line from
373  * \param buf buffer to write read data to
374  * \param bufsiz how many bytes to read
375  * \return  number of bytes read???
376  */
377 int client_getln(int sock, char *buf, int bufsiz)
378 {
379         int i, retval;
380
381         /* Read one character at a time.*/
382         for (i = 0;; i++) {
383                 retval = client_read(sock, &buf[i], 1);
384                 if (retval != 1 || buf[i] == '\n' || i == (bufsiz-1))
385                         break;
386                 if ( (!isspace(buf[i])) && (!isprint(buf[i])) ) {
387                         /* Non printable character recieved from client */
388                         return(-1);
389                 }
390         }
391
392         /* If we got a long line, discard characters until the newline. */
393         if (i == (bufsiz-1))
394                 while (buf[i] != '\n' && retval == 1)
395                         retval = client_read(sock, &buf[i], 1);
396
397         /*
398          * Strip any trailing non-printable characters.
399          */
400         buf[i] = 0;
401         while ((i > 0) && (!isprint(buf[i - 1]))) {
402                 buf[--i] = 0;
403         }
404         return (retval);
405 }
406
407 /*
408  * \brief Shut us down the regular way.
409  * \param signum the signal we want to forward
410  */
411 pid_t current_child;
412 void graceful_shutdown_watcher(int signum) {
413         lprintf (1, "bye; shutting down watcher.");
414         kill(current_child, signum);
415         if (signum != SIGHUP)
416                 exit(0);
417 }
418
419 /*
420  * \brief shut us down the regular way.
421  * \param signum the signal we want to forward
422  */
423 pid_t current_child;
424 void graceful_shutdown(int signum) {
425 //      kill(current_child, signum);
426         char wd[SIZ];
427         FILE *FD;
428         int fd;
429         getcwd(wd, SIZ);
430         lprintf (1, "bye going down gracefull.[%d][%s]\n", signum, wd);
431         fd = msock;
432         msock = -1;
433         time_to_die = 1;
434         FD=fdopen(fd, "a+");
435         fflush (FD);
436         fclose (FD);
437         close(fd);
438 }
439
440
441 /*
442  * \brief       Start running as a daemon.  
443  *
444  * param        do_close_stdio          Only close stdio if set.
445  */
446
447 /*
448  * Start running as a daemon.
449  */
450 void start_daemon(char *pid_file) 
451 {
452         int status = 0;
453         pid_t child = 0;
454         FILE *fp;
455         int do_restart = 0;
456
457         current_child = 0;
458
459         /* Close stdin/stdout/stderr and replace them with /dev/null.
460          * We don't just call close() because we don't want these fd's
461          * to be reused for other files.
462          */
463         chdir("/");
464
465         signal(SIGHUP, SIG_IGN);
466         signal(SIGINT, SIG_IGN);
467         signal(SIGQUIT, SIG_IGN);
468
469         child = fork();
470         if (child != 0) {
471                 exit(0);
472         }
473
474         setsid();
475         umask(0);
476         freopen("/dev/null", "r", stdin);
477         freopen("/dev/null", "w", stdout);
478         freopen("/dev/null", "w", stderr);
479         signal(SIGTERM, graceful_shutdown_watcher);
480         signal(SIGHUP, graceful_shutdown_watcher);
481
482         do {
483                 current_child = fork();
484
485         
486                 if (current_child < 0) {
487                         perror("fork");
488                         ShutDownLibCitadel ();
489                         exit(errno);
490                 }
491         
492                 else if (current_child == 0) {  // child process
493 //                      signal(SIGTERM, graceful_shutdown);
494                         signal(SIGHUP, graceful_shutdown);
495
496                         return; /* continue starting webcit. */
497                 }
498         
499                 else { // watcher process
500 //                      signal(SIGTERM, SIG_IGN);
501 //                      signal(SIGHUP, SIG_IGN);
502                         if (pid_file) {
503                                 fp = fopen(pid_file, "w");
504                                 if (fp != NULL) {
505                                         fprintf(fp, "%d\n", getpid());
506                                         fclose(fp);
507                                 }
508                         }
509                         waitpid(current_child, &status, 0);
510                 }
511
512                 do_restart = 0;
513
514                 /* Did the main process exit with an actual exit code? */
515                 if (WIFEXITED(status)) {
516
517                         /* Exit code 0 means the watcher should exit */
518                         if (WEXITSTATUS(status) == 0) {
519                                 do_restart = 0;
520                         }
521
522                         /* Exit code 101-109 means the watcher should exit */
523                         else if ( (WEXITSTATUS(status) >= 101) && (WEXITSTATUS(status) <= 109) ) {
524                                 do_restart = 0;
525                         }
526
527                         /* Any other exit code means we should restart. */
528                         else {
529                                 do_restart = 1;
530                         }
531                 }
532
533                 /* Any other type of termination (signals, etc.) should also restart. */
534                 else {
535                         do_restart = 1;
536                 }
537
538         } while (do_restart);
539
540         if (pid_file) {
541                 unlink(pid_file);
542         }
543         ShutDownLibCitadel ();
544         exit(WEXITSTATUS(status));
545 }
546
547 /*
548  * \brief       Spawn an additional worker thread into the pool.
549  */
550 void spawn_another_worker_thread()
551 {
552         pthread_t SessThread;   /*< Thread descriptor */
553         pthread_attr_t attr;    /*< Thread attributes */
554         int ret;
555
556         lprintf(3, "Creating a new thread\n");
557
558         /* set attributes for the new thread */
559         pthread_attr_init(&attr);
560         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
561
562         /*
563          * Our per-thread stacks need to be bigger than the default size, otherwise
564          * the MIME parser crashes on FreeBSD, and the IMAP service crashes on
565          * 64-bit Linux.
566          */
567         if ((ret = pthread_attr_setstacksize(&attr, 1024 * 1024))) {
568                 lprintf(1, "pthread_attr_setstacksize: %s\n",
569                         strerror(ret));
570                 pthread_attr_destroy(&attr);
571         }
572
573         /* now create the thread */
574         if (pthread_create(&SessThread, &attr,
575                            (void *(*)(void *)) worker_entry, NULL)
576             != 0) {
577                 lprintf(1, "Can't create thread: %s\n", strerror(errno));
578         }
579
580         /* free up the attributes */
581         pthread_attr_destroy(&attr);
582 }
583
584 //#define DBG_PRINNT_HOOKS_AT_START
585 #ifdef DBG_PRINNT_HOOKS_AT_START
586 const char foobuf[32];
587 const char *nix(void *vptr) {snprintf(foobuf, 32, "%0x", (long) vptr); return foobuf;}
588 #endif 
589
590 /*
591  * \brief Here's where it all begins.
592  * \param argc number of commandline args
593  * \param argv the commandline arguments
594  */
595 int main(int argc, char **argv)
596 {
597         pthread_t SessThread;   /*< Thread descriptor */
598         pthread_attr_t attr;    /*< Thread attributes */
599         int a, i;                       /*< General-purpose variables */
600         char tracefile[PATH_MAX];
601         char ip_addr[256]="0.0.0.0";
602         char dirbuffer[PATH_MAX]="";
603         int relh=0;
604         int home=0;
605         int home_specified=0;
606         char relhome[PATH_MAX]="";
607         char webcitdir[PATH_MAX] = DATADIR;
608         char *pidfile = NULL;
609         char *hdir;
610         const char *basedir;
611 #ifdef ENABLE_NLS
612         char *locale = NULL;
613         char *mo = NULL;
614 #endif /* ENABLE_NLS */
615         char uds_listen_path[PATH_MAX]; /*< listen on a unix domain socket? */
616
617         HandlerHash = NewHash(1, NULL);
618         initialise_modules();
619
620 #ifdef DBG_PRINNT_HOOKS_AT_START
621         dbg_PrintHash(HandlerHash, nix, NULL);
622 #endif
623
624         /* Ensure that we are linked to the correct version of libcitadel */
625         if (libcitadel_version_number() < LIBCITADEL_VERSION_NUMBER) {
626                 fprintf(stderr, " You are running libcitadel version %d.%02d\n",
627                         (libcitadel_version_number() / 100), (libcitadel_version_number() % 100));
628                 fprintf(stderr, "WebCit was compiled against version %d.%02d\n",
629                         (LIBCITADEL_VERSION_NUMBER / 100), (LIBCITADEL_VERSION_NUMBER % 100));
630                 return(1);
631         }
632
633         strcpy(uds_listen_path, "");
634
635         /* Parse command line */
636 #ifdef HAVE_OPENSSL
637         while ((a = getopt(argc, argv, "h:i:p:t:x:dD:cfs")) != EOF)
638 #else
639         while ((a = getopt(argc, argv, "h:i:p:t:x:dD:cf")) != EOF)
640 #endif
641                 switch (a) {
642                 case 'h':
643                         hdir = strdup(optarg);
644                         relh=hdir[0]!='/';
645                         if (!relh) safestrncpy(webcitdir, hdir,
646                                                                    sizeof webcitdir);
647                         else
648                                 safestrncpy(relhome, relhome,
649                                                         sizeof relhome);
650                         /* free(hdir); TODO: SHOULD WE DO THIS? */
651                         home_specified = 1;
652                         home=1;
653                         break;
654                 case 'd':
655                         running_as_daemon = 1;
656                         break;
657                 case 'D':
658                         pidfile = strdup(optarg);
659                         running_as_daemon = 1;
660                         break;
661                 case 'i':
662                         safestrncpy(ip_addr, optarg, sizeof ip_addr);
663                         break;
664                 case 'p':
665                         http_port = atoi(optarg);
666                         if (http_port == 0) {
667                                 safestrncpy(uds_listen_path, optarg, sizeof uds_listen_path);
668                         }
669                         break;
670                 case 't':
671                         safestrncpy(tracefile, optarg, sizeof tracefile);
672                         freopen(tracefile, "w", stdout);
673                         freopen(tracefile, "w", stderr);
674                         freopen(tracefile, "r", stdin);
675                         break;
676                 case 'x':
677                         verbosity = atoi(optarg);
678                         break;
679                 case 'f':
680                         follow_xff = 1;
681                         break;
682                 case 'c':
683                         server_cookie = malloc(256);
684                         if (server_cookie != NULL) {
685                                 safestrncpy(server_cookie,
686                                        "Set-cookie: wcserver=",
687                                         256);
688                                 if (gethostname
689                                     (&server_cookie[strlen(server_cookie)],
690                                      200) != 0) {
691                                         lprintf(2, "gethostname: %s\n",
692                                                 strerror(errno));
693                                         free(server_cookie);
694                                 }
695                         }
696                         break;
697                 case 's':
698                         is_https = 1;
699                         break;
700                 default:
701                         fprintf(stderr, "usage: webcit "
702                                 "[-i ip_addr] [-p http_port] "
703                                 "[-t tracefile] [-c] [-f] "
704                                 "[-d] "
705 #ifdef HAVE_OPENSSL
706                                 "[-s] "
707 #endif
708                                 "[remotehost [remoteport]]\n");
709                         return 1;
710                 }
711
712         if (optind < argc) {
713                 ctdlhost = argv[optind];
714                 if (++optind < argc)
715                         ctdlport = argv[optind];
716         }
717
718         /* daemonize, if we were asked to */
719         if (running_as_daemon) {
720                 start_daemon(pidfile);
721         }
722         else {
723 ///             signal(SIGTERM, graceful_shutdown);
724                 signal(SIGHUP, graceful_shutdown);
725         }
726
727         /* Tell 'em who's in da house */
728         lprintf(1, PACKAGE_STRING "\n");
729         lprintf(1, "Copyright (C) 1996-2008 by the Citadel development team.\n"
730                 "This software is distributed under the terms of the "
731                 "GNU General Public License.\n\n"
732         );
733
734
735         /* initialize the International Bright Young Thing */
736 #ifdef ENABLE_NLS
737         initialize_locales();
738
739         locale = setlocale(LC_ALL, "");
740
741         mo = malloc(strlen(webcitdir) + 20);
742         lprintf(9, "Message catalog directory: %s\n", bindtextdomain("webcit", LOCALEDIR"/locale"));
743         free(mo);
744         lprintf(9, "Text domain: %s\n", textdomain("webcit"));
745         lprintf(9, "Text domain Charset: %s\n", bind_textdomain_codeset("webcit","UTF8"));
746         preset_locale();
747 #endif
748
749
750         /* calculate all our path on a central place */
751     /* where to keep our config */
752         
753 #define COMPUTE_DIRECTORY(SUBDIR) memcpy(dirbuffer,SUBDIR, sizeof dirbuffer);\
754         snprintf(SUBDIR,sizeof SUBDIR,  "%s%s%s%s%s%s%s", \
755                          (home&!relh)?webcitdir:basedir, \
756              ((basedir!=webcitdir)&(home&!relh))?basedir:"/", \
757              ((basedir!=webcitdir)&(home&!relh))?"/":"", \
758                          relhome, \
759              (relhome[0]!='\0')?"/":"",\
760                          dirbuffer,\
761                          (dirbuffer[0]!='\0')?"/":"");
762         basedir=RUNDIR;
763         COMPUTE_DIRECTORY(socket_dir);
764         basedir=WWWDIR "/static";
765         COMPUTE_DIRECTORY(static_dir);
766         basedir=WWWDIR "/static/icons";
767         COMPUTE_DIRECTORY(static_icon_dir);
768         basedir=WWWDIR "/static.local";
769         COMPUTE_DIRECTORY(static_local_dir);
770
771         snprintf(file_crpt_file_key,
772                  sizeof file_crpt_file_key, 
773                  "%s/citadel.key",
774                  ctdl_key_dir);
775         snprintf(file_crpt_file_csr,
776                  sizeof file_crpt_file_csr, 
777                  "%s/citadel.csr",
778                  ctdl_key_dir);
779         snprintf(file_crpt_file_cer,
780                  sizeof file_crpt_file_cer, 
781                  "%s/citadel.cer",
782                  ctdl_key_dir);
783
784         /* we should go somewhere we can leave our coredump, if enabled... */
785         lprintf(9, "Changing directory to %s\n", socket_dir);
786         if (chdir(webcitdir) != 0) {
787                 perror("chdir");
788         }
789         LoadIconDir(static_icon_dir);
790         initialize_viewdefs();
791         initialize_axdefs();
792
793         /*
794          * Set up a place to put thread-specific data.
795          * We only need a single pointer per thread - it points to the
796          * wcsession struct to which the thread is currently bound.
797          */
798         if (pthread_key_create(&MyConKey, NULL) != 0) {
799                 lprintf(1, "Can't create TSD key: %s\n", strerror(errno));
800         }
801         InitialiseSemaphores ();
802
803         /*
804          * Set up a place to put thread-specific SSL data.
805          * We don't stick this in the wcsession struct because SSL starts
806          * up before the session is bound, and it gets torn down between
807          * transactions.
808          */
809 #ifdef HAVE_OPENSSL
810         if (pthread_key_create(&ThreadSSL, NULL) != 0) {
811                 lprintf(1, "Can't create TSD key: %s\n", strerror(errno));
812         }
813 #endif
814
815         /*
816          * Bind the server to our favorite port.
817          * There is no need to check for errors, because ig_tcp_server()
818          * exits if it doesn't succeed.
819          */
820
821         if (!IsEmptyStr(uds_listen_path)) {
822                 lprintf(2, "Attempting to create listener socket at %s...\n", uds_listen_path);
823                 msock = ig_uds_server(uds_listen_path, LISTEN_QUEUE_LENGTH);
824         }
825         else {
826                 lprintf(2, "Attempting to bind to port %d...\n", http_port);
827                 msock = ig_tcp_server(ip_addr, http_port, LISTEN_QUEUE_LENGTH);
828         }
829
830         lprintf(2, "Listening on socket %d\n", msock);
831         signal(SIGPIPE, SIG_IGN);
832
833         pthread_mutex_init(&SessionListMutex, NULL);
834
835         /*
836          * Start up the housekeeping thread
837          */
838         pthread_attr_init(&attr);
839         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
840         pthread_create(&SessThread, &attr,
841                        (void *(*)(void *)) housekeeping_loop, NULL);
842
843
844         /*
845          * If this is an HTTPS server, fire up SSL
846          */
847 #ifdef HAVE_OPENSSL
848         if (is_https) {
849                 init_ssl();
850         }
851 #endif
852
853         /* Start a few initial worker threads */
854         for (i = 0; i < (MIN_WORKER_THREADS); ++i) {
855                 spawn_another_worker_thread();
856         }
857
858         /* now the original thread becomes another worker */
859         worker_entry();
860         ShutDownLibCitadel ();
861         DeleteHash(&HandlerHash);
862         return 0;
863 }
864
865
866 /*
867  * Entry point for worker threads
868  */
869 void worker_entry(void)
870 {
871         int ssock;
872         int i = 0;
873         int fail_this_transaction = 0;
874         int ret;
875         struct timeval tv;
876         fd_set readset, tempset;
877
878         tv.tv_sec = 0;
879         tv.tv_usec = 10000;
880         FD_ZERO(&readset);
881         FD_SET(msock, &readset);
882
883         do {
884                 /* Only one thread can accept at a time */
885                 fail_this_transaction = 0;
886                 ssock = -1; 
887                 errno = EAGAIN;
888                 do {
889                         ret = -1; /* just one at once should select... */
890                         begin_critical_section(S_SELECT);
891
892                         FD_ZERO(&tempset);
893                         if (msock > 0) FD_SET(msock, &tempset);
894                         tv.tv_sec = 0;
895                         tv.tv_usec = 10000;
896                         if (msock > 0)  ret = select(msock+1, &tempset, NULL, NULL,  &tv);
897                         end_critical_section(S_SELECT);
898                         if ((ret < 0) && (errno != EINTR) && (errno != EAGAIN))
899                         {// EINTR and EAGAIN are thrown but not of interest.
900                                 lprintf(2, "accept() failed:%d %s\n",
901                                         errno, strerror(errno));
902                         }
903                         else if ((ret > 0) && (msock > 0) && FD_ISSET(msock, &tempset))
904                         {// Successfully selected, and still not shutting down? Accept!
905                                 ssock = accept(msock, NULL, 0);
906                         }
907                         
908                 } while ((msock > 0) && (ssock < 0)  && (time_to_die == 0));
909
910                 if ((msock == -1)||(time_to_die))
911                 {// ok, we're going down.
912                         int shutdown = 0;
913
914                         /* the first to come here will have to do the cleanup.
915                          * make shure its realy just one.
916                          */
917                         begin_critical_section(S_SHUTDOWN);
918                         if (msock == -1)
919                         {
920                                 msock = -2;
921                                 shutdown = 1;
922                         }
923                         end_critical_section(S_SHUTDOWN);
924                         if (shutdown == 1)
925                         {// we're the one to cleanup the mess.
926                                 lprintf(2, "I'm master shutdown: tagging sessions to be killed.\n");
927                                 shutdown_sessions();
928                                 lprintf(2, "master shutdown: waiting for others\n");
929                                 sleeeeeeeeeep(1); // wait so some others might finish...
930                                 lprintf(2, "master shutdown: cleaning up sessions\n");
931                                 do_housekeeping();
932                                 lprintf(2, "master shutdown: cleaning up libical\n");
933                                 free_zone_directory ();
934                                 icaltimezone_release_zone_tab ();
935                                 icalmemory_free_ring ();
936                                 ShutDownLibCitadel ();
937                                 lprintf(2, "master shutdown exiting!.\n");                              
938                                 exit(0);
939                         }
940                         break;
941                 }
942                 if (ssock < 0 ) continue;
943
944                 if (msock < 0) {
945                         if (ssock > 0) close (ssock);
946                         lprintf(2, "inbetween.");
947                         pthread_exit(NULL);
948                 } else { // Got it? do some real work!
949                         /* Set the SO_REUSEADDR socket option */
950                         i = 1;
951                         setsockopt(ssock, SOL_SOCKET, SO_REUSEADDR,
952                                    &i, sizeof(i));
953
954                         /* If we are an HTTPS server, go crypto now. */
955 #ifdef HAVE_OPENSSL
956                         if (is_https) {
957                                 if (starttls(ssock) != 0) {
958                                         fail_this_transaction = 1;
959                                         close(ssock);
960                                 }
961                         }
962 #endif
963
964                         if (fail_this_transaction == 0) {
965
966                                 /* Perform an HTTP transaction... */
967                                 context_loop(ssock);
968
969                                 /* Shut down SSL/TLS if required... */
970 #ifdef HAVE_OPENSSL
971                                 if (is_https) {
972                                         endtls();
973                                 }
974 #endif
975
976                                 /* ...and close the socket. */
977                                 lingering_close(ssock);
978                         }
979
980                 }
981
982         } while (!time_to_die);
983
984         lprintf (1, "bye\n");
985         pthread_exit(NULL);
986 }
987
988 /*
989  * \brief print log messages 
990  * logs to stderr if loglevel is lower than the verbosity set at startup
991  * \param loglevel level of the message
992  * \param format the printf like format string
993  * \param ... the strings to put into format
994  */
995 int lprintf(int loglevel, const char *format, ...)
996 {
997         va_list ap;
998
999         if (loglevel <= verbosity) {
1000                 va_start(ap, format);
1001                 vfprintf(stderr, format, ap);
1002                 va_end(ap);
1003                 fflush(stderr);
1004         }
1005         return 1;
1006 }
1007
1008
1009 /*
1010  * \brief print the actual stack frame.
1011  */
1012 void wc_backtrace(void)
1013 {
1014 #ifdef HAVE_BACKTRACE
1015         void *stack_frames[50];
1016         size_t size, i;
1017         char **strings;
1018
1019
1020         size = backtrace(stack_frames, sizeof(stack_frames) / sizeof(void*));
1021         strings = backtrace_symbols(stack_frames, size);
1022         for (i = 0; i < size; i++) {
1023                 if (strings != NULL)
1024                         lprintf(1, "%s\n", strings[i]);
1025                 else
1026                         lprintf(1, "%p\n", stack_frames[i]);
1027         }
1028         free(strings);
1029 #endif
1030 }
1031
1032 /*@}*/