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