The encoding and decoding tables for Base64 are
[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         if (getenv("TZ") == NULL)
674                 putenv("TZ=UTC");
675
676         /* Parse command line */
677 #ifdef HAVE_OPENSSL
678         while ((a = getopt(argc, argv, "h:i:p:t:x:dD:cfs")) != EOF)
679 #else
680         while ((a = getopt(argc, argv, "h:i:p:t:x:dD:cf")) != EOF)
681 #endif
682                 switch (a) {
683                 case 'h':
684                         hdir = strdup(optarg);
685                         relh=hdir[0]!='/';
686                         if (!relh) safestrncpy(webcitdir, hdir,
687                                                                    sizeof webcitdir);
688                         else
689                                 safestrncpy(relhome, relhome,
690                                                         sizeof relhome);
691                         /* free(hdir); TODO: SHOULD WE DO THIS? */
692                         home_specified = 1;
693                         home=1;
694                         break;
695                 case 'd':
696                         running_as_daemon = 1;
697                         break;
698                 case 'D':
699                         pidfile = strdup(optarg);
700                         running_as_daemon = 1;
701                         break;
702                 case 'i':
703                         safestrncpy(ip_addr, optarg, sizeof ip_addr);
704                         break;
705                 case 'p':
706                         http_port = atoi(optarg);
707                         if (http_port == 0) {
708                                 safestrncpy(uds_listen_path, optarg, sizeof uds_listen_path);
709                         }
710                         break;
711                 case 't':
712                         safestrncpy(tracefile, optarg, sizeof tracefile);
713                         freopen(tracefile, "w", stdout);
714                         freopen(tracefile, "w", stderr);
715                         freopen(tracefile, "r", stdin);
716                         break;
717                 case 'x':
718                         verbosity = atoi(optarg);
719                         break;
720                 case 'f':
721                         follow_xff = 1;
722                         break;
723                 case 'c':
724                         server_cookie = malloc(256);
725                         if (server_cookie != NULL) {
726                                 safestrncpy(server_cookie,
727                                        "Set-cookie: wcserver=",
728                                         256);
729                                 if (gethostname
730                                     (&server_cookie[strlen(server_cookie)],
731                                      200) != 0) {
732                                         lprintf(2, "gethostname: %s\n",
733                                                 strerror(errno));
734                                         free(server_cookie);
735                                 }
736                         }
737                         break;
738                 case 's':
739                         is_https = 1;
740                         break;
741                 default:
742                         fprintf(stderr, "usage: webserver "
743                                 "[-i ip_addr] [-p http_port] "
744                                 "[-t tracefile] [-c] [-f] "
745                                 "[-d] "
746 #ifdef HAVE_OPENSSL
747                                 "[-s] "
748 #endif
749                                 "[remotehost [remoteport]]\n");
750                         return 1;
751                 }
752
753         if (optind < argc) {
754                 ctdlhost = argv[optind];
755                 if (++optind < argc)
756                         ctdlport = argv[optind];
757         }
758
759         /* daemonize, if we were asked to */
760         if (running_as_daemon) {
761                 start_daemon(pidfile);
762         }
763         else {
764 ///             signal(SIGTERM, graceful_shutdown);
765                 signal(SIGHUP, graceful_shutdown);
766         }
767
768         /* Tell 'em who's in da house */
769         lprintf(1, PACKAGE_STRING "\n");
770         lprintf(1, "Copyright (C) 1996-2008 by the Citadel development team.\n"
771                 "This software is distributed under the terms of the "
772                 "GNU General Public License.\n\n"
773         );
774
775
776         /* initialize the International Bright Young Thing */
777 #ifdef ENABLE_NLS
778         initialize_locales();
779         locale = setlocale(LC_ALL, "");
780         mo = malloc(strlen(webcitdir) + 20);
781         lprintf(9, "Message catalog directory: %s\n", bindtextdomain("webcit", LOCALEDIR"/locale"));
782         free(mo);
783         lprintf(9, "Text domain: %s\n", textdomain("webcit"));
784         lprintf(9, "Text domain Charset: %s\n", bind_textdomain_codeset("webcit","UTF8"));
785 #endif
786
787
788         /* calculate all our path on a central place */
789     /* where to keep our config */
790         
791 #define COMPUTE_DIRECTORY(SUBDIR) memcpy(dirbuffer,SUBDIR, sizeof dirbuffer);\
792         snprintf(SUBDIR,sizeof SUBDIR,  "%s%s%s%s%s%s%s", \
793                          (home&!relh)?webcitdir:basedir, \
794              ((basedir!=webcitdir)&(home&!relh))?basedir:"/", \
795              ((basedir!=webcitdir)&(home&!relh))?"/":"", \
796                          relhome, \
797              (relhome[0]!='\0')?"/":"",\
798                          dirbuffer,\
799                          (dirbuffer[0]!='\0')?"/":"");
800         basedir=RUNDIR;
801         COMPUTE_DIRECTORY(socket_dir);
802         basedir=WWWDIR "/static";
803         COMPUTE_DIRECTORY(static_dir);
804         basedir=WWWDIR "/static.local";
805         COMPUTE_DIRECTORY(static_local_dir);
806
807         snprintf(file_crpt_file_key,
808                  sizeof file_crpt_file_key, 
809                  "%s/citadel.key",
810                  ctdl_key_dir);
811         snprintf(file_crpt_file_csr,
812                  sizeof file_crpt_file_csr, 
813                  "%s/citadel.csr",
814                  ctdl_key_dir);
815         snprintf(file_crpt_file_cer,
816                  sizeof file_crpt_file_cer, 
817                  "%s/citadel.cer",
818                  ctdl_key_dir);
819
820         /* we should go somewhere we can leave our coredump, if enabled... */
821         lprintf(9, "Changing directory to %s\n", socket_dir);
822         if (chdir(webcitdir) != 0) {
823                 perror("chdir");
824         }       
825         initialize_viewdefs();
826         initialize_axdefs();
827
828         /*
829          * Set up a place to put thread-specific data.
830          * We only need a single pointer per thread - it points to the
831          * wcsession struct to which the thread is currently bound.
832          */
833         if (pthread_key_create(&MyConKey, NULL) != 0) {
834                 lprintf(1, "Can't create TSD key: %s\n", strerror(errno));
835         }
836         InitialiseSemaphores ();
837
838         /*
839          * Set up a place to put thread-specific SSL data.
840          * We don't stick this in the wcsession struct because SSL starts
841          * up before the session is bound, and it gets torn down between
842          * transactions.
843          */
844 #ifdef HAVE_OPENSSL
845         if (pthread_key_create(&ThreadSSL, NULL) != 0) {
846                 lprintf(1, "Can't create TSD key: %s\n", strerror(errno));
847         }
848 #endif
849
850         /*
851          * Bind the server to our favorite port.
852          * There is no need to check for errors, because ig_tcp_server()
853          * exits if it doesn't succeed.
854          */
855
856         if (!IsEmptyStr(uds_listen_path)) {
857                 lprintf(2, "Attempting to create listener socket at %s...\n", uds_listen_path);
858                 msock = ig_uds_server(uds_listen_path, LISTEN_QUEUE_LENGTH);
859         }
860         else {
861                 lprintf(2, "Attempting to bind to port %d...\n", http_port);
862                 msock = ig_tcp_server(ip_addr, http_port, LISTEN_QUEUE_LENGTH);
863         }
864
865         lprintf(2, "Listening on socket %d\n", msock);
866         signal(SIGPIPE, SIG_IGN);
867
868         pthread_mutex_init(&SessionListMutex, NULL);
869
870         /*
871          * Start up the housekeeping thread
872          */
873         pthread_attr_init(&attr);
874         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
875         pthread_create(&SessThread, &attr,
876                        (void *(*)(void *)) housekeeping_loop, NULL);
877
878
879         /*
880          * If this is an HTTPS server, fire up SSL
881          */
882 #ifdef HAVE_OPENSSL
883         if (is_https) {
884                 init_ssl();
885         }
886 #endif
887
888         /* Start a few initial worker threads */
889         for (i = 0; i < (MIN_WORKER_THREADS); ++i) {
890                 spawn_another_worker_thread();
891         }
892
893         /* now the original thread becomes another worker */
894         worker_entry();
895         return 0;
896 }
897
898
899 /*
900  * Entry point for worker threads
901  */
902 void worker_entry(void)
903 {
904         int ssock;
905         int i = 0;
906         int fail_this_transaction = 0;
907         int ret;
908         struct timeval tv;
909         fd_set readset, tempset;
910
911         tv.tv_sec = 0;
912         tv.tv_usec = 10000;
913         FD_ZERO(&readset);
914         FD_SET(msock, &readset);
915
916         do {
917                 /* Only one thread can accept at a time */
918                 fail_this_transaction = 0;
919                 ssock = -1; 
920                 errno = EAGAIN;
921                 do {
922                         ret = -1; /* just one at once should select... */
923                         begin_critical_section(S_SELECT);
924
925                         FD_ZERO(&tempset);
926                         if (msock > 0) FD_SET(msock, &tempset);
927                         tv.tv_sec = 0;
928                         tv.tv_usec = 10000;
929                         if (msock > 0)  ret = select(msock+1, &tempset, NULL, NULL,  &tv);
930                         end_critical_section(S_SELECT);
931                         if ((ret < 0) && (errno != EINTR) && (errno != EAGAIN))
932                         {// EINTR and EAGAIN are thrown but not of interest.
933                                 lprintf(2, "accept() failed:%d %s\n",
934                                         errno, strerror(errno));
935                         }
936                         else if ((ret > 0) && (msock > 0) && FD_ISSET(msock, &tempset))
937                         {// Successfully selected, and still not shutting down? Accept!
938                                 ssock = accept(msock, NULL, 0);
939                         }
940                         
941                 } while ((msock > 0) && (ssock < 0)  && (time_to_die == 0));
942
943                 if ((msock == -1)||(time_to_die))
944                 {// ok, we're going down.
945                         int shutdown = 0;
946
947                         /* the first to come here will have to do the cleanup.
948                          * make shure its realy just one.
949                          */
950                         begin_critical_section(S_SHUTDOWN);
951                         if (msock == -1)
952                         {
953                                 msock = -2;
954                                 shutdown = 1;
955                         }
956                         end_critical_section(S_SHUTDOWN);
957                         if (shutdown == 1)
958                         {// we're the one to cleanup the mess.
959                                 lprintf(2, "I'm master shutdown: tagging sessions to be killed.\n");
960                                 shutdown_sessions();
961                                 lprintf(2, "master shutdown: waiting for others\n");
962                                 sleeeeeeeeeep(1); // wait so some others might finish...
963                                 lprintf(2, "master shutdown: cleaning up sessions\n");
964                                 do_housekeeping();
965 #ifdef WEBCIT_WITH_CALENDAR_SERVICE
966                                 lprintf(2, "master shutdown: cleaning up libical\n");
967                                 free_zone_directory ();
968                                 icaltimezone_release_zone_tab ();
969                                 icalmemory_free_ring ();
970 #endif
971                                 lprintf(2, "master shutdown exiting!.\n");                              
972                                 exit(0);
973                         }
974                         break;
975                 }
976                 if (ssock < 0 ) continue;
977
978                 if (msock < 0) {
979                         if (ssock > 0) close (ssock);
980                         lprintf(2, "inbetween.");
981                         pthread_exit(NULL);
982                 } else { // Got it? do some real work!
983                         /* Set the SO_REUSEADDR socket option */
984                         i = 1;
985                         setsockopt(ssock, SOL_SOCKET, SO_REUSEADDR,
986                                    &i, sizeof(i));
987
988                         /* If we are an HTTPS server, go crypto now. */
989 #ifdef HAVE_OPENSSL
990                         if (is_https) {
991                                 if (starttls(ssock) != 0) {
992                                         fail_this_transaction = 1;
993                                         close(ssock);
994                                 }
995                         }
996 #endif
997
998                         if (fail_this_transaction == 0) {
999
1000                                 /* Perform an HTTP transaction... */
1001                                 context_loop(ssock);
1002
1003                                 /* Shut down SSL/TLS if required... */
1004 #ifdef HAVE_OPENSSL
1005                                 if (is_https) {
1006                                         endtls();
1007                                 }
1008 #endif
1009
1010                                 /* ...and close the socket. */
1011                                 lingering_close(ssock);
1012                         }
1013
1014                 }
1015
1016         } while (!time_to_die);
1017
1018         lprintf (1, "bye\n");
1019         pthread_exit(NULL);
1020 }
1021
1022 /*
1023  * \brief logprintf. log messages 
1024  * logs to stderr if loglevel is lower than the verbosity set at startup
1025  * \param loglevel level of the message
1026  * \param format the printf like format string
1027  * \param ... the strings to put into format
1028  */
1029 int lprintf(int loglevel, const char *format, ...)
1030 {
1031         va_list ap;
1032
1033         if (loglevel <= verbosity) {
1034                 va_start(ap, format);
1035                 vfprintf(stderr, format, ap);
1036                 va_end(ap);
1037                 fflush(stderr);
1038         }
1039         return 1;
1040 }
1041
1042
1043 /*
1044  * \brief print the actual stack frame.
1045  */
1046 void wc_backtrace(void)
1047 {
1048 #ifdef HAVE_BACKTRACE
1049         void *stack_frames[50];
1050         size_t size, i;
1051         char **strings;
1052
1053
1054         size = backtrace(stack_frames, sizeof(stack_frames) / sizeof(void*));
1055         strings = backtrace_symbols(stack_frames, size);
1056         for (i = 0; i < size; i++) {
1057                 if (strings != NULL)
1058                         lprintf(1, "%s\n", strings[i]);
1059                 else
1060                         lprintf(1, "%p\n", stack_frames[i]);
1061         }
1062         free(strings);
1063 #endif
1064 }
1065
1066 /*@}*/