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