7b366df3c2d020dd8e5b68a79688a18bc7689e7d
[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
412         /* Parse command line */
413 #ifdef HAVE_OPENSSL
414         while ((a = getopt(argc, argv, "hi:p:t:x:cs")) != EOF)
415 #else
416         while ((a = getopt(argc, argv, "hi:p:t:x:c")) != EOF)
417 #endif
418                 switch (a) {
419                 case 'i':
420                         safestrncpy(ip_addr, optarg, sizeof ip_addr);
421                         break;
422                 case 'p':
423                         port = atoi(optarg);
424                         break;
425                 case 't':
426                         safestrncpy(tracefile, optarg, sizeof tracefile);
427                         freopen(tracefile, "w", stdout);
428                         freopen(tracefile, "w", stderr);
429                         freopen(tracefile, "r", stdin);
430                         break;
431                 case 'x':
432                         verbosity = atoi(optarg);
433                         break;
434                 case 'c':
435                         server_cookie = malloc(256);
436                         if (server_cookie != NULL) {
437                                 safestrncpy(server_cookie,
438                                        "Set-cookie: wcserver=",
439                                         256);
440                                 if (gethostname
441                                     (&server_cookie[strlen(server_cookie)],
442                                      200) != 0) {
443                                         lprintf(2, "gethostname: %s\n",
444                                                 strerror(errno));
445                                         free(server_cookie);
446                                 }
447                         }
448                         break;
449                 case 's':
450                         is_https = 1;
451                         break;
452                 default:
453                         fprintf(stderr, "usage: webserver "
454                                 "[-i ip_addr] [-p http_port] "
455                                 "[-t tracefile] [-c] "
456 #ifdef HAVE_OPENSSL
457                                 "[-s] "
458 #endif
459                                 "[remotehost [remoteport]]\n");
460                         return 1;
461                 }
462
463         if (optind < argc) {
464                 ctdlhost = argv[optind];
465                 if (++optind < argc)
466                         ctdlport = argv[optind];
467         }
468         /* Tell 'em who's in da house */
469         lprintf(1, SERVER "\n"
470                 "Copyright (C) 1996-2005 by the Citadel/UX development team.\n"
471                 "This software is distributed under the terms of the GNU General Public\n"
472                 "License.  If you paid for this software, someone is ripping you off.\n\n");
473
474         if (chdir(WEBCITDIR) != 0)
475                 perror("chdir");
476
477         /*
478          * Set up a place to put thread-specific data.
479          * We only need a single pointer per thread - it points to the
480          * wcsession struct to which the thread is currently bound.
481          */
482         if (pthread_key_create(&MyConKey, NULL) != 0) {
483                 lprintf(1, "Can't create TSD key: %s\n", strerror(errno));
484         }
485
486         /*
487          * Set up a place to put thread-specific SSL data.
488          * We don't stick this in the wcsession struct because SSL starts
489          * up before the session is bound, and it gets torn down between
490          * transactions.
491          */
492 #ifdef HAVE_OPENSSL
493         if (pthread_key_create(&ThreadSSL, NULL) != 0) {
494                 lprintf(1, "Can't create TSD key: %s\n", strerror(errno));
495         }
496 #endif
497
498         /*
499          * Bind the server to our favorite port.
500          * There is no need to check for errors, because ig_tcp_server()
501          * exits if it doesn't succeed.
502          */
503         lprintf(2, "Attempting to bind to port %d...\n", port);
504         msock = ig_tcp_server(ip_addr, port, LISTEN_QUEUE_LENGTH);
505         lprintf(2, "Listening on socket %d\n", msock);
506         signal(SIGPIPE, SIG_IGN);
507
508         pthread_mutex_init(&SessionListMutex, NULL);
509
510         /*
511          * Start up the housekeeping thread
512          */
513         pthread_attr_init(&attr);
514         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
515         pthread_create(&SessThread, &attr,
516                        (void *(*)(void *)) housekeeping_loop, NULL);
517
518
519         /*
520          * If this is an HTTPS server, fire up SSL
521          */
522 #ifdef HAVE_OPENSSL
523         if (is_https) {
524                 init_ssl();
525         }
526 #endif
527
528         /* Start a few initial worker threads */
529         for (i = 0; i < (MIN_WORKER_THREADS); ++i) {
530                 spawn_another_worker_thread();
531         }
532
533         /* now the original thread becomes another worker */
534         worker_entry();
535         return 0;
536 }
537
538
539 /*
540  * Entry point for worker threads
541  */
542 void worker_entry(void)
543 {
544         int ssock;
545         int i = 0;
546         int time_to_die = 0;
547         int fail_this_transaction = 0;
548
549         do {
550                 /* Only one thread can accept at a time */
551                 fail_this_transaction = 0;
552                 ssock = accept(msock, NULL, 0);
553                 if (ssock < 0) {
554                         lprintf(2, "accept() failed: %s\n",
555                                 strerror(errno));
556                 } else {
557                         /* Set the SO_REUSEADDR socket option */
558                         i = 1;
559                         setsockopt(ssock, SOL_SOCKET, SO_REUSEADDR,
560                                    &i, sizeof(i));
561
562                         /* If we are an HTTPS server, go crypto now. */
563 #ifdef HAVE_OPENSSL
564                         if (is_https) {
565                                 if (starttls(ssock) != 0) {
566                                         fail_this_transaction = 1;
567                                         close(ssock);
568                                 }
569                         }
570 #endif
571
572                         if (fail_this_transaction == 0) {
573                                 /* Perform an HTTP transaction... */
574                                 context_loop(ssock);
575                                 /* ...and close the socket. */
576                                 lingering_close(ssock);
577                         }
578
579                 }
580
581         } while (!time_to_die);
582
583         pthread_exit(NULL);
584 }
585
586
587 int lprintf(int loglevel, const char *format, ...)
588 {
589         va_list ap;
590
591         if (loglevel <= verbosity) {
592                 va_start(ap, format);
593                 vfprintf(stderr, format, ap);
594                 va_end(ap);
595                 fflush(stderr);
596         }
597         return 1;
598 }