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