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