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