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