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