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