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