Began making changes to do better handling of character sets.
[citadel.git] / webcit / webserver.c
1 /*
2  * $Id$
3  */
4 /**
5  * \defgroup Webserver This contains a simple multithreaded TCP server manager.  It sits around
6  * waiting on the specified port for incoming HTTP connections.  When a
7  * connection is established, it calls context_loop() from context_loop.c.
8  * \ingroup WebcitHttpServer
9  */
10
11 /*@{*/
12 #include "webcit.h"
13 #include "webserver.h"
14
15 #ifndef HAVE_SNPRINTF
16 int vsnprintf(char *buf, size_t max, const char *fmt, va_list argp);
17 #endif
18
19 int verbosity = 9;              /**< Logging level */
20 int msock;                          /**< master listening socket */
21 int is_https = 0;               /**< Nonzero if I am an HTTPS service */
22 int follow_xff = 0;             /**< Follow X-Forwarded-For: header */
23 extern void *context_loop(int);
24 extern void *housekeeping_loop(void);
25 extern pthread_mutex_t SessionListMutex;
26 extern pthread_key_t MyConKey;
27
28
29 char *server_cookie = NULL; /**< our Cookie connection to the client */
30
31 int http_port = PORT_NUM;       /**< Port to listen on */
32
33 char *ctdlhost = DEFAULT_HOST; /**< our name */
34 char *ctdlport = DEFAULT_PORT; /**< our Port */
35 int setup_wizard = 0;          /**< should we run the setup wizard? \todo */
36 char wizard_filename[PATH_MAX];/**< where's the setup wizard? */
37
38 /** 
39  * \brief This is a generic function to set up a master socket for listening on
40  * a TCP port.  The server shuts down if the bind fails.
41  * \param ip_addr ip to bind to
42  * \param port_number the port to bind to 
43  * \param queue_len the size of the input queue ????
44  */
45 int ig_tcp_server(char *ip_addr, int port_number, int queue_len)
46 {
47         struct sockaddr_in sin;
48         int s, i;
49
50         memset(&sin, 0, sizeof(sin));
51         sin.sin_family = AF_INET;
52         if (ip_addr == NULL) {
53                 sin.sin_addr.s_addr = INADDR_ANY;
54         } else {
55                 sin.sin_addr.s_addr = inet_addr(ip_addr);
56         }
57
58         if (sin.sin_addr.s_addr == INADDR_NONE) {
59                 sin.sin_addr.s_addr = INADDR_ANY;
60         }
61
62         if (port_number == 0) {
63                 lprintf(1, "Cannot start: no port number specified.\n");
64                 exit(1);
65         }
66         sin.sin_port = htons((u_short) port_number);
67
68         s = socket(PF_INET, SOCK_STREAM, (getprotobyname("tcp")->p_proto));
69         if (s < 0) {
70                 lprintf(1, "Can't create a socket: %s\n", strerror(errno));
71                 exit(errno);
72         }
73         /** Set some socket options that make sense. */
74         i = 1;
75         setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
76
77         if (bind(s, (struct sockaddr *) &sin, sizeof(sin)) < 0) {
78                 lprintf(1, "Can't bind: %s\n", strerror(errno));
79                 exit(errno);
80         }
81         if (listen(s, queue_len) < 0) {
82                 lprintf(1, "Can't listen: %s\n", strerror(errno));
83                 exit(errno);
84         }
85         return (s);
86 }
87
88
89
90 /**
91  * \brief Create a Unix domain socket and listen on it
92  * \param sockpath file name of the unix domain socket
93  * \param queue_len queue size of the kernel fifo????
94  */
95 int ig_uds_server(char *sockpath, int queue_len)
96 {
97         struct sockaddr_un addr;
98         int s;
99         int i;
100         int actual_queue_len;
101
102         actual_queue_len = queue_len;
103         if (actual_queue_len < 5) actual_queue_len = 5;
104
105         i = unlink(sockpath);
106         if (i != 0) if (errno != ENOENT) {
107                 lprintf(1, "citserver: can't unlink %s: %s\n",
108                         sockpath, strerror(errno));
109                 exit(errno);
110         }
111
112         memset(&addr, 0, sizeof(addr));
113         addr.sun_family = AF_UNIX;
114         safestrncpy(addr.sun_path, sockpath, sizeof addr.sun_path);
115
116         s = socket(AF_UNIX, SOCK_STREAM, 0);
117         if (s < 0) {
118                 lprintf(1, "citserver: Can't create a socket: %s\n",
119                         strerror(errno));
120                 exit(errno);
121         }
122
123         if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
124                 lprintf(1, "citserver: Can't bind: %s\n",
125                         strerror(errno));
126                 exit(errno);
127         }
128
129         if (listen(s, actual_queue_len) < 0) {
130                 lprintf(1, "citserver: Can't listen: %s\n",
131                         strerror(errno));
132                 exit(errno);
133         }
134
135         chmod(sockpath, 0777);
136         return(s);
137 }
138
139
140
141
142 /**
143  * \brief Read data from the client socket.
144  * \param sock socket fd to read from ???
145  * \param buf buffer to read into 
146  * \param bytes how large is the read buffer?
147  * \param timeout how long should we wait for input?
148  * \return values are\
149  *      1       Requested number of bytes has been read.\
150  *      0       Request timed out.\
151  *         -1           Connection is broken, or other error.
152  */
153 int client_read_to(int sock, char *buf, int bytes, int timeout)
154 {
155         int len, rlen;
156         fd_set rfds;
157         struct timeval tv;
158         int retval;
159
160
161 #ifdef HAVE_OPENSSL
162         if (is_https) {
163                 return (client_read_ssl(buf, bytes, timeout));
164         }
165 #endif
166
167         len = 0;
168         while (len < bytes) {
169                 FD_ZERO(&rfds);
170                 FD_SET(sock, &rfds);
171                 tv.tv_sec = timeout;
172                 tv.tv_usec = 0;
173
174                 retval = select((sock) + 1, &rfds, NULL, NULL, &tv);
175                 if (FD_ISSET(sock, &rfds) == 0) {
176                         return (0);
177                 }
178
179                 rlen = read(sock, &buf[len], bytes - len);
180
181                 if (rlen < 1) {
182                         lprintf(2, "client_read() failed: %s\n",
183                                 strerror(errno));
184                         return (-1);
185                 }
186                 len = len + rlen;
187         }
188
189 #ifdef HTTP_TRACING
190         write(2, "\033[32m", 5);
191         write(2, buf, bytes);
192         write(2, "\033[30m", 5);
193 #endif
194         return (1);
195 }
196
197 /**
198  * \brief write data to the client
199  * \param buf data to write to the client
200  * \param count size of buffer
201  */
202 ssize_t client_write(const void *buf, size_t count)
203 {
204         char *newptr;
205         size_t newalloc;
206
207         if (WC->burst != NULL) {
208                 if ((WC->burst_len + count) >= WC->burst_alloc) {
209                         newalloc = (WC->burst_alloc * 2);
210                         if ((WC->burst_len + count) >= newalloc) {
211                                 newalloc += count;
212                         }
213                         newptr = realloc(WC->burst, newalloc);
214                         if (newptr != NULL) {
215                                 WC->burst = newptr;
216                                 WC->burst_alloc = newalloc;
217                         }
218                 }
219                 if ((WC->burst_len + count) < WC->burst_alloc) {
220                         memcpy(&WC->burst[WC->burst_len], buf, count);
221                         WC->burst_len += count;
222                         return (count);
223                 }
224                 else {
225                         return(-1);
226                 }
227         }
228 #ifdef HAVE_OPENSSL
229         if (is_https) {
230                 client_write_ssl((char *) buf, count);
231                 return (count);
232         }
233 #endif
234 #ifdef HTTP_TRACING
235         write(2, "\033[34m", 5);
236         write(2, buf, count);
237         write(2, "\033[30m", 5);
238 #endif
239         return (write(WC->http_sock, buf, count));
240 }
241
242 /**
243  * \brief what burst???
244  */
245 void begin_burst(void)
246 {
247         if (WC->burst != NULL) {
248                 free(WC->burst);
249                 WC->burst = NULL;
250         }
251         WC->burst_len = 0;
252         WC->burst_alloc = 32768;
253         WC->burst = malloc(WC->burst_alloc);
254 }
255
256
257 /**
258  * \brief uses the same calling syntax as compress2(), but it
259  * creates a stream compatible with HTTP "Content-encoding: gzip"
260  */
261 #ifdef HAVE_ZLIB
262 #define DEF_MEM_LEVEL 8 /**< memlevel??? */
263 #define OS_CODE 0x03    /**< unix */
264 int ZEXPORT compress_gzip(Bytef * dest,         /**< compressed buffer*/
265                                                   uLongf * destLen,     /**< length of the compresed data */
266                                                   const Bytef * source, /**< source to encode */
267                                                   uLong sourceLen,      /**< length of the source to encode */
268                                                   int level)            /**< what level??? */
269 {
270         const int gz_magic[2] = { 0x1f, 0x8b }; /** gzip magic header */
271
272         /** write gzip header */
273         sprintf((char *) dest, "%c%c%c%c%c%c%c%c%c%c",
274                 gz_magic[0], gz_magic[1], Z_DEFLATED,
275                 0 /*flags */ , 0, 0, 0, 0 /*time */ , 0 /** xflags */ ,
276                 OS_CODE);
277
278         /* normal deflate */
279         z_stream stream;
280         int err;
281         stream.next_in = (Bytef *) source;
282         stream.avail_in = (uInt) sourceLen;
283         stream.next_out = dest + 10L;   // after header
284         stream.avail_out = (uInt) * destLen;
285         if ((uLong) stream.avail_out != *destLen)
286                 return Z_BUF_ERROR;
287
288         stream.zalloc = (alloc_func) 0;
289         stream.zfree = (free_func) 0;
290         stream.opaque = (voidpf) 0;
291
292         err = deflateInit2(&stream, level, Z_DEFLATED, -MAX_WBITS,
293                            DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
294         if (err != Z_OK)
295                 return err;
296
297         err = deflate(&stream, Z_FINISH);
298         if (err != Z_STREAM_END) {
299                 deflateEnd(&stream);
300                 return err == Z_OK ? Z_BUF_ERROR : err;
301         }
302         *destLen = stream.total_out + 10L;
303
304         /* write CRC and Length */
305         uLong crc = crc32(0L, source, sourceLen);
306         int n;
307         for (n = 0; n < 4; ++n, ++*destLen) {
308                 dest[*destLen] = (int) (crc & 0xff);
309                 crc >>= 8;
310         }
311         uLong len = stream.total_in;
312         for (n = 0; n < 4; ++n, ++*destLen) {
313                 dest[*destLen] = (int) (len & 0xff);
314                 len >>= 8;
315         }
316         err = deflateEnd(&stream);
317         return err;
318 }
319 #endif
320
321 /**
322  * \brief what burst???
323  */
324 void end_burst(void)
325 {
326         size_t the_len;
327         char *the_data;
328
329         if (WC->burst == NULL)
330                 return;
331
332         the_len = WC->burst_len;
333         the_data = WC->burst;
334
335         WC->burst_len = 0;
336         WC->burst_alloc = 0;
337         WC->burst = NULL;
338
339 #ifdef HAVE_ZLIB
340         /* Handle gzip compression */
341         if (WC->gzip_ok) {
342                 char *compressed_data = NULL;
343                 uLongf compressed_len;
344
345                 compressed_len = (uLongf) ((the_len * 101) / 100) + 100;
346                 compressed_data = malloc(compressed_len);
347
348                 if (compress_gzip((Bytef *) compressed_data,
349                                   &compressed_len,
350                                   (Bytef *) the_data,
351                                   (uLongf) the_len, Z_BEST_SPEED) == Z_OK) {
352                         wprintf("Content-encoding: gzip\r\n");
353                         free(the_data);
354                         the_data = compressed_data;
355                         the_len = compressed_len;
356                 } else {
357                         free(compressed_data);
358                 }
359         }
360 #endif                          /* HAVE_ZLIB */
361
362         wprintf("Content-length: %d\r\n\r\n", the_len);
363         client_write(the_data, the_len);
364         free(the_data);
365         return;
366 }
367
368
369
370 /**
371  * \brief Read data from the client socket with default timeout.
372  * (This is implemented in terms of client_read_to() and could be
373  * justifiably moved out of sysdep.c)
374  * \param sock the socket fd to read from???
375  * \param buf the buffer to write to
376  * \param bytes how large is the buffer
377  */
378 int client_read(int sock, char *buf, int bytes)
379 {
380         return (client_read_to(sock, buf, bytes, SLEEPING));
381 }
382
383
384 /**
385  * \brief Get a LF-terminated line of text from the client.
386  * (This is implemented in terms of client_read() and could be
387  * justifiably moved out of sysdep.c)
388  * \param sock socket fd to get client line from???
389  * \param buf buffer to write read data to
390  * \param bufsiz how many bytes to read
391  * \return  numer of bytes read???
392  */
393 int client_getln(int sock, char *buf, int bufsiz)
394 {
395         int i, retval;
396
397         /** Read one character at a time.*/
398         for (i = 0;; i++) {
399                 retval = client_read(sock, &buf[i], 1);
400                 if (retval != 1 || buf[i] == '\n' || i == (bufsiz-1))
401                         break;
402                 if ( (!isspace(buf[i])) && (!isprint(buf[i])) ) {
403                         /** Non printable character recieved from client */
404                         return(-1);
405                 }
406         }
407
408         /** If we got a long line, discard characters until the newline. */
409         if (i == (bufsiz-1))
410                 while (buf[i] != '\n' && retval == 1)
411                         retval = client_read(sock, &buf[i], 1);
412
413         /**
414          * Strip any trailing non-printable characters.
415          */
416         buf[i] = 0;
417         while ((strlen(buf) > 0) && (!isprint(buf[strlen(buf) - 1]))) {
418                 buf[strlen(buf) - 1] = 0;
419         }
420         return (retval);
421 }
422
423
424 /**
425  * \brief       Start running as a daemon.  
426  *
427  * param        do_close_stdio          Only close stdio if set.
428  */
429 void start_daemon(int do_close_stdio)
430 {
431         if (do_close_stdio) {
432                 /* close(0); */
433                 close(1);
434                 close(2);
435         }
436         signal(SIGHUP, SIG_IGN);
437         signal(SIGINT, SIG_IGN);
438         signal(SIGQUIT, SIG_IGN);
439         if (fork() != 0) {
440                 exit(0);
441         }
442 }
443
444 /**
445  * \brief       Spawn an additional worker thread into the pool.
446  */
447 void spawn_another_worker_thread()
448 {
449         pthread_t SessThread;   /**< Thread descriptor */
450         pthread_attr_t attr;    /**< Thread attributes */
451         int ret;
452
453         lprintf(3, "Creating a new thread\n");
454
455         /** set attributes for the new thread */
456         pthread_attr_init(&attr);
457         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
458
459         /**
460          * Our per-thread stacks need to be bigger than the default size, otherwise
461          * the MIME parser crashes on FreeBSD, and the IMAP service crashes on
462          * 64-bit Linux.
463          */
464         if ((ret = pthread_attr_setstacksize(&attr, 1024 * 1024))) {
465                 lprintf(1, "pthread_attr_setstacksize: %s\n",
466                         strerror(ret));
467                 pthread_attr_destroy(&attr);
468         }
469
470         /** now create the thread */
471         if (pthread_create(&SessThread, &attr,
472                            (void *(*)(void *)) worker_entry, NULL)
473             != 0) {
474                 lprintf(1, "Can't create thread: %s\n", strerror(errno));
475         }
476
477         /** free up the attributes */
478         pthread_attr_destroy(&attr);
479 }
480
481 /**
482  * \brief Here's where it all begins.
483  * \param argc number of commandline args
484  * \param argv the commandline arguments
485  */
486 int main(int argc, char **argv)
487 {
488         pthread_t SessThread;   /**< Thread descriptor */
489         pthread_attr_t attr;    /**< Thread attributes */
490         int a, i;                       /**< General-purpose variables */
491         char tracefile[PATH_MAX];
492         char ip_addr[256];
493         char *webcitdir = WEBCITDIR;
494 #ifdef ENABLE_NLS
495         char *locale = NULL;
496         char *mo = NULL;
497 #endif /* ENABLE_NLS */
498         char uds_listen_path[PATH_MAX]; /**< listen on a unix domain socket? */
499
500         strcpy(uds_listen_path, "");
501
502         /** Parse command line */
503 #ifdef HAVE_OPENSSL
504         while ((a = getopt(argc, argv, "h:i:p:t:x:cfs")) != EOF)
505 #else
506         while ((a = getopt(argc, argv, "h:i:p:t:x:cf")) != EOF)
507 #endif
508                 switch (a) {
509                 case 'h':
510                         webcitdir = strdup(optarg);
511                         break;
512                 case 'i':
513                         safestrncpy(ip_addr, optarg, sizeof ip_addr);
514                         break;
515                 case 'p':
516                         http_port = atoi(optarg);
517                         if (http_port == 0) {
518                                 safestrncpy(uds_listen_path, optarg, sizeof uds_listen_path);
519                         }
520                         break;
521                 case 't':
522                         safestrncpy(tracefile, optarg, sizeof tracefile);
523                         freopen(tracefile, "w", stdout);
524                         freopen(tracefile, "w", stderr);
525                         freopen(tracefile, "r", stdin);
526                         break;
527                 case 'x':
528                         verbosity = atoi(optarg);
529                         break;
530                 case 'f':
531                         follow_xff = 1;
532                         break;
533                 case 'c':
534                         server_cookie = malloc(256);
535                         if (server_cookie != NULL) {
536                                 safestrncpy(server_cookie,
537                                        "Set-cookie: wcserver=",
538                                         256);
539                                 if (gethostname
540                                     (&server_cookie[strlen(server_cookie)],
541                                      200) != 0) {
542                                         lprintf(2, "gethostname: %s\n",
543                                                 strerror(errno));
544                                         free(server_cookie);
545                                 }
546                         }
547                         break;
548                 case 's':
549                         is_https = 1;
550                         break;
551                 default:
552                         fprintf(stderr, "usage: webserver "
553                                 "[-i ip_addr] [-p http_port] "
554                                 "[-t tracefile] [-c] [-f] "
555 #ifdef HAVE_OPENSSL
556                                 "[-s] "
557 #endif
558                                 "[remotehost [remoteport]]\n");
559                         return 1;
560                 }
561
562         if (optind < argc) {
563                 ctdlhost = argv[optind];
564                 if (++optind < argc)
565                         ctdlport = argv[optind];
566         }
567         /** Tell 'em who's in da house */
568         lprintf(1, SERVER "\n");
569         lprintf(1, "Copyright (C) 1996-2006 by the Citadel development team.\n"
570                 "This software is distributed under the terms of the "
571                 "GNU General Public License.\n\n"
572         );
573
574         lprintf(9, "Changing directory to %s\n", webcitdir);
575         if (chdir(webcitdir) != 0) {
576                 perror("chdir");
577         }
578
579         /** initialize the International Bright Young Thing */
580 #ifdef ENABLE_NLS
581
582         initialize_locales();
583
584         locale = setlocale(LC_ALL, "");
585
586         mo = malloc(strlen(webcitdir) + 20);
587         sprintf(mo, "%s/locale", webcitdir);
588         lprintf(9, "Message catalog directory: %s\n",
589                 bindtextdomain("webcit", mo)
590         );
591         free(mo);
592         lprintf(9, "Text domain: %s\n",
593                 textdomain("webcit")
594         );
595         lprintf(9, "Text domain Charset: %s\n",
596                         bind_textdomain_codeset("webcit","UTF8")
597         );
598 #endif
599
600         initialize_viewdefs();
601         initialize_axdefs();
602
603         /**
604          * Set up a place to put thread-specific data.
605          * We only need a single pointer per thread - it points to the
606          * wcsession struct to which the thread is currently bound.
607          */
608         if (pthread_key_create(&MyConKey, NULL) != 0) {
609                 lprintf(1, "Can't create TSD key: %s\n", strerror(errno));
610         }
611
612         /**
613          * Set up a place to put thread-specific SSL data.
614          * We don't stick this in the wcsession struct because SSL starts
615          * up before the session is bound, and it gets torn down between
616          * transactions.
617          */
618 #ifdef HAVE_OPENSSL
619         if (pthread_key_create(&ThreadSSL, NULL) != 0) {
620                 lprintf(1, "Can't create TSD key: %s\n", strerror(errno));
621         }
622 #endif
623
624         /**
625          * Bind the server to our favorite port.
626          * There is no need to check for errors, because ig_tcp_server()
627          * exits if it doesn't succeed.
628          */
629
630         if (strlen(uds_listen_path) > 0) {
631                 lprintf(2, "Attempting to create listener socket at %s...\n", uds_listen_path);
632                 msock = ig_uds_server(uds_listen_path, LISTEN_QUEUE_LENGTH);
633         }
634         else {
635                 lprintf(2, "Attempting to bind to port %d...\n", http_port);
636                 msock = ig_tcp_server(ip_addr, http_port, LISTEN_QUEUE_LENGTH);
637         }
638
639         lprintf(2, "Listening on socket %d\n", msock);
640         signal(SIGPIPE, SIG_IGN);
641
642         pthread_mutex_init(&SessionListMutex, NULL);
643
644         /**
645          * Start up the housekeeping thread
646          */
647         pthread_attr_init(&attr);
648         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
649         pthread_create(&SessThread, &attr,
650                        (void *(*)(void *)) housekeeping_loop, NULL);
651
652
653         /**
654          * If this is an HTTPS server, fire up SSL
655          */
656 #ifdef HAVE_OPENSSL
657         if (is_https) {
658                 init_ssl();
659         }
660 #endif
661
662         /** Start a few initial worker threads */
663         for (i = 0; i < (MIN_WORKER_THREADS); ++i) {
664                 spawn_another_worker_thread();
665         }
666
667         /* now the original thread becomes another worker */
668         worker_entry();
669         return 0;
670 }
671
672
673 /**
674  * Entry point for worker threads
675  */
676 void worker_entry(void)
677 {
678         int ssock;
679         int i = 0;
680         int time_to_die = 0;
681         int fail_this_transaction = 0;
682
683         do {
684                 /** Only one thread can accept at a time */
685                 fail_this_transaction = 0;
686                 ssock = accept(msock, NULL, 0);
687                 if (ssock < 0) {
688                         lprintf(2, "accept() failed: %s\n",
689                                 strerror(errno));
690                 } else {
691                         /** Set the SO_REUSEADDR socket option */
692                         i = 1;
693                         setsockopt(ssock, SOL_SOCKET, SO_REUSEADDR,
694                                    &i, sizeof(i));
695
696                         /** If we are an HTTPS server, go crypto now. */
697 #ifdef HAVE_OPENSSL
698                         if (is_https) {
699                                 if (starttls(ssock) != 0) {
700                                         fail_this_transaction = 1;
701                                         close(ssock);
702                                 }
703                         }
704 #endif
705
706                         if (fail_this_transaction == 0) {
707                                 /** Perform an HTTP transaction... */
708                                 context_loop(ssock);
709                                 /** ...and close the socket. */
710                                 lingering_close(ssock);
711                         }
712
713                 }
714
715         } while (!time_to_die);
716
717         pthread_exit(NULL);
718 }
719
720 /**
721  * \brief logprintf. log messages 
722  * logs to stderr if loglevel is lower than the verbosity set at startup
723  * \param loglevel level of the message
724  * \param format the printf like format string
725  * \param ... the strings to put into format
726  */
727 int lprintf(int loglevel, const char *format, ...)
728 {
729         va_list ap;
730
731         if (loglevel <= verbosity) {
732                 va_start(ap, format);
733                 vfprintf(stderr, format, ap);
734                 va_end(ap);
735                 fflush(stderr);
736         }
737         return 1;
738 }
739
740
741 /**
742  * \brief print the actual stack frame.
743  */
744 void wc_backtrace(void)
745 {
746 #ifdef HAVE_BACKTRACE
747         void *stack_frames[50];
748         size_t size, i;
749         char **strings;
750
751
752         size = backtrace(stack_frames, sizeof(stack_frames) / sizeof(void*));
753         strings = backtrace_symbols(stack_frames, size);
754         for (i = 0; i < size; i++) {
755                 if (strings != NULL)
756                         lprintf(1, "%s\n", strings[i]);
757                 else
758                         lprintf(1, "%p\n", stack_frames[i]);
759         }
760         free(strings);
761 #endif
762 }
763
764 /*@}*/