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