]> code.citadel.org Git - citadel.git/blob - webcit/webserver.c
2cdb0bbdfbce15344ed6350a4db70d88c1f06135
[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         if (WC->burst == NULL) return;
206
207         the_len = WC->burst_len;
208         the_data = WC->burst;
209
210         WC->burst_len = 0;
211         WC->burst = NULL;
212
213         wprintf("Content-length: %d\r\n\r\n", the_len);
214         client_write(the_data, the_len);
215         free(the_data);
216 }
217
218
219
220 /*
221  * Read data from the client socket with default timeout.
222  * (This is implemented in terms of client_read_to() and could be
223  * justifiably moved out of sysdep.c)
224  */
225 int client_read(int sock, char *buf, int bytes)
226 {
227         return (client_read_to(sock, buf, bytes, SLEEPING));
228 }
229
230
231 /*
232  * client_gets()   ...   Get a LF-terminated line of text from the client.
233  * (This is implemented in terms of client_read() and could be
234  * justifiably moved out of sysdep.c)
235  */
236 int client_gets(int sock, char *buf)
237 {
238         int i, retval;
239
240         /* Read one character at a time.
241          */
242         for (i = 0;; i++) {
243                 retval = client_read(sock, &buf[i], 1);
244                 if (retval != 1 || buf[i] == '\n' || i == 255)
245                         break;
246         }
247
248         /* If we got a long line, discard characters until the newline.
249          */
250         if (i == 255)
251                 while (buf[i] != '\n' && retval == 1)
252                         retval = client_read(sock, &buf[i], 1);
253
254         /*
255          * Strip any trailing non-printable characters.
256          */
257         buf[i] = 0;
258         while ((strlen(buf) > 0) && (!isprint(buf[strlen(buf) - 1]))) {
259                 buf[strlen(buf) - 1] = 0;
260         }
261         return (retval);
262 }
263
264
265 /*
266  * Start running as a daemon.  Only close stdio if do_close_stdio is set.
267  */
268 void start_daemon(int do_close_stdio)
269 {
270         if (do_close_stdio) {
271                 /* close(0); */
272                 close(1);
273                 close(2);
274         }
275         signal(SIGHUP, SIG_IGN);
276         signal(SIGINT, SIG_IGN);
277         signal(SIGQUIT, SIG_IGN);
278         if (fork() != 0)
279                 exit(0);
280 }
281
282 void spawn_another_worker_thread() {
283         pthread_t SessThread;   /* Thread descriptor */
284         pthread_attr_t attr;    /* Thread attributes */
285         int ret;
286
287         lprintf(3, "Creating a new thread\n");
288
289         /* set attributes for the new thread */
290         pthread_attr_init(&attr);
291         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
292
293         /* Our per-thread stacks need to be bigger than the default size, otherwise
294          * the MIME parser crashes on FreeBSD, and the IMAP service crashes on
295          * 64-bit Linux.
296          */
297         if ((ret = pthread_attr_setstacksize(&attr, 1024 * 1024))) {
298                 lprintf(1, "pthread_attr_setstacksize: %s\n", strerror(ret));
299                 pthread_attr_destroy(&attr);
300         }
301
302         /* now create the thread */
303         if (pthread_create(&SessThread, &attr,
304                         (void *(*)(void *)) worker_entry, NULL)
305                    != 0) {
306                 lprintf(1, "Can't create thread: %s\n",
307                         strerror(errno));
308         }
309
310         /* free up the attributes */
311         pthread_attr_destroy(&attr);
312 }
313
314 /*
315  * Here's where it all begins.
316  */
317 int main(int argc, char **argv)
318 {
319         pthread_t SessThread;   /* Thread descriptor */
320         pthread_attr_t attr;    /* Thread attributes */
321         int a, i;               /* General-purpose variables */
322         int port = PORT_NUM;    /* Port to listen on */
323         char tracefile[PATH_MAX];
324         char ip_addr[256];
325
326         /* Parse command line */
327 #ifdef HAVE_OPENSSL
328         while ((a = getopt(argc, argv, "hi:p:t:cs")) != EOF)
329 #else
330         while ((a = getopt(argc, argv, "hi:p:t:c")) != EOF)
331 #endif
332                 switch (a) {
333                 case 'i':
334                         strcpy(ip_addr, optarg);
335                         break;
336                 case 'p':
337                         port = atoi(optarg);
338                         break;
339                 case 't':
340                         strcpy(tracefile, optarg);
341                         freopen(tracefile, "w", stdout);
342                         freopen(tracefile, "w", stderr);
343                         freopen(tracefile, "r", stdin);
344                         break;
345                 case 'x':
346                         verbosity = atoi(optarg);
347                         break;
348                 case 'c':
349                         server_cookie = malloc(SIZ);
350                         if (server_cookie != NULL) {
351                                 strcpy(server_cookie, "Set-cookie: wcserver=");
352                                 if (gethostname(
353                                    &server_cookie[strlen(server_cookie)],
354                                    200) != 0) {
355                                         lprintf(2, "gethostname: %s\n",
356                                                 strerror(errno));
357                                         free(server_cookie);
358                                 }
359                         }
360                         break;
361                 case 's':
362                         is_https = 1;
363                         break;
364                 default:
365                         fprintf(stderr, "usage: webserver "
366                                 "[-i ip_addr] [-p http_port] "
367                                 "[-t tracefile] [-c] "
368 #ifdef HAVE_OPENSSL
369                                 "[-s] "
370 #endif
371                                 "[remotehost [remoteport]]\n");
372                         return 1;
373                 }
374
375         if (optind < argc) {
376                 ctdlhost = argv[optind];
377                 if (++optind < argc)
378                         ctdlport = argv[optind];
379         }
380         /* Tell 'em who's in da house */
381         lprintf(1, SERVER "\n"
382 "Copyright (C) 1996-2005 by the Citadel/UX development team.\n"
383 "This software is distributed under the terms of the GNU General Public\n"
384 "License.  If you paid for this software, someone is ripping you off.\n\n");
385
386         if (chdir(WEBCITDIR) != 0)
387                 perror("chdir");
388
389         /*
390          * Set up a place to put thread-specific data.
391          * We only need a single pointer per thread - it points to the
392          * wcsession struct to which the thread is currently bound.
393          */
394         if (pthread_key_create(&MyConKey, NULL) != 0) {
395                 lprintf(1, "Can't create TSD key: %s\n", strerror(errno));
396         }
397
398         /*
399          * Set up a place to put thread-specific SSL data.
400          * We don't stick this in the wcsession struct because SSL starts
401          * up before the session is bound, and it gets torn down between
402          * transactions.
403          */
404 #ifdef HAVE_OPENSSL
405         if (pthread_key_create(&ThreadSSL, NULL) != 0) {
406                 lprintf(1, "Can't create TSD key: %s\n", strerror(errno));
407         }
408 #endif
409
410         /*
411          * Bind the server to our favorite port.
412          * There is no need to check for errors, because ig_tcp_server()
413          * exits if it doesn't succeed.
414          */
415         lprintf(2, "Attempting to bind to port %d...\n", port);
416         msock = ig_tcp_server(ip_addr, port, LISTEN_QUEUE_LENGTH);
417         lprintf(2, "Listening on socket %d\n", msock);
418         signal(SIGPIPE, SIG_IGN);
419
420         pthread_mutex_init(&SessionListMutex, NULL);
421
422         /*
423          * Start up the housekeeping thread
424          */
425         pthread_attr_init(&attr);
426         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
427         pthread_create(&SessThread, &attr,
428                        (void *(*)(void *)) housekeeping_loop, NULL);
429
430
431         /*
432          * If this is an HTTPS server, fire up SSL
433          */
434 #ifdef HAVE_OPENSSL
435         if (is_https) {
436                 init_ssl();
437         }
438 #endif
439
440         /* Start a few initial worker threads */
441         for (i=0; i<(MIN_WORKER_THREADS); ++i) {
442                 spawn_another_worker_thread();
443         }
444
445         /* now the original thread becomes another worker */
446         worker_entry();
447         return 0;
448 }
449
450
451 /*
452  * Entry point for worker threads
453  */
454 void worker_entry(void) {
455         int ssock;
456         int i = 0;
457         int time_to_die = 0;
458         int fail_this_transaction = 0;
459
460         do {
461                 /* Only one thread can accept at a time */
462                 fail_this_transaction = 0;
463                 ssock = accept(msock, NULL, 0);
464                 if (ssock < 0) {
465                         lprintf(2, "accept() failed: %s\n", strerror(errno));
466                 } else {
467                         /* Set the SO_REUSEADDR socket option */
468                         i = 1;
469                         setsockopt(ssock, SOL_SOCKET, SO_REUSEADDR,
470                                 &i, sizeof(i));
471
472                         /* If we are an HTTPS server, go crypto now. */
473 #ifdef HAVE_OPENSSL
474                         if (is_https) {
475                                 if (starttls(ssock) != 0) {
476                                         fail_this_transaction = 1;
477                                         close(ssock);
478                                 }
479                         }
480 #endif
481
482                         if (fail_this_transaction == 0) {
483                                 /* Perform an HTTP transaction... */
484                                 context_loop(ssock);
485                                 /* ...and close the socket. */
486                                 lingering_close(ssock);
487                         }
488
489                 }
490
491         } while (!time_to_die);
492
493         pthread_exit(NULL);
494 }
495
496
497 int lprintf(int loglevel, const char *format, ...)
498 {
499         va_list ap;
500
501         if (loglevel <= verbosity) {
502                 va_start(ap, format);
503                 vfprintf(stderr, format, ap);
504                 va_end(ap);
505                 fflush(stderr);
506         }
507         return 1;
508 }