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