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