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