963a11422856a58eb1f8c2f77e47bcce3ce426b2
[citadel.git] / webcit / webserver.c
1 /*
2  * $Id$
3  *
4  * This contains a simple multithreaded TCP server manager.  It sits around
5  * waiting on the specified port for incoming HTTP connections.  When a
6  * connection is established, it calls context_loop() from context_loop.c.
7  *
8  */
9
10
11 #include "webcit.h"
12 #include "webserver.h"
13
14 #ifndef HAVE_SNPRINTF
15 int vsnprintf(char *buf, size_t max, const char *fmt, va_list argp);
16 #endif
17
18 int verbosity = 9;              /* Logging level */
19 int msock;                      /* master listening socket */
20 int is_https = 0;               /* Nonzero if I am an HTTPS service */
21 int follow_xff = 0;             /* Follow X-Forwarded-For: header */
22 extern void *context_loop(int);
23 extern void *housekeeping_loop(void);
24 extern pthread_mutex_t SessionListMutex;
25 extern pthread_key_t MyConKey;
26
27
28 char *server_cookie = NULL;
29
30
31 char *ctdlhost = DEFAULT_HOST;
32 char *ctdlport = DEFAULT_PORT;
33 int setup_wizard = 0;
34 char wizard_filename[PATH_MAX];
35
36 /*
37  * This is a generic function to set up a master socket for listening on
38  * a TCP port.  The server shuts down if the bind fails.
39  */
40 int ig_tcp_server(char *ip_addr, int port_number, int queue_len)
41 {
42         struct sockaddr_in sin;
43         int s, i;
44
45         memset(&sin, 0, sizeof(sin));
46         sin.sin_family = AF_INET;
47         if (ip_addr == NULL) {
48                 sin.sin_addr.s_addr = INADDR_ANY;
49         } else {
50                 sin.sin_addr.s_addr = inet_addr(ip_addr);
51         }
52
53         if (sin.sin_addr.s_addr == INADDR_NONE) {
54                 sin.sin_addr.s_addr = INADDR_ANY;
55         }
56
57         if (port_number == 0) {
58                 lprintf(1, "Cannot start: no port number specified.\n");
59                 exit(1);
60         }
61         sin.sin_port = htons((u_short) port_number);
62
63         s = socket(PF_INET, SOCK_STREAM, (getprotobyname("tcp")->p_proto));
64         if (s < 0) {
65                 lprintf(1, "Can't create a socket: %s\n", strerror(errno));
66                 exit(errno);
67         }
68         /* Set some socket options that make sense. */
69         i = 1;
70         setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
71
72         if (bind(s, (struct sockaddr *) &sin, sizeof(sin)) < 0) {
73                 lprintf(1, "Can't bind: %s\n", strerror(errno));
74                 exit(errno);
75         }
76         if (listen(s, queue_len) < 0) {
77                 lprintf(1, "Can't listen: %s\n", strerror(errno));
78                 exit(errno);
79         }
80         return (s);
81 }
82
83
84
85 /*
86  * Create a Unix domain socket and listen on it
87  */
88 int ig_uds_server(char *sockpath, int queue_len)
89 {
90         struct sockaddr_un addr;
91         int s;
92         int i;
93         int actual_queue_len;
94
95         actual_queue_len = queue_len;
96         if (actual_queue_len < 5) actual_queue_len = 5;
97
98         i = unlink(sockpath);
99         if (i != 0) if (errno != ENOENT) {
100                 lprintf(1, "citserver: can't unlink %s: %s\n",
101                         sockpath, strerror(errno));
102                 exit(errno);
103         }
104
105         memset(&addr, 0, sizeof(addr));
106         addr.sun_family = AF_UNIX;
107         safestrncpy(addr.sun_path, sockpath, sizeof addr.sun_path);
108
109         s = socket(AF_UNIX, SOCK_STREAM, 0);
110         if (s < 0) {
111                 lprintf(1, "citserver: Can't create a socket: %s\n",
112                         strerror(errno));
113                 exit(errno);
114         }
115
116         if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
117                 lprintf(1, "citserver: Can't bind: %s\n",
118                         strerror(errno));
119                 exit(errno);
120         }
121
122         if (listen(s, actual_queue_len) < 0) {
123                 lprintf(1, "citserver: Can't listen: %s\n",
124                         strerror(errno));
125                 exit(errno);
126         }
127
128         chmod(sockpath, 0777);
129         return(s);
130 }
131
132
133
134
135 /*
136  * Read data from the client socket.
137  * Return values are:
138  *      1       Requested number of bytes has been read.
139  *      0       Request timed out.
140  *      -1      Connection is broken, or other error.
141  */
142 int client_read_to(int sock, char *buf, int bytes, int timeout)
143 {
144         int len, rlen;
145         fd_set rfds;
146         struct timeval tv;
147         int retval;
148
149
150 #ifdef HAVE_OPENSSL
151         if (is_https) {
152                 return (client_read_ssl(buf, bytes, timeout));
153         }
154 #endif
155
156         len = 0;
157         while (len < bytes) {
158                 FD_ZERO(&rfds);
159                 FD_SET(sock, &rfds);
160                 tv.tv_sec = timeout;
161                 tv.tv_usec = 0;
162
163                 retval = select((sock) + 1, &rfds, NULL, NULL, &tv);
164                 if (FD_ISSET(sock, &rfds) == 0) {
165                         return (0);
166                 }
167
168                 rlen = read(sock, &buf[len], bytes - len);
169
170                 if (rlen < 1) {
171                         lprintf(2, "client_read() failed: %s\n",
172                                 strerror(errno));
173                         return (-1);
174                 }
175                 len = len + rlen;
176         }
177
178 #ifdef HTTP_TRACING
179         write(2, "\033[32m", 5);
180         write(2, buf, bytes);
181         write(2, "\033[30m", 5);
182 #endif
183         return (1);
184 }
185
186
187 ssize_t client_write(const void *buf, size_t count)
188 {
189
190         if (WC->burst != NULL) {
191                 WC->burst =
192                     realloc(WC->burst, (WC->burst_len + count + 2));
193                 memcpy(&WC->burst[WC->burst_len], buf, count);
194                 WC->burst_len += count;
195                 return (count);
196         }
197 #ifdef HAVE_OPENSSL
198         if (is_https) {
199                 client_write_ssl((char *) buf, count);
200                 return (count);
201         }
202 #endif
203 #ifdef HTTP_TRACING
204         write(2, "\033[34m", 5);
205         write(2, buf, count);
206         write(2, "\033[30m", 5);
207 #endif
208         return (write(WC->http_sock, buf, count));
209 }
210
211
212 void begin_burst(void)
213 {
214         if (WC->burst != NULL) {
215                 free(WC->burst);
216                 WC->burst = NULL;
217         }
218         WC->burst_len = 0;
219         WC->burst = malloc(SIZ);
220 }
221
222
223 /*
224  * compress_gzip() uses the same calling syntax as compress2(), but it
225  * creates a stream compatible with HTTP "Content-encoding: gzip"
226  */
227 #ifdef HAVE_ZLIB
228 #define DEF_MEM_LEVEL 8
229 #define OS_CODE 0x03    /* unix */
230 int ZEXPORT compress_gzip(Bytef * dest, uLongf * destLen,
231                           const Bytef * source, uLong sourceLen, int level)
232 {
233         const int gz_magic[2] = { 0x1f, 0x8b }; /* gzip magic header */
234
235         /* write gzip header */
236         sprintf((char *) dest, "%c%c%c%c%c%c%c%c%c%c",
237                 gz_magic[0], gz_magic[1], Z_DEFLATED,
238                 0 /*flags */ , 0, 0, 0, 0 /*time */ , 0 /*xflags */ ,
239                 OS_CODE);
240
241         /* normal deflate */
242         z_stream stream;
243         int err;
244         stream.next_in = (Bytef *) source;
245         stream.avail_in = (uInt) sourceLen;
246         stream.next_out = dest + 10L;   // after header
247         stream.avail_out = (uInt) * destLen;
248         if ((uLong) stream.avail_out != *destLen)
249                 return Z_BUF_ERROR;
250
251         stream.zalloc = (alloc_func) 0;
252         stream.zfree = (free_func) 0;
253         stream.opaque = (voidpf) 0;
254
255         err = deflateInit2(&stream, level, Z_DEFLATED, -MAX_WBITS,
256                            DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
257         if (err != Z_OK)
258                 return err;
259
260         err = deflate(&stream, Z_FINISH);
261         if (err != Z_STREAM_END) {
262                 deflateEnd(&stream);
263                 return err == Z_OK ? Z_BUF_ERROR : err;
264         }
265         *destLen = stream.total_out + 10L;
266
267         /* write CRC and Length */
268         uLong crc = crc32(0L, source, sourceLen);
269         int n;
270         for (n = 0; n < 4; ++n, ++*destLen) {
271                 dest[*destLen] = (int) (crc & 0xff);
272                 crc >>= 8;
273         }
274         uLong len = stream.total_in;
275         for (n = 0; n < 4; ++n, ++*destLen) {
276                 dest[*destLen] = (int) (len & 0xff);
277                 len >>= 8;
278         }
279         err = deflateEnd(&stream);
280         return err;
281 }
282 #endif
283
284 void end_burst(void)
285 {
286         size_t the_len;
287         char *the_data;
288
289         if (WC->burst == NULL)
290                 return;
291
292         the_len = WC->burst_len;
293         the_data = WC->burst;
294
295         WC->burst_len = 0;
296         WC->burst = NULL;
297
298 #ifdef HAVE_ZLIB
299         /* Handle gzip compression */
300         if (WC->gzip_ok) {
301                 char *compressed_data = NULL;
302                 uLongf compressed_len;
303
304                 compressed_len = (uLongf) ((the_len * 101) / 100) + 100;
305                 compressed_data = malloc(compressed_len);
306
307                 if (compress_gzip((Bytef *) compressed_data,
308                                   &compressed_len,
309                                   (Bytef *) the_data,
310                                   (uLongf) the_len, Z_BEST_SPEED) == Z_OK) {
311                         wprintf("Content-encoding: gzip\r\n");
312                         free(the_data);
313                         the_data = compressed_data;
314                         the_len = compressed_len;
315                 } else {
316                         free(compressed_data);
317                 }
318         }
319 #endif                          /* HAVE_ZLIB */
320
321         wprintf("Content-length: %d\r\n\r\n", the_len);
322         client_write(the_data, the_len);
323         free(the_data);
324         return;
325 }
326
327
328
329 /*
330  * Read data from the client socket with default timeout.
331  * (This is implemented in terms of client_read_to() and could be
332  * justifiably moved out of sysdep.c)
333  */
334 int client_read(int sock, char *buf, int bytes)
335 {
336         return (client_read_to(sock, buf, bytes, SLEEPING));
337 }
338
339
340 /*
341  * client_getln()   ...   Get a LF-terminated line of text from the client.
342  * (This is implemented in terms of client_read() and could be
343  * justifiably moved out of sysdep.c)
344  */
345 int client_getln(int sock, char *buf, int bufsiz)
346 {
347         int i, retval;
348
349         /* Read one character at a time.
350          */
351         for (i = 0;; i++) {
352                 retval = client_read(sock, &buf[i], 1);
353                 if (retval != 1 || buf[i] == '\n' || i == (bufsiz-1))
354                         break;
355         }
356
357         /* If we got a long line, discard characters until the newline.
358          */
359         if (i == (bufsiz-1))
360                 while (buf[i] != '\n' && retval == 1)
361                         retval = client_read(sock, &buf[i], 1);
362
363         /*
364          * Strip any trailing non-printable characters.
365          */
366         buf[i] = 0;
367         while ((strlen(buf) > 0) && (!isprint(buf[strlen(buf) - 1]))) {
368                 buf[strlen(buf) - 1] = 0;
369         }
370         return (retval);
371 }
372
373
374 /*
375  * Start running as a daemon.  Only close stdio if do_close_stdio is set.
376  */
377 void start_daemon(int do_close_stdio)
378 {
379         if (do_close_stdio) {
380                 /* close(0); */
381                 close(1);
382                 close(2);
383         }
384         signal(SIGHUP, SIG_IGN);
385         signal(SIGINT, SIG_IGN);
386         signal(SIGQUIT, SIG_IGN);
387         if (fork() != 0)
388                 exit(0);
389 }
390
391 void spawn_another_worker_thread()
392 {
393         pthread_t SessThread;   /* Thread descriptor */
394         pthread_attr_t attr;    /* Thread attributes */
395         int ret;
396
397         lprintf(3, "Creating a new thread\n");
398
399         /* set attributes for the new thread */
400         pthread_attr_init(&attr);
401         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
402
403         /* Our per-thread stacks need to be bigger than the default size, otherwise
404          * the MIME parser crashes on FreeBSD, and the IMAP service crashes on
405          * 64-bit Linux.
406          */
407         if ((ret = pthread_attr_setstacksize(&attr, 1024 * 1024))) {
408                 lprintf(1, "pthread_attr_setstacksize: %s\n",
409                         strerror(ret));
410                 pthread_attr_destroy(&attr);
411         }
412
413         /* now create the thread */
414         if (pthread_create(&SessThread, &attr,
415                            (void *(*)(void *)) worker_entry, NULL)
416             != 0) {
417                 lprintf(1, "Can't create thread: %s\n", strerror(errno));
418         }
419
420         /* free up the attributes */
421         pthread_attr_destroy(&attr);
422 }
423
424 /*
425  * Here's where it all begins.
426  */
427 int main(int argc, char **argv)
428 {
429         pthread_t SessThread;   /* Thread descriptor */
430         pthread_attr_t attr;    /* Thread attributes */
431         int a, i;               /* General-purpose variables */
432         int port = PORT_NUM;    /* Port to listen on */
433         char tracefile[PATH_MAX];
434         char ip_addr[256];
435         char *webcitdir = WEBCITDIR;
436 #ifdef ENABLE_NLS
437         char *locale = NULL;
438         char *mo = NULL;
439 #endif /* ENABLE_NLS */
440         char uds_listen_path[PATH_MAX]; /* listen on a unix domain socket? */
441
442         strcpy(uds_listen_path, "");
443
444         /* Parse command line */
445 #ifdef HAVE_OPENSSL
446         while ((a = getopt(argc, argv, "h:i:p:t:x:cfs")) != EOF)
447 #else
448         while ((a = getopt(argc, argv, "h:i:p:t:x:cf")) != EOF)
449 #endif
450                 switch (a) {
451                 case 'h':
452                         webcitdir = strdup(optarg);
453                         break;
454                 case 'i':
455                         safestrncpy(ip_addr, optarg, sizeof ip_addr);
456                         break;
457                 case 'p':
458                         port = atoi(optarg);
459                         if (port == 0) {
460                                 safestrncpy(uds_listen_path, optarg, sizeof uds_listen_path);
461                         }
462                         break;
463                 case 't':
464                         safestrncpy(tracefile, optarg, sizeof tracefile);
465                         freopen(tracefile, "w", stdout);
466                         freopen(tracefile, "w", stderr);
467                         freopen(tracefile, "r", stdin);
468                         break;
469                 case 'x':
470                         verbosity = atoi(optarg);
471                         break;
472                 case 'f':
473                         follow_xff = 1;
474                         break;
475                 case 'c':
476                         server_cookie = malloc(256);
477                         if (server_cookie != NULL) {
478                                 safestrncpy(server_cookie,
479                                        "Set-cookie: wcserver=",
480                                         256);
481                                 if (gethostname
482                                     (&server_cookie[strlen(server_cookie)],
483                                      200) != 0) {
484                                         lprintf(2, "gethostname: %s\n",
485                                                 strerror(errno));
486                                         free(server_cookie);
487                                 }
488                         }
489                         break;
490                 case 's':
491                         is_https = 1;
492                         break;
493                 default:
494                         fprintf(stderr, "usage: webserver "
495                                 "[-i ip_addr] [-p http_port] "
496                                 "[-t tracefile] [-c] [-f] "
497 #ifdef HAVE_OPENSSL
498                                 "[-s] "
499 #endif
500                                 "[remotehost [remoteport]]\n");
501                         return 1;
502                 }
503
504         if (optind < argc) {
505                 ctdlhost = argv[optind];
506                 if (++optind < argc)
507                         ctdlport = argv[optind];
508         }
509         /* Tell 'em who's in da house */
510         lprintf(1, SERVER "\n");
511         lprintf(1, "Copyright (C) 1996-2005 by the Citadel development team.\n"
512                 "This software is distributed under the terms of the "
513                 "GNU General Public License.\n\n"
514         );
515
516         lprintf(9, "Changing directory to %s\n", webcitdir);
517         if (chdir(webcitdir) != 0) {
518                 perror("chdir");
519         }
520
521         /* initialize the International Bright Young Thing */
522 #ifdef ENABLE_NLS
523
524         initialize_locales();
525
526         locale = setlocale(LC_ALL, "");
527
528         mo = malloc(strlen(webcitdir) + 20);
529         sprintf(mo, "%s/locale", webcitdir);
530         lprintf(9, "Message catalog directory: %s\n",
531                 bindtextdomain("webcit", mo)
532         );
533         free(mo);
534         lprintf(9, "Text domain: %s\n",
535                 textdomain("webcit")
536         );
537         lprintf(9, "Text domain Charset: %s\n",
538                         bind_textdomain_codeset("webcit","UTF8")
539         );
540 #endif
541
542         initialize_viewdefs();
543         initialize_axdefs();
544
545         /*
546          * Set up a place to put thread-specific data.
547          * We only need a single pointer per thread - it points to the
548          * wcsession struct to which the thread is currently bound.
549          */
550         if (pthread_key_create(&MyConKey, NULL) != 0) {
551                 lprintf(1, "Can't create TSD key: %s\n", strerror(errno));
552         }
553
554         /*
555          * Set up a place to put thread-specific SSL data.
556          * We don't stick this in the wcsession struct because SSL starts
557          * up before the session is bound, and it gets torn down between
558          * transactions.
559          */
560 #ifdef HAVE_OPENSSL
561         if (pthread_key_create(&ThreadSSL, NULL) != 0) {
562                 lprintf(1, "Can't create TSD key: %s\n", strerror(errno));
563         }
564 #endif
565
566         /*
567          * Bind the server to our favorite port.
568          * There is no need to check for errors, because ig_tcp_server()
569          * exits if it doesn't succeed.
570          */
571
572         if (strlen(uds_listen_path) > 0) {
573                 lprintf(2, "Attempting to create listener socket at %s...\n", uds_listen_path);
574                 msock = ig_uds_server(uds_listen_path, LISTEN_QUEUE_LENGTH);
575         }
576         else {
577                 lprintf(2, "Attempting to bind to port %d...\n", port);
578                 msock = ig_tcp_server(ip_addr, port, LISTEN_QUEUE_LENGTH);
579         }
580
581         lprintf(2, "Listening on socket %d\n", msock);
582         signal(SIGPIPE, SIG_IGN);
583
584         pthread_mutex_init(&SessionListMutex, NULL);
585
586         /*
587          * Start up the housekeeping thread
588          */
589         pthread_attr_init(&attr);
590         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
591         pthread_create(&SessThread, &attr,
592                        (void *(*)(void *)) housekeeping_loop, NULL);
593
594
595         /*
596          * If this is an HTTPS server, fire up SSL
597          */
598 #ifdef HAVE_OPENSSL
599         if (is_https) {
600                 init_ssl();
601         }
602 #endif
603
604         /* Start a few initial worker threads */
605         for (i = 0; i < (MIN_WORKER_THREADS); ++i) {
606                 spawn_another_worker_thread();
607         }
608
609         /* now the original thread becomes another worker */
610         worker_entry();
611         return 0;
612 }
613
614
615 /*
616  * Entry point for worker threads
617  */
618 void worker_entry(void)
619 {
620         int ssock;
621         int i = 0;
622         int time_to_die = 0;
623         int fail_this_transaction = 0;
624
625         do {
626                 /* Only one thread can accept at a time */
627                 fail_this_transaction = 0;
628                 ssock = accept(msock, NULL, 0);
629                 if (ssock < 0) {
630                         lprintf(2, "accept() failed: %s\n",
631                                 strerror(errno));
632                 } else {
633                         /* Set the SO_REUSEADDR socket option */
634                         i = 1;
635                         setsockopt(ssock, SOL_SOCKET, SO_REUSEADDR,
636                                    &i, sizeof(i));
637
638                         /* If we are an HTTPS server, go crypto now. */
639 #ifdef HAVE_OPENSSL
640                         if (is_https) {
641                                 if (starttls(ssock) != 0) {
642                                         fail_this_transaction = 1;
643                                         close(ssock);
644                                 }
645                         }
646 #endif
647
648                         if (fail_this_transaction == 0) {
649                                 /* Perform an HTTP transaction... */
650                                 context_loop(ssock);
651                                 /* ...and close the socket. */
652                                 lingering_close(ssock);
653                         }
654
655                 }
656
657         } while (!time_to_die);
658
659         pthread_exit(NULL);
660 }
661
662
663 int lprintf(int loglevel, const char *format, ...)
664 {
665         va_list ap;
666
667         if (loglevel <= verbosity) {
668                 va_start(ap, format);
669                 vfprintf(stderr, format, ap);
670                 va_end(ap);
671                 fflush(stderr);
672         }
673         return 1;
674 }