]> code.citadel.org Git - citadel.git/blob - webcit/webserver.c
* When the "begin_burst() / end_burst()" semantics are in use, perform
[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 #define HTTP_TRACING 1
13  */
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 #ifdef HAVE_ZLIB
47 #include <zlib.h>
48 #endif
49
50 #ifndef HAVE_SNPRINTF
51 int vsnprintf(char *buf, size_t max, const char *fmt, va_list argp);
52 #endif
53
54 int verbosity = 9;              /* Logging level */
55 int msock;                      /* master listening socket */
56 int is_https = 0;               /* Nonzero if I am an HTTPS service */
57 extern void *context_loop(int);
58 extern void *housekeeping_loop(void);
59 extern pthread_mutex_t SessionListMutex;
60 extern pthread_key_t MyConKey;
61
62
63 char *server_cookie = NULL;
64
65
66 char *ctdlhost = DEFAULT_HOST;
67 char *ctdlport = DEFAULT_PORT;
68
69 /*
70  * This is a generic function to set up a master socket for listening on
71  * a TCP port.  The server shuts down if the bind fails.
72  */
73 int ig_tcp_server(char *ip_addr, int port_number, int queue_len)
74 {
75         struct sockaddr_in sin;
76         int s, i;
77
78         memset(&sin, 0, sizeof(sin));
79         sin.sin_family = AF_INET;
80         if (ip_addr == NULL) {
81                 sin.sin_addr.s_addr = INADDR_ANY;
82         } else {
83                 sin.sin_addr.s_addr = inet_addr(ip_addr);
84         }
85
86         if (sin.sin_addr.s_addr == INADDR_NONE) {
87                 sin.sin_addr.s_addr = INADDR_ANY;
88         }
89
90         if (port_number == 0) {
91                 lprintf(1, "Cannot start: no port number specified.\n");
92                 exit(1);
93         }
94         sin.sin_port = htons((u_short) port_number);
95
96         s = socket(PF_INET, SOCK_STREAM, (getprotobyname("tcp")->p_proto));
97         if (s < 0) {
98                 lprintf(1, "Can't create a socket: %s\n", strerror(errno));
99                 exit(errno);
100         }
101         /* Set some socket options that make sense. */
102         i = 1;
103         setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
104
105         if (bind(s, (struct sockaddr *) &sin, sizeof(sin)) < 0) {
106                 lprintf(1, "Can't bind: %s\n", strerror(errno));
107                 exit(errno);
108         }
109         if (listen(s, queue_len) < 0) {
110                 lprintf(1, "Can't listen: %s\n", strerror(errno));
111                 exit(errno);
112         }
113         return (s);
114 }
115
116
117 /*
118  * Read data from the client socket.
119  * Return values are:
120  *      1       Requested number of bytes has been read.
121  *      0       Request timed out.
122  *      -1      Connection is broken, or other error.
123  */
124 int client_read_to(int sock, char *buf, int bytes, int timeout)
125 {
126         int len, rlen;
127         fd_set rfds;
128         struct timeval tv;
129         int retval;
130
131
132 #ifdef HAVE_OPENSSL
133         if (is_https) {
134                 return (client_read_ssl(buf, bytes, timeout));
135         }
136 #endif
137
138         len = 0;
139         while (len < bytes) {
140                 FD_ZERO(&rfds);
141                 FD_SET(sock, &rfds);
142                 tv.tv_sec = timeout;
143                 tv.tv_usec = 0;
144
145                 retval = select((sock) + 1, &rfds, NULL, NULL, &tv);
146                 if (FD_ISSET(sock, &rfds) == 0) {
147                         return (0);
148                 }
149
150                 rlen = read(sock, &buf[len], bytes - len);
151
152                 if (rlen < 1) {
153                         lprintf(2, "client_read() failed: %s\n",
154                                 strerror(errno));
155                         return (-1);
156                 }
157                 len = len + rlen;
158         }
159
160 #ifdef HTTP_TRACING
161         write(2, "\033[32m", 5);
162         write(2, buf, bytes);
163         write(2, "\033[30m", 5);
164 #endif
165         return (1);
166 }
167
168
169 ssize_t client_write(const void *buf, size_t count)
170 {
171
172         if (WC->burst != NULL) {
173                 WC->burst =
174                     realloc(WC->burst, (WC->burst_len + count + 2));
175                 memcpy(&WC->burst[WC->burst_len], buf, count);
176                 WC->burst_len += count;
177                 return (count);
178         }
179 #ifdef HAVE_OPENSSL
180         if (is_https) {
181                 client_write_ssl((char *) buf, count);
182                 return (count);
183         }
184 #endif
185 #ifdef HTTP_TRACING
186         write(2, "\033[34m", 5);
187         write(2, buf, count);
188         write(2, "\033[30m", 5);
189 #endif
190         return (write(WC->http_sock, buf, count));
191 }
192
193
194 void begin_burst(void)
195 {
196         if (WC->burst != NULL) {
197                 free(WC->burst);
198                 WC->burst = NULL;
199         }
200         WC->burst_len = 0;
201         WC->burst = malloc(SIZ);
202 }
203
204
205 /*
206  * compress_gzip() uses the same calling syntax as compress2(), but it
207  * creates a stream compatible with HTTP "Content-encoding: gzip"
208  */
209 #ifdef HAVE_ZLIB
210 #define DEF_MEM_LEVEL 8
211 #define OS_CODE 0x03    /* unix */
212 int ZEXPORT compress_gzip(Bytef * dest, uLongf * destLen,
213                           const Bytef * source, uLong sourceLen, int level)
214 {
215         const int gz_magic[2] = { 0x1f, 0x8b }; /* gzip magic header */
216
217         /* write gzip header */
218         sprintf((char *) dest, "%c%c%c%c%c%c%c%c%c%c",
219                 gz_magic[0], gz_magic[1], Z_DEFLATED,
220                 0 /*flags */ , 0, 0, 0, 0 /*time */ , 0 /*xflags */ ,
221                 OS_CODE);
222
223         /* normal deflate */
224         z_stream stream;
225         int err;
226         stream.next_in = (Bytef *) source;
227         stream.avail_in = (uInt) sourceLen;
228         stream.next_out = dest + 10L;   // after header
229         stream.avail_out = (uInt) * destLen;
230         if ((uLong) stream.avail_out != *destLen)
231                 return Z_BUF_ERROR;
232
233         stream.zalloc = (alloc_func) 0;
234         stream.zfree = (free_func) 0;
235         stream.opaque = (voidpf) 0;
236
237         err = deflateInit2(&stream, level, Z_DEFLATED, -MAX_WBITS,
238                            DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
239         if (err != Z_OK)
240                 return err;
241
242         err = deflate(&stream, Z_FINISH);
243         if (err != Z_STREAM_END) {
244                 deflateEnd(&stream);
245                 return err == Z_OK ? Z_BUF_ERROR : err;
246         }
247         *destLen = stream.total_out + 10L;
248
249         /* write CRC and Length */
250         uLong crc = crc32(0L, source, sourceLen);
251         int n;
252         for (n = 0; n < 4; ++n, ++*destLen) {
253                 dest[*destLen] = (int) (crc & 0xff);
254                 crc >>= 8;
255         }
256         uLong len = stream.total_in;
257         for (n = 0; n < 4; ++n, ++*destLen) {
258                 dest[*destLen] = (int) (len & 0xff);
259                 len >>= 8;
260         }
261         err = deflateEnd(&stream);
262         return err;
263 }
264 #endif
265
266 void end_burst(void)
267 {
268         size_t the_len;
269         char *the_data;
270
271         if (WC->burst == NULL)
272                 return;
273
274         the_len = WC->burst_len;
275         the_data = WC->burst;
276
277         WC->burst_len = 0;
278         WC->burst = NULL;
279
280 #ifdef HAVE_ZLIB
281         /* Handle gzip compression */
282         if (WC->gzip_ok) {
283                 char *compressed_data = NULL;
284                 uLongf compressed_len;
285
286                 compressed_len = (uLongf) ((the_len * 101) / 100) + 100;
287                 compressed_data = malloc(compressed_len);
288
289                 if (compress_gzip((Bytef *) compressed_data,
290                                   &compressed_len,
291                                   (Bytef *) the_data,
292                                   (uLongf) the_len, 9) == Z_OK) {
293                         wprintf("Content-encoding: gzip\r\n");
294                         free(the_data);
295                         the_data = compressed_data;
296                         the_len = compressed_len;
297                 } else {
298                         free(compressed_data);
299                 }
300         }
301 #endif                          /* HAVE_ZLIB */
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:cs")) != EOF)
421 #else
422         while ((a = getopt(argc, argv, "hi:p:t:c")) != EOF)
423 #endif
424                 switch (a) {
425                 case 'i':
426                         strcpy(ip_addr, optarg);
427                         break;
428                 case 'p':
429                         port = atoi(optarg);
430                         break;
431                 case 't':
432                         strcpy(tracefile, optarg);
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(SIZ);
442                         if (server_cookie != NULL) {
443                                 strcpy(server_cookie,
444                                        "Set-cookie: wcserver=");
445                                 if (gethostname
446                                     (&server_cookie[strlen(server_cookie)],
447                                      200) != 0) {
448                                         lprintf(2, "gethostname: %s\n",
449                                                 strerror(errno));
450                                         free(server_cookie);
451                                 }
452                         }
453                         break;
454                 case 's':
455                         is_https = 1;
456                         break;
457                 default:
458                         fprintf(stderr, "usage: webserver "
459                                 "[-i ip_addr] [-p http_port] "
460                                 "[-t tracefile] [-c] "
461 #ifdef HAVE_OPENSSL
462                                 "[-s] "
463 #endif
464                                 "[remotehost [remoteport]]\n");
465                         return 1;
466                 }
467
468         if (optind < argc) {
469                 ctdlhost = argv[optind];
470                 if (++optind < argc)
471                         ctdlport = argv[optind];
472         }
473         /* Tell 'em who's in da house */
474         lprintf(1, SERVER "\n"
475                 "Copyright (C) 1996-2005 by the Citadel/UX development team.\n"
476                 "This software is distributed under the terms of the GNU General Public\n"
477                 "License.  If you paid for this software, someone is ripping you off.\n\n");
478
479         if (chdir(WEBCITDIR) != 0)
480                 perror("chdir");
481
482         /*
483          * Set up a place to put thread-specific data.
484          * We only need a single pointer per thread - it points to the
485          * wcsession struct to which the thread is currently bound.
486          */
487         if (pthread_key_create(&MyConKey, NULL) != 0) {
488                 lprintf(1, "Can't create TSD key: %s\n", strerror(errno));
489         }
490
491         /*
492          * Set up a place to put thread-specific SSL data.
493          * We don't stick this in the wcsession struct because SSL starts
494          * up before the session is bound, and it gets torn down between
495          * transactions.
496          */
497 #ifdef HAVE_OPENSSL
498         if (pthread_key_create(&ThreadSSL, NULL) != 0) {
499                 lprintf(1, "Can't create TSD key: %s\n", strerror(errno));
500         }
501 #endif
502
503         /*
504          * Bind the server to our favorite port.
505          * There is no need to check for errors, because ig_tcp_server()
506          * exits if it doesn't succeed.
507          */
508         lprintf(2, "Attempting to bind to port %d...\n", port);
509         msock = ig_tcp_server(ip_addr, port, LISTEN_QUEUE_LENGTH);
510         lprintf(2, "Listening on socket %d\n", msock);
511         signal(SIGPIPE, SIG_IGN);
512
513         pthread_mutex_init(&SessionListMutex, NULL);
514
515         /*
516          * Start up the housekeeping thread
517          */
518         pthread_attr_init(&attr);
519         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
520         pthread_create(&SessThread, &attr,
521                        (void *(*)(void *)) housekeeping_loop, NULL);
522
523
524         /*
525          * If this is an HTTPS server, fire up SSL
526          */
527 #ifdef HAVE_OPENSSL
528         if (is_https) {
529                 init_ssl();
530         }
531 #endif
532
533         /* Start a few initial worker threads */
534         for (i = 0; i < (MIN_WORKER_THREADS); ++i) {
535                 spawn_another_worker_thread();
536         }
537
538         /* now the original thread becomes another worker */
539         worker_entry();
540         return 0;
541 }
542
543
544 /*
545  * Entry point for worker threads
546  */
547 void worker_entry(void)
548 {
549         int ssock;
550         int i = 0;
551         int time_to_die = 0;
552         int fail_this_transaction = 0;
553
554         do {
555                 /* Only one thread can accept at a time */
556                 fail_this_transaction = 0;
557                 ssock = accept(msock, NULL, 0);
558                 if (ssock < 0) {
559                         lprintf(2, "accept() failed: %s\n",
560                                 strerror(errno));
561                 } else {
562                         /* Set the SO_REUSEADDR socket option */
563                         i = 1;
564                         setsockopt(ssock, SOL_SOCKET, SO_REUSEADDR,
565                                    &i, sizeof(i));
566
567                         /* If we are an HTTPS server, go crypto now. */
568 #ifdef HAVE_OPENSSL
569                         if (is_https) {
570                                 if (starttls(ssock) != 0) {
571                                         fail_this_transaction = 1;
572                                         close(ssock);
573                                 }
574                         }
575 #endif
576
577                         if (fail_this_transaction == 0) {
578                                 /* Perform an HTTP transaction... */
579                                 context_loop(ssock);
580                                 /* ...and close the socket. */
581                                 lingering_close(ssock);
582                         }
583
584                 }
585
586         } while (!time_to_die);
587
588         pthread_exit(NULL);
589 }
590
591
592 int lprintf(int loglevel, const char *format, ...)
593 {
594         va_list ap;
595
596         if (loglevel <= verbosity) {
597                 va_start(ap, format);
598                 vfprintf(stderr, format, ap);
599                 va_end(ap);
600                 fflush(stderr);
601         }
602         return 1;
603 }