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