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