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