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