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