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