2f05519fab730aa8fdb63ddfe2ad612fee1e551d
[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
40 #ifndef HAVE_SNPRINTF
41 int vsnprintf(char *buf, size_t max, const char *fmt, va_list argp);
42 #endif
43
44 int msock;                      /* master listening socket */
45 extern void *context_loop(int);
46 extern void *housekeeping_loop(void);
47 extern pthread_mutex_t SessionListMutex;
48 extern pthread_key_t MyConKey;
49
50
51 char *server_cookie = NULL;
52
53
54 char *defaulthost = DEFAULT_HOST;
55 char *defaultport = DEFAULT_PORT;
56
57 pthread_mutex_t AcceptQueue;
58
59 /*
60  * This is a generic function to set up a master socket for listening on
61  * a TCP port.  The server shuts down if the bind fails.
62  */
63 int ig_tcp_server(int port_number, int queue_len)
64 {
65         struct sockaddr_in sin;
66         int s, i;
67
68         memset(&sin, 0, sizeof(sin));
69         sin.sin_family = AF_INET;
70         sin.sin_addr.s_addr = INADDR_ANY;
71
72         if (port_number == 0) {
73                 fprintf(stderr,
74                         "webcit: 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                 fprintf(stderr, "webcit: 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                 fprintf(stderr, "webcit: Can't bind: %s\n", strerror(errno));
91                 exit(errno);
92         }
93         if (listen(s, queue_len) < 0) {
94                 fprintf(stderr, "webcit: 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                         fprintf(stderr, "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         fprintf(stderr, "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                 fprintf(stderr, "webcit: 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         while ((a = getopt(argc, argv, "hp:t:c")) != EOF)
232                 switch (a) {
233                 case 'p':
234                         port = atoi(optarg);
235                         break;
236                 case 't':
237                         strcpy(tracefile, optarg);
238                         freopen(tracefile, "w", stdout);
239                         freopen(tracefile, "w", stderr);
240                         freopen(tracefile, "r", stdin);
241                         break;
242                 case 'c':
243                         server_cookie = malloc(256);
244                         if (server_cookie != NULL) {
245                                 strcpy(server_cookie, "Set-cookie: wcserver=");
246                                 if (gethostname(
247                                    &server_cookie[strlen(server_cookie)],
248                                    200) != 0) {
249                                         fprintf(stderr, "gethostname: %s\n",
250                                                 strerror(errno));
251                                         free(server_cookie);
252                                 }
253                         }
254                         break;
255                 default:
256                         fprintf(stderr, "usage: webserver [-p localport] "
257                                 "[-t tracefile] [-c] "
258                                 "[remotehost [remoteport]]\n");
259                         return 1;
260                 }
261
262         if (optind < argc) {
263                 defaulthost = argv[optind];
264                 if (++optind < argc)
265                         defaultport = argv[optind];
266         }
267         /* Tell 'em who's in da house */
268         fprintf(stderr, SERVER "\n"
269                 "Copyright (C) 1996-2001\n"
270                 "This software is distributed under the terms of the GNU\n"
271                 "General Public License.  All other rights reserved.\n\n");
272
273         if (chdir(WEBCITDIR) != 0)
274                 perror("chdir");
275
276         /*
277          * Set up a place to put thread-specific data.
278          * We only need a single pointer per thread - it points to the
279          * wcsession struct to which the thread is currently bound.
280          */
281         if (pthread_key_create(&MyConKey, NULL) != 0) {
282                 fprintf(stderr, "Can't create TSD key: %s\n", strerror(errno));
283         }
284
285         /*
286          * Bind the server to our favorite port.
287          * There is no need to check for errors, because ig_tcp_server()
288          * exits if it doesn't succeed.
289          */
290         fprintf(stderr, "Attempting to bind to port %d...\n", port);
291         msock = ig_tcp_server(port, LISTEN_QUEUE_LENGTH);
292         fprintf(stderr, "Listening on socket %d\n", msock);
293         signal(SIGPIPE, SIG_IGN);
294
295         pthread_mutex_init(&SessionListMutex, NULL);
296         pthread_mutex_init(&AcceptQueue, NULL);
297
298         /*
299          * Start up the housekeeping thread
300          */
301         pthread_attr_init(&attr);
302         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
303         pthread_create(&SessThread, &attr,
304                        (void *(*)(void *)) housekeeping_loop, NULL);
305
306
307         /* Start a few initial worker threads */
308         for (i=0; i<(INITIAL_WORKER_THREADS); ++i) {
309                 spawn_another_worker_thread();
310         }
311
312         /* now the original thread can go away. */
313         pthread_exit(NULL);
314         return 0;
315 }
316
317
318 /*
319  * Entry point for worker threads
320  */
321 void worker_entry(void) {
322         int ssock;
323         struct sockaddr_in fsin;
324         int alen;
325         int i = 0;
326         int time_to_die = 0;
327         time_t start_time, stop_time;
328
329         do {
330                 /* Only one thread can accept at a time */
331                 start_time = time(NULL);
332                 pthread_mutex_lock(&AcceptQueue);
333                 ssock = accept(msock, (struct sockaddr *) &fsin, &alen);
334                 pthread_mutex_unlock(&AcceptQueue);
335                 stop_time = time(NULL);
336
337                 /* Augment the thread pool if we're not blocking at all */
338                 if ( (stop_time - start_time) == 0L) {
339                         spawn_another_worker_thread();
340                 }
341
342                 if (ssock < 0) {
343                         fprintf(stderr, "webcit: accept() failed: %s\n",
344                         strerror(errno));
345                 } else {
346                         /* Set the SO_REUSEADDR socket option */
347                         i = 1;
348                         setsockopt(ssock, SOL_SOCKET, SO_REUSEADDR,
349                                 &i, sizeof(i));
350
351                         /* Perform an HTTP transaction... */
352                         context_loop(ssock);
353
354                         /* ...and close the socket. */
355                         lingering_close(ssock);
356                 }
357
358         } while (!time_to_die);
359
360         pthread_exit(NULL);
361 }