]> code.citadel.org Git - citadel.git/blob - webcit/webserver.c
More conversion of date/time strings to strftime-based functions.
[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
205         if (WC->burst != NULL) {
206                 WC->burst =
207                     realloc(WC->burst, (WC->burst_len + count + 2));
208                 memcpy(&WC->burst[WC->burst_len], buf, count);
209                 WC->burst_len += count;
210                 return (count);
211         }
212 #ifdef HAVE_OPENSSL
213         if (is_https) {
214                 client_write_ssl((char *) buf, count);
215                 return (count);
216         }
217 #endif
218 #ifdef HTTP_TRACING
219         write(2, "\033[34m", 5);
220         write(2, buf, count);
221         write(2, "\033[30m", 5);
222 #endif
223         return (write(WC->http_sock, buf, count));
224 }
225
226 /**
227  * \brief what burst???
228  */
229 void begin_burst(void)
230 {
231         if (WC->burst != NULL) {
232                 free(WC->burst);
233                 WC->burst = NULL;
234         }
235         WC->burst_len = 0;
236         WC->burst = malloc(SIZ);
237 }
238
239
240 /**
241  * \brief uses the same calling syntax as compress2(), but it
242  * creates a stream compatible with HTTP "Content-encoding: gzip"
243  */
244 #ifdef HAVE_ZLIB
245 #define DEF_MEM_LEVEL 8 /**< memlevel??? */
246 #define OS_CODE 0x03    /**< unix */
247 int ZEXPORT compress_gzip(Bytef * dest,         /**< compressed buffer*/
248                                                   uLongf * destLen,     /**< length of the compresed data */
249                                                   const Bytef * source, /**< source to encode */
250                                                   uLong sourceLen,      /**< length of the source to encode */
251                                                   int level)            /**< what level??? */
252 {
253         const int gz_magic[2] = { 0x1f, 0x8b }; /** gzip magic header */
254
255         /** write gzip header */
256         sprintf((char *) dest, "%c%c%c%c%c%c%c%c%c%c",
257                 gz_magic[0], gz_magic[1], Z_DEFLATED,
258                 0 /*flags */ , 0, 0, 0, 0 /*time */ , 0 /** xflags */ ,
259                 OS_CODE);
260
261         /* normal deflate */
262         z_stream stream;
263         int err;
264         stream.next_in = (Bytef *) source;
265         stream.avail_in = (uInt) sourceLen;
266         stream.next_out = dest + 10L;   // after header
267         stream.avail_out = (uInt) * destLen;
268         if ((uLong) stream.avail_out != *destLen)
269                 return Z_BUF_ERROR;
270
271         stream.zalloc = (alloc_func) 0;
272         stream.zfree = (free_func) 0;
273         stream.opaque = (voidpf) 0;
274
275         err = deflateInit2(&stream, level, Z_DEFLATED, -MAX_WBITS,
276                            DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
277         if (err != Z_OK)
278                 return err;
279
280         err = deflate(&stream, Z_FINISH);
281         if (err != Z_STREAM_END) {
282                 deflateEnd(&stream);
283                 return err == Z_OK ? Z_BUF_ERROR : err;
284         }
285         *destLen = stream.total_out + 10L;
286
287         /* write CRC and Length */
288         uLong crc = crc32(0L, source, sourceLen);
289         int n;
290         for (n = 0; n < 4; ++n, ++*destLen) {
291                 dest[*destLen] = (int) (crc & 0xff);
292                 crc >>= 8;
293         }
294         uLong len = stream.total_in;
295         for (n = 0; n < 4; ++n, ++*destLen) {
296                 dest[*destLen] = (int) (len & 0xff);
297                 len >>= 8;
298         }
299         err = deflateEnd(&stream);
300         return err;
301 }
302 #endif
303
304 /**
305  * \brief what burst???
306  */
307 void end_burst(void)
308 {
309         size_t the_len;
310         char *the_data;
311
312         if (WC->burst == NULL)
313                 return;
314
315         the_len = WC->burst_len;
316         the_data = WC->burst;
317
318         WC->burst_len = 0;
319         WC->burst = NULL;
320
321 #ifdef HAVE_ZLIB
322         /* Handle gzip compression */
323         if (WC->gzip_ok) {
324                 char *compressed_data = NULL;
325                 uLongf compressed_len;
326
327                 compressed_len = (uLongf) ((the_len * 101) / 100) + 100;
328                 compressed_data = malloc(compressed_len);
329
330                 if (compress_gzip((Bytef *) compressed_data,
331                                   &compressed_len,
332                                   (Bytef *) the_data,
333                                   (uLongf) the_len, Z_BEST_SPEED) == Z_OK) {
334                         wprintf("Content-encoding: gzip\r\n");
335                         free(the_data);
336                         the_data = compressed_data;
337                         the_len = compressed_len;
338                 } else {
339                         free(compressed_data);
340                 }
341         }
342 #endif                          /* HAVE_ZLIB */
343
344         wprintf("Content-length: %d\r\n\r\n", the_len);
345         client_write(the_data, the_len);
346         free(the_data);
347         return;
348 }
349
350
351
352 /**
353  * \brief Read data from the client socket with default timeout.
354  * (This is implemented in terms of client_read_to() and could be
355  * justifiably moved out of sysdep.c)
356  * \param sock the socket fd to read from???
357  * \param buf the buffer to write to
358  * \param bytes how large is the buffer
359  */
360 int client_read(int sock, char *buf, int bytes)
361 {
362         return (client_read_to(sock, buf, bytes, SLEEPING));
363 }
364
365
366 /**
367  * \brief Get a LF-terminated line of text from the client.
368  * (This is implemented in terms of client_read() and could be
369  * justifiably moved out of sysdep.c)
370  * \param sock socket fd to get client line from???
371  * \param buf buffer to write read data to
372  * \param bufsiz how many bytes to read
373  * \return  numer of bytes read???
374  */
375 int client_getln(int sock, char *buf, int bufsiz)
376 {
377         int i, retval;
378
379         /** Read one character at a time.*/
380         for (i = 0;; i++) {
381                 retval = client_read(sock, &buf[i], 1);
382                 if (retval != 1 || buf[i] == '\n' || i == (bufsiz-1))
383                         break;
384                 if ( (!isspace(buf[i])) && (!isprint(buf[i])) ) {
385                         lprintf(2, "Non printable character recieved from client\n");
386                         return(-1);
387                 }
388         }
389
390
391         /** If we got a long line, discard characters until the newline.         */
392         if (i == (bufsiz-1))
393                 while (buf[i] != '\n' && retval == 1)
394                         retval = client_read(sock, &buf[i], 1);
395
396         /**
397          * Strip any trailing non-printable characters.
398          */
399         buf[i] = 0;
400         while ((strlen(buf) > 0) && (!isprint(buf[strlen(buf) - 1]))) {
401                 buf[strlen(buf) - 1] = 0;
402         }
403         return (retval);
404 }
405
406
407 /**
408  * \brief Start running as a daemon.  
409  * param do_close_stdio Only close stdio if set.
410  */
411 void start_daemon(int do_close_stdio)
412 {
413         if (do_close_stdio) {
414                 /* close(0); */
415                 close(1);
416                 close(2);
417         }
418         signal(SIGHUP, SIG_IGN);
419         signal(SIGINT, SIG_IGN);
420         signal(SIGQUIT, SIG_IGN);
421         if (fork() != 0)
422                 exit(0);
423 }
424
425 void spawn_another_worker_thread()
426 {
427         pthread_t SessThread;   /**< Thread descriptor */
428         pthread_attr_t attr;    /**< Thread attributes */
429         int ret;
430
431         lprintf(3, "Creating a new thread\n");
432
433         /** set attributes for the new thread */
434         pthread_attr_init(&attr);
435         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
436
437         /**
438          * Our per-thread stacks need to be bigger than the default size, otherwise
439          * the MIME parser crashes on FreeBSD, and the IMAP service crashes on
440          * 64-bit Linux.
441          */
442         if ((ret = pthread_attr_setstacksize(&attr, 1024 * 1024))) {
443                 lprintf(1, "pthread_attr_setstacksize: %s\n",
444                         strerror(ret));
445                 pthread_attr_destroy(&attr);
446         }
447
448         /** now create the thread */
449         if (pthread_create(&SessThread, &attr,
450                            (void *(*)(void *)) worker_entry, NULL)
451             != 0) {
452                 lprintf(1, "Can't create thread: %s\n", strerror(errno));
453         }
454
455         /** free up the attributes */
456         pthread_attr_destroy(&attr);
457 }
458
459 /**
460  * \brief Here's where it all begins.
461  * \param argc number of commandline args
462  * \param argv the commandline arguments
463  */
464 int main(int argc, char **argv)
465 {
466         pthread_t SessThread;   /**< Thread descriptor */
467         pthread_attr_t attr;    /**< Thread attributes */
468         int a, i;                       /**< General-purpose variables */
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                         http_port = atoi(optarg);
495                         if (http_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-2006 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
581         /**
582          * Set up a place to put thread-specific data.
583          * We only need a single pointer per thread - it points to the
584          * wcsession struct to which the thread is currently bound.
585          */
586         if (pthread_key_create(&MyConKey, NULL) != 0) {
587                 lprintf(1, "Can't create TSD key: %s\n", strerror(errno));
588         }
589
590         /**
591          * Set up a place to put thread-specific SSL data.
592          * We don't stick this in the wcsession struct because SSL starts
593          * up before the session is bound, and it gets torn down between
594          * transactions.
595          */
596 #ifdef HAVE_OPENSSL
597         if (pthread_key_create(&ThreadSSL, NULL) != 0) {
598                 lprintf(1, "Can't create TSD key: %s\n", strerror(errno));
599         }
600 #endif
601
602         /**
603          * Bind the server to our favorite port.
604          * There is no need to check for errors, because ig_tcp_server()
605          * exits if it doesn't succeed.
606          */
607
608         if (strlen(uds_listen_path) > 0) {
609                 lprintf(2, "Attempting to create listener socket at %s...\n", uds_listen_path);
610                 msock = ig_uds_server(uds_listen_path, LISTEN_QUEUE_LENGTH);
611         }
612         else {
613                 lprintf(2, "Attempting to bind to port %d...\n", http_port);
614                 msock = ig_tcp_server(ip_addr, http_port, LISTEN_QUEUE_LENGTH);
615         }
616
617         lprintf(2, "Listening on socket %d\n", msock);
618         signal(SIGPIPE, SIG_IGN);
619
620         pthread_mutex_init(&SessionListMutex, NULL);
621
622         /**
623          * Start up the housekeeping thread
624          */
625         pthread_attr_init(&attr);
626         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
627         pthread_create(&SessThread, &attr,
628                        (void *(*)(void *)) housekeeping_loop, NULL);
629
630
631         /**
632          * If this is an HTTPS server, fire up SSL
633          */
634 #ifdef HAVE_OPENSSL
635         if (is_https) {
636                 init_ssl();
637         }
638 #endif
639
640         /** Start a few initial worker threads */
641         for (i = 0; i < (MIN_WORKER_THREADS); ++i) {
642                 spawn_another_worker_thread();
643         }
644
645         /* now the original thread becomes another worker */
646         worker_entry();
647         return 0;
648 }
649
650
651 /**
652  * Entry point for worker threads
653  */
654 void worker_entry(void)
655 {
656         int ssock;
657         int i = 0;
658         int time_to_die = 0;
659         int fail_this_transaction = 0;
660
661         do {
662                 /** Only one thread can accept at a time */
663                 fail_this_transaction = 0;
664                 ssock = accept(msock, NULL, 0);
665                 if (ssock < 0) {
666                         lprintf(2, "accept() failed: %s\n",
667                                 strerror(errno));
668                 } else {
669                         /** Set the SO_REUSEADDR socket option */
670                         i = 1;
671                         setsockopt(ssock, SOL_SOCKET, SO_REUSEADDR,
672                                    &i, sizeof(i));
673
674                         /** If we are an HTTPS server, go crypto now. */
675 #ifdef HAVE_OPENSSL
676                         if (is_https) {
677                                 if (starttls(ssock) != 0) {
678                                         fail_this_transaction = 1;
679                                         close(ssock);
680                                 }
681                         }
682 #endif
683
684                         if (fail_this_transaction == 0) {
685                                 /** Perform an HTTP transaction... */
686                                 context_loop(ssock);
687                                 /** ...and close the socket. */
688                                 lingering_close(ssock);
689                         }
690
691                 }
692
693         } while (!time_to_die);
694
695         pthread_exit(NULL);
696 }
697
698 /**
699  * \brief logprintf. log messages 
700  * logs to stderr if loglevel is lower than the verbosity set at startup
701  * \param loglevel level of the message
702  * \param format the printf like format string
703  * \param ... the strings to put into format
704  */
705 int lprintf(int loglevel, const char *format, ...)
706 {
707         va_list ap;
708
709         if (loglevel <= verbosity) {
710                 va_start(ap, format);
711                 vfprintf(stderr, format, ap);
712                 va_end(ap);
713                 fflush(stderr);
714         }
715         return 1;
716 }
717
718
719 /*@}*/