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