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