* Moved all diagnostic output to stderr
[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                 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  * client_write()   ...    Send binary data to the client.
103  */
104 void client_write(int sock, char *buf, int nbytes)
105 {
106         int bytes_written = 0;
107         int retval;
108         while (bytes_written < nbytes) {
109                 retval = write(sock, &buf[bytes_written],
110                                nbytes - bytes_written);
111                 if (retval < 1) {
112                         fprintf(stderr, "client_write() failed: %s\n",
113                                strerror(errno));
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                         fprintf(stderr, "client_read() failed: %s\n",
165                                strerror(errno));
166                 }
167                 len = len + rlen;
168         }
169         return (1);
170 }
171
172 /*
173  * Read data from the client socket with default timeout.
174  * (This is implemented in terms of client_read_to() and could be
175  * justifiably moved out of sysdep.c)
176  */
177 int client_read(int sock, char *buf, int bytes)
178 {
179         return (client_read_to(sock, buf, bytes, SLEEPING));
180 }
181
182
183 /*
184  * client_gets()   ...   Get a LF-terminated line of text from the client.
185  * (This is implemented in terms of client_read() and could be
186  * justifiably moved out of sysdep.c)
187  */
188 int client_gets(int sock, char *buf)
189 {
190         int i, retval;
191
192         /* Read one character at a time.
193          */
194         for (i = 0;; i++) {
195                 retval = client_read(sock, &buf[i], 1);
196                 if (retval != 1 || buf[i] == '\n' || i == 255)
197                         break;
198         }
199
200         /* If we got a long line, discard characters until the newline.
201          */
202         if (i == 255)
203                 while (buf[i] != '\n' && retval == 1)
204                         retval = client_read(sock, &buf[i], 1);
205
206         /*
207          * Strip any trailing not-printable characters.
208          */
209         buf[i] = 0;
210         while ((strlen(buf) > 0) && (!isprint(buf[strlen(buf) - 1]))) {
211                 buf[strlen(buf) - 1] = 0;
212         }
213         return (retval);
214 }
215
216
217 /*
218  * Start running as a daemon.  Only close stdio if do_close_stdio is set.
219  */
220 void start_daemon(int do_close_stdio)
221 {
222         if (do_close_stdio) {
223                 /* close(0); */
224                 close(1);
225                 close(2);
226         }
227         signal(SIGHUP, SIG_IGN);
228         signal(SIGINT, SIG_IGN);
229         signal(SIGQUIT, SIG_IGN);
230         if (fork() != 0)
231                 exit(0);
232 }
233
234 /*
235  * Here's where it all begins.
236  */
237 int main(int argc, char **argv)
238 {
239         pthread_t SessThread;   /* Thread descriptor */
240         pthread_attr_t attr;    /* Thread attributes */
241         int a, i;               /* General-purpose variables */
242         int port = PORT_NUM;    /* Port to listen on */
243         char tracefile[PATH_MAX];
244
245         /* Parse command line */
246         while ((a = getopt(argc, argv, "hp:t:")) != EOF)
247                 switch (a) {
248                 case 'p':
249                         port = atoi(optarg);
250                         break;
251                 case 't':
252                         strcpy(tracefile, optarg);
253                         freopen(tracefile, "w", stdout);
254                         freopen(tracefile, "w", stderr);
255                         freopen(tracefile, "r", stdin);
256                         break;
257                 default:
258                         fprintf(stderr, "usage: webserver [-p localport] "
259                                 "[-t tracefile] "
260                                 "[remotehost [remoteport]]\n");
261                         return 1;
262                 }
263
264         if (optind < argc) {
265                 defaulthost = argv[optind];
266                 if (++optind < argc)
267                         defaultport = argv[optind];
268         }
269         /* Tell 'em who's in da house */
270         fprintf(stderr, SERVER "\n"
271                 "Copyright (C) 1996-1999.  All 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, 5);
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
308         /* FIX ... we need to auto-size the thread pool */
309         for (i=0; i<10; ++i) {
310
311                 /* set attributes for the new thread */
312                 pthread_attr_init(&attr);
313                 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
314
315                 /* now create the thread */
316                 if (pthread_create(&SessThread, &attr,
317                                 (void *(*)(void *)) worker_entry, NULL)
318                     != 0) {
319                         fprintf(stderr, "webcit: can't create thread: %s\n",
320                                strerror(errno));
321                 }
322         }
323
324         /* now become a worker thread too */
325         worker_entry();
326         pthread_exit(NULL);
327 }
328
329
330 /*
331  * Entry point for worker threads
332  */
333 void worker_entry(void) {
334         int ssock;
335         struct sockaddr_in fsin;
336         int alen;
337         int i = 0;
338         int time_to_die = 0;
339
340         do {
341                 /* Only one thread can accept at a time */
342                 pthread_mutex_lock(&AcceptQueue);
343                 ssock = accept(msock, (struct sockaddr *) &fsin, &alen);
344                 pthread_mutex_unlock(&AcceptQueue);
345
346                 if (ssock < 0) {
347                         fprintf(stderr, "webcit: accept() failed: %s\n",
348                         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                         context_loop(ssock);
355                 }
356
357         } while (!time_to_die);
358
359         pthread_exit(NULL);
360 }