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