]> code.citadel.org Git - citadel.git/blob - webcit/webserver.c
* wildmat.c, braindamage.c: added
[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         sin.sin_port = htons((u_short) port_number);
70
71         s = socket(PF_INET, SOCK_STREAM, (getprotobyname("tcp")->p_proto));
72         if (s < 0) {
73                 printf("webcit: Can't create a socket: %s\n",
74                        strerror(errno));
75                 exit(errno);
76         }
77         /* Set some socket options that make sense. */
78         i = 1;
79         setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
80
81         if (bind(s, (struct sockaddr *) &sin, sizeof(sin)) < 0) {
82                 printf("webcit: Can't bind: %s\n", strerror(errno));
83                 exit(errno);
84         }
85         if (listen(s, queue_len) < 0) {
86                 printf("webcit: Can't listen: %s\n", strerror(errno));
87                 exit(errno);
88         }
89         return (s);
90 }
91
92
93 /*
94  * client_write()   ...    Send binary data to the client.
95  */
96 void client_write(int sock, char *buf, int nbytes)
97 {
98         int bytes_written = 0;
99         int retval;
100         while (bytes_written < nbytes) {
101                 retval = write(sock, &buf[bytes_written],
102                                nbytes - bytes_written);
103                 if (retval < 1) {
104                         printf("client_write() failed: %s\n",
105                                strerror(errno));
106                         pthread_exit(NULL);
107                 }
108                 bytes_written = bytes_written + retval;
109         }
110 }
111
112
113 /*
114  * cprintf()  ...   Send formatted printable data to the client.
115  */
116 void cprintf(int sock, const char *format,...)
117 {
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                 rlen = read(sock, &buf[len], bytes - len);
156                 if (rlen < 1) {
157                         printf("client_read() failed: %s\n",
158                                strerror(errno));
159                         pthread_exit(NULL);
160                 }
161                 len = len + rlen;
162         }
163         return (1);
164 }
165
166 /*
167  * Read data from the client socket with default timeout.
168  * (This is implemented in terms of client_read_to() and could be
169  * justifiably moved out of sysdep.c)
170  */
171 int client_read(int sock, char *buf, int bytes)
172 {
173         return (client_read_to(sock, buf, bytes, SLEEPING));
174 }
175
176
177 /*
178  * client_gets()   ...   Get a LF-terminated line of text from the client.
179  * (This is implemented in terms of client_read() and could be
180  * justifiably moved out of sysdep.c)
181  */
182 int client_gets(int sock, char *buf)
183 {
184         int i, retval;
185
186         /* Read one character at a time.
187          */
188         for (i = 0;; i++) {
189                 retval = client_read(sock, &buf[i], 1);
190                 if (retval != 1 || buf[i] == '\n' || i == 255)
191                         break;
192         }
193
194         /* If we got a long line, discard characters until the newline.
195          */
196         if (i == 255)
197                 while (buf[i] != '\n' && retval == 1)
198                         retval = client_read(sock, &buf[i], 1);
199
200         /*
201          * Strip any trailing not-printable characters.
202          */
203         buf[i] = 0;
204         while ((strlen(buf) > 0) && (!isprint(buf[strlen(buf) - 1]))) {
205                 buf[strlen(buf) - 1] = 0;
206         }
207         return (retval);
208 }
209
210
211 /*
212  * Start running as a daemon.  Only close stdio if do_close_stdio is set.
213  */
214 void start_daemon(int do_close_stdio)
215 {
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)
225                 exit(0);
226 }
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         /* Tell 'em who's in da house */
259         printf("WebCit v2 experimental\n");
260         printf("Copyright (C) 1996-1998 by Art Cancro.  ");
261         printf("All rights reserved.\n\n");
262
263         if (chdir(WEBCITDIR) != 0)
264                 perror("chdir");
265
266         /*
267          * Bind the server to our favourite port.
268          * There is no need to check for errors, because ig_tcp_server()
269          * exits if it doesn't succeed.
270          */
271         printf("Attempting to bind to port %d...\n", port);
272         msock = ig_tcp_server(port, 5);
273         printf("Listening on socket %d\n", msock);
274         signal(SIGPIPE, SIG_IGN);
275
276         pthread_mutex_init(&MasterCritter, NULL);
277
278
279
280         /*
281          * Start up the housekeeping thread
282          */
283         pthread_attr_init(&attr);
284         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
285         pthread_create(&SessThread, &attr,
286                        (void *(*)(void *)) housekeeping_loop, NULL);
287
288
289
290         /* 
291          * Endless loop.  Listen on the master socket.  When a connection
292          * comes in, create a socket, a context, and a thread.
293          */
294         while (1) {
295                 ssock = accept(msock, (struct sockaddr *) &fsin, &alen);
296                 printf("New connection on socket %d\n", ssock);
297                 if (ssock < 0) {
298                         printf("webcit: accept() failed: %s\n",
299                                strerror(errno));
300                 } else {
301                         /* Set the SO_REUSEADDR socket option */
302                         i = 1;
303                         setsockopt(ssock, SOL_SOCKET, SO_REUSEADDR,
304                                    &i, sizeof(i));
305
306                         /* set attributes for the new thread */
307                         pthread_attr_init(&attr);
308                         pthread_attr_setdetachstate(&attr,
309                                                 PTHREAD_CREATE_DETACHED);
310
311                         /* now create the thread */
312                         if (pthread_create(&SessThread, &attr,
313                                         (void *(*)(void *)) context_loop,
314                                            (void *) ssock)
315                             != 0) {
316                                 printf("webcit: can't create thread: %s\n",
317                                        strerror(errno));
318                         }
319                 }
320         }
321 }