]> code.citadel.org Git - citadel.git/blob - webcit/context_loop.c
2f0c5a3824d73d47cd9aa51823706af68562c31c
[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  * Set do_lock to 1, to lock the list while manipulating it.  The ONLY
85  * situation in which this should _not_ be done is when it's already locked
86  * by the caller.
87  */
88 void remove_session(struct wc_session *TheSession, int do_lock)
89 {
90         struct wc_session *sptr;
91
92         printf("Removing session.\n");
93
94         /* Lock the list while manipulating it */
95         if (do_lock)
96                 pthread_mutex_lock(&MasterCritter);
97
98         if (SessionList == TheSession) {
99                 SessionList = SessionList->next;
100         } else {
101                 for (sptr = SessionList; sptr != NULL; sptr = sptr->next) {
102                         if (sptr->next == TheSession) {
103                                 sptr->next = TheSession->next;
104                         }
105                 }
106         }
107
108         if (do_lock)
109                 pthread_mutex_unlock(&MasterCritter);
110
111         /* Now finish destroying the session */
112         close(TheSession->inpipe[1]);
113         close(TheSession->outpipe[0]);
114         if (do_lock)
115                 unlock_session(TheSession);
116         free(TheSession);
117
118 }
119
120
121
122
123 void do_housekeeping(void)
124 {
125         struct wc_session *sptr;
126
127         pthread_mutex_lock(&MasterCritter);
128
129         /* Kill idle sessions */
130         for (sptr = SessionList; sptr != NULL; sptr = sptr->next) {
131                 if ((time(NULL) - (sptr->lastreq)) > (time_t) WEBCIT_TIMEOUT) {
132                         kill(sptr->webcit_pid, 15);
133                 }
134         }
135
136         /* Remove dead sessions */
137         for (sptr = SessionList; sptr != NULL; sptr = sptr->next) {
138                 if (kill(sptr->webcit_pid, 0)) {
139                         remove_session(sptr, 0);
140                 }
141         }
142
143         pthread_mutex_unlock(&MasterCritter);
144 }
145
146
147 /* 
148  * Wake up occasionally and clean house
149  */
150 void housekeeping_loop(void)
151 {
152         while (1) {
153                 sleep(HOUSEKEEPING);
154                 do_housekeeping();
155         }
156 }
157
158
159
160
161
162 int GenerateSessionID(void)
163 {
164         return getpid();
165 }
166
167
168 void gets0(int fd, char buf[])
169 {
170
171         buf[0] = 0;
172         do {
173                 buf[strlen(buf) + 1] = 0;
174                 read(fd, &buf[strlen(buf)], 1);
175         } while (buf[strlen(buf) - 1] >= 32);
176         buf[strlen(buf) - 1] = 0;
177 }
178
179 /*
180  * Collapse multiple cookies on one line
181  */
182 void req_gets(int sock, char *buf, char *hold)
183 {
184         int a;
185
186         if (strlen(hold) == 0) {
187                 client_gets(sock, buf);
188         } else {
189                 strcpy(buf, hold);
190         }
191         strcpy(hold, "");
192
193         if (!strncasecmp(buf, "Cookie: ", 8)) {
194                 for (a = 0; a < strlen(buf); ++a)
195                         if (buf[a] == ';') {
196                                 sprintf(hold, "Cookie: %s", &buf[a + 1]);
197                                 buf[a] = 0;
198                                 while (isspace(hold[8]))
199                                         strcpy(&hold[8], &hold[9]);
200                                 return;
201                         }
202         }
203 }
204
205 /*
206  * lingering_close() a`la Apache. see
207  * http://www.apache.org/docs/misc/fin_wait_2.html for rationale
208  */
209
210 static int lingering_close(int fd)
211 {
212         char buf[256];
213         int i;
214         fd_set set;
215         struct timeval tv, start;
216
217         gettimeofday(&start, NULL);
218         shutdown(fd, 1);
219         do {
220                 do {
221                         gettimeofday(&tv, NULL);
222                         tv.tv_sec = SLEEPING - (tv.tv_sec - start.tv_sec);
223                         tv.tv_usec = start.tv_usec - tv.tv_usec;
224                         if (tv.tv_usec < 0) {
225                                 tv.tv_sec--;
226                                 tv.tv_usec += 1000000;
227                         }
228                         FD_ZERO(&set);
229                         FD_SET(fd, &set);
230                         i = select(fd + 1, &set, NULL, NULL, &tv);
231                 } while (i == -1 && errno == EINTR);
232
233                 if (i <= 0)
234                         break;
235
236                 i = read(fd, buf, sizeof buf);
237         } while (i != 0 && (i != -1 || errno == EINTR));
238
239         return close(fd);
240 }
241
242 /*
243  * This loop gets called once for every HTTP connection made to WebCit.
244  */
245 void *context_loop(int sock)
246 {
247         char (*req)[256];
248         char buf[256], hold[256];
249         char browser_host[256];
250         char browser[256];
251         int num_lines = 0;
252         int a;
253         int f;
254         int desired_session = 0;
255         int got_cookie = 0;
256         char str_session[256];
257         struct wc_session *sptr;
258         struct wc_session *TheSession;
259         int ContentLength;
260         int CloseSession = 0;
261
262         if ((req = malloc((long) sizeof(char[256][256]))) == NULL) {
263                 sprintf(buf, "Can't malloc buffers; dropping connection.\n");
264                 fprintf(stderr, "%s", buf);
265                 write(sock, buf, strlen(buf));
266                 close(sock);
267                 pthread_exit(NULL);
268         }
269         bzero(req, sizeof(char[256][256]));     /* clear it out */
270         strcpy(browser, "unknown");
271
272         printf("Reading request from socket %d\n", sock);
273
274         /*
275          * Find out what it is that the web browser is asking for
276          */
277         ContentLength = 0;
278         do {
279                 req_gets(sock, buf, hold);
280                 if (!strncasecmp(buf, "Cookie: webcit=", 15)) {
281                         cookie_to_stuff(&buf[15], &desired_session,
282                                 NULL, NULL, NULL);
283                         got_cookie = 1;
284                 }
285                 else if (!strncasecmp(buf, "Content-length: ", 16)) {
286                         ContentLength = atoi(&buf[16]);
287                 }
288                 else if (!strncasecmp(buf, "User-agent: ", 12)) {
289                         strcpy(browser, &buf[12]);
290                 }
291                 strcpy(&req[num_lines++][0], buf);
292         } while (strlen(buf) > 0);
293
294
295         /*
296          * If requesting a non-root page, there should already be a cookie
297          * set.  If there isn't, the client browser has cookies turned off
298          * (or doesn't support them) and we have to barf & bail.
299          */
300         strcpy(buf, &req[0][0]);
301         if (!strncasecmp(buf, "GET ", 4)) strcpy(buf, &buf[4]);
302         else if (!strncasecmp(buf, "HEAD ", 5)) strcpy(buf, &buf[5]);
303         if (buf[1]==' ') buf[1]=0;
304
305         /*
306          * While we're at it, gracefully handle requests for the
307          * robots.txt file...
308          */
309         if (!strncasecmp(buf, "/robots.txt", 11)) {
310                 strcpy(&req[0][0], "GET /static/robots.txt HTTP/1.0");
311         }
312
313         /* Do the non-root-cookie check now. */
314         else if ( (strcmp(buf, "/")) && (got_cookie == 0)) {
315                 strcpy(&req[0][0], "GET /static/nocookies.html HTTP/1.0");
316         }
317
318
319
320         /*
321          * See if there's an existing session open with the desired ID
322          */
323         TheSession = NULL;
324         if (desired_session != 0) {
325                 pthread_mutex_lock(&MasterCritter);
326                 for (sptr = SessionList; sptr != NULL; sptr = sptr->next) {
327                         if (sptr->session_id == desired_session) {
328                                 TheSession = sptr;
329                         }
330                 }
331                 pthread_mutex_unlock(&MasterCritter);
332         }
333
334         /*
335          * Before we trumpet to the universe that the session we're looking
336          * for actually exists, check first to make sure it's still there.
337          */
338         if (TheSession != NULL) {
339                 if (kill(TheSession->webcit_pid, 0)) {
340                         printf("   Session is *DEAD* !!\n");
341                         remove_session(TheSession, 1);
342                         TheSession = NULL;
343                 }
344         }
345
346         /*
347          * Create a new session if we have to
348          */
349         if (TheSession == NULL) {
350                 printf("Creating a new session\n");
351                 locate_host(browser_host, sock);
352                 TheSession = (struct wc_session *)
353                     malloc(sizeof(struct wc_session));
354                 TheSession->session_id = GenerateSessionID();
355                 pipe(TheSession->inpipe);
356                 pipe(TheSession->outpipe);
357                 pthread_mutex_init(&TheSession->critter, NULL);
358
359                 pthread_mutex_lock(&MasterCritter);
360                 TheSession->next = SessionList;
361                 SessionList = TheSession;
362                 pthread_mutex_unlock(&MasterCritter);
363
364                 sprintf(str_session, "%d", TheSession->session_id);
365                 f = fork();
366                 if (f > 0)
367                         TheSession->webcit_pid = f;
368
369                 fflush(stdout);
370                 fflush(stdin);
371                 if (f == 0) {
372
373                         /* Hook stdio to the ends of the pipe we're using */
374                         dup2(TheSession->inpipe[0], 0);
375                         dup2(TheSession->outpipe[1], 1);
376
377                         /* Close the ends of the pipes that we're not using */
378                         close(TheSession->inpipe[1]);
379                         close(TheSession->outpipe[0]);
380
381                         /* Close the HTTP socket in this pid; don't need it */
382                         close(sock);
383
384                         /* Run the actual WebCit session */
385                         execlp("./webcit", "webcit", str_session, defaulthost,
386                                defaultport, browser_host, browser, NULL);
387
388                         /* Simple page to display if exec fails */
389                         printf("HTTP/1.0 404 WebCit Failure\n\n");
390                         printf("Server: %s\n", SERVER);
391                         printf("X-WebCit-Session: close\n");
392                         printf("Content-type: text/html\n");
393                         printf("Content-length: 76\n");
394                         printf("\n");
395                         printf("<HTML><HEAD><TITLE>Error</TITLE></HEAD><BODY>\n");
396                         printf("execlp() failed: %s</BODY></HTML>\n", strerror(errno));
397                         exit(0);
398                 } else {
399                         /* Close the ends of the pipes that we're not using */
400                         close(TheSession->inpipe[0]);
401                         close(TheSession->outpipe[1]);
402                 }
403         }
404
405         /* 
406          * Send the request to the appropriate session...
407          */
408         lock_session(TheSession);
409         TheSession->lastreq = time(NULL);
410         printf("   Writing %d lines of command\n", num_lines);
411         printf("%s\n", &req[0][0]);
412         for (a = 0; a < num_lines; ++a) {
413                 write(TheSession->inpipe[1], &req[a][0], strlen(&req[a][0]));
414                 write(TheSession->inpipe[1], "\n", 1);
415         }
416         printf("   Writing %d bytes of content\n", ContentLength);
417         while (ContentLength > 0) {
418                 a = ContentLength;
419                 if (a > sizeof buf)
420                         a = sizeof buf;
421                 if (!client_read(sock, buf, a))
422                         goto end;
423                 if (write(TheSession->inpipe[1], buf, a) != a)
424                         goto end;
425                 ContentLength -= a;
426         }
427
428         /*
429          * ...and get the response.
430          */
431         printf("   Reading response\n");
432         ContentLength = 0;
433         do {
434                 gets0(TheSession->outpipe[0], buf);
435                 write(sock, buf, strlen(buf));
436                 write(sock, "\n", 1);
437                 if (!strncasecmp(buf, "Content-length: ", 16))
438                         ContentLength = atoi(&buf[16]);
439                 if (!strcasecmp(buf, "X-WebCit-Session: close")) {
440                         CloseSession = 1;
441                 }
442         } while (strlen(buf) > 0);
443
444         printf("   Reading %d bytes of content\n", ContentLength);
445
446         while (ContentLength--) {
447                 read(TheSession->outpipe[0], buf, 1);
448                 write(sock, buf, 1);
449         }
450
451         /*
452          * If the last response included a "close session" directive,
453          * remove the context now.
454          */
455         if (CloseSession) {
456                 remove_session(TheSession, 1);
457         } else {
458 end:            unlock_session(TheSession);
459         }
460         free(req);
461
462
463         /*
464          * Now our HTTP connection is done.  It would be relatively easy
465          * to support HTTP/1.1 "persistent" connections by looping back to
466          * the top of this function.  For now, we'll just close.
467          */
468         printf("   Closing socket %d ... ret=%d\n", sock,
469                lingering_close(sock));
470
471         /*
472          * The thread handling this HTTP connection is now finished.
473          * Instead of calling pthread_exit(), just return. It does the same
474          * thing, and supresses a compiler warning.
475          */
476         return NULL;
477 }