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