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