* converted to autoconf and began port to Digital UNIX
[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 #include <unistd.h>
14 #include <stdio.h>
15 #include <fcntl.h>
16 #include <signal.h>
17 #include <sys/types.h>
18 #include <sys/wait.h>
19 #include <sys/socket.h>
20 #include <sys/time.h>
21 #include <limits.h>
22 #include <netinet/in.h>
23 #include <netdb.h>
24 #include <string.h>
25 #include <pwd.h>
26 #include <errno.h>
27 #include <stdarg.h>
28 #include <pthread.h>
29 #include "webcit.h"
30
31 int msock;                                      /* master listening socket */
32 extern void *context_loop(int);
33 extern pthread_mutex_t MasterCritter;
34
35 /*
36  * This is a generic function to set up a master socket for listening on
37  * a TCP port.  The server shuts down if the bind fails.
38  */
39 int ig_tcp_server(int port_number, int queue_len)
40 {
41         struct sockaddr_in sin;
42         int s, i;
43         struct linger WebLinger = { 1, 9000 };
44
45         memset(&sin, 0, sizeof(sin));
46         sin.sin_family = AF_INET;
47         sin.sin_addr.s_addr = INADDR_ANY;
48
49         if (port_number == 0) {
50                 printf("webcit: Cannot start: no port number specified.\n");
51                 exit(1);
52                 }
53         
54         sin.sin_port = htons((u_short)port_number);
55
56         s = socket(PF_INET, SOCK_STREAM, (getprotobyname("tcp")->p_proto));
57         if (s < 0) {
58                 printf("webcit: Can't create a socket: %s\n",
59                         strerror(errno));
60                 exit(errno);
61                 }
62
63         /* Set some socket options that make sense. */
64         i = 1;
65         setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
66         setsockopt(s, SOL_SOCKET, SO_LINGER, &WebLinger, sizeof(WebLinger));
67
68         if (bind(s, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
69                 printf("webcit: Can't bind: %s\n", strerror(errno));
70                 exit(errno);
71                 }
72
73         if (listen(s, queue_len) < 0) {
74                 printf("webcit: Can't listen: %s\n", strerror(errno));
75                 exit(errno);
76                 }
77
78         return(s);
79         }
80
81
82 /*
83  * client_write()   ...    Send binary data to the client.
84  */
85 void client_write(int sock, char *buf, int nbytes)
86 {
87         int bytes_written = 0;
88         int retval;
89         while (bytes_written < nbytes) {
90                 retval = write(sock, &buf[bytes_written],
91                         nbytes - bytes_written);
92                 if (retval < 1) {
93                         printf("client_write() failed: %s\n",
94                                 strerror(errno));
95                         pthread_exit(NULL);
96                         }
97                 bytes_written = bytes_written + retval;
98                 }
99         }
100
101
102 /*
103  * cprintf()  ...   Send formatted printable data to the client.   It is
104  *                  implemented in terms of client_write() but remains in
105  *                  sysdep.c in case we port to somewhere without va_args...
106  */
107 void cprintf(int sock, const char *format, ...) {   
108         va_list arg_ptr;   
109         char buf[256];   
110    
111         va_start(arg_ptr, format);   
112         if (vsnprintf(buf, sizeof buf, format, arg_ptr) == -1)
113                 buf[sizeof buf - 2] = '\n';
114         client_write(sock, buf, strlen(buf)); 
115         va_end(arg_ptr);
116         }   
117
118
119 /*
120  * Read data from the client socket.
121  * Return values are:
122  *      1       Requested number of bytes has been read.
123  *      0       Request timed out.
124  * If the socket breaks, the session is immediately terminated.
125  */
126 int client_read_to(int sock, char *buf, int bytes, int timeout)
127 {
128         int len,rlen;
129         fd_set rfds;
130         struct timeval tv;
131         int retval;
132
133         len = 0;
134         while(len<bytes) {
135                 FD_ZERO(&rfds);
136                 FD_SET(sock, &rfds);
137                 tv.tv_sec = timeout;
138                 tv.tv_usec = 0;
139
140                 retval = select( (sock)+1, 
141                                         &rfds, NULL, NULL, &tv);
142                 if (FD_ISSET(sock, &rfds) == 0) {
143                         return(0);
144                         }
145
146                 rlen = read(sock, &buf[len], bytes-len);
147                 if (rlen<1) {
148                         printf("client_read() failed: %s\n",
149                                 strerror(errno));
150                         pthread_exit(NULL);
151                         }
152                 len = len + rlen;
153                 }
154         return(1);
155         }
156
157 /*
158  * Read data from the client socket with default timeout.
159  * (This is implemented in terms of client_read_to() and could be
160  * justifiably moved out of sysdep.c)
161  */
162 int client_read(int sock, char *buf, int bytes)
163 {
164         return(client_read_to(sock, buf, bytes, SLEEPING));
165         }
166
167
168 /*
169  * client_gets()   ...   Get a LF-terminated line of text from the client.
170  * (This is implemented in terms of client_read() and could be
171  * justifiably moved out of sysdep.c)
172  */
173 int client_gets(int sock, char *buf)
174 {
175         int i, retval;
176
177         /* Read one character at a time.
178          */
179         for (i = 0;;i++) {
180                 retval = client_read(sock, &buf[i], 1);
181                 if (retval != 1 || buf[i] == '\n' || i == 255)
182                         break;
183                 }
184
185         /* If we got a long line, discard characters until the newline.
186          */
187         if (i == 255)
188                 while (buf[i] != '\n' && retval == 1)
189                         retval = client_read(sock, &buf[i], 1);
190
191         /*
192          * Strip any trailing not-printable characters.
193          */
194         buf[i] = 0;
195         while ((strlen(buf)>0)&&(!isprint(buf[strlen(buf)-1]))) {
196                 buf[strlen(buf)-1] = 0;
197                 }
198         return(retval);
199         }
200
201
202 /*
203  * Start running as a daemon.  Only close stdio if do_close_stdio is set.
204  */
205 void start_daemon(int do_close_stdio) {
206         if (do_close_stdio) {
207                 /* close(0); */
208                 close(1);
209                 close(2);
210                 }
211         signal(SIGHUP,SIG_IGN);
212         signal(SIGINT,SIG_IGN);
213         signal(SIGQUIT,SIG_IGN);
214         if (fork()!=0) exit(0);
215         }
216
217 /*
218  * Issue an HTTP Redirect header
219  * url must be a complete url (with http://)
220  */
221 void redirect(char *url) {
222         printf("Location: %s\n\n", url);
223 }
224
225 const char *defaulthost = DEFAULT_HOST;
226 const char *defaultport = DEFAULT_PORT;
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
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