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