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