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