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