* Brought over the SSL/TLS stuff from Citadel. I think it's complete but
[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 <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(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         sin.sin_addr.s_addr = INADDR_ANY;
72
73         if (port_number == 0) {
74                 lprintf(1, "Cannot start: no port number specified.\n");
75                 exit(1);
76         }
77         sin.sin_port = htons((u_short) port_number);
78
79         s = socket(PF_INET, SOCK_STREAM, (getprotobyname("tcp")->p_proto));
80         if (s < 0) {
81                 lprintf(1, "Can't create a socket: %s\n",
82                        strerror(errno));
83                 exit(errno);
84         }
85         /* Set some socket options that make sense. */
86         i = 1;
87         setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
88
89         if (bind(s, (struct sockaddr *) &sin, sizeof(sin)) < 0) {
90                 lprintf(1, "Can't bind: %s\n", strerror(errno));
91                 exit(errno);
92         }
93         if (listen(s, queue_len) < 0) {
94                 lprintf(1, "Can't listen: %s\n", strerror(errno));
95                 exit(errno);
96         }
97         return (s);
98 }
99
100
101 /*
102  * Read data from the client socket.
103  * Return values are:
104  *      1       Requested number of bytes has been read.
105  *      0       Request timed out.
106  *      -1      Connection is broken, or other error.
107  */
108 int client_read_to(int sock, char *buf, int bytes, int timeout)
109 {
110         int len, rlen;
111         fd_set rfds;
112         struct timeval tv;
113         int retval;
114
115         len = 0;
116         while (len < bytes) {
117                 FD_ZERO(&rfds);
118                 FD_SET(sock, &rfds);
119                 tv.tv_sec = timeout;
120                 tv.tv_usec = 0;
121
122                 retval = select((sock) + 1,
123                                 &rfds, NULL, NULL, &tv);
124                 if (FD_ISSET(sock, &rfds) == 0) {
125                         return (0);
126                 }
127                 rlen = read(sock, &buf[len], bytes - len);
128                 if (rlen < 1) {
129                         lprintf(2, "client_read() failed: %s\n",
130                                strerror(errno));
131                         return(-1);
132                 }
133                 len = len + rlen;
134         }
135         return (1);
136 }
137
138 /*
139  * Read data from the client socket with default timeout.
140  * (This is implemented in terms of client_read_to() and could be
141  * justifiably moved out of sysdep.c)
142  */
143 int client_read(int sock, char *buf, int bytes)
144 {
145         return (client_read_to(sock, buf, bytes, SLEEPING));
146 }
147
148
149 /*
150  * client_gets()   ...   Get a LF-terminated line of text from the client.
151  * (This is implemented in terms of client_read() and could be
152  * justifiably moved out of sysdep.c)
153  */
154 int client_gets(int sock, char *buf)
155 {
156         int i, retval;
157
158         /* Read one character at a time.
159          */
160         for (i = 0;; i++) {
161                 retval = client_read(sock, &buf[i], 1);
162                 if (retval != 1 || buf[i] == '\n' || i == 255)
163                         break;
164         }
165
166         /* If we got a long line, discard characters until the newline.
167          */
168         if (i == 255)
169                 while (buf[i] != '\n' && retval == 1)
170                         retval = client_read(sock, &buf[i], 1);
171
172         /*
173          * Strip any trailing non-printable characters.
174          */
175         buf[i] = 0;
176         while ((strlen(buf) > 0) && (!isprint(buf[strlen(buf) - 1]))) {
177                 buf[strlen(buf) - 1] = 0;
178         }
179         return (retval);
180 }
181
182
183 /*
184  * Start running as a daemon.  Only close stdio if do_close_stdio is set.
185  */
186 void start_daemon(int do_close_stdio)
187 {
188         if (do_close_stdio) {
189                 /* close(0); */
190                 close(1);
191                 close(2);
192         }
193         signal(SIGHUP, SIG_IGN);
194         signal(SIGINT, SIG_IGN);
195         signal(SIGQUIT, SIG_IGN);
196         if (fork() != 0)
197                 exit(0);
198 }
199
200 void spawn_another_worker_thread() {
201         pthread_t SessThread;   /* Thread descriptor */
202         pthread_attr_t attr;    /* Thread attributes */
203
204         lprintf(3, "Creating a new thread\n");
205
206         /* set attributes for the new thread */
207         pthread_attr_init(&attr);
208         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
209
210         /* now create the thread */
211         if (pthread_create(&SessThread, &attr,
212                         (void *(*)(void *)) worker_entry, NULL)
213                    != 0) {
214                 lprintf(1, "Can't create thread: %s\n",
215                         strerror(errno));
216         }
217 }
218
219 /*
220  * Here's where it all begins.
221  */
222 int main(int argc, char **argv)
223 {
224         pthread_t SessThread;   /* Thread descriptor */
225         pthread_attr_t attr;    /* Thread attributes */
226         int a, i;               /* General-purpose variables */
227         int port = PORT_NUM;    /* Port to listen on */
228         char tracefile[PATH_MAX];
229
230         /* Parse command line */
231 #ifdef HAVE_OPENSSL
232         while ((a = getopt(argc, argv, "hp:t:cs")) != EOF)
233 #else
234         while ((a = getopt(argc, argv, "hp:t:c")) != EOF)
235 #endif
236                 switch (a) {
237                 case 'p':
238                         port = atoi(optarg);
239                         break;
240                 case 't':
241                         strcpy(tracefile, optarg);
242                         freopen(tracefile, "w", stdout);
243                         freopen(tracefile, "w", stderr);
244                         freopen(tracefile, "r", stdin);
245                         break;
246                 case 'x':
247                         verbosity = atoi(optarg);
248                         break;
249                 case 'c':
250                         server_cookie = malloc(SIZ);
251                         if (server_cookie != NULL) {
252                                 strcpy(server_cookie, "Set-cookie: wcserver=");
253                                 if (gethostname(
254                                    &server_cookie[strlen(server_cookie)],
255                                    200) != 0) {
256                                         lprintf(2, "gethostname: %s\n",
257                                                 strerror(errno));
258                                         free(server_cookie);
259                                 }
260                         }
261                         break;
262                 case 's':
263                         is_https = 1;
264                         break;
265                 default:
266                         fprintf(stderr, "usage: webserver [-p localport] "
267                                 "[-t tracefile] [-c] "
268 #ifdef HAVE_OPENSSL
269                                 "[-s] "
270 #endif
271                                 "[remotehost [remoteport]]\n");
272                         return 1;
273                 }
274
275         if (optind < argc) {
276                 ctdlhost = argv[optind];
277                 if (++optind < argc)
278                         ctdlport = argv[optind];
279         }
280         /* Tell 'em who's in da house */
281         lprintf(1, SERVER "\n"
282 "Copyright (C) 1996-2004 by the Citadel/UX development team.\n"
283 "This software is distributed under the terms of the GNU General Public\n"
284 "License.  If you paid for this software, someone is ripping you off.\n\n");
285
286         if (chdir(WEBCITDIR) != 0)
287                 perror("chdir");
288
289         /*
290          * Set up a place to put thread-specific data.
291          * We only need a single pointer per thread - it points to the
292          * wcsession struct to which the thread is currently bound.
293          */
294         if (pthread_key_create(&MyConKey, NULL) != 0) {
295                 lprintf(1, "Can't create TSD key: %s\n", strerror(errno));
296         }
297
298         /*
299          * Bind the server to our favorite port.
300          * There is no need to check for errors, because ig_tcp_server()
301          * exits if it doesn't succeed.
302          */
303         lprintf(2, "Attempting to bind to port %d...\n", port);
304         msock = ig_tcp_server(port, LISTEN_QUEUE_LENGTH);
305         lprintf(2, "Listening on socket %d\n", msock);
306         signal(SIGPIPE, SIG_IGN);
307
308         pthread_mutex_init(&SessionListMutex, NULL);
309
310         /*
311          * Start up the housekeeping thread
312          */
313         pthread_attr_init(&attr);
314         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
315         pthread_create(&SessThread, &attr,
316                        (void *(*)(void *)) housekeeping_loop, NULL);
317
318
319         /*
320          * If this is an HTTPS server, fire up SSL
321          */
322 #ifdef HAVE_OPENSSL
323         if (is_https) {
324                 init_ssl();
325         }
326 #endif
327
328         /* Start a few initial worker threads */
329         for (i=0; i<(MIN_WORKER_THREADS); ++i) {
330                 spawn_another_worker_thread();
331         }
332
333         /* now the original thread becomes another worker */
334         worker_entry();
335         return 0;
336 }
337
338
339 /*
340  * Entry point for worker threads
341  */
342 void worker_entry(void) {
343         int ssock;
344         int i = 0;
345         int time_to_die = 0;
346         int fail_this_transaction = 0;
347
348         do {
349                 /* Only one thread can accept at a time */
350                 fail_this_transaction = 0;
351                 ssock = accept(msock, NULL, 0);
352                 if (ssock < 0) {
353                         lprintf(2, "accept() failed: %s\n", strerror(errno));
354                 } else {
355                         /* Set the SO_REUSEADDR socket option */
356                         i = 1;
357                         setsockopt(ssock, SOL_SOCKET, SO_REUSEADDR,
358                                 &i, sizeof(i));
359
360                         /* If we are an HTTPS server, go crypto now. */
361 #ifdef HAVE_OPENSSL
362                         if (is_https) {
363                                 if (starttls() != 0) {
364                                         fail_this_transaction = 1;
365                                 }
366                         }
367 #endif
368
369                         /* Perform an HTTP transaction... */
370                         if (fail_this_transaction == 0) {
371                                 context_loop(ssock);
372                         }
373
374                         /* ...and close the socket. */
375                         lingering_close(ssock);
376                 }
377
378         } while (!time_to_die);
379
380         pthread_exit(NULL);
381 }
382
383
384 int lprintf(int loglevel, const char *format, ...)
385 {
386         va_list ap;
387         char buf[4096];
388
389         va_start(ap, format);
390         vsprintf(buf, format, ap);
391         va_end(ap);
392
393         if (loglevel <= verbosity) {
394                 struct timeval tv;
395                 struct tm *tim;
396
397                 gettimeofday(&tv, NULL);
398                 tim = localtime((time_t *)&(tv.tv_sec));
399
400                 if (WC && WC->wc_session) {
401                         fprintf(stderr,
402                                 "%04d/%02d/%02d %2d:%02d:%02d.%03ld [%ld:%d] %s",
403                                 tim->tm_year + 1900, tim->tm_mon + 1,
404                                 tim->tm_mday, tim->tm_hour, tim->tm_min,
405                                 tim->tm_sec, (long)tv.tv_usec / 1000,
406                                 (long)pthread_self(),
407                                 WC->wc_session, buf);
408                 } else {
409                         fprintf(stderr,
410                                 "%04d/%02d/%02d %2d:%02d:%02d.%03ld [%ld] %s",
411                                 tim->tm_year + 1900, tim->tm_mon + 1,
412                                 tim->tm_mday, tim->tm_hour, tim->tm_min,
413                                 tim->tm_sec, (long)tv.tv_usec / 1000,
414                                 (long)pthread_self(),
415                                 buf);
416                 }
417                 fflush(stderr);
418         }
419         return 1;
420 }