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