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