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