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