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