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