* Detect locale from Browser Environment
[citadel.git] / webcit / context_loop.c
1 /*
2  * $Id$
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  */
10
11 #include "webcit.h"
12 #include "webserver.h"
13
14 /* Only one thread may manipulate SessionList at a time... */
15 pthread_mutex_t SessionListMutex;
16
17 struct wcsession *SessionList = NULL;
18
19 pthread_key_t MyConKey;                         /* TSD key for MySession() */
20
21
22 void free_attachments(struct wcsession *sess) {
23         struct wc_attachment *att;
24
25         while (sess->first_attachment != NULL) {
26                 att = sess->first_attachment;
27                 sess->first_attachment = sess->first_attachment->next;
28                 free(att->data);
29                 free(att);
30         }
31 }
32
33
34 void do_housekeeping(void)
35 {
36         struct wcsession *sptr, *ss;
37         struct wcsession *sessions_to_kill = NULL;
38         int num_sessions = 0;
39         static int num_threads = MIN_WORKER_THREADS;
40
41         /*
42          * Lock the session list, moving any candidates for euthanasia into
43          * a separate list.
44          */
45         pthread_mutex_lock(&SessionListMutex);
46         num_sessions = 0;
47         for (sptr = SessionList; sptr != NULL; sptr = sptr->next) {
48                 ++num_sessions;
49
50                 /* Kill idle sessions */
51                 if ((time(NULL) - (sptr->lastreq)) >
52                    (time_t) WEBCIT_TIMEOUT) {
53                         sptr->killthis = 1;
54                 }
55
56                 /* Remove sessions flagged for kill */
57                 if (sptr->killthis) {
58
59                         /* remove session from linked list */
60                         if (sptr == SessionList) {
61                                 SessionList = SessionList->next;
62                         }
63                         else for (ss=SessionList;ss!=NULL;ss=ss->next) {
64                                 if (ss->next == sptr) {
65                                         ss->next = ss->next->next;
66                                 }
67                         }
68
69                         sptr->next = sessions_to_kill;
70                         sessions_to_kill = sptr;
71                 }
72         }
73         pthread_mutex_unlock(&SessionListMutex);
74
75         /*
76          * Now free up and destroy the culled sessions.
77          */
78         while (sessions_to_kill != NULL) {
79                 lprintf(3, "Destroying session %d\n", sessions_to_kill->wc_session);
80                 pthread_mutex_lock(&sessions_to_kill->SessionMutex);
81                 close(sessions_to_kill->serv_sock);
82                 close(sessions_to_kill->chat_sock);
83                 if (sessions_to_kill->preferences != NULL) {
84                         free(sessions_to_kill->preferences);
85                 }
86                 free_attachments(sessions_to_kill);
87                 pthread_mutex_unlock(&sessions_to_kill->SessionMutex);
88                 sptr = sessions_to_kill->next;
89                 free(sessions_to_kill);
90                 sessions_to_kill = sptr;
91                 --num_sessions;
92         }
93
94         /*
95          * If there are more sessions than threads, then we should spawn
96          * more threads ... up to a predefined maximum.
97          */
98         while ( (num_sessions > num_threads)
99               && (num_threads <= MAX_WORKER_THREADS) ) {
100                 spawn_another_worker_thread();
101                 ++num_threads;
102                 lprintf(3, "There are %d sessions and %d threads active.\n",
103                         num_sessions, num_threads);
104         }
105 }
106
107
108 /* 
109  * Wake up occasionally and clean house
110  */
111 void housekeeping_loop(void)
112 {
113         while (1) {
114                 sleeeeeeeeeep(HOUSEKEEPING);
115                 do_housekeeping();
116         }
117 }
118
119
120 /*
121  * Generate a unique WebCit session ID (which is not the same thing as the
122  * Citadel session ID).
123  *
124  * FIXME ... ensure that session number is truly unique
125  *
126  */
127 int GenerateSessionID(void)
128 {
129         static int seq = (-1);
130
131         if (seq < 0) {
132                 seq = (int) time(NULL);
133         }
134                 
135         return ++seq;
136 }
137
138
139 /*
140  * Collapse multiple cookies on one line
141  */
142 int req_gets(int sock, char *buf, char *hold)
143 {
144         int a;
145
146         if (strlen(hold) == 0) {
147                 strcpy(buf, "");
148                 a = client_getln(sock, buf, SIZ);
149                 if (a<1) return(-1);
150         } else {
151                 safestrncpy(buf, hold, SIZ);
152         }
153         strcpy(hold, "");
154
155         if (!strncasecmp(buf, "Cookie: ", 8)) {
156                 for (a = 0; a < strlen(buf); ++a)
157                         if (buf[a] == ';') {
158                                 sprintf(hold, "Cookie: %s", &buf[a + 1]);
159                                 buf[a] = 0;
160                                 while (isspace(hold[8]))
161                                         strcpy(&hold[8], &hold[9]);
162                                 return(0);
163                         }
164         }
165
166         return(0);
167 }
168
169 /*
170  * lingering_close() a`la Apache. see
171  * http://www.apache.org/docs/misc/fin_wait_2.html for rationale
172  */
173
174 int lingering_close(int fd)
175 {
176         char buf[SIZ];
177         int i;
178         fd_set set;
179         struct timeval tv, start;
180
181         gettimeofday(&start, NULL);
182         shutdown(fd, 1);
183         do {
184                 do {
185                         gettimeofday(&tv, NULL);
186                         tv.tv_sec = SLEEPING - (tv.tv_sec - start.tv_sec);
187                         tv.tv_usec = start.tv_usec - tv.tv_usec;
188                         if (tv.tv_usec < 0) {
189                                 tv.tv_sec--;
190                                 tv.tv_usec += 1000000;
191                         }
192                         FD_ZERO(&set);
193                         FD_SET(fd, &set);
194                         i = select(fd + 1, &set, NULL, NULL, &tv);
195                 } while (i == -1 && errno == EINTR);
196
197                 if (i <= 0)
198                         break;
199
200                 i = read(fd, buf, sizeof buf);
201         } while (i != 0 && (i != -1 || errno == EINTR));
202
203         return close(fd);
204 }
205
206
207
208 /*
209  * Check for bogus requests coming from (for example) brain-dead
210  * Windoze boxes that are infected with the latest worm-of-the-week.
211  * If we detect one of these, bail out without bothering our Citadel
212  * server.
213  */
214 int is_bogus(char *http_cmd) {
215
216         if (!strncasecmp(http_cmd, "GET /scripts/root.exe", 21)) return(1);
217         if (!strncasecmp(http_cmd, "GET /c/winnt", 12)) return(2);
218         if (!strncasecmp(http_cmd, "GET /MSADC/", 11)) return(3);
219
220         return(0);      /* probably ok */
221 }
222
223
224
225 /*
226  * This loop gets called once for every HTTP connection made to WebCit.  At
227  * this entry point we have an HTTP socket with a browser allegedly on the
228  * other end, but we have not yet bound to a WebCit session.
229  *
230  * The job of this function is to locate the correct session and bind to it,
231  * or create a session if necessary and bind to it, then run the WebCit
232  * transaction loop.  Afterwards, we unbind from the session.  When this
233  * function returns, the worker thread is then free to handle another
234  * transaction.
235  */
236 void context_loop(int sock)
237 {
238         struct httprequest *req = NULL;
239         struct httprequest *last = NULL;
240         struct httprequest *hptr;
241         char buf[SIZ], hold[SIZ];
242         int desired_session = 0;
243         int got_cookie = 0;
244         int gzip_ok = 0;
245         struct wcsession *TheSession, *sptr;
246         char httpauth_string[SIZ];
247         char httpauth_user[SIZ];
248         char httpauth_pass[SIZ];
249         char *ptr = NULL;
250
251         strcpy(httpauth_string, "");
252         strcpy(httpauth_user, DEFAULT_HTTPAUTH_USER);
253         strcpy(httpauth_pass, DEFAULT_HTTPAUTH_PASS);
254
255         /*
256          * Find out what it is that the web browser is asking for
257          */
258         memset(hold, 0, sizeof(hold));
259         do {
260                 if (req_gets(sock, buf, hold) < 0) return;
261
262                 /*
263                  * Can we compress?
264                  */
265                 if (!strncasecmp(buf, "Accept-encoding:", 16)) {
266                         if (strstr(&buf[16], "gzip")) {
267                                 gzip_ok = 1;
268                         }
269                 }
270
271                 /*
272                  * Browser-based sessions use cookies for session authentication
273                  */
274                 if (!strncasecmp(buf, "Cookie: webcit=", 15)) {
275                         cookie_to_stuff(&buf[15], &desired_session,
276                                 NULL, 0, NULL, 0, NULL, 0);
277                         got_cookie = 1;
278                 }
279
280                 /*
281                  * GroupDAV-based sessions use HTTP authentication
282                  */
283                 if (!strncasecmp(buf, "Authorization: Basic ", 21)) {
284                         CtdlDecodeBase64(httpauth_string, &buf[21], strlen(&buf[21]));
285                         extract_token(httpauth_user, httpauth_string, 0, ':', sizeof httpauth_user);
286                         extract_token(httpauth_pass, httpauth_string, 1, ':', sizeof httpauth_pass);
287                 }
288
289                 if (!strncasecmp(buf, "If-Modified-Since: ", 19)) {
290                         if_modified_since = httpdate_to_timestamp(&buf[19]);
291                 }
292
293                 if (!strncasecmp(buf, "Accept-Language: ", 17)) {
294                         httplang_to_locale(&buf[17]);
295                 }
296
297                 /*
298                  * Read in the request
299                  */
300                 hptr = (struct httprequest *)
301                         malloc(sizeof(struct httprequest));
302                 if (req == NULL)
303                         req = hptr;
304                 else
305                         last->next = hptr;
306                 hptr->next = NULL;
307                 last = hptr;
308
309                 safestrncpy(hptr->line, buf, sizeof hptr->line);
310
311         } while (strlen(buf) > 0);
312
313         /*
314          * If the request is prefixed by "/webcit" then chop that off.  This
315          * allows a front end web server to forward all /webcit requests to us
316          * while still using the same web server port for other things.
317          */
318         
319         ptr = strstr(req->line, " /webcit ");   /* Handle "/webcit" */
320         if (ptr != NULL) {
321                 strcpy(ptr+2, ptr+8);
322         }
323
324         ptr = strstr(req->line, " /webcit");    /* Handle "/webcit/" */
325         if (ptr != NULL) {
326                 strcpy(ptr+1, ptr+8);
327         }
328
329         /* Begin parsing the request. */
330
331         safestrncpy(buf, req->line, sizeof buf);
332         lprintf(5, "HTTP: %s\n", buf);
333
334         /* Check for bogus requests */
335         if (is_bogus(buf)) goto bail;
336
337         /*
338          * Strip out the method, leaving the URL up front...
339          */
340         remove_token(buf, 0, ' ');
341         if (buf[1]==' ') buf[1]=0;
342
343         /*
344          * While we're at it, gracefully handle requests for the
345          * robots.txt and favicon.ico files.
346          */
347         if (!strncasecmp(buf, "/robots.txt", 11)) {
348                 strcpy(req->line, "GET /static/robots.txt"
349                                 "?force_close_session=yes HTTP/1.1");
350         }
351         else if (!strncasecmp(buf, "/favicon.ico", 12)) {
352                 strcpy(req->line, "GET /static/favicon.ico");
353         }
354
355         /* These are the URL's which may be executed without a
356          * session cookie already set.  If it's not one of these,
357          * force the session to close because cookies are
358          * probably disabled on the client browser.
359          */
360         else if ( (strcmp(buf, "/"))
361                 && (strncasecmp(buf, "/listsub", 8))
362                 && (strncasecmp(buf, "/freebusy", 9))
363                 && (strncasecmp(buf, "/do_logout", 10))
364                 && (strncasecmp(buf, "/groupdav", 9))
365                 && (strncasecmp(buf, "/static", 7))
366                 && (strncasecmp(buf, "/rss", 4))
367                 && (got_cookie == 0)) {
368                 strcpy(req->line, "GET /static/nocookies.html"
369                                 "?force_close_session=yes HTTP/1.1");
370         }
371
372         /*
373          * See if there's an existing session open with the desired ID or user/pass
374          */
375         TheSession = NULL;
376
377         if (TheSession == NULL) {
378                 pthread_mutex_lock(&SessionListMutex);
379                 for (sptr = SessionList; sptr != NULL; sptr = sptr->next) {
380
381                         /* If HTTP-AUTH, look for a session with matching credentials */
382                         if ( (strlen(httpauth_user) > 0)
383                            &&(!strcasecmp(sptr->httpauth_user, httpauth_user))
384                            &&(!strcasecmp(sptr->httpauth_pass, httpauth_pass)) ) {
385                                 TheSession = sptr;
386                         }
387
388                         /* If cookie-session, look for a session with matching session ID */
389                         if ( (desired_session != 0) && (sptr->wc_session == desired_session)) {
390                                 TheSession = sptr;
391                         }
392
393                 }
394                 pthread_mutex_unlock(&SessionListMutex);
395         }
396
397         /*
398          * Create a new session if we have to
399          */
400         if (TheSession == NULL) {
401                 lprintf(3, "Creating a new session\n");
402                 TheSession = (struct wcsession *)
403                         malloc(sizeof(struct wcsession));
404                 memset(TheSession, 0, sizeof(struct wcsession));
405                 TheSession->serv_sock = (-1);
406                 TheSession->chat_sock = (-1);
407                 TheSession->wc_session = GenerateSessionID();
408                 strcpy(TheSession->httpauth_user, httpauth_user);
409                 strcpy(TheSession->httpauth_pass, httpauth_pass);
410                 pthread_mutex_init(&TheSession->SessionMutex, NULL);
411
412                 pthread_mutex_lock(&SessionListMutex);
413                 TheSession->next = SessionList;
414                 SessionList = TheSession;
415                 pthread_mutex_unlock(&SessionListMutex);
416         }
417
418         /*
419          * A future improvement might be to check the session integrity
420          * at this point before continuing.
421          */
422
423         /*
424          * Bind to the session and perform the transaction
425          */
426         pthread_mutex_lock(&TheSession->SessionMutex);          /* bind */
427         pthread_setspecific(MyConKey, (void *)TheSession);
428         TheSession->http_sock = sock;
429         TheSession->lastreq = time(NULL);                       /* log */
430         TheSession->gzip_ok = gzip_ok;
431         session_loop(req);                              /* do transaction */
432         pthread_mutex_unlock(&TheSession->SessionMutex);        /* unbind */
433
434         /* Free the request buffer */
435 bail:   while (req != NULL) {
436                 hptr = req->next;
437                 free(req);
438                 req = hptr;
439         }
440
441         /* Free up any session-local substitution variables which
442          * were set during this transaction
443          */
444         clear_local_substs();
445 }