]> code.citadel.org Git - citadel.git/blob - webcit/webserver.c
* Rewrote the HTTP engine and application coupling to run in a worker thread
[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
52
53
54 const char *defaulthost = DEFAULT_HOST;
55 const 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                 printf("webcit: Cannot start: no port number specified.\n");
74                 exit(1);
75         }
76         sin.sin_port = htons((u_short) port_number);
77
78         s = socket(PF_INET, SOCK_STREAM, (getprotobyname("tcp")->p_proto));
79         if (s < 0) {
80                 printf("webcit: Can't create a socket: %s\n",
81                        strerror(errno));
82                 exit(errno);
83         }
84         /* Set some socket options that make sense. */
85         i = 1;
86         setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
87
88         if (bind(s, (struct sockaddr *) &sin, sizeof(sin)) < 0) {
89                 printf("webcit: Can't bind: %s\n", strerror(errno));
90                 exit(errno);
91         }
92         if (listen(s, queue_len) < 0) {
93                 printf("webcit: Can't listen: %s\n", strerror(errno));
94                 exit(errno);
95         }
96         return (s);
97 }
98
99
100 /*
101  * client_write()   ...    Send binary data to the client.
102  */
103 void client_write(int sock, char *buf, int nbytes)
104 {
105         int bytes_written = 0;
106         int retval;
107         while (bytes_written < nbytes) {
108                 retval = write(sock, &buf[bytes_written],
109                                nbytes - bytes_written);
110                 if (retval < 1) {
111                         printf("client_write() failed: %s\n",
112                                strerror(errno));
113                         pthread_exit(NULL);
114                 }
115                 bytes_written = bytes_written + retval;
116         }
117 }
118
119
120 /*
121  * cprintf()  ...   Send formatted printable data to the client.
122  */
123 void cprintf(int sock, const char *format,...)
124 {
125         va_list arg_ptr;
126         char buf[256];
127
128         va_start(arg_ptr, format);
129         if (vsnprintf(buf, sizeof buf, format, arg_ptr) == -1)
130                 buf[sizeof buf - 2] = '\n';
131         client_write(sock, buf, strlen(buf));
132         va_end(arg_ptr);
133 }
134
135
136 /*
137  * Read data from the client socket.
138  * Return values are:
139  *      1       Requested number of bytes has been read.
140  *      0       Request timed out.
141  * If the socket breaks, the session is immediately terminated.
142  */
143 int client_read_to(int sock, char *buf, int bytes, int timeout)
144 {
145         int len, rlen;
146         fd_set rfds;
147         struct timeval tv;
148         int retval;
149
150         len = 0;
151         while (len < bytes) {
152                 FD_ZERO(&rfds);
153                 FD_SET(sock, &rfds);
154                 tv.tv_sec = timeout;
155                 tv.tv_usec = 0;
156
157                 retval = select((sock) + 1,
158                                 &rfds, NULL, NULL, &tv);
159                 if (FD_ISSET(sock, &rfds) == 0) {
160                         return (0);
161                 }
162                 rlen = read(sock, &buf[len], bytes - len);
163                 if (rlen < 1) {
164                         printf("client_read() failed: %s\n",
165                                strerror(errno));
166                         pthread_exit(NULL);
167                 }
168                 len = len + rlen;
169         }
170         return (1);
171 }
172
173 /*
174  * Read data from the client socket with default timeout.
175  * (This is implemented in terms of client_read_to() and could be
176  * justifiably moved out of sysdep.c)
177  */
178 int client_read(int sock, char *buf, int bytes)
179 {
180         return (client_read_to(sock, buf, bytes, SLEEPING));
181 }
182
183
184 /*
185  * client_gets()   ...   Get a LF-terminated line of text from the client.
186  * (This is implemented in terms of client_read() and could be
187  * justifiably moved out of sysdep.c)
188  */
189 int client_gets(int sock, char *buf)
190 {
191         int i, retval;
192
193         /* Read one character at a time.
194          */
195         for (i = 0;; i++) {
196                 retval = client_read(sock, &buf[i], 1);
197                 if (retval != 1 || buf[i] == '\n' || i == 255)
198                         break;
199         }
200
201         /* If we got a long line, discard characters until the newline.
202          */
203         if (i == 255)
204                 while (buf[i] != '\n' && retval == 1)
205                         retval = client_read(sock, &buf[i], 1);
206
207         /*
208          * Strip any trailing not-printable characters.
209          */
210         buf[i] = 0;
211         while ((strlen(buf) > 0) && (!isprint(buf[strlen(buf) - 1]))) {
212                 buf[strlen(buf) - 1] = 0;
213         }
214         return (retval);
215 }
216
217
218 /*
219  * Start running as a daemon.  Only close stdio if do_close_stdio is set.
220  */
221 void start_daemon(int do_close_stdio)
222 {
223         if (do_close_stdio) {
224                 /* close(0); */
225                 close(1);
226                 close(2);
227         }
228         signal(SIGHUP, SIG_IGN);
229         signal(SIGINT, SIG_IGN);
230         signal(SIGQUIT, SIG_IGN);
231         if (fork() != 0)
232                 exit(0);
233 }
234
235 /*
236  * Here's where it all begins.
237  */
238 int main(int argc, char **argv)
239 {
240         pthread_t SessThread;   /* Thread descriptor */
241         pthread_attr_t attr;    /* Thread attributes */
242         int a, i;               /* General-purpose variables */
243         int port = PORT_NUM;    /* Port to listen on */
244         char tracefile[PATH_MAX];
245
246         /* Parse command line */
247         while ((a = getopt(argc, argv, "hp:t:")) != EOF)
248                 switch (a) {
249                 case 'p':
250                         port = atoi(optarg);
251                         break;
252                 case 't':
253                         strcpy(tracefile, optarg);
254                         freopen(tracefile, "w", stdout);
255                         freopen(tracefile, "w", stderr);
256                         freopen(tracefile, "r", stdin);
257                         break;
258                 default:
259                         fprintf(stderr, "usage: webserver [-p localport] "
260                                 "[-t tracefile] "
261                                 "[remotehost [remoteport]]\n");
262                         return 1;
263                 }
264
265         if (optind < argc) {
266                 defaulthost = argv[optind];
267                 if (++optind < argc)
268                         defaultport = argv[optind];
269         }
270         /* Tell 'em who's in da house */
271         fprintf(stderr, SERVER "\n"
272                 "Copyright (C) 1996-1999.  All rights reserved.\n\n");
273
274         if (chdir(WEBCITDIR) != 0)
275                 perror("chdir");
276
277         /*
278          * Set up a place to put thread-specific data.
279          * We only need a single pointer per thread - it points to the
280          * wcsession struct to which the thread is currently bound.
281          */
282         if (pthread_key_create(&MyConKey, NULL) != 0) {
283                 fprintf(stderr, "Can't create TSD key: %s\n", strerror(errno));
284         }
285
286         /*
287          * Bind the server to our favorite port.
288          * There is no need to check for errors, because ig_tcp_server()
289          * exits if it doesn't succeed.
290          */
291         printf("Attempting to bind to port %d...\n", port);
292         msock = ig_tcp_server(port, 5);
293         printf("Listening on socket %d\n", msock);
294         signal(SIGPIPE, SIG_IGN);
295
296         pthread_mutex_init(&SessionListMutex, NULL);
297         pthread_mutex_init(&AcceptQueue, NULL);
298
299         /*
300          * Start up the housekeeping thread
301          */
302         pthread_attr_init(&attr);
303         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
304         pthread_create(&SessThread, &attr,
305                        (void *(*)(void *)) housekeeping_loop, NULL);
306
307
308
309         /* FIX make this variable */
310         for (i=0; i<10; ++i) {
311
312                 /* set attributes for the new thread */
313                 pthread_attr_init(&attr);
314                 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
315
316                 /* now create the thread */
317                 if (pthread_create(&SessThread, &attr,
318                                 (void *(*)(void *)) worker_entry, NULL)
319                     != 0) {
320                         printf("webcit: can't create thread: %s\n",
321                                strerror(errno));
322                 }
323         }
324
325         /* now become a worker thread too */
326         worker_entry();
327         pthread_exit(NULL);
328 }
329
330
331 /*
332  * Entry point for worker threads
333  */
334 void worker_entry(void) {
335         int ssock;
336         struct sockaddr_in fsin;
337         int alen;
338         int i = 0;
339         int time_to_die = 0;
340
341         do {
342                 /* Only one thread can accept at a time */
343                 pthread_mutex_lock(&AcceptQueue);
344                 ssock = accept(msock, (struct sockaddr *) &fsin, &alen);
345                 pthread_mutex_unlock(&AcceptQueue);
346
347                 printf("New connection on socket %d\n", ssock);
348                 if (ssock < 0) {
349                         printf("webcit: accept() failed: %s\n",
350                         strerror(errno));
351                 } else {
352                         /* Set the SO_REUSEADDR socket option */
353                         i = 1;
354                         setsockopt(ssock, SOL_SOCKET, SO_REUSEADDR,
355                                 &i, sizeof(i));
356                         context_loop(ssock);
357                 }
358
359         } while (!time_to_die);
360
361         pthread_exit(NULL);
362 }