* Added some HTTP Date: header output
[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  * Uncomment to dump an HTTP trace to stderr
12 #define HTTP_TRACING 1
13  */
14
15 #include <ctype.h>
16 #include <stdlib.h>
17 #ifdef HAVE_UNISTD_H
18 #include <unistd.h>
19 #endif
20 #include <stdio.h>
21 #ifdef HAVE_FCNTL_H
22 #include <fcntl.h>
23 #endif
24 #include <signal.h>
25 #include <sys/types.h>
26 #include <sys/wait.h>
27 #include <sys/socket.h>
28 #ifdef HAVE_SYS_TIME_H
29 #include <sys/time.h>
30 #endif
31 #ifdef HAVE_LIMITS_H
32 #include <limits.h>
33 #endif
34 #include <netinet/in.h>
35 #include <arpa/inet.h>
36 #include <netdb.h>
37 #include <string.h>
38 #include <pwd.h>
39 #include <errno.h>
40 #include <stdarg.h>
41 #include <pthread.h>
42 #include <signal.h>
43 #include "webcit.h"
44 #include "webserver.h"
45
46 #ifndef HAVE_SNPRINTF
47 int vsnprintf(char *buf, size_t max, const char *fmt, va_list argp);
48 #endif
49
50 int verbosity = 9;              /* Logging level */
51 int msock;                      /* master listening socket */
52 int is_https = 0;               /* Nonzero if I am an HTTPS service */
53 extern void *context_loop(int);
54 extern void *housekeeping_loop(void);
55 extern pthread_mutex_t SessionListMutex;
56 extern pthread_key_t MyConKey;
57
58
59 char *server_cookie = NULL;
60
61
62 char *ctdlhost = DEFAULT_HOST;
63 char *ctdlport = DEFAULT_PORT;
64
65 /*
66  * This is a generic function to set up a master socket for listening on
67  * a TCP port.  The server shuts down if the bind fails.
68  */
69 int ig_tcp_server(char *ip_addr, int port_number, int queue_len)
70 {
71         struct sockaddr_in sin;
72         int s, i;
73
74         memset(&sin, 0, sizeof(sin));
75         sin.sin_family = AF_INET;
76         if (ip_addr == NULL) {
77                 sin.sin_addr.s_addr = INADDR_ANY;
78         }
79         else {
80                 sin.sin_addr.s_addr = inet_addr(ip_addr);
81         }
82
83         if (sin.sin_addr.s_addr == INADDR_NONE) {
84                 sin.sin_addr.s_addr = INADDR_ANY;
85         }
86
87         if (port_number == 0) {
88                 lprintf(1, "Cannot start: no port number specified.\n");
89                 exit(1);
90         }
91         sin.sin_port = htons((u_short) port_number);
92
93         s = socket(PF_INET, SOCK_STREAM, (getprotobyname("tcp")->p_proto));
94         if (s < 0) {
95                 lprintf(1, "Can't create a socket: %s\n",
96                        strerror(errno));
97                 exit(errno);
98         }
99         /* Set some socket options that make sense. */
100         i = 1;
101         setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
102
103         if (bind(s, (struct sockaddr *) &sin, sizeof(sin)) < 0) {
104                 lprintf(1, "Can't bind: %s\n", strerror(errno));
105                 exit(errno);
106         }
107         if (listen(s, queue_len) < 0) {
108                 lprintf(1, "Can't listen: %s\n", strerror(errno));
109                 exit(errno);
110         }
111         return (s);
112 }
113
114
115 /*
116  * Read data from the client socket.
117  * Return values are:
118  *      1       Requested number of bytes has been read.
119  *      0       Request timed out.
120  *      -1      Connection is broken, or other error.
121  */
122 int client_read_to(int sock, char *buf, int bytes, int timeout)
123 {
124         int len, rlen;
125         fd_set rfds;
126         struct timeval tv;
127         int retval;
128
129
130 #ifdef HAVE_OPENSSL
131         if (is_https) {
132                 return(client_read_ssl(buf, bytes, timeout));
133         }
134 #endif
135
136         len = 0;
137         while (len < bytes) {
138                 FD_ZERO(&rfds);
139                 FD_SET(sock, &rfds);
140                 tv.tv_sec = timeout;
141                 tv.tv_usec = 0;
142
143                 retval = select((sock) + 1,
144                                 &rfds, NULL, NULL, &tv);
145                 if (FD_ISSET(sock, &rfds) == 0) {
146                         return (0);
147                 }
148
149                 rlen = read(sock, &buf[len], bytes - len);
150
151                 if (rlen < 1) {
152                         lprintf(2, "client_read() failed: %s\n",
153                                strerror(errno));
154                         return(-1);
155                 }
156                 len = len + rlen;
157         }
158
159 #ifdef HTTP_TRACING
160         write(2, "\033[32m", 5);
161         write(2, buf, bytes);
162         write(2, "\033[30m", 5);
163 #endif
164         return (1);
165 }
166
167
168 ssize_t client_write(const void *buf, size_t count) {
169
170         if (WC->burst != NULL) {
171                 WC->burst = realloc(WC->burst, (WC->burst_len + count + 2));
172                 memcpy(&WC->burst[WC->burst_len], buf, count);
173                 WC->burst_len += count;
174                 return(count);
175         }
176
177 #ifdef HAVE_OPENSSL
178         if (is_https) {
179                 client_write_ssl((char *)buf, count);
180                 return(count);
181         }
182 #endif
183 #ifdef HTTP_TRACING
184         write(2, "\033[34m", 5);
185         write(2, buf, count);
186         write(2, "\033[30m", 5);
187 #endif
188         return(write(WC->http_sock, buf, count));
189 }
190
191
192 void begin_burst(void) {
193         if (WC->burst != NULL) {
194                 free(WC->burst);
195                 WC->burst = NULL;
196         }
197         WC->burst_len = 0;
198         WC->burst = malloc(SIZ);
199 }
200
201 void end_burst(void) {
202         size_t the_len;
203         char *the_data;
204
205         the_len = WC->burst_len;
206         the_data = WC->burst;
207
208         WC->burst_len = 0;
209         WC->burst = NULL;
210
211         wprintf("Content-length: %d\r\n\r\n", the_len);
212         client_write(the_data, the_len);
213         free(the_data);
214 }
215
216
217
218 /*
219  * Read data from the client socket with default timeout.
220  * (This is implemented in terms of client_read_to() and could be
221  * justifiably moved out of sysdep.c)
222  */
223 int client_read(int sock, char *buf, int bytes)
224 {
225         return (client_read_to(sock, buf, bytes, SLEEPING));
226 }
227
228
229 /*
230  * client_gets()   ...   Get a LF-terminated line of text from the client.
231  * (This is implemented in terms of client_read() and could be
232  * justifiably moved out of sysdep.c)
233  */
234 int client_gets(int sock, char *buf)
235 {
236         int i, retval;
237
238         /* Read one character at a time.
239          */
240         for (i = 0;; i++) {
241                 retval = client_read(sock, &buf[i], 1);
242                 if (retval != 1 || buf[i] == '\n' || i == 255)
243                         break;
244         }
245
246         /* If we got a long line, discard characters until the newline.
247          */
248         if (i == 255)
249                 while (buf[i] != '\n' && retval == 1)
250                         retval = client_read(sock, &buf[i], 1);
251
252         /*
253          * Strip any trailing non-printable characters.
254          */
255         buf[i] = 0;
256         while ((strlen(buf) > 0) && (!isprint(buf[strlen(buf) - 1]))) {
257                 buf[strlen(buf) - 1] = 0;
258         }
259         return (retval);
260 }
261
262
263 /*
264  * Start running as a daemon.  Only close stdio if do_close_stdio is set.
265  */
266 void start_daemon(int do_close_stdio)
267 {
268         if (do_close_stdio) {
269                 /* close(0); */
270                 close(1);
271                 close(2);
272         }
273         signal(SIGHUP, SIG_IGN);
274         signal(SIGINT, SIG_IGN);
275         signal(SIGQUIT, SIG_IGN);
276         if (fork() != 0)
277                 exit(0);
278 }
279
280 void spawn_another_worker_thread() {
281         pthread_t SessThread;   /* Thread descriptor */
282         pthread_attr_t attr;    /* Thread attributes */
283         int ret;
284
285         lprintf(3, "Creating a new thread\n");
286
287         /* set attributes for the new thread */
288         pthread_attr_init(&attr);
289         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
290
291         /* Our per-thread stacks need to be bigger than the default size, otherwise
292          * the MIME parser crashes on FreeBSD, and the IMAP service crashes on
293          * 64-bit Linux.
294          */
295         if ((ret = pthread_attr_setstacksize(&attr, 1024 * 1024))) {
296                 lprintf(1, "pthread_attr_setstacksize: %s\n", strerror(ret));
297                 pthread_attr_destroy(&attr);
298         }
299
300         /* now create the thread */
301         if (pthread_create(&SessThread, &attr,
302                         (void *(*)(void *)) worker_entry, NULL)
303                    != 0) {
304                 lprintf(1, "Can't create thread: %s\n",
305                         strerror(errno));
306         }
307
308         /* free up the attributes */
309         pthread_attr_destroy(&attr);
310 }
311
312 /*
313  * Here's where it all begins.
314  */
315 int main(int argc, char **argv)
316 {
317         pthread_t SessThread;   /* Thread descriptor */
318         pthread_attr_t attr;    /* Thread attributes */
319         int a, i;               /* General-purpose variables */
320         int port = PORT_NUM;    /* Port to listen on */
321         char tracefile[PATH_MAX];
322         char ip_addr[256];
323
324         /* Parse command line */
325 #ifdef HAVE_OPENSSL
326         while ((a = getopt(argc, argv, "hi:p:t:cs")) != EOF)
327 #else
328         while ((a = getopt(argc, argv, "hi:p:t:c")) != EOF)
329 #endif
330                 switch (a) {
331                 case 'i':
332                         strcpy(ip_addr, optarg);
333                         break;
334                 case 'p':
335                         port = atoi(optarg);
336                         break;
337                 case 't':
338                         strcpy(tracefile, optarg);
339                         freopen(tracefile, "w", stdout);
340                         freopen(tracefile, "w", stderr);
341                         freopen(tracefile, "r", stdin);
342                         break;
343                 case 'x':
344                         verbosity = atoi(optarg);
345                         break;
346                 case 'c':
347                         server_cookie = malloc(SIZ);
348                         if (server_cookie != NULL) {
349                                 strcpy(server_cookie, "Set-cookie: wcserver=");
350                                 if (gethostname(
351                                    &server_cookie[strlen(server_cookie)],
352                                    200) != 0) {
353                                         lprintf(2, "gethostname: %s\n",
354                                                 strerror(errno));
355                                         free(server_cookie);
356                                 }
357                         }
358                         break;
359                 case 's':
360                         is_https = 1;
361                         break;
362                 default:
363                         fprintf(stderr, "usage: webserver "
364                                 "[-i ip_addr] [-p http_port] "
365                                 "[-t tracefile] [-c] "
366 #ifdef HAVE_OPENSSL
367                                 "[-s] "
368 #endif
369                                 "[remotehost [remoteport]]\n");
370                         return 1;
371                 }
372
373         if (optind < argc) {
374                 ctdlhost = argv[optind];
375                 if (++optind < argc)
376                         ctdlport = argv[optind];
377         }
378         /* Tell 'em who's in da house */
379         lprintf(1, SERVER "\n"
380 "Copyright (C) 1996-2005 by the Citadel/UX development team.\n"
381 "This software is distributed under the terms of the GNU General Public\n"
382 "License.  If you paid for this software, someone is ripping you off.\n\n");
383
384         if (chdir(WEBCITDIR) != 0)
385                 perror("chdir");
386
387         /*
388          * Set up a place to put thread-specific data.
389          * We only need a single pointer per thread - it points to the
390          * wcsession struct to which the thread is currently bound.
391          */
392         if (pthread_key_create(&MyConKey, NULL) != 0) {
393                 lprintf(1, "Can't create TSD key: %s\n", strerror(errno));
394         }
395
396         /*
397          * Set up a place to put thread-specific SSL data.
398          * We don't stick this in the wcsession struct because SSL starts
399          * up before the session is bound, and it gets torn down between
400          * transactions.
401          */
402 #ifdef HAVE_OPENSSL
403         if (pthread_key_create(&ThreadSSL, NULL) != 0) {
404                 lprintf(1, "Can't create TSD key: %s\n", strerror(errno));
405         }
406 #endif
407
408         /*
409          * Bind the server to our favorite port.
410          * There is no need to check for errors, because ig_tcp_server()
411          * exits if it doesn't succeed.
412          */
413         lprintf(2, "Attempting to bind to port %d...\n", port);
414         msock = ig_tcp_server(ip_addr, port, LISTEN_QUEUE_LENGTH);
415         lprintf(2, "Listening on socket %d\n", msock);
416         signal(SIGPIPE, SIG_IGN);
417
418         pthread_mutex_init(&SessionListMutex, NULL);
419
420         /*
421          * Start up the housekeeping thread
422          */
423         pthread_attr_init(&attr);
424         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
425         pthread_create(&SessThread, &attr,
426                        (void *(*)(void *)) housekeeping_loop, NULL);
427
428
429         /*
430          * If this is an HTTPS server, fire up SSL
431          */
432 #ifdef HAVE_OPENSSL
433         if (is_https) {
434                 init_ssl();
435         }
436 #endif
437
438         /* Start a few initial worker threads */
439         for (i=0; i<(MIN_WORKER_THREADS); ++i) {
440                 spawn_another_worker_thread();
441         }
442
443         /* now the original thread becomes another worker */
444         worker_entry();
445         return 0;
446 }
447
448
449 /*
450  * Entry point for worker threads
451  */
452 void worker_entry(void) {
453         int ssock;
454         int i = 0;
455         int time_to_die = 0;
456         int fail_this_transaction = 0;
457
458         do {
459                 /* Only one thread can accept at a time */
460                 fail_this_transaction = 0;
461                 ssock = accept(msock, NULL, 0);
462                 if (ssock < 0) {
463                         lprintf(2, "accept() failed: %s\n", strerror(errno));
464                 } else {
465                         /* Set the SO_REUSEADDR socket option */
466                         i = 1;
467                         setsockopt(ssock, SOL_SOCKET, SO_REUSEADDR,
468                                 &i, sizeof(i));
469
470                         /* If we are an HTTPS server, go crypto now. */
471 #ifdef HAVE_OPENSSL
472                         if (is_https) {
473                                 if (starttls(ssock) != 0) {
474                                         fail_this_transaction = 1;
475                                         close(ssock);
476                                 }
477                         }
478 #endif
479
480                         if (fail_this_transaction == 0) {
481                                 /* Perform an HTTP transaction... */
482                                 context_loop(ssock);
483                                 /* ...and close the socket. */
484                                 lingering_close(ssock);
485                         }
486
487                 }
488
489         } while (!time_to_die);
490
491         pthread_exit(NULL);
492 }
493
494
495 int lprintf(int loglevel, const char *format, ...)
496 {
497         va_list ap;
498
499         if (loglevel <= verbosity) {
500                 va_start(ap, format);
501                 vfprintf(stderr, format, ap);
502                 va_end(ap);
503                 fflush(stderr);
504         }
505         return 1;
506 }