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