* Began an assault on strcpy()
[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 #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 #ifdef HAVE_ZLIB
279         /* Handle gzip compression */
280         if (WC->gzip_ok) {
281                 char *compressed_data = NULL;
282                 uLongf compressed_len;
283
284                 compressed_len = (uLongf) ((the_len * 101) / 100) + 100;
285                 compressed_data = malloc(compressed_len);
286
287                 if (compress_gzip((Bytef *) compressed_data,
288                                   &compressed_len,
289                                   (Bytef *) the_data,
290                                   (uLongf) the_len, Z_BEST_SPEED) == Z_OK) {
291                         wprintf("Content-encoding: gzip\r\n");
292                         free(the_data);
293                         the_data = compressed_data;
294                         the_len = compressed_len;
295                 } else {
296                         free(compressed_data);
297                 }
298         }
299 #endif                          /* HAVE_ZLIB */
300
301         wprintf("Content-length: %d\r\n\r\n", the_len);
302         client_write(the_data, the_len);
303         free(the_data);
304         return;
305 }
306
307
308
309 /*
310  * Read data from the client socket with default timeout.
311  * (This is implemented in terms of client_read_to() and could be
312  * justifiably moved out of sysdep.c)
313  */
314 int client_read(int sock, char *buf, int bytes)
315 {
316         return (client_read_to(sock, buf, bytes, SLEEPING));
317 }
318
319
320 /*
321  * client_gets()   ...   Get a LF-terminated line of text from the client.
322  * (This is implemented in terms of client_read() and could be
323  * justifiably moved out of sysdep.c)
324  */
325 int client_gets(int sock, char *buf)
326 {
327         int i, retval;
328
329         /* Read one character at a time.
330          */
331         for (i = 0;; i++) {
332                 retval = client_read(sock, &buf[i], 1);
333                 if (retval != 1 || buf[i] == '\n' || i == 255)
334                         break;
335         }
336
337         /* If we got a long line, discard characters until the newline.
338          */
339         if (i == 255)
340                 while (buf[i] != '\n' && retval == 1)
341                         retval = client_read(sock, &buf[i], 1);
342
343         /*
344          * Strip any trailing non-printable characters.
345          */
346         buf[i] = 0;
347         while ((strlen(buf) > 0) && (!isprint(buf[strlen(buf) - 1]))) {
348                 buf[strlen(buf) - 1] = 0;
349         }
350         return (retval);
351 }
352
353
354 /*
355  * Start running as a daemon.  Only close stdio if do_close_stdio is set.
356  */
357 void start_daemon(int do_close_stdio)
358 {
359         if (do_close_stdio) {
360                 /* close(0); */
361                 close(1);
362                 close(2);
363         }
364         signal(SIGHUP, SIG_IGN);
365         signal(SIGINT, SIG_IGN);
366         signal(SIGQUIT, SIG_IGN);
367         if (fork() != 0)
368                 exit(0);
369 }
370
371 void spawn_another_worker_thread()
372 {
373         pthread_t SessThread;   /* Thread descriptor */
374         pthread_attr_t attr;    /* Thread attributes */
375         int ret;
376
377         lprintf(3, "Creating a new thread\n");
378
379         /* set attributes for the new thread */
380         pthread_attr_init(&attr);
381         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
382
383         /* Our per-thread stacks need to be bigger than the default size, otherwise
384          * the MIME parser crashes on FreeBSD, and the IMAP service crashes on
385          * 64-bit Linux.
386          */
387         if ((ret = pthread_attr_setstacksize(&attr, 1024 * 1024))) {
388                 lprintf(1, "pthread_attr_setstacksize: %s\n",
389                         strerror(ret));
390                 pthread_attr_destroy(&attr);
391         }
392
393         /* now create the thread */
394         if (pthread_create(&SessThread, &attr,
395                            (void *(*)(void *)) worker_entry, NULL)
396             != 0) {
397                 lprintf(1, "Can't create thread: %s\n", strerror(errno));
398         }
399
400         /* free up the attributes */
401         pthread_attr_destroy(&attr);
402 }
403
404 /*
405  * Here's where it all begins.
406  */
407 int main(int argc, char **argv)
408 {
409         pthread_t SessThread;   /* Thread descriptor */
410         pthread_attr_t attr;    /* Thread attributes */
411         int a, i;               /* General-purpose variables */
412         int port = PORT_NUM;    /* Port to listen on */
413         char tracefile[PATH_MAX];
414         char ip_addr[256];
415
416         /* Parse command line */
417 #ifdef HAVE_OPENSSL
418         while ((a = getopt(argc, argv, "hi:p:t:x:cs")) != EOF)
419 #else
420         while ((a = getopt(argc, argv, "hi:p:t:x:c")) != EOF)
421 #endif
422                 switch (a) {
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/UX development team.\n"
475                 "This software is distributed under the terms of the GNU General Public\n"
476                 "License.  If you paid for this software, someone is ripping you off.\n\n");
477
478         if (chdir(WEBCITDIR) != 0)
479                 perror("chdir");
480
481         /*
482          * Set up a place to put thread-specific data.
483          * We only need a single pointer per thread - it points to the
484          * wcsession struct to which the thread is currently bound.
485          */
486         if (pthread_key_create(&MyConKey, NULL) != 0) {
487                 lprintf(1, "Can't create TSD key: %s\n", strerror(errno));
488         }
489
490         /*
491          * Set up a place to put thread-specific SSL data.
492          * We don't stick this in the wcsession struct because SSL starts
493          * up before the session is bound, and it gets torn down between
494          * transactions.
495          */
496 #ifdef HAVE_OPENSSL
497         if (pthread_key_create(&ThreadSSL, NULL) != 0) {
498                 lprintf(1, "Can't create TSD key: %s\n", strerror(errno));
499         }
500 #endif
501
502         /*
503          * Bind the server to our favorite port.
504          * There is no need to check for errors, because ig_tcp_server()
505          * exits if it doesn't succeed.
506          */
507         lprintf(2, "Attempting to bind to port %d...\n", port);
508         msock = ig_tcp_server(ip_addr, port, LISTEN_QUEUE_LENGTH);
509         lprintf(2, "Listening on socket %d\n", msock);
510         signal(SIGPIPE, SIG_IGN);
511
512         pthread_mutex_init(&SessionListMutex, NULL);
513
514         /*
515          * Start up the housekeeping thread
516          */
517         pthread_attr_init(&attr);
518         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
519         pthread_create(&SessThread, &attr,
520                        (void *(*)(void *)) housekeeping_loop, NULL);
521
522
523         /*
524          * If this is an HTTPS server, fire up SSL
525          */
526 #ifdef HAVE_OPENSSL
527         if (is_https) {
528                 init_ssl();
529         }
530 #endif
531
532         /* Start a few initial worker threads */
533         for (i = 0; i < (MIN_WORKER_THREADS); ++i) {
534                 spawn_another_worker_thread();
535         }
536
537         /* now the original thread becomes another worker */
538         worker_entry();
539         return 0;
540 }
541
542
543 /*
544  * Entry point for worker threads
545  */
546 void worker_entry(void)
547 {
548         int ssock;
549         int i = 0;
550         int time_to_die = 0;
551         int fail_this_transaction = 0;
552
553         do {
554                 /* Only one thread can accept at a time */
555                 fail_this_transaction = 0;
556                 ssock = accept(msock, NULL, 0);
557                 if (ssock < 0) {
558                         lprintf(2, "accept() failed: %s\n",
559                                 strerror(errno));
560                 } else {
561                         /* Set the SO_REUSEADDR socket option */
562                         i = 1;
563                         setsockopt(ssock, SOL_SOCKET, SO_REUSEADDR,
564                                    &i, sizeof(i));
565
566                         /* If we are an HTTPS server, go crypto now. */
567 #ifdef HAVE_OPENSSL
568                         if (is_https) {
569                                 if (starttls(ssock) != 0) {
570                                         fail_this_transaction = 1;
571                                         close(ssock);
572                                 }
573                         }
574 #endif
575
576                         if (fail_this_transaction == 0) {
577                                 /* Perform an HTTP transaction... */
578                                 context_loop(ssock);
579                                 /* ...and close the socket. */
580                                 lingering_close(ssock);
581                         }
582
583                 }
584
585         } while (!time_to_die);
586
587         pthread_exit(NULL);
588 }
589
590
591 int lprintf(int loglevel, const char *format, ...)
592 {
593         va_list ap;
594
595         if (loglevel <= verbosity) {
596                 va_start(ap, format);
597                 vfprintf(stderr, format, ap);
598                 va_end(ap);
599                 fflush(stderr);
600         }
601         return 1;
602 }