3f6055a9a3670bd8d02d8543f095952e575993c3
[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 /* Only one thread may manipulate SessionList at a time... */
42 pthread_mutex_t SessionListMutex;
43
44 struct wcsession *SessionList = NULL;
45
46 pthread_key_t MyConKey;                         /* TSD key for MySession() */
47
48 void do_housekeeping(void)
49 {
50         struct wcsession *sptr, *ss, *session_to_kill;
51
52         do {
53                 session_to_kill = NULL;
54                 pthread_mutex_lock(&SessionListMutex);
55                 for (sptr = SessionList; sptr != NULL; sptr = sptr->next) {
56
57                         /* Kill idle sessions */
58                         if ((time(NULL) - (sptr->lastreq)) >
59                            (time_t) WEBCIT_TIMEOUT) {
60                                 sptr->killthis = 1;
61                         }
62
63                         /* Remove sessions flagged for kill */
64                         if (sptr->killthis) {
65
66                                 /* remove session from linked list */
67                                 if (sptr == SessionList) {
68                                         SessionList = SessionList->next;
69                                 }
70                                 else for (ss=SessionList;ss!=NULL;ss=ss->next) {
71                                         if (ss->next == sptr) {
72                                                 ss->next = ss->next->next;
73                                         }
74                                 }
75
76                                 session_to_kill = sptr;
77                                 goto BREAKOUT;
78                         }
79                 }
80 BREAKOUT:       pthread_mutex_unlock(&SessionListMutex);
81
82                 if (session_to_kill != NULL) {
83                         pthread_mutex_lock(&session_to_kill->SessionMutex);
84                         close(session_to_kill->serv_sock);
85                         pthread_mutex_unlock(&session_to_kill->SessionMutex);
86                         free(session_to_kill);
87                 }
88
89         } while (session_to_kill != NULL);
90 }
91
92
93 /* 
94  * Wake up occasionally and clean house
95  */
96 void housekeeping_loop(void)
97 {
98         while (1) {
99                 sleep(HOUSEKEEPING);
100                 do_housekeeping();
101         }
102 }
103
104
105 /*
106  * Generate a unique WebCit session ID (which is not the same thing as the
107  * Citadel session ID).
108  *
109  * FIX ... ensure that session number is truly unique
110  *
111  */
112 int GenerateSessionID(void)
113 {
114         static int seq = (-1);
115
116         if (seq < 0) {
117                 seq = (int) time(NULL);
118         }
119                 
120         return ++seq;
121 }
122
123
124 void gets0(int fd, char buf[])
125 {
126
127         buf[0] = 0;
128         do {
129                 buf[strlen(buf) + 1] = 0;
130                 read(fd, &buf[strlen(buf)], 1);
131         } while (buf[strlen(buf) - 1] >= 32);
132         buf[strlen(buf) - 1] = 0;
133 }
134
135 /*
136  * Collapse multiple cookies on one line
137  */
138 void req_gets(int sock, char *buf, char *hold)
139 {
140         int a;
141
142         if (strlen(hold) == 0) {
143                 client_gets(sock, buf);
144         } else {
145                 strcpy(buf, hold);
146         }
147         strcpy(hold, "");
148
149         if (!strncasecmp(buf, "Cookie: ", 8)) {
150                 for (a = 0; a < strlen(buf); ++a)
151                         if (buf[a] == ';') {
152                                 sprintf(hold, "Cookie: %s", &buf[a + 1]);
153                                 buf[a] = 0;
154                                 while (isspace(hold[8]))
155                                         strcpy(&hold[8], &hold[9]);
156                                 return;
157                         }
158         }
159 }
160
161 /*
162  * lingering_close() a`la Apache. see
163  * http://www.apache.org/docs/misc/fin_wait_2.html for rationale
164  */
165
166 static int lingering_close(int fd)
167 {
168         char buf[256];
169         int i;
170         fd_set set;
171         struct timeval tv, start;
172
173         gettimeofday(&start, NULL);
174         shutdown(fd, 1);
175         do {
176                 do {
177                         gettimeofday(&tv, NULL);
178                         tv.tv_sec = SLEEPING - (tv.tv_sec - start.tv_sec);
179                         tv.tv_usec = start.tv_usec - tv.tv_usec;
180                         if (tv.tv_usec < 0) {
181                                 tv.tv_sec--;
182                                 tv.tv_usec += 1000000;
183                         }
184                         FD_ZERO(&set);
185                         FD_SET(fd, &set);
186                         i = select(fd + 1, &set, NULL, NULL, &tv);
187                 } while (i == -1 && errno == EINTR);
188
189                 if (i <= 0)
190                         break;
191
192                 i = read(fd, buf, sizeof buf);
193         } while (i != 0 && (i != -1 || errno == EINTR));
194
195         return close(fd);
196 }
197
198
199
200
201 /*
202  * This loop gets called once for every HTTP connection made to WebCit.  At
203  * this entry point we have an HTTP socket with a browser allegedly on the
204  * other end, but we have not yet bound to a WebCit session.
205  *
206  * The job of this function is to locate the correct session and bind to it,
207  * or create a session if necessary and bind to it, then run the WebCit
208  * transaction loop.  Afterwards, we unbind from the session.  When this
209  * function returns, the worker thread is then free to handle another
210  * transaction.
211  */
212 void context_loop(int sock)
213 {
214         struct httprequest *req = NULL;
215         struct httprequest *last = NULL;
216         struct httprequest *hptr;
217         char buf[256], hold[256];
218         int desired_session = 0;
219         int got_cookie = 0;
220         struct wcsession *TheSession, *sptr;
221
222         /*
223          * Find out what it is that the web browser is asking for
224          */
225         do {
226                 req_gets(sock, buf, hold);
227                 if (!strncasecmp(buf, "Cookie: webcit=", 15)) {
228                         cookie_to_stuff(&buf[15], &desired_session,
229                                 NULL, NULL, NULL);
230                         got_cookie = 1;
231                 }
232
233                 hptr = (struct httprequest *)
234                         malloc(sizeof(struct httprequest));
235                 if (req == NULL)
236                         req = hptr;
237                 else
238                         last->next = hptr;
239                 hptr->next = NULL;
240                 last = hptr;
241
242                 strcpy(hptr->line, buf);
243
244         } while (strlen(buf) > 0);
245
246
247         /*
248          * If requesting a non-root page, there should already be a cookie
249          * set.  If there isn't, the client browser has cookies turned off
250          * (or doesn't support them) and we have to barf & bail.
251          */
252         strcpy(buf, req->line);
253         if (!strncasecmp(buf, "GET ", 4)) strcpy(buf, &buf[4]);
254         else if (!strncasecmp(buf, "HEAD ", 5)) strcpy(buf, &buf[5]);
255         if (buf[1]==' ') buf[1]=0;
256
257         /*
258          * While we're at it, gracefully handle requests for the
259          * robots.txt file...
260          */
261         if (!strncasecmp(buf, "/robots.txt", 11)) {
262                 strcpy(req->line, "GET /static/robots.txt HTTP/1.0");
263         }
264
265         /* Do the non-root-cookie check now. */
266         else if ( (strcmp(buf, "/")) && (got_cookie == 0)) {
267                 strcpy(req->line, "GET /static/nocookies.html HTTP/1.0");
268         }
269
270
271
272         /*
273          * See if there's an existing session open with the desired ID
274          */
275         TheSession = NULL;
276         if (desired_session != 0) {
277                 pthread_mutex_lock(&SessionListMutex);
278                 for (sptr = SessionList; sptr != NULL; sptr = sptr->next) {
279                         if (sptr->wc_session == desired_session) {
280                                 TheSession = sptr;
281                         }
282                 }
283                 pthread_mutex_unlock(&SessionListMutex);
284         }
285
286         /*
287          * Create a new session if we have to
288          */
289         if (TheSession == NULL) {
290                 printf("Creating a new session\n");
291                 TheSession = (struct wcsession *)
292                         malloc(sizeof(struct wcsession));
293                 memset(TheSession, 0, sizeof(struct wcsession));
294                 TheSession->wc_session = GenerateSessionID();
295                 pthread_mutex_init(&TheSession->SessionMutex, NULL);
296
297                 pthread_mutex_lock(&SessionListMutex);
298                 TheSession->next = SessionList;
299                 SessionList = TheSession;
300                 pthread_mutex_unlock(&SessionListMutex);
301         }
302
303
304         /*
305          *
306          * FIX ... check session integrity here before continuing
307          *
308          */
309
310
311
312         /*
313          * Bind to the session and perform the transaction
314          */
315         pthread_mutex_lock(&TheSession->SessionMutex);          /* bind */
316         pthread_setspecific(MyConKey, (void *)TheSession);
317         TheSession->http_sock = sock;
318         TheSession->lastreq = time(NULL);                       /* log */
319         fprintf(stderr, "%s\n", req->line);
320         session_loop(req);              /* perform the requested transaction */
321         pthread_mutex_unlock(&TheSession->SessionMutex);        /* unbind */
322
323         /* Free the request buffer */
324         while (req != NULL) {
325                 hptr = req->next;
326                 free(req);
327                 req = hptr;
328         }
329
330         /*
331          * Now our HTTP connection is done.  Close the socket and exit this
332          * function, so the worker thread can handle a new HTTP connection.
333          */
334         lingering_close(sock);
335 }