]> code.citadel.org Git - citadel.git/blob - webcit/context_loop.c
Resolve the name of the connecting host and pass it on to Citadel
[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         int num_lines = 0;
232         int a;
233         int f;
234         int desired_session = 0;
235         char str_session[256];
236         struct wc_session *sptr;
237         struct wc_session *TheSession;
238         int ContentLength;
239         int CloseSession = 0;
240
241         if ((req = malloc((long)sizeof(char[256][256]))) == NULL) {
242                 sprintf(buf, "Can't malloc buffers; dropping connection.\n");
243                 fprintf(stderr, "%s", buf);
244                 write(sock, buf, strlen(buf));
245                 close (sock);
246                 pthread_exit(NULL);
247                 }
248
249         bzero(req, sizeof(char[256][256]));     /* clear it out */
250
251         printf("Reading request from socket %d\n", sock);
252
253         /*
254          * Find out what it is that the web browser is asking for
255          */
256         ContentLength = 0;
257         do {
258                 req_gets(sock, buf, hold);
259                 if (!strncasecmp(buf, "Cookie: webcit=", 15)) {
260                         cookie_to_stuff(&buf[15], &desired_session, NULL, NULL, NULL, NULL);
261                         }
262                 if (!strncasecmp(buf, "Content-length: ", 16)) {
263                         ContentLength = atoi(&buf[16]);
264                         }
265                 strcpy(&req[num_lines++][0], buf);
266                 } while(strlen(buf)>0);
267
268         /*
269          * See if there's an existing session open with the desired ID
270          */
271         TheSession = NULL;
272         if (desired_session != 0) {
273                 pthread_mutex_lock(&MasterCritter);
274                 for (sptr=SessionList; sptr!=NULL; sptr=sptr->next) {
275                         if (sptr->session_id == desired_session) {
276                                 TheSession = sptr;
277                                 lock_session(TheSession);
278                                 }
279                         }
280                 pthread_mutex_unlock(&MasterCritter);
281                 }
282
283         /*
284          * Before we trumpet to the universe that the session we're looking
285          * for actually exists, check first to make sure it's still there.
286          */
287         if (TheSession != NULL) {
288                 if (kill(TheSession->webcit_pid, 0)) {
289                         printf("   Session is *DEAD* !!\n");
290                         remove_session(TheSession, 1);
291                         TheSession = NULL;
292                         }
293                 }
294
295         /*
296          * Create a new session if we have to
297          */
298         if (TheSession == NULL) {
299                 printf("Creating a new session\n");
300                 locate_host(browser_host, sock);
301                 pthread_mutex_lock(&MasterCritter);
302                 TheSession = (struct wc_session *)
303                         malloc(sizeof(struct wc_session));
304                 TheSession->session_id = GenerateSessionID();
305                 pipe(TheSession->inpipe);
306                 pipe(TheSession->outpipe);
307                 pthread_mutex_init(&TheSession->critter, NULL);
308                 lock_session(TheSession);
309                 TheSession->next = SessionList;
310                 SessionList = TheSession;
311                 pthread_mutex_unlock(&MasterCritter);
312                 sprintf(str_session, "%d", TheSession->session_id);
313                 f = fork();
314                 if (f > 0) TheSession->webcit_pid = f;
315                 
316                 fflush(stdout); fflush(stdin);
317                 if (f==0) {
318
319                         /* Hook stdio to the ends of the pipe we're using */
320                         dup2(TheSession->inpipe[0], 0);
321                         dup2(TheSession->outpipe[1], 1);
322
323                         /* Close the ends of the pipes that we're not using */
324                         close(TheSession->inpipe[1]);
325                         close(TheSession->outpipe[0]);
326         
327                         /* Close the HTTP socket in this pid; don't need it */
328                         close(sock);
329
330                         /* Run the actual WebCit session */
331                         execlp("./webcit", "webcit", str_session, defaulthost,
332                                defaultport, browser_host, NULL);
333
334                         /* Simple page to display if exec fails */
335                         printf("HTTP/1.0 404 WebCit Failure\n\n");
336                         printf("Server: %s\n", SERVER);
337                         printf("X-WebCit-Session: close\n");
338                         printf("Content-type: text/html\n");
339                         printf("Content-length: 76\n");
340                         printf("\n");
341                         printf("<HTML><HEAD><TITLE>Error</TITLE></HEAD><BODY>\n");
342                         printf("execlp() failed: %s</BODY></HTML>\n", strerror(errno));
343                         exit(0);
344                         }
345                 else {
346                         /* Close the ends of the pipes that we're not using */
347                         close(TheSession->inpipe[0]);
348                         close(TheSession->outpipe[1]);
349                         }
350                 }
351
352         /* 
353          * Send the request to the appropriate session...
354          */
355         TheSession->lastreq = time(NULL);
356         printf("   Writing %d lines of command\n", num_lines);
357         printf("%s\n", &req[0][0]);
358         for (a=0; a<num_lines; ++a) {
359                 write(TheSession->inpipe[1], &req[a][0], strlen(&req[a][0]));
360                 write(TheSession->inpipe[1], "\n", 1);
361                 }
362         printf("   Writing %d bytes of content\n", ContentLength);
363         while (ContentLength > 0) {
364                 a = ContentLength;
365                 if (a > sizeof buf) a = sizeof buf;
366                 if (!client_read(sock, buf, a)) goto end;
367                 if (write(TheSession->inpipe[1], buf, a) != a) goto end;
368                 ContentLength -= a;
369                 }
370
371         /*
372          * ...and get the response.
373          */
374         printf("   Reading response\n");
375         ContentLength = 0;
376         do {
377                 gets0(TheSession->outpipe[0], buf);
378                 write(sock, buf, strlen(buf));
379                 write(sock, "\n", 1);
380                 if (!strncasecmp(buf, "Content-length: ", 16))
381                         ContentLength = atoi(&buf[16]);
382                 if (!strcasecmp(buf, "X-WebCit-Session: close")) {
383                         CloseSession = 1;
384                         }
385                 } while (strlen(buf) > 0);
386
387         printf("   Reading %d bytes of content\n", ContentLength);
388         while(ContentLength--) {
389                 read(TheSession->outpipe[0], buf, 1);
390                 write(sock, buf, 1);
391                 }
392
393         /*
394          * If the last response included a "close session" directive,
395          * remove the context now.
396          */
397         if (CloseSession) {
398                 remove_session(TheSession, 1);
399                 }
400         else {
401 end:            unlock_session(TheSession);
402                 }
403         free(req);
404
405
406         /*
407          * Now our HTTP connection is done.  It would be relatively easy
408          * to support HTTP/1.1 "persistent" connections by looping back to
409          * the top of this function.  For now, we'll just close.
410          */
411         printf("   Closing socket %d ... ret=%d\n", sock,
412                lingering_close(sock));
413
414         /*
415          * The thread handling this HTTP connection is now finished.
416          */
417         pthread_exit(NULL);
418         }