7eafa289dc3c0e6da84e85dd90dd1e893cae2f79
[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                           uLongf * 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         sprintf((char *) dest, "%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                 uLongf compressed_len;
381
382                 compressed_len = (uLongf) ((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         exit(0);
469 }
470
471 /**
472  * \brief shut us down the regular way.
473  * param signum the signal we want to forward
474  */
475 pid_t current_child;
476 void graceful_shutdown(int signum) {
477 //      kill(current_child, signum);
478         char wd[SIZ];
479         FILE *FD;
480         int fd;
481         getcwd(wd, SIZ);
482         lprintf (1, "bye going down gracefull.[%d][%s]\n", signum, wd);
483         fd = msock;
484         msock = -1;
485         time_to_die = 1;
486         FD=fdopen(fd, "a+");
487         fflush (FD);
488         fclose (FD);
489         close(fd);
490 }
491
492
493 /**
494  * \brief       Start running as a daemon.  
495  *
496  * param        do_close_stdio          Only close stdio if set.
497  */
498
499 /*
500  * Start running as a daemon.
501  */
502 void start_daemon(char *pid_file) 
503 {
504         int status = 0;
505         pid_t child = 0;
506         FILE *fp;
507         int do_restart = 0;
508
509         current_child = 0;
510
511         /* Close stdin/stdout/stderr and replace them with /dev/null.
512          * We don't just call close() because we don't want these fd's
513          * to be reused for other files.
514          */
515         chdir("/");
516
517         signal(SIGHUP, SIG_IGN);
518         signal(SIGINT, SIG_IGN);
519         signal(SIGQUIT, SIG_IGN);
520
521         child = fork();
522         if (child != 0) {
523                 exit(0);
524         }
525
526         setsid();
527         umask(0);
528         freopen("/dev/null", "r", stdin);
529         freopen("/dev/null", "w", stdout);
530         freopen("/dev/null", "w", stderr);
531 ///     signal(SIGTERM, graceful_shutdown_watcher);
532         signal(SIGHUP, graceful_shutdown_watcher);
533
534         do {
535                 current_child = fork();
536
537         
538                 if (current_child < 0) {
539                         perror("fork");
540                         exit(errno);
541                 }
542         
543                 else if (current_child == 0) {
544 ////                    signal(SIGTERM, graceful_shutdown);
545                         signal(SIGHUP, graceful_shutdown);
546
547                         return; /* continue starting webcit. */
548                 }
549         
550                 else {
551 ////                    signal(SIGTERM, SIG_IGN);
552                         signal(SIGHUP, SIG_IGN);
553                         if (pid_file) {
554                                 fp = fopen(pid_file, "w");
555                                 if (fp != NULL) {
556                                         fprintf(fp, "%d\n", current_child);
557                                         fclose(fp);
558                                 }
559                         }
560                         waitpid(current_child, &status, 0);
561                 }
562
563                 do_restart = 0;
564
565                 /* Did the main process exit with an actual exit code? */
566                 if (WIFEXITED(status)) {
567
568                         /* Exit code 0 means the watcher should exit */
569                         if (WEXITSTATUS(status) == 0) {
570                                 do_restart = 0;
571                         }
572
573                         /* Exit code 101-109 means the watcher should exit */
574                         else if ( (WEXITSTATUS(status) >= 101) && (WEXITSTATUS(status) <= 109) ) {
575                                 do_restart = 0;
576                         }
577
578                         /* Any other exit code means we should restart. */
579                         else {
580                                 do_restart = 1;
581                         }
582                 }
583
584                 /* Any other type of termination (signals, etc.) should also restart. */
585                 else {
586                         do_restart = 1;
587                 }
588
589         } while (do_restart);
590
591         if (pid_file) {
592                 unlink(pid_file);
593         }
594         exit(WEXITSTATUS(status));
595 }
596
597 /**
598  * \brief       Spawn an additional worker thread into the pool.
599  */
600 void spawn_another_worker_thread()
601 {
602         pthread_t SessThread;   /**< Thread descriptor */
603         pthread_attr_t attr;    /**< Thread attributes */
604         int ret;
605
606         lprintf(3, "Creating a new thread\n");
607
608         /** set attributes for the new thread */
609         pthread_attr_init(&attr);
610         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
611
612         /**
613          * Our per-thread stacks need to be bigger than the default size, otherwise
614          * the MIME parser crashes on FreeBSD, and the IMAP service crashes on
615          * 64-bit Linux.
616          */
617         if ((ret = pthread_attr_setstacksize(&attr, 1024 * 1024))) {
618                 lprintf(1, "pthread_attr_setstacksize: %s\n",
619                         strerror(ret));
620                 pthread_attr_destroy(&attr);
621         }
622
623         /** now create the thread */
624         if (pthread_create(&SessThread, &attr,
625                            (void *(*)(void *)) worker_entry, NULL)
626             != 0) {
627                 lprintf(1, "Can't create thread: %s\n", strerror(errno));
628         }
629
630         /** free up the attributes */
631         pthread_attr_destroy(&attr);
632 }
633
634 /**
635  * \brief Here's where it all begins.
636  * \param argc number of commandline args
637  * \param argv the commandline arguments
638  */
639 int main(int argc, char **argv)
640 {
641         pthread_t SessThread;   /**< Thread descriptor */
642         pthread_attr_t attr;    /**< Thread attributes */
643         int a, i;                       /**< General-purpose variables */
644         char tracefile[PATH_MAX];
645         char ip_addr[256]="0.0.0.0";
646         char dirbuffer[PATH_MAX]="";
647         int relh=0;
648         int home=0;
649         int home_specified=0;
650         char relhome[PATH_MAX]="";
651         char webcitdir[PATH_MAX] = DATADIR;
652         char *pidfile = NULL;
653         char *hdir;
654         const char *basedir;
655 #ifdef ENABLE_NLS
656         char *locale = NULL;
657         char *mo = NULL;
658 #endif /* ENABLE_NLS */
659         char uds_listen_path[PATH_MAX]; /**< listen on a unix domain socket? */
660
661         strcpy(uds_listen_path, "");
662
663         /** Parse command line */
664 #ifdef HAVE_OPENSSL
665         while ((a = getopt(argc, argv, "h:i:p:t:x:dD:cfs")) != EOF)
666 #else
667         while ((a = getopt(argc, argv, "h:i:p:t:x:dD:cf")) != EOF)
668 #endif
669                 switch (a) {
670                 case 'h':
671                         hdir = strdup(optarg);
672                         relh=hdir[0]!='/';
673                         if (!relh) safestrncpy(webcitdir, hdir,
674                                                                    sizeof webcitdir);
675                         else
676                                 safestrncpy(relhome, relhome,
677                                                         sizeof relhome);
678                         /* free(hdir); TODO: SHOULD WE DO THIS? */
679                         home_specified = 1;
680                         home=1;
681                         break;
682                 case 'd':
683                         running_as_daemon = 1;
684                         break;
685                 case 'D':
686                         pidfile = strdup(optarg);
687                         running_as_daemon = 1;
688                         break;
689                 case 'i':
690                         safestrncpy(ip_addr, optarg, sizeof ip_addr);
691                         break;
692                 case 'p':
693                         http_port = atoi(optarg);
694                         if (http_port == 0) {
695                                 safestrncpy(uds_listen_path, optarg, sizeof uds_listen_path);
696                         }
697                         break;
698                 case 't':
699                         safestrncpy(tracefile, optarg, sizeof tracefile);
700                         freopen(tracefile, "w", stdout);
701                         freopen(tracefile, "w", stderr);
702                         freopen(tracefile, "r", stdin);
703                         break;
704                 case 'x':
705                         verbosity = atoi(optarg);
706                         break;
707                 case 'f':
708                         follow_xff = 1;
709                         break;
710                 case 'c':
711                         server_cookie = malloc(256);
712                         if (server_cookie != NULL) {
713                                 safestrncpy(server_cookie,
714                                        "Set-cookie: wcserver=",
715                                         256);
716                                 if (gethostname
717                                     (&server_cookie[strlen(server_cookie)],
718                                      200) != 0) {
719                                         lprintf(2, "gethostname: %s\n",
720                                                 strerror(errno));
721                                         free(server_cookie);
722                                 }
723                         }
724                         break;
725                 case 's':
726                         is_https = 1;
727                         break;
728                 default:
729                         fprintf(stderr, "usage: webserver "
730                                 "[-i ip_addr] [-p http_port] "
731                                 "[-t tracefile] [-c] [-f] "
732                                 "[-d] "
733 #ifdef HAVE_OPENSSL
734                                 "[-s] "
735 #endif
736                                 "[remotehost [remoteport]]\n");
737                         return 1;
738                 }
739
740         if (optind < argc) {
741                 ctdlhost = argv[optind];
742                 if (++optind < argc)
743                         ctdlport = argv[optind];
744         }
745
746         /* daemonize, if we were asked to */
747         if (running_as_daemon) {
748                 start_daemon(pidfile);
749         }
750         else {
751 ///             signal(SIGTERM, graceful_shutdown);
752                 signal(SIGHUP, graceful_shutdown);
753         }
754
755         /** Tell 'em who's in da house */
756         lprintf(1, PACKAGE_STRING "\n");
757         lprintf(1, "Copyright (C) 1996-2007 by the Citadel development team.\n"
758                 "This software is distributed under the terms of the "
759                 "GNU General Public License.\n\n"
760         );
761
762
763         /** initialize the International Bright Young Thing */
764 #ifdef ENABLE_NLS
765         initialize_locales();
766         locale = setlocale(LC_ALL, "");
767         mo = malloc(strlen(webcitdir) + 20);
768         lprintf(9, "Message catalog directory: %s\n", bindtextdomain("webcit", LOCALEDIR"/locale"));
769         free(mo);
770         lprintf(9, "Text domain: %s\n", textdomain("webcit"));
771         lprintf(9, "Text domain Charset: %s\n", bind_textdomain_codeset("webcit","UTF8"));
772 #endif
773
774
775         /* calculate all our path on a central place */
776     /* where to keep our config */
777         
778 #define COMPUTE_DIRECTORY(SUBDIR) memcpy(dirbuffer,SUBDIR, sizeof dirbuffer);\
779         snprintf(SUBDIR,sizeof SUBDIR,  "%s%s%s%s%s%s%s", \
780                          (home&!relh)?webcitdir:basedir, \
781              ((basedir!=webcitdir)&(home&!relh))?basedir:"/", \
782              ((basedir!=webcitdir)&(home&!relh))?"/":"", \
783                          relhome, \
784              (relhome[0]!='\0')?"/":"",\
785                          dirbuffer,\
786                          (dirbuffer[0]!='\0')?"/":"");
787         basedir=RUNDIR;
788         COMPUTE_DIRECTORY(socket_dir);
789         basedir=WWWDIR "/static";
790         COMPUTE_DIRECTORY(static_dir);
791         basedir=WWWDIR "/static.local";
792         COMPUTE_DIRECTORY(static_local_dir);
793
794         snprintf(file_crpt_file_key,
795                  sizeof file_crpt_file_key, 
796                  "%s/citadel.key",
797                  ctdl_key_dir);
798         snprintf(file_crpt_file_csr,
799                  sizeof file_crpt_file_csr, 
800                  "%s/citadel.csr",
801                  ctdl_key_dir);
802         snprintf(file_crpt_file_cer,
803                  sizeof file_crpt_file_cer, 
804                  "%s/citadel.cer",
805                  ctdl_key_dir);
806
807         /** we should go somewhere we can leave our coredump, if enabled... */
808         lprintf(9, "Changing directory to %s\n", socket_dir);
809         if (chdir(webcitdir) != 0) {
810                 perror("chdir");
811         }
812         initialize_viewdefs();
813         initialize_axdefs();
814
815         /**
816          * Set up a place to put thread-specific data.
817          * We only need a single pointer per thread - it points to the
818          * wcsession struct to which the thread is currently bound.
819          */
820         if (pthread_key_create(&MyConKey, NULL) != 0) {
821                 lprintf(1, "Can't create TSD key: %s\n", strerror(errno));
822         }
823         InitialiseSemaphores ();
824
825         /**
826          * Set up a place to put thread-specific SSL data.
827          * We don't stick this in the wcsession struct because SSL starts
828          * up before the session is bound, and it gets torn down between
829          * transactions.
830          */
831 #ifdef HAVE_OPENSSL
832         if (pthread_key_create(&ThreadSSL, NULL) != 0) {
833                 lprintf(1, "Can't create TSD key: %s\n", strerror(errno));
834         }
835 #endif
836
837         /**
838          * Bind the server to our favorite port.
839          * There is no need to check for errors, because ig_tcp_server()
840          * exits if it doesn't succeed.
841          */
842
843         if (!IsEmptyStr(uds_listen_path)) {
844                 lprintf(2, "Attempting to create listener socket at %s...\n", uds_listen_path);
845                 msock = ig_uds_server(uds_listen_path, LISTEN_QUEUE_LENGTH);
846         }
847         else {
848                 lprintf(2, "Attempting to bind to port %d...\n", http_port);
849                 msock = ig_tcp_server(ip_addr, http_port, LISTEN_QUEUE_LENGTH);
850         }
851
852         lprintf(2, "Listening on socket %d\n", msock);
853         signal(SIGPIPE, SIG_IGN);
854
855         pthread_mutex_init(&SessionListMutex, NULL);
856
857         /**
858          * Start up the housekeeping thread
859          */
860         pthread_attr_init(&attr);
861         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
862         pthread_create(&SessThread, &attr,
863                        (void *(*)(void *)) housekeeping_loop, NULL);
864
865
866         /**
867          * If this is an HTTPS server, fire up SSL
868          */
869 #ifdef HAVE_OPENSSL
870         if (is_https) {
871                 init_ssl();
872         }
873 #endif
874
875         /** Start a few initial worker threads */
876         for (i = 0; i < (MIN_WORKER_THREADS); ++i) {
877                 spawn_another_worker_thread();
878         }
879
880         /* now the original thread becomes another worker */
881         worker_entry();
882         return 0;
883 }
884
885
886 /**
887  * Entry point for worker threads
888  */
889 void worker_entry(void)
890 {
891         int ssock;
892         int i = 0;
893         int fail_this_transaction = 0;
894         int ret;
895         struct timeval tv;
896         fd_set readset, tempset;
897
898         tv.tv_sec = 0;
899         tv.tv_usec = 10000;
900         FD_ZERO(&readset);
901         FD_SET(msock, &readset);
902
903         do {
904                 /** Only one thread can accept at a time */
905                 fail_this_transaction = 0;
906                 ssock = -1; 
907                 errno = EAGAIN;
908                 do {
909                         ret = -1; /* just one at once should select... */
910                         begin_critical_section(S_SELECT);
911
912                         FD_ZERO(&tempset);
913                         if (msock > 0) FD_SET(msock, &tempset);
914                         tv.tv_sec = 0;
915                         tv.tv_usec = 10000;
916                         if (msock > 0)  ret = select(msock+1, &tempset, NULL, NULL,  &tv);
917                         end_critical_section(S_SELECT);
918                         if ((ret < 0) && (errno != EINTR) && (errno != EAGAIN))
919                         {// EINTR and EAGAIN are thrown but not of interest.
920                                 lprintf(2, "accept() failed:%d %s\n",
921                                         errno, strerror(errno));
922                         }
923                         else if ((ret > 0) && (msock > 0) && FD_ISSET(msock, &tempset))
924                         {// Successfully selected, and still not shutting down? Accept!
925                                 ssock = accept(msock, NULL, 0);
926                         }
927                         
928                 } while ((msock > 0) && (ssock < 0)  && (time_to_die == 0));
929
930                 if ((msock == -1)||(time_to_die))
931                 {// ok, we're going down.
932                         int shutdown = 0;
933
934                         /* the first to come here will have to do the cleanup.
935                          * make shure its realy just one.
936                          */
937                         begin_critical_section(S_SHUTDOWN);
938                         if (msock == -1)
939                         {
940                                 msock = -2;
941                                 shutdown = 1;
942                         }
943                         end_critical_section(S_SHUTDOWN);
944                         if (shutdown == 1)
945                         {// we're the one to cleanup the mess.
946                                 lprintf(2, "I'm master shutdown: tagging sessions to be killed.\n");
947                                 shutdown_sessions();
948                                 lprintf(2, "master shutdown: waiting for others\n");
949                                 sleeeeeeeeeep(1); // wait so some others might finish...
950                                 lprintf(2, "master shutdown: cleaning up sessions\n");
951                                 do_housekeeping();
952 #ifdef WEBCIT_WITH_CALENDAR_SERVICE
953                                 free_zone_directory ();
954                                 icaltimezone_release_zone_tab ();
955 #endif
956                                 lprintf(2, "master shutdown exiting!.\n");                              
957                                 exit(0);
958                         }
959                         break;
960                 }
961                 if (ssock < 0 ) continue;
962
963                 if (msock < 0) {
964                         if (ssock > 0) close (ssock);
965                         lprintf(2, "inbetween.");
966                         pthread_exit(NULL);
967                 } else { // Got it? do some real work!
968                         /** Set the SO_REUSEADDR socket option */
969                         i = 1;
970                         setsockopt(ssock, SOL_SOCKET, SO_REUSEADDR,
971                                    &i, sizeof(i));
972
973                         /** If we are an HTTPS server, go crypto now. */
974 #ifdef HAVE_OPENSSL
975                         if (is_https) {
976                                 if (starttls(ssock) != 0) {
977                                         fail_this_transaction = 1;
978                                         close(ssock);
979                                 }
980                         }
981 #endif
982
983                         if (fail_this_transaction == 0) {
984
985                                 /** Perform an HTTP transaction... */
986                                 context_loop(ssock);
987
988                                 /** Shut down SSL/TLS if required... */
989 #ifdef HAVE_OPENSSL
990                                 if (is_https) {
991                                         endtls();
992                                 }
993 #endif
994
995                                 /** ...and close the socket. */
996                                 lingering_close(ssock);
997                         }
998
999                 }
1000
1001         } while (!time_to_die);
1002
1003         lprintf (1, "bye\n");
1004         pthread_exit(NULL);
1005 }
1006
1007 /**
1008  * \brief logprintf. log messages 
1009  * logs to stderr if loglevel is lower than the verbosity set at startup
1010  * \param loglevel level of the message
1011  * \param format the printf like format string
1012  * \param ... the strings to put into format
1013  */
1014 int lprintf(int loglevel, const char *format, ...)
1015 {
1016         va_list ap;
1017
1018         if (loglevel <= verbosity) {
1019                 va_start(ap, format);
1020                 vfprintf(stderr, format, ap);
1021                 va_end(ap);
1022                 fflush(stderr);
1023         }
1024         return 1;
1025 }
1026
1027
1028 /**
1029  * \brief print the actual stack frame.
1030  */
1031 void wc_backtrace(void)
1032 {
1033 #ifdef HAVE_BACKTRACE
1034         void *stack_frames[50];
1035         size_t size, i;
1036         char **strings;
1037
1038
1039         size = backtrace(stack_frames, sizeof(stack_frames) / sizeof(void*));
1040         strings = backtrace_symbols(stack_frames, size);
1041         for (i = 0; i < size; i++) {
1042                 if (strings != NULL)
1043                         lprintf(1, "%s\n", strings[i]);
1044                 else
1045                         lprintf(1, "%p\n", stack_frames[i]);
1046         }
1047         free(strings);
1048 #endif
1049 }
1050
1051 /*@}*/