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