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