* ok, we want the LANG feature. but now we make it dependant on WEBCIT_LANG instead...
[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)
393 {
394         const char *Error, *pch, *pchs;
395         int rlen, len, retval = 0;
396
397         if (is_https) {
398                 int ntries = 0;
399                 if (StrLength(CLineBuf) > 0) {
400                         pchs = ChrPtr(CLineBuf);
401                         pch = strchr(pchs, '\n');
402                         if (pch != NULL) {
403                                 rlen = 0;
404                                 len = pch - pchs;
405                                 if (len > 0 && (*(pch - 1) == '\r') )
406                                         rlen ++;
407                                 StrBufSub(Target, CLineBuf, 0, len - rlen);
408                                 StrBufCutLeft(CLineBuf, len + 1);
409                                 return len - rlen;
410                         }
411                 }
412
413                 while (retval == 0) { 
414                                 pch = NULL;
415                                 pchs = ChrPtr(CLineBuf);
416                                 if (*pchs != '\0')
417                                         pch = strchr(pchs, '\n');
418                                 if (pch == NULL) {
419                                         retval = client_read_sslbuffer(CLineBuf, SLEEPING);
420                                         pchs = ChrPtr(CLineBuf);
421                                         pch = strchr(pchs, '\n');
422                                 }
423                                 if (retval == 0) {
424                                         sleeeeeeeeeep(1);
425                                         ntries ++;
426                                 }
427                                 if (ntries > 10)
428                                         return 0;
429                 }
430                 if ((retval > 0) && (pch != NULL)) {
431                         rlen = 0;
432                         len = pch - pchs;
433                         if (len > 0 && (*(pch - 1) == '\r') )
434                                 rlen ++;
435                         StrBufSub(Target, CLineBuf, 0, len - rlen);
436                         StrBufCutLeft(CLineBuf, len + 1);
437                         return len - rlen;
438
439                 }
440                 else 
441                         return -1;
442         }
443         else 
444                 return StrBufTCP_read_buffered_line(Target, 
445                                                     CLineBuf,
446                                                     sock,
447                                                     5,
448                                                     1,
449                                                     &Error);
450 }
451
452
453
454 /*
455  * Shut us down the regular way.
456  * signum is the signal we want to forward
457  */
458 pid_t current_child;
459 void graceful_shutdown(int signum) {
460         char wd[SIZ];
461         FILE *FD;
462         int fd;
463         getcwd(wd, SIZ);
464         lprintf (1, "bye going down gracefull.[%d][%s]\n", signum, wd);
465         fd = msock;
466         msock = -1;
467         time_to_die = 1;
468         FD=fdopen(fd, "a+");
469         fflush (FD);
470         fclose (FD);
471         close(fd);
472 }
473
474
475 /*
476  * Start running as a daemon.
477  */
478 void start_daemon(char *pid_file) 
479 {
480         int status = 0;
481         pid_t child = 0;
482         FILE *fp;
483         int do_restart = 0;
484
485         current_child = 0;
486
487         /* Close stdin/stdout/stderr and replace them with /dev/null.
488          * We don't just call close() because we don't want these fd's
489          * to be reused for other files.
490          */
491         chdir("/");
492
493         signal(SIGHUP, SIG_IGN);
494         signal(SIGINT, SIG_IGN);
495         signal(SIGQUIT, SIG_IGN);
496
497         child = fork();
498         if (child != 0) {
499                 exit(0);
500         }
501
502         setsid();
503         umask(0);
504         freopen("/dev/null", "r", stdin);
505         freopen("/dev/null", "w", stdout);
506         freopen("/dev/null", "w", stderr);
507         signal(SIGTERM, graceful_shutdown_watcher);
508         signal(SIGHUP, graceful_shutdown_watcher);
509
510         do {
511                 current_child = fork();
512
513         
514                 if (current_child < 0) {
515                         perror("fork");
516                         ShutDownLibCitadel ();
517                         exit(errno);
518                 }
519         
520                 else if (current_child == 0) {  /* child process */
521                         signal(SIGHUP, graceful_shutdown);
522
523                         return; /* continue starting webcit. */
524                 }
525                 else { /* watcher process */
526                         if (pid_file) {
527                                 fp = fopen(pid_file, "w");
528                                 if (fp != NULL) {
529                                         fprintf(fp, "%d\n", getpid());
530                                         fclose(fp);
531                                 }
532                         }
533                         waitpid(current_child, &status, 0);
534                 }
535
536                 do_restart = 0;
537
538                 /* Did the main process exit with an actual exit code? */
539                 if (WIFEXITED(status)) {
540
541                         /* Exit code 0 means the watcher should exit */
542                         if (WEXITSTATUS(status) == 0) {
543                                 do_restart = 0;
544                         }
545
546                         /* Exit code 101-109 means the watcher should exit */
547                         else if ( (WEXITSTATUS(status) >= 101) && (WEXITSTATUS(status) <= 109) ) {
548                                 do_restart = 0;
549                         }
550
551                         /* Any other exit code means we should restart. */
552                         else {
553                                 do_restart = 1;
554                         }
555                 }
556
557                 /* Any other type of termination (signals, etc.) should also restart. */
558                 else {
559                         do_restart = 1;
560                 }
561
562         } while (do_restart);
563
564         if (pid_file) {
565                 unlink(pid_file);
566         }
567         ShutDownLibCitadel ();
568         exit(WEXITSTATUS(status));
569 }
570
571 /*
572  * Spawn an additional worker thread into the pool.
573  */
574 void spawn_another_worker_thread()
575 {
576         pthread_t SessThread;   /* Thread descriptor */
577         pthread_attr_t attr;    /* Thread attributes */
578         int ret;
579
580         lprintf(3, "Creating a new thread\n");
581
582         /* set attributes for the new thread */
583         pthread_attr_init(&attr);
584         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
585
586         /*
587          * Our per-thread stacks need to be bigger than the default size, otherwise
588          * the MIME parser crashes on FreeBSD, and the IMAP service crashes on
589          * 64-bit Linux.
590          */
591         if ((ret = pthread_attr_setstacksize(&attr, 1024 * 1024))) {
592                 lprintf(1, "pthread_attr_setstacksize: %s\n",
593                         strerror(ret));
594                 pthread_attr_destroy(&attr);
595         }
596
597         /* now create the thread */
598         if (pthread_create(&SessThread, &attr,
599                            (void *(*)(void *)) worker_entry, NULL)
600             != 0) {
601                 lprintf(1, "Can't create thread: %s\n", strerror(errno));
602         }
603
604         /* free up the attributes */
605         pthread_attr_destroy(&attr);
606 }
607
608 /* #define DBG_PRINNT_HOOKS_AT_START */
609 #ifdef DBG_PRINNT_HOOKS_AT_START
610 const char foobuf[32];
611 const char *nix(void *vptr) {snprintf(foobuf, 32, "%0x", (long) vptr); return foobuf;}
612 #endif 
613 extern int dbg_analyze_msg;
614 extern int dbg_bactrace_template_errors;
615 extern int DumpTemplateI18NStrings;
616 extern StrBuf *I18nDump;
617 void InitTemplateCache(void);
618 extern int LoadTemplates;
619 extern void LoadZoneFiles(void);
620 StrBuf *csslocal = NULL;
621 /*
622  * Here's where it all begins.
623  */
624 int main(int argc, char **argv)
625 {
626         pthread_t SessThread;           /* Thread descriptor */
627         pthread_attr_t attr;            /* Thread attributes */
628         int a, i;                       /* General-purpose variables */
629         char tracefile[PATH_MAX];
630         char ip_addr[256]="0.0.0.0";
631         char dirbuffer[PATH_MAX]="";
632         int relh=0;
633         int home=0;
634         int home_specified=0;
635         char relhome[PATH_MAX]="";
636         char webcitdir[PATH_MAX] = DATADIR;
637         char *pidfile = NULL;
638         char *hdir;
639         const char *basedir;
640 #ifdef ENABLE_NLS
641         char *locale = NULL;
642         char *mo = NULL;
643 #endif /* ENABLE_NLS */
644         char uds_listen_path[PATH_MAX]; /* listen on a unix domain socket? */
645         const char *I18nDumpFile;
646
647         WildFireInitBacktrace(argv[0], 2);
648
649         HandlerHash = NewHash(1, NULL);
650         PreferenceHooks = NewHash(1, NULL);
651         WirelessTemplateCache = NewHash(1, NULL);
652         WirelessLocalTemplateCache = NewHash(1, NULL);
653         LocalTemplateCache = NewHash(1, NULL);
654         TemplateCache = NewHash(1, NULL);
655         GlobalNS = NewHash(1, NULL);
656         Iterators = NewHash(1, NULL);
657         Conditionals = NewHash(1, NULL);
658         MsgHeaderHandler = NewHash(1, NULL);
659         MimeRenderHandler = NewHash(1, NULL);
660         SortHash = NewHash(1, NULL);
661
662         LoadZoneFiles();
663
664 #ifdef DBG_PRINNT_HOOKS_AT_START
665         dbg_PrintHash(HandlerHash, nix, NULL);
666 #endif
667
668         /* Ensure that we are linked to the correct version of libcitadel */
669         if (libcitadel_version_number() < LIBCITADEL_VERSION_NUMBER) {
670                 fprintf(stderr, " You are running libcitadel version %d.%02d\n",
671                         (libcitadel_version_number() / 100), (libcitadel_version_number() % 100));
672                 fprintf(stderr, "WebCit was compiled against version %d.%02d\n",
673                         (LIBCITADEL_VERSION_NUMBER / 100), (LIBCITADEL_VERSION_NUMBER % 100));
674                 return(1);
675         }
676
677         strcpy(uds_listen_path, "");
678
679         /* Parse command line */
680 #ifdef HAVE_OPENSSL
681         while ((a = getopt(argc, argv, "h:i:p:t:T:x:dD:G:cfsZ")) != EOF)
682 #else
683         while ((a = getopt(argc, argv, "h:i:p:t:T:x:dD:G:cfZ")) != EOF)
684 #endif
685                 switch (a) {
686                 case 'h':
687                         hdir = strdup(optarg);
688                         relh=hdir[0]!='/';
689                         if (!relh) safestrncpy(webcitdir, hdir,
690                                                                    sizeof webcitdir);
691                         else
692                                 safestrncpy(relhome, relhome,
693                                                         sizeof relhome);
694                         /* free(hdir); TODO: SHOULD WE DO THIS? */
695                         home_specified = 1;
696                         home=1;
697                         break;
698                 case 'd':
699                         running_as_daemon = 1;
700                         break;
701                 case 'D':
702                         pidfile = strdup(optarg);
703                         running_as_daemon = 1;
704                         break;
705                 case 'i':
706                         safestrncpy(ip_addr, optarg, sizeof ip_addr);
707                         break;
708                 case 'p':
709                         http_port = atoi(optarg);
710                         if (http_port == 0) {
711                                 safestrncpy(uds_listen_path, optarg, sizeof uds_listen_path);
712                         }
713                         break;
714                 case 't':
715                         safestrncpy(tracefile, optarg, sizeof tracefile);
716                         freopen(tracefile, "w", stdout);
717                         freopen(tracefile, "w", stderr);
718                         freopen(tracefile, "r", stdin);
719                         break;
720                 case 'T':
721                         LoadTemplates = atoi(optarg);
722                         dbg_analyze_msg = (LoadTemplates && (1<<1)) != 0;
723                         dbg_bactrace_template_errors = (LoadTemplates && (1<<2)) != 0;
724                         break;
725                 case 'Z':
726                         DisableGzip = 1;
727                         break;
728                 case 'x':
729                         verbosity = atoi(optarg);
730                         break;
731                 case 'f':
732                         follow_xff = 1;
733                         break;
734                 case 'c':
735                         server_cookie = malloc(256);
736                         if (server_cookie != NULL) {
737                                 safestrncpy(server_cookie,
738                                        "Set-cookie: wcserver=",
739                                         256);
740                                 if (gethostname
741                                     (&server_cookie[strlen(server_cookie)],
742                                      200) != 0) {
743                                         lprintf(2, "gethostname: %s\n",
744                                                 strerror(errno));
745                                         free(server_cookie);
746                                 }
747                         }
748                         break;
749                 case 's':
750                         is_https = 1;
751                         break;
752                 case 'G':
753                         DumpTemplateI18NStrings = 1;
754                         I18nDump = NewStrBufPlain(HKEY("int templatestrings(void)\n{\n"));
755                         I18nDumpFile = optarg;
756                         break;
757                 default:
758                         fprintf(stderr, "usage: webcit "
759                                 "[-i ip_addr] [-p http_port] "
760                                 "[-t tracefile] [-c] [-f] "
761                                 "[-T Templatedebuglevel] "
762                                 "[-d] [-Z] [-G i18ndumpfile] "
763 #ifdef HAVE_OPENSSL
764                                 "[-s] "
765 #endif
766                                 "[remotehost [remoteport]]\n");
767                         return 1;
768                 }
769
770         if (optind < argc) {
771                 ctdlhost = argv[optind];
772                 if (++optind < argc)
773                         ctdlport = argv[optind];
774         }
775
776         /* daemonize, if we were asked to */
777         if (!DumpTemplateI18NStrings && running_as_daemon) {
778                 start_daemon(pidfile);
779         }
780         else {
781                 signal(SIGHUP, graceful_shutdown);
782         }
783
784         /* Tell 'em who's in da house */
785         lprintf(1, PACKAGE_STRING "\n");
786         lprintf(1, "Copyright (C) 1996-2009 by the Citadel development team.\n"
787                 "This software is distributed under the terms of the "
788                 "GNU General Public License.\n\n"
789         );
790
791
792         /* initialize the International Bright Young Thing */
793 #ifdef ENABLE_NLS
794         initialize_locales();
795
796
797         locale = setlocale(LC_ALL, "");
798
799         mo = malloc(strlen(webcitdir) + 20);
800         lprintf(9, "Message catalog directory: %s\n", bindtextdomain("webcit", LOCALEDIR"/locale"));
801         free(mo);
802         lprintf(9, "Text domain: %s\n", textdomain("webcit"));
803         lprintf(9, "Text domain Charset: %s\n", bind_textdomain_codeset("webcit","UTF8"));
804         preset_locale();
805 #endif
806
807
808         /* calculate all our path on a central place */
809     /* where to keep our config */
810         
811 #define COMPUTE_DIRECTORY(SUBDIR) memcpy(dirbuffer,SUBDIR, sizeof dirbuffer);\
812         snprintf(SUBDIR,sizeof SUBDIR,  "%s%s%s%s%s%s%s", \
813                          (home&!relh)?webcitdir:basedir, \
814              ((basedir!=webcitdir)&(home&!relh))?basedir:"/", \
815              ((basedir!=webcitdir)&(home&!relh))?"/":"", \
816                          relhome, \
817              (relhome[0]!='\0')?"/":"",\
818                          dirbuffer,\
819                          (dirbuffer[0]!='\0')?"/":"");
820         basedir=RUNDIR;
821         COMPUTE_DIRECTORY(socket_dir);
822         basedir=WWWDIR "/static";
823         COMPUTE_DIRECTORY(static_dir);
824         basedir=WWWDIR "/static/icons";
825         COMPUTE_DIRECTORY(static_icon_dir);
826         basedir=WWWDIR "/static.local";
827         COMPUTE_DIRECTORY(static_local_dir);
828
829         snprintf(file_crpt_file_key,
830                  sizeof file_crpt_file_key, 
831                  "%s/citadel.key",
832                  ctdl_key_dir);
833         snprintf(file_crpt_file_csr,
834                  sizeof file_crpt_file_csr, 
835                  "%s/citadel.csr",
836                  ctdl_key_dir);
837         snprintf(file_crpt_file_cer,
838                  sizeof file_crpt_file_cer, 
839                  "%s/citadel.cer",
840                  ctdl_key_dir);
841
842         /* we should go somewhere we can leave our coredump, if enabled... */
843         lprintf(9, "Changing directory to %s\n", socket_dir);
844         if (chdir(webcitdir) != 0) {
845                 perror("chdir");
846         }
847         LoadIconDir(static_icon_dir);
848
849         initialise_modules();
850         initialize_viewdefs();
851         initialize_axdefs();
852
853         InitTemplateCache();
854         if (DumpTemplateI18NStrings) {
855                 FILE *fd;
856                 StrBufAppendBufPlain(I18nDump, HKEY("}\n"), 0);
857                 if (StrLength(I18nDump) < 50) {
858                         lprintf(1, "********************************************************************************\n");
859                         lprintf(1, "*        No strings found in templates! are you shure they're there?           *\n");
860                         lprintf(1, "********************************************************************************\n");
861                         return -1;
862                 }
863                 fd = fopen(I18nDumpFile, "w");
864                 if (fd == NULL) {
865                         lprintf(1, "********************************************************************************\n");
866                         lprintf(1, "*                  unable to open I18N dumpfile [%s]         *\n", I18nDumpFile);
867                         lprintf(1, "********************************************************************************\n");
868                         return -1;
869                 }
870                 fwrite(ChrPtr(I18nDump), 1, StrLength(I18nDump), fd);
871                 fclose(fd);
872                 return 0;
873         }
874
875         if (!access("static.local/webcit.css", R_OK)) {
876                 csslocal = NewStrBufPlain(HKEY("<link href=\"static.local/webcit.css\" rel=\"stylesheet\" type=\"text/css\">"));
877         }
878
879         /* Tell libical to return an error instead of aborting if it sees badly formed iCalendar data. */
880         icalerror_errors_are_fatal = 0;
881
882         /* Use our own prefix on tzid's generated from system tzdata */
883         icaltimezone_set_tzid_prefix("/citadel.org/");
884
885         /*
886          * Set up a place to put thread-specific data.
887          * We only need a single pointer per thread - it points to the
888          * wcsession struct to which the thread is currently bound.
889          */
890         if (pthread_key_create(&MyConKey, NULL) != 0) {
891                 lprintf(1, "Can't create TSD key: %s\n", strerror(errno));
892         }
893         InitialiseSemaphores ();
894
895         /*
896          * Set up a place to put thread-specific SSL data.
897          * We don't stick this in the wcsession struct because SSL starts
898          * up before the session is bound, and it gets torn down between
899          * transactions.
900          */
901 #ifdef HAVE_OPENSSL
902         if (pthread_key_create(&ThreadSSL, NULL) != 0) {
903                 lprintf(1, "Can't create TSD key: %s\n", strerror(errno));
904         }
905 #endif
906
907         /*
908          * Bind the server to our favorite port.
909          * There is no need to check for errors, because ig_tcp_server()
910          * exits if it doesn't succeed.
911          */
912
913         if (!IsEmptyStr(uds_listen_path)) {
914                 lprintf(2, "Attempting to create listener socket at %s...\n", uds_listen_path);
915                 msock = ig_uds_server(uds_listen_path, LISTEN_QUEUE_LENGTH);
916         }
917         else {
918                 lprintf(2, "Attempting to bind to port %d...\n", http_port);
919                 msock = ig_tcp_server(ip_addr, http_port, LISTEN_QUEUE_LENGTH);
920         }
921
922         lprintf(2, "Listening on socket %d\n", msock);
923         signal(SIGPIPE, SIG_IGN);
924
925         pthread_mutex_init(&SessionListMutex, NULL);
926
927         /*
928          * Start up the housekeeping thread
929          */
930         pthread_attr_init(&attr);
931         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
932         pthread_create(&SessThread, &attr,
933                        (void *(*)(void *)) housekeeping_loop, NULL);
934
935
936         /*
937          * If this is an HTTPS server, fire up SSL
938          */
939 #ifdef HAVE_OPENSSL
940         if (is_https) {
941                 init_ssl();
942         }
943 #endif
944
945         /* Start a few initial worker threads */
946         for (i = 0; i < (MIN_WORKER_THREADS); ++i) {
947                 spawn_another_worker_thread();
948         }
949
950         /* now the original thread becomes another worker */
951         worker_entry();
952         ShutDownLibCitadel ();
953         DeleteHash(&HandlerHash);
954         DeleteHash(&PreferenceHooks);
955         return 0;
956 }
957
958
959 void ShutDownWebcit(void)
960 {
961         DeleteHash(&ZoneHash);
962         free_zone_directory ();
963         icaltimezone_release_zone_tab ();
964         icalmemory_free_ring ();
965         ShutDownLibCitadel ();
966         DeleteHash(&HandlerHash);
967         DeleteHash(&PreferenceHooks);
968         DeleteHash(&GlobalNS);
969         DeleteHash(&WirelessTemplateCache);
970         DeleteHash(&WirelessLocalTemplateCache);
971         DeleteHash(&TemplateCache);
972         DeleteHash(&LocalTemplateCache);
973         DeleteHash(&Iterators);
974         DeleteHash(&MimeRenderHandler);
975         DeleteHash(&Conditionals);
976         DeleteHash(&MsgHeaderHandler);
977         DeleteHash(&SortHash);
978 #ifdef ENABLE_NLS
979         ShutdownLocale();
980 #endif
981 #ifdef HAVE_OPENSSL
982         if (is_https) {
983                 shutdown_ssl();
984         }
985 #endif
986 }
987
988 /*
989  * Entry point for worker threads
990  */
991 void worker_entry(void)
992 {
993         int ssock;
994         int i = 0;
995         int fail_this_transaction = 0;
996         int ret;
997         struct timeval tv;
998         fd_set readset, tempset;
999
1000         tv.tv_sec = 0;
1001         tv.tv_usec = 10000;
1002         FD_ZERO(&readset);
1003         FD_SET(msock, &readset);
1004
1005         do {
1006                 /* Only one thread can accept at a time */
1007                 fail_this_transaction = 0;
1008                 ssock = -1; 
1009                 errno = EAGAIN;
1010                 do {
1011                         ret = -1; /* just one at once should select... */
1012                         begin_critical_section(S_SELECT);
1013
1014                         FD_ZERO(&tempset);
1015                         if (msock > 0) FD_SET(msock, &tempset);
1016                         tv.tv_sec = 0;
1017                         tv.tv_usec = 10000;
1018                         if (msock > 0)  ret = select(msock+1, &tempset, NULL, NULL,  &tv);
1019                         end_critical_section(S_SELECT);
1020                         if ((ret < 0) && (errno != EINTR) && (errno != EAGAIN))
1021                         {/* EINTR and EAGAIN are thrown but not of interest. */
1022                                 lprintf(2, "accept() failed:%d %s\n",
1023                                         errno, strerror(errno));
1024                         }
1025                         else if ((ret > 0) && (msock > 0) && FD_ISSET(msock, &tempset))
1026                         {/* Successfully selected, and still not shutting down? Accept! */
1027                                 ssock = accept(msock, NULL, 0);
1028                         }
1029                         
1030                 } while ((msock > 0) && (ssock < 0)  && (time_to_die == 0));
1031
1032                 if ((msock == -1)||(time_to_die))
1033                 {/* ok, we're going down. */
1034                         int shutdown = 0;
1035
1036                         /* the first to come here will have to do the cleanup.
1037                          * make shure its realy just one.
1038                          */
1039                         begin_critical_section(S_SHUTDOWN);
1040                         if (msock == -1)
1041                         {
1042                                 msock = -2;
1043                                 shutdown = 1;
1044                         }
1045                         end_critical_section(S_SHUTDOWN);
1046                         if (shutdown == 1)
1047                         {/* we're the one to cleanup the mess. */
1048                                 lprintf(2, "I'm master shutdown: tagging sessions to be killed.\n");
1049                                 shutdown_sessions();
1050                                 lprintf(2, "master shutdown: waiting for others\n");
1051                                 sleeeeeeeeeep(1); /* wait so some others might finish... */
1052                                 lprintf(2, "master shutdown: cleaning up sessions\n");
1053                                 do_housekeeping();
1054                                 lprintf(2, "master shutdown: cleaning up libical\n");
1055
1056                                 ShutDownWebcit();
1057
1058                                 lprintf(2, "master shutdown exiting!.\n");                              
1059                                 exit(0);
1060                         }
1061                         break;
1062                 }
1063                 if (ssock < 0 ) continue;
1064
1065                 if (msock < 0) {
1066                         if (ssock > 0) close (ssock);
1067                         lprintf(2, "inbetween.");
1068                         pthread_exit(NULL);
1069                 } else { /* Got it? do some real work! */
1070                         /* Set the SO_REUSEADDR socket option */
1071                         i = 1;
1072                         setsockopt(ssock, SOL_SOCKET, SO_REUSEADDR,
1073                                    &i, sizeof(i));
1074
1075                         /* If we are an HTTPS server, go crypto now. */
1076 #ifdef HAVE_OPENSSL
1077                         if (is_https) {
1078                                 if (starttls(ssock) != 0) {
1079                                         fail_this_transaction = 1;
1080                                         close(ssock);
1081                                 }
1082                         }
1083 #endif
1084
1085                         if (fail_this_transaction == 0) {
1086
1087                                 /* Perform an HTTP transaction... */
1088                                 context_loop(&ssock);
1089
1090                                 /* Shut down SSL/TLS if required... */
1091 #ifdef HAVE_OPENSSL
1092                                 if (is_https) {
1093                                         endtls();
1094                                 }
1095 #endif
1096
1097                                 /* ...and close the socket. */
1098                                 if (ssock > 0)
1099                                         lingering_close(ssock);
1100                         }
1101
1102                 }
1103
1104         } while (!time_to_die);
1105
1106         lprintf (1, "bye\n");
1107         pthread_exit(NULL);
1108 }
1109
1110 /*
1111  * print log messages 
1112  * logs to stderr if loglevel is lower than the verbosity set at startup
1113  *
1114  * loglevel     level of the message
1115  * format       the printf like format string
1116  * ...          the strings to put into format
1117  */
1118 int lprintf(int loglevel, const char *format, ...)
1119 {
1120         va_list ap;
1121
1122         if (loglevel <= verbosity) {
1123                 va_start(ap, format);
1124                 vfprintf(stderr, format, ap);
1125                 va_end(ap);
1126                 fflush(stderr);
1127         }
1128         return 1;
1129 }
1130
1131
1132 /*
1133  * print the actual stack frame.
1134  */
1135 void wc_backtrace(void)
1136 {
1137 #ifdef HAVE_BACKTRACE
1138         void *stack_frames[50];
1139         size_t size, i;
1140         char **strings;
1141
1142
1143         size = backtrace(stack_frames, sizeof(stack_frames) / sizeof(void*));
1144         strings = backtrace_symbols(stack_frames, size);
1145         for (i = 0; i < size; i++) {
1146                 if (strings != NULL)
1147                         lprintf(1, "%s\n", strings[i]);
1148                 else
1149                         lprintf(1, "%p\n", stack_frames[i]);
1150         }
1151         free(strings);
1152 #endif
1153 }
1154