* Ditched the frames mode completely. It wasn't working properly in,
[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         int got_cookie = 0;
248         char str_session[256];
249         struct wc_session *sptr;
250         struct wc_session *TheSession;
251         int ContentLength;
252         int CloseSession = 0;
253
254         if ((req = malloc((long) sizeof(char[256][256]))) == NULL) {
255                 sprintf(buf, "Can't malloc buffers; dropping connection.\n");
256                 fprintf(stderr, "%s", buf);
257                 write(sock, buf, strlen(buf));
258                 close(sock);
259                 pthread_exit(NULL);
260         }
261         bzero(req, sizeof(char[256][256]));     /* clear it out */
262         strcpy(browser, "unknown");
263
264         printf("Reading request from socket %d\n", sock);
265
266         /*
267          * Find out what it is that the web browser is asking for
268          */
269         ContentLength = 0;
270         do {
271                 req_gets(sock, buf, hold);
272                 if (!strncasecmp(buf, "Cookie: webcit=", 15)) {
273                         cookie_to_stuff(&buf[15], &desired_session,
274                                 NULL, NULL, NULL);
275                         got_cookie = 1;
276                 }
277                 else if (!strncasecmp(buf, "Content-length: ", 16)) {
278                         ContentLength = atoi(&buf[16]);
279                 }
280                 else if (!strncasecmp(buf, "User-agent: ", 12)) {
281                         strcpy(browser, &buf[12]);
282                 }
283                 strcpy(&req[num_lines++][0], buf);
284         } while (strlen(buf) > 0);
285
286
287         /*
288          * If requesting a non-root page, there should already be a cookie
289          * set.  If there isn't, the client browser has cookies turned off
290          * (or doesn't support them) and we have to barf & bail.
291          */
292         strcpy(buf, &req[0][0]);
293         if (!strncasecmp(buf, "GET ", 4)) strcpy(buf, &buf[4]);
294         else if (!strncasecmp(buf, "HEAD ", 5)) strcpy(buf, &buf[5]);
295         if (buf[1]==' ') buf[1]=0;
296         if ( (strcmp(buf, "/")) && (got_cookie == 0)) {
297                 strcpy(&req[0][0], "GET /static/nocookies.html HTTP/1.0");
298         }
299
300
301         /*
302          * See if there's an existing session open with the desired ID
303          */
304         TheSession = NULL;
305         if (desired_session != 0) {
306                 pthread_mutex_lock(&MasterCritter);
307                 for (sptr = SessionList; sptr != NULL; sptr = sptr->next) {
308                         if (sptr->session_id == desired_session) {
309                                 TheSession = sptr;
310                                 lock_session(TheSession);
311                         }
312                 }
313                 pthread_mutex_unlock(&MasterCritter);
314         }
315         /*
316          * Before we trumpet to the universe that the session we're looking
317          * for actually exists, check first to make sure it's still there.
318          */
319         if (TheSession != NULL) {
320                 if (kill(TheSession->webcit_pid, 0)) {
321                         printf("   Session is *DEAD* !!\n");
322                         remove_session(TheSession, 1);
323                         TheSession = NULL;
324                 }
325         }
326         /*
327          * Create a new session if we have to
328          */
329         if (TheSession == NULL) {
330                 printf("Creating a new session\n");
331                 locate_host(browser_host, sock);
332                 pthread_mutex_lock(&MasterCritter);
333                 TheSession = (struct wc_session *)
334                     malloc(sizeof(struct wc_session));
335                 TheSession->session_id = GenerateSessionID();
336                 pipe(TheSession->inpipe);
337                 pipe(TheSession->outpipe);
338                 pthread_mutex_init(&TheSession->critter, NULL);
339                 lock_session(TheSession);
340                 TheSession->next = SessionList;
341                 SessionList = TheSession;
342                 pthread_mutex_unlock(&MasterCritter);
343                 sprintf(str_session, "%d", TheSession->session_id);
344                 f = fork();
345                 if (f > 0)
346                         TheSession->webcit_pid = f;
347
348                 fflush(stdout);
349                 fflush(stdin);
350                 if (f == 0) {
351
352                         /* Hook stdio to the ends of the pipe we're using */
353                         dup2(TheSession->inpipe[0], 0);
354                         dup2(TheSession->outpipe[1], 1);
355
356                         /* Close the ends of the pipes that we're not using */
357                         close(TheSession->inpipe[1]);
358                         close(TheSession->outpipe[0]);
359
360                         /* Close the HTTP socket in this pid; don't need it */
361                         close(sock);
362
363                         /* Run the actual WebCit session */
364                         execlp("./webcit", "webcit", str_session, defaulthost,
365                                defaultport, browser_host, browser, NULL);
366
367                         /* Simple page to display if exec fails */
368                         printf("HTTP/1.0 404 WebCit Failure\n\n");
369                         printf("Server: %s\n", SERVER);
370                         printf("X-WebCit-Session: close\n");
371                         printf("Content-type: text/html\n");
372                         printf("Content-length: 76\n");
373                         printf("\n");
374                         printf("<HTML><HEAD><TITLE>Error</TITLE></HEAD><BODY>\n");
375                         printf("execlp() failed: %s</BODY></HTML>\n", strerror(errno));
376                         exit(0);
377                 } else {
378                         /* Close the ends of the pipes that we're not using */
379                         close(TheSession->inpipe[0]);
380                         close(TheSession->outpipe[1]);
381                 }
382         }
383         /* 
384          * Send the request to the appropriate session...
385          */
386         TheSession->lastreq = time(NULL);
387         printf("   Writing %d lines of command\n", num_lines);
388         printf("%s\n", &req[0][0]);
389         for (a = 0; a < num_lines; ++a) {
390                 write(TheSession->inpipe[1], &req[a][0], strlen(&req[a][0]));
391                 write(TheSession->inpipe[1], "\n", 1);
392         }
393         printf("   Writing %d bytes of content\n", ContentLength);
394         while (ContentLength > 0) {
395                 a = ContentLength;
396                 if (a > sizeof buf)
397                         a = sizeof buf;
398                 if (!client_read(sock, buf, a))
399                         goto end;
400                 if (write(TheSession->inpipe[1], buf, a) != a)
401                         goto end;
402                 ContentLength -= a;
403         }
404
405         /*
406          * ...and get the response.
407          */
408         printf("   Reading response\n");
409         ContentLength = 0;
410         do {
411                 gets0(TheSession->outpipe[0], buf);
412                 write(sock, buf, strlen(buf));
413                 write(sock, "\n", 1);
414                 if (!strncasecmp(buf, "Content-length: ", 16))
415                         ContentLength = atoi(&buf[16]);
416                 if (!strcasecmp(buf, "X-WebCit-Session: close")) {
417                         CloseSession = 1;
418                 }
419         } while (strlen(buf) > 0);
420
421         printf("   Reading %d bytes of content\n", ContentLength);
422
423         while (ContentLength--) {
424                 read(TheSession->outpipe[0], buf, 1);
425                 write(sock, buf, 1);
426         }
427
428         /*
429          * If the last response included a "close session" directive,
430          * remove the context now.
431          */
432         if (CloseSession) {
433                 remove_session(TheSession, 1);
434         } else {
435 end:            unlock_session(TheSession);
436         }
437         free(req);
438
439
440         /*
441          * Now our HTTP connection is done.  It would be relatively easy
442          * to support HTTP/1.1 "persistent" connections by looping back to
443          * the top of this function.  For now, we'll just close.
444          */
445         printf("   Closing socket %d ... ret=%d\n", sock,
446                lingering_close(sock));
447
448         /*
449          * The thread handling this HTTP connection is now finished.
450          * Instead of calling pthread_exit(), just return. It does the same
451          * thing, and supresses a compiler warning.
452          */
453         return NULL;
454 }