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