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