* webcit.c: modified getz() to *exit* the program when fgets()
[citadel.git] / webcit / context_loop.c
1 /*
2  * context_loop.c
3  *
4  * This is the other half of the webserver.  It handles the task of hooking
5  * up HTTP requests with the session they belong to, using HTTP cookies to
6  * keep track of things.  If the HTTP request doesn't belong to any currently
7  * active session, a new session is spawned.
8  *
9  * $Id$
10  */
11
12 #include <ctype.h>
13 #include <stdlib.h>
14 #ifdef HAVE_UNISTD_H
15 #include <unistd.h>
16 #endif
17 #include <stdio.h>
18 #ifdef HAVE_FCNTL_H
19 #include <fcntl.h>
20 #endif
21 #include <signal.h>
22 #include <sys/types.h>
23 #include <sys/wait.h>
24 #include <sys/socket.h>
25 #ifdef HAVE_SYS_TIME_H
26 #include <sys/time.h>
27 #endif
28 #ifdef HAVE_LIMITS_H
29 #include <limits.h>
30 #endif
31 #include <netinet/in.h>
32 #include <netdb.h>
33 #include <string.h>
34 #include <errno.h>
35 #include <stdarg.h>
36 #include <pthread.h>
37 #include <signal.h>
38 #include "webcit.h"
39 #include "webserver.h"
40
41 /*
42  * We keep one of these around for each active session
43  */
44 struct wc_session {
45         struct wc_session *next;        /* Next session in list */
46         int session_id;         /* Session ID */
47         pid_t webcit_pid;       /* PID of the webcit process */
48         int inpipe[2];          /* Data from webserver to session */
49         int outpipe[2];         /* Data from session to webserver */
50         pthread_mutex_t critter;        /* Critical section uses pipes */
51         time_t lastreq;         /* Timestamp of most recent http */
52 };
53
54 struct wc_session *SessionList = NULL;
55 extern const char *defaulthost;
56 extern const char *defaultport;
57
58 /* Only one thread may manipulate SessionList at a time... */
59 pthread_mutex_t MasterCritter;
60
61
62 /*
63  * Grab a lock on the session, so other threads don't try to access
64  * the pipes at the same time.
65  */
66 static void lock_session(struct wc_session *session)
67 {
68         printf("Locking session %d...\n", session->session_id);
69         pthread_mutex_lock(&session->critter);
70         printf("   ...got lock\n");
71 }
72
73 /*
74  * Let go of the lock.
75  */
76 static void unlock_session(struct wc_session *session)
77 {
78         printf("Unlocking.\n");
79         pthread_mutex_unlock(&session->critter);
80 }
81
82 /*
83  * Remove a session context from the list
84  */
85 void remove_session(struct wc_session *TheSession, int do_lock)
86 {
87         struct wc_session *sptr;
88
89         printf("Removing session.\n");
90         if (do_lock)
91                 pthread_mutex_lock(&MasterCritter);
92
93         if (SessionList == TheSession) {
94                 SessionList = SessionList->next;
95         } else {
96                 for (sptr = SessionList; sptr != NULL; sptr = sptr->next) {
97                         if (sptr->next == TheSession) {
98                                 sptr->next = TheSession->next;
99                         }
100                 }
101         }
102
103         close(TheSession->inpipe[1]);
104         close(TheSession->outpipe[0]);
105         if (do_lock)
106                 unlock_session(TheSession);
107         free(TheSession);
108
109         pthread_mutex_unlock(&MasterCritter);
110 }
111
112
113
114
115 void do_housekeeping(void)
116 {
117         struct wc_session *sptr;
118
119         pthread_mutex_lock(&MasterCritter);
120
121         /* Kill idle sessions */
122         for (sptr = SessionList; sptr != NULL; sptr = sptr->next) {
123                 if ((time(NULL) - (sptr->lastreq)) > (time_t) WEBCIT_TIMEOUT) {
124                         kill(sptr->webcit_pid, 15);
125                 }
126         }
127
128         /* Remove dead sessions */
129         for (sptr = SessionList; sptr != NULL; sptr = sptr->next) {
130                 if (kill(sptr->webcit_pid, 0)) {
131                         remove_session(sptr, 0);
132                 }
133         }
134
135         pthread_mutex_unlock(&MasterCritter);
136 }
137
138
139 /* 
140  * Wake up occasionally and clean house
141  */
142 void housekeeping_loop(void)
143 {
144         while (1) {
145                 sleep(HOUSEKEEPING);
146                 do_housekeeping();
147         }
148 }
149
150
151
152
153
154 int GenerateSessionID(void)
155 {
156         return getpid();
157 }
158
159
160 void gets0(int fd, char buf[])
161 {
162
163         buf[0] = 0;
164         do {
165                 buf[strlen(buf) + 1] = 0;
166                 read(fd, &buf[strlen(buf)], 1);
167         } while (buf[strlen(buf) - 1] >= 32);
168         buf[strlen(buf) - 1] = 0;
169 }
170
171 /*
172  * Collapse multiple cookies on one line
173  */
174 void req_gets(int sock, char *buf, char *hold)
175 {
176         int a;
177
178         if (strlen(hold) == 0) {
179                 client_gets(sock, buf);
180         } else {
181                 strcpy(buf, hold);
182         }
183         strcpy(hold, "");
184
185         if (!strncasecmp(buf, "Cookie: ", 8)) {
186                 for (a = 0; a < strlen(buf); ++a)
187                         if (buf[a] == ';') {
188                                 sprintf(hold, "Cookie: %s", &buf[a + 1]);
189                                 buf[a] = 0;
190                                 while (isspace(hold[8]))
191                                         strcpy(&hold[8], &hold[9]);
192                                 return;
193                         }
194         }
195 }
196
197 /*
198  * lingering_close() a`la Apache. see
199  * http://www.apache.org/docs/misc/fin_wait_2.html for rationale
200  */
201
202 static int lingering_close(int fd)
203 {
204         char buf[256];
205         int i;
206         fd_set set;
207         struct timeval tv, start;
208
209         gettimeofday(&start, NULL);
210         shutdown(fd, 1);
211         do {
212                 do {
213                         gettimeofday(&tv, NULL);
214                         tv.tv_sec = SLEEPING - (tv.tv_sec - start.tv_sec);
215                         tv.tv_usec = start.tv_usec - tv.tv_usec;
216                         if (tv.tv_usec < 0) {
217                                 tv.tv_sec--;
218                                 tv.tv_usec += 1000000;
219                         }
220                         FD_ZERO(&set);
221                         FD_SET(fd, &set);
222                         i = select(fd + 1, &set, NULL, NULL, &tv);
223                 } while (i == -1 && errno == EINTR);
224
225                 if (i <= 0)
226                         break;
227
228                 i = read(fd, buf, sizeof buf);
229         } while (i != 0 && (i != -1 || errno == EINTR));
230
231         return close(fd);
232 }
233
234 /*
235  * This loop gets called once for every HTTP connection made to WebCit.
236  */
237 void *context_loop(int sock)
238 {
239         char (*req)[256];
240         char buf[256], hold[256];
241         char browser_host[256];
242         char browser[256];
243         int num_lines = 0;
244         int a;
245         int f;
246         int desired_session = 0;
247         char str_session[256];
248         struct wc_session *sptr;
249         struct wc_session *TheSession;
250         int ContentLength;
251         int CloseSession = 0;
252
253         if ((req = malloc((long) sizeof(char[256][256]))) == NULL) {
254                 sprintf(buf, "Can't malloc buffers; dropping connection.\n");
255                 fprintf(stderr, "%s", buf);
256                 write(sock, buf, strlen(buf));
257                 close(sock);
258                 pthread_exit(NULL);
259         }
260         bzero(req, sizeof(char[256][256]));     /* clear it out */
261         strcpy(browser, "unknown");
262
263         printf("Reading request from socket %d\n", sock);
264
265         /*
266          * Find out what it is that the web browser is asking for
267          */
268         ContentLength = 0;
269         do {
270                 req_gets(sock, buf, hold);
271                 if (!strncasecmp(buf, "Cookie: webcit=", 15)) {
272                         cookie_to_stuff(&buf[15], &desired_session, NULL, NULL, NULL, NULL);
273                 }
274                 else if (!strncasecmp(buf, "Content-length: ", 16)) {
275                         ContentLength = atoi(&buf[16]);
276                 }
277                 else if (!strncasecmp(buf, "User-agent: ", 12)) {
278                         strcpy(browser, &buf[12]);
279                 }
280                 strcpy(&req[num_lines++][0], buf);
281         } while (strlen(buf) > 0);
282
283         /*
284          * See if there's an existing session open with the desired ID
285          */
286         TheSession = NULL;
287         if (desired_session != 0) {
288                 pthread_mutex_lock(&MasterCritter);
289                 for (sptr = SessionList; sptr != NULL; sptr = sptr->next) {
290                         if (sptr->session_id == desired_session) {
291                                 TheSession = sptr;
292                                 lock_session(TheSession);
293                         }
294                 }
295                 pthread_mutex_unlock(&MasterCritter);
296         }
297         /*
298          * Before we trumpet to the universe that the session we're looking
299          * for actually exists, check first to make sure it's still there.
300          */
301         if (TheSession != NULL) {
302                 if (kill(TheSession->webcit_pid, 0)) {
303                         printf("   Session is *DEAD* !!\n");
304                         remove_session(TheSession, 1);
305                         TheSession = NULL;
306                 }
307         }
308         /*
309          * Create a new session if we have to
310          */
311         if (TheSession == NULL) {
312                 printf("Creating a new session\n");
313                 locate_host(browser_host, sock);
314                 pthread_mutex_lock(&MasterCritter);
315                 TheSession = (struct wc_session *)
316                     malloc(sizeof(struct wc_session));
317                 TheSession->session_id = GenerateSessionID();
318                 pipe(TheSession->inpipe);
319                 pipe(TheSession->outpipe);
320                 pthread_mutex_init(&TheSession->critter, NULL);
321                 lock_session(TheSession);
322                 TheSession->next = SessionList;
323                 SessionList = TheSession;
324                 pthread_mutex_unlock(&MasterCritter);
325                 sprintf(str_session, "%d", TheSession->session_id);
326                 f = fork();
327                 if (f > 0)
328                         TheSession->webcit_pid = f;
329
330                 fflush(stdout);
331                 fflush(stdin);
332                 if (f == 0) {
333
334                         /* Hook stdio to the ends of the pipe we're using */
335                         dup2(TheSession->inpipe[0], 0);
336                         dup2(TheSession->outpipe[1], 1);
337
338                         /* Close the ends of the pipes that we're not using */
339                         close(TheSession->inpipe[1]);
340                         close(TheSession->outpipe[0]);
341
342                         /* Close the HTTP socket in this pid; don't need it */
343                         close(sock);
344
345                         /* Run the actual WebCit session */
346                         execlp("./webcit", "webcit", str_session, defaulthost,
347                                defaultport, browser_host, browser, NULL);
348
349                         /* Simple page to display if exec fails */
350                         printf("HTTP/1.0 404 WebCit Failure\n\n");
351                         printf("Server: %s\n", SERVER);
352                         printf("X-WebCit-Session: close\n");
353                         printf("Content-type: text/html\n");
354                         printf("Content-length: 76\n");
355                         printf("\n");
356                         printf("<HTML><HEAD><TITLE>Error</TITLE></HEAD><BODY>\n");
357                         printf("execlp() failed: %s</BODY></HTML>\n", strerror(errno));
358                         exit(0);
359                 } else {
360                         /* Close the ends of the pipes that we're not using */
361                         close(TheSession->inpipe[0]);
362                         close(TheSession->outpipe[1]);
363                 }
364         }
365         /* 
366          * Send the request to the appropriate session...
367          */
368         TheSession->lastreq = time(NULL);
369         printf("   Writing %d lines of command\n", num_lines);
370         printf("%s\n", &req[0][0]);
371         for (a = 0; a < num_lines; ++a) {
372                 write(TheSession->inpipe[1], &req[a][0], strlen(&req[a][0]));
373                 write(TheSession->inpipe[1], "\n", 1);
374         }
375         printf("   Writing %d bytes of content\n", ContentLength);
376         while (ContentLength > 0) {
377                 a = ContentLength;
378                 if (a > sizeof buf)
379                         a = sizeof buf;
380                 if (!client_read(sock, buf, a))
381                         goto end;
382                 if (write(TheSession->inpipe[1], buf, a) != a)
383                         goto end;
384                 ContentLength -= a;
385         }
386
387         /*
388          * ...and get the response.
389          */
390         printf("   Reading response\n");
391         ContentLength = 0;
392         do {
393                 gets0(TheSession->outpipe[0], buf);
394                 write(sock, buf, strlen(buf));
395                 write(sock, "\n", 1);
396                 if (!strncasecmp(buf, "Content-length: ", 16))
397                         ContentLength = atoi(&buf[16]);
398                 if (!strcasecmp(buf, "X-WebCit-Session: close")) {
399                         CloseSession = 1;
400                 }
401         } while (strlen(buf) > 0);
402
403         printf("   Reading %d bytes of content\n", ContentLength);
404
405         while (ContentLength--) {
406                 read(TheSession->outpipe[0], buf, 1);
407                 write(sock, buf, 1);
408         }
409
410         /*
411          * If the last response included a "close session" directive,
412          * remove the context now.
413          */
414         if (CloseSession) {
415                 remove_session(TheSession, 1);
416         } else {
417 end:            unlock_session(TheSession);
418         }
419         free(req);
420
421
422         /*
423          * Now our HTTP connection is done.  It would be relatively easy
424          * to support HTTP/1.1 "persistent" connections by looping back to
425          * the top of this function.  For now, we'll just close.
426          */
427         printf("   Closing socket %d ... ret=%d\n", sock,
428                lingering_close(sock));
429
430         /*
431          * The thread handling this HTTP connection is now finished.
432          * Instead of calling pthread_exit(), just return. It does the same
433          * thing, and supresses a compiler warning.
434          */
435         return NULL;
436 }