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