]> code.citadel.org Git - citadel.git/blob - webcit/webserver.c
* msgbase.c: cmd_ent0(): Fix another unbuffer_output()
[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
250 /*
251  * Here's where it all begins.
252  */
253 int main(int argc, char **argv)
254 {
255         pthread_t SessThread;   /* Thread descriptor */
256         pthread_attr_t attr;    /* Thread attributes */
257         int a, i;               /* General-purpose variables */
258         int port = PORT_NUM;    /* Port to listen on */
259         char tracefile[PATH_MAX];
260         char ip_addr[256];
261
262         /* Parse command line */
263 #ifdef HAVE_OPENSSL
264         while ((a = getopt(argc, argv, "hi:p:t:cs")) != EOF)
265 #else
266         while ((a = getopt(argc, argv, "hi:p:t:c")) != EOF)
267 #endif
268                 switch (a) {
269                 case 'i':
270                         strcpy(ip_addr, optarg);
271                         break;
272                 case 'p':
273                         port = atoi(optarg);
274                         break;
275                 case 't':
276                         strcpy(tracefile, optarg);
277                         freopen(tracefile, "w", stdout);
278                         freopen(tracefile, "w", stderr);
279                         freopen(tracefile, "r", stdin);
280                         break;
281                 case 'x':
282                         verbosity = atoi(optarg);
283                         break;
284                 case 'c':
285                         server_cookie = malloc(SIZ);
286                         if (server_cookie != NULL) {
287                                 strcpy(server_cookie, "Set-cookie: wcserver=");
288                                 if (gethostname(
289                                    &server_cookie[strlen(server_cookie)],
290                                    200) != 0) {
291                                         lprintf(2, "gethostname: %s\n",
292                                                 strerror(errno));
293                                         free(server_cookie);
294                                 }
295                         }
296                         break;
297                 case 's':
298                         is_https = 1;
299                         break;
300                 default:
301                         fprintf(stderr, "usage: webserver "
302                                 "[-i ip_addr] [-p http_port] "
303                                 "[-t tracefile] [-c] "
304 #ifdef HAVE_OPENSSL
305                                 "[-s] "
306 #endif
307                                 "[remotehost [remoteport]]\n");
308                         return 1;
309                 }
310
311         if (optind < argc) {
312                 ctdlhost = argv[optind];
313                 if (++optind < argc)
314                         ctdlport = argv[optind];
315         }
316         /* Tell 'em who's in da house */
317         lprintf(1, SERVER "\n"
318 "Copyright (C) 1996-2004 by the Citadel/UX development team.\n"
319 "This software is distributed under the terms of the GNU General Public\n"
320 "License.  If you paid for this software, someone is ripping you off.\n\n");
321
322         if (chdir(WEBCITDIR) != 0)
323                 perror("chdir");
324
325         /*
326          * Set up a place to put thread-specific data.
327          * We only need a single pointer per thread - it points to the
328          * wcsession struct to which the thread is currently bound.
329          */
330         if (pthread_key_create(&MyConKey, NULL) != 0) {
331                 lprintf(1, "Can't create TSD key: %s\n", strerror(errno));
332         }
333
334         /*
335          * Set up a place to put thread-specific SSL data.
336          * We don't stick this in the wcsession struct because SSL starts
337          * up before the session is bound, and it gets torn down between
338          * transactions.
339          */
340 #ifdef HAVE_OPENSSL
341         if (pthread_key_create(&ThreadSSL, NULL) != 0) {
342                 lprintf(1, "Can't create TSD key: %s\n", strerror(errno));
343         }
344 #endif
345
346         /*
347          * Bind the server to our favorite port.
348          * There is no need to check for errors, because ig_tcp_server()
349          * exits if it doesn't succeed.
350          */
351         lprintf(2, "Attempting to bind to port %d...\n", port);
352         msock = ig_tcp_server(ip_addr, port, LISTEN_QUEUE_LENGTH);
353         lprintf(2, "Listening on socket %d\n", msock);
354         signal(SIGPIPE, SIG_IGN);
355
356         pthread_mutex_init(&SessionListMutex, NULL);
357
358         /*
359          * Start up the housekeeping thread
360          */
361         pthread_attr_init(&attr);
362         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
363         pthread_create(&SessThread, &attr,
364                        (void *(*)(void *)) housekeeping_loop, NULL);
365
366
367         /*
368          * If this is an HTTPS server, fire up SSL
369          */
370 #ifdef HAVE_OPENSSL
371         if (is_https) {
372                 init_ssl();
373         }
374 #endif
375
376         /* Start a few initial worker threads */
377         for (i=0; i<(MIN_WORKER_THREADS); ++i) {
378                 spawn_another_worker_thread();
379         }
380
381         /* now the original thread becomes another worker */
382         worker_entry();
383         return 0;
384 }
385
386
387 /*
388  * Entry point for worker threads
389  */
390 void worker_entry(void) {
391         int ssock;
392         int i = 0;
393         int time_to_die = 0;
394         int fail_this_transaction = 0;
395
396         do {
397                 /* Only one thread can accept at a time */
398                 fail_this_transaction = 0;
399                 ssock = accept(msock, NULL, 0);
400                 if (ssock < 0) {
401                         lprintf(2, "accept() failed: %s\n", strerror(errno));
402                 } else {
403                         /* Set the SO_REUSEADDR socket option */
404                         i = 1;
405                         setsockopt(ssock, SOL_SOCKET, SO_REUSEADDR,
406                                 &i, sizeof(i));
407
408                         /* If we are an HTTPS server, go crypto now. */
409 #ifdef HAVE_OPENSSL
410                         if (is_https) {
411                                 if (starttls(ssock) != 0) {
412                                         fail_this_transaction = 1;
413                                         close(ssock);
414                                 }
415                         }
416 #endif
417
418                         if (fail_this_transaction == 0) {
419                                 /* Perform an HTTP transaction... */
420                                 context_loop(ssock);
421                                 /* ...and close the socket. */
422                                 lingering_close(ssock);
423                         }
424
425                 }
426
427         } while (!time_to_die);
428
429         pthread_exit(NULL);
430 }
431
432
433 int lprintf(int loglevel, const char *format, ...)
434 {
435         va_list ap;
436         char buf[4096];
437
438         va_start(ap, format);
439         vsprintf(buf, format, ap);
440         va_end(ap);
441
442         if (loglevel <= verbosity) {
443                 struct timeval tv;
444                 struct tm *tim;
445
446                 gettimeofday(&tv, NULL);
447                 tim = localtime((time_t *)&(tv.tv_sec));
448
449                 if (WC && WC->wc_session) {
450                         fprintf(stderr,
451                                 "%04d/%02d/%02d %2d:%02d:%02d.%03ld [%ld:%d] %s",
452                                 tim->tm_year + 1900, tim->tm_mon + 1,
453                                 tim->tm_mday, tim->tm_hour, tim->tm_min,
454                                 tim->tm_sec, (long)tv.tv_usec / 1000,
455                                 (long)pthread_self(),
456                                 WC->wc_session, buf);
457                 } else {
458                         fprintf(stderr,
459                                 "%04d/%02d/%02d %2d:%02d:%02d.%03ld [%ld] %s",
460                                 tim->tm_year + 1900, tim->tm_mon + 1,
461                                 tim->tm_mday, tim->tm_hour, tim->tm_min,
462                                 tim->tm_sec, (long)tv.tv_usec / 1000,
463                                 (long)pthread_self(),
464                                 buf);
465                 }
466                 fflush(stderr);
467         }
468         return 1;
469 }