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