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