8d7bb9e6666acef7b190aeaf9267bfe80e27e23e
[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; /**< our sessions ????*/
18
19 pthread_key_t MyConKey;         /**< TSD key for MySession() */
20
21
22 /*
23  * free the memory used for viewing atachments
24  */
25 void free_attachments(struct wcsession *sess) {
26         struct wc_attachment *att;
27
28         while (sess->first_attachment != NULL) {
29                 att = sess->first_attachment;
30                 sess->first_attachment = sess->first_attachment->next;
31                 free(att->data);
32                 free(att);
33         }
34 }
35
36
37 void shutdown_sessions(void)
38 {
39         struct wcsession *sptr;
40         
41         for (sptr = SessionList; sptr != NULL; sptr = sptr->next) {
42                         sptr->killthis = 1;
43         }
44 }
45
46 void do_housekeeping(void)
47 {
48         struct wcsession *sptr, *ss;
49         struct wcsession *sessions_to_kill = NULL;
50         int num_sessions = 0;
51         static int num_threads = MIN_WORKER_THREADS;
52
53         /**
54          * Lock the session list, moving any candidates for euthanasia into
55          * a separate list.
56          */
57         pthread_mutex_lock(&SessionListMutex);
58         num_sessions = 0;
59         for (sptr = SessionList; sptr != NULL; sptr = sptr->next) {
60                 ++num_sessions;
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                         /** remove session from linked list */
72                         if (sptr == SessionList) {
73                                 SessionList = SessionList->next;
74                         }
75                         else for (ss=SessionList;ss!=NULL;ss=ss->next) {
76                                 if (ss->next == sptr) {
77                                         ss->next = ss->next->next;
78                                 }
79                         }
80
81                         sptr->next = sessions_to_kill;
82                         sessions_to_kill = sptr;
83                 }
84         }
85         pthread_mutex_unlock(&SessionListMutex);
86
87         /**
88          * Now free up and destroy the culled sessions.
89          */
90         while (sessions_to_kill != NULL) {
91                 lprintf(3, "Destroying session %d\n", sessions_to_kill->wc_session);
92                 pthread_mutex_lock(&sessions_to_kill->SessionMutex);
93                 close(sessions_to_kill->serv_sock);
94                 close(sessions_to_kill->chat_sock);
95 //              if (sessions_to_kill->preferences != NULL) {
96 //                      free(sessions_to_kill->preferences);
97 //              }
98                 if (sessions_to_kill->cache_fold != NULL) {
99                         free(sessions_to_kill->cache_fold);
100                 }
101                 free_attachments(sessions_to_kill);
102                 free_march_list(sessions_to_kill);
103                 DeleteHash(&(sessions_to_kill->hash_prefs));
104                 
105                 pthread_mutex_unlock(&sessions_to_kill->SessionMutex);
106                 sptr = sessions_to_kill->next;
107                 free(sessions_to_kill);
108                 sessions_to_kill = sptr;
109                 --num_sessions;
110         }
111
112         /**
113          * If there are more sessions than threads, then we should spawn
114          * more threads ... up to a predefined maximum.
115          */
116         while ( (num_sessions > num_threads)
117               && (num_threads <= MAX_WORKER_THREADS) ) {
118                 spawn_another_worker_thread();
119                 ++num_threads;
120                 lprintf(3, "There are %d sessions and %d threads active.\n",
121                         num_sessions, num_threads);
122         }
123 }
124
125
126 /**
127  * \brief Wake up occasionally and clean house
128  */
129 void housekeeping_loop(void)
130 {
131         while (1) {
132                 sleeeeeeeeeep(HOUSEKEEPING);
133                 do_housekeeping();
134         }
135 }
136
137
138 /**
139  * \brief Create a Session id
140  * Generate a unique WebCit session ID (which is not the same thing as the
141  * Citadel session ID).
142  *
143  * \todo FIXME ... ensure that session number is truly unique
144  *
145  */
146 int GenerateSessionID(void)
147 {
148         static int seq = (-1);
149
150         if (seq < 0) {
151                 seq = (int) time(NULL);
152         }
153                 
154         return ++seq;
155 }
156
157
158 /*
159  * Collapse multiple cookies on one line
160  */
161 int req_gets(int sock, char *buf, char *hold, size_t hlen)
162 {
163         int a, b;
164
165         if (IsEmptyStr(hold)) {
166                 strcpy(buf, "");
167                 a = client_getln(sock, buf, SIZ);
168                 if (a<1) return(-1);
169         } else {
170                 safestrncpy(buf, hold, SIZ);
171         }
172         strcpy(hold, "");
173
174         if (!strncasecmp(buf, "Cookie: ", 8)) {
175                 int len;
176                 len = strlen(buf);
177                 for (a = 0; a < len; ++a)
178                         if (buf[a] == ';') {
179                                 // we don't refresh len, because of we 
180                                 // only exit from here.
181                                 snprintf(hold, hlen, "Cookie: %s", &buf[a + 1]);
182                                 buf[a] = 0;
183                                 b = 8;
184                                 while (isspace(hold[b]))
185                                         b++;
186                                 
187                                 memmove(&hold[8], &hold[b], len - b + 1);
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 int lingering_close(int fd)
200 {
201         char buf[SIZ];
202         int i;
203         fd_set set;
204         struct timeval tv, start;
205
206         gettimeofday(&start, NULL);
207         shutdown(fd, 1);
208         do {
209                 do {
210                         gettimeofday(&tv, NULL);
211                         tv.tv_sec = SLEEPING - (tv.tv_sec - start.tv_sec);
212                         tv.tv_usec = start.tv_usec - tv.tv_usec;
213                         if (tv.tv_usec < 0) {
214                                 tv.tv_sec--;
215                                 tv.tv_usec += 1000000;
216                         }
217                         FD_ZERO(&set);
218                         FD_SET(fd, &set);
219                         i = select(fd + 1, &set, NULL, NULL, &tv);
220                 } while (i == -1 && errno == EINTR);
221
222                 if (i <= 0)
223                         break;
224
225                 i = read(fd, buf, sizeof buf);
226         } while (i != 0 && (i != -1 || errno == EINTR));
227
228         return close(fd);
229 }
230
231
232
233 /**
234  * \brief       sanity requests
235  *              Check for bogus requests coming from brain-dead Windows boxes.
236  *
237  * \param       http_cmd        The HTTP request to check
238  */
239 int is_bogus(char *http_cmd) {
240         char *url;
241         int i, max;
242
243         url = strstr(http_cmd, " ");
244         if (url == NULL) return(1);
245         ++url;
246
247         char *bogus_prefixes[] = {
248                 "/scripts/root.exe",    /**< Worms and trojans and viruses, oh my! */
249                 "/c/winnt",
250                 "/MSADC/",
251                 "/_vti",                /**< Broken Microsoft DAV implementation */
252                 "/MSOffice"             /**< Stoopid MSOffice thinks everyone is IIS */
253         };
254
255         max = sizeof(bogus_prefixes) / sizeof(char *);
256
257         for (i=0; i<max; ++i) {
258                 if (!strncasecmp(url, bogus_prefixes[i], strlen(bogus_prefixes[i]))) {
259                         return(2);
260                 }
261         }
262
263         return(0);      /* probably ok */
264 }
265
266
267
268 /**
269  * \brief handle one request
270  * This loop gets called once for every HTTP connection made to WebCit.  At
271  * this entry point we have an HTTP socket with a browser allegedly on the
272  * other end, but we have not yet bound to a WebCit session.
273  *
274  * The job of this function is to locate the correct session and bind to it,
275  * or create a session if necessary and bind to it, then run the WebCit
276  * transaction loop.  Afterwards, we unbind from the session.  When this
277  * function returns, the worker thread is then free to handle another
278  * transaction.
279  * \param sock the socket we will put our answer to
280  */
281 void context_loop(int sock)
282 {
283         struct httprequest *req = NULL;
284         struct httprequest *last = NULL;
285         struct httprequest *hptr;
286         char buf[SIZ], hold[SIZ];
287         int desired_session = 0;
288         int got_cookie = 0;
289         int gzip_ok = 0;
290         struct wcsession *TheSession, *sptr;
291         char httpauth_string[1024];
292         char httpauth_user[1024];
293         char httpauth_pass[1024];
294         char accept_language[256];
295         char *ptr = NULL;
296         int session_is_new = 0;
297
298         strcpy(httpauth_string, "");
299         strcpy(httpauth_user, DEFAULT_HTTPAUTH_USER);
300         strcpy(httpauth_pass, DEFAULT_HTTPAUTH_PASS);
301
302         /**
303          * Find out what it is that the web browser is asking for
304          */
305         memset(hold, 0, sizeof(hold));
306         do {
307                 if (req_gets(sock, buf, hold, SIZ) < 0) return;
308
309                 /**
310                  * Can we compress?
311                  */
312                 if (!strncasecmp(buf, "Accept-encoding:", 16)) {
313                         if (strstr(&buf[16], "gzip")) {
314                                 gzip_ok = 1;
315                         }
316                 }
317
318                 /**
319                  * Browser-based sessions use cookies for session authentication
320                  */
321                 if (!strncasecmp(buf, "Cookie: webcit=", 15)) {
322                         cookie_to_stuff(&buf[15], &desired_session,
323                                 NULL, 0, NULL, 0, NULL, 0);
324                         got_cookie = 1;
325                 }
326
327                 /**
328                  * GroupDAV-based sessions use HTTP authentication
329                  */
330                 if (!strncasecmp(buf, "Authorization: Basic ", 21)) {
331                         CtdlDecodeBase64(httpauth_string, &buf[21], strlen(&buf[21]));
332                         extract_token(httpauth_user, httpauth_string, 0, ':', sizeof httpauth_user);
333                         extract_token(httpauth_pass, httpauth_string, 1, ':', sizeof httpauth_pass);
334                 }
335
336                 if (!strncasecmp(buf, "If-Modified-Since: ", 19)) {
337                         if_modified_since = httpdate_to_timestamp(&buf[19]);
338                 }
339
340                 if (!strncasecmp(buf, "Accept-Language: ", 17)) {
341                         safestrncpy(accept_language, &buf[17], sizeof accept_language);
342                 }
343
344                 /**
345                  * Read in the request
346                  */
347                 hptr = (struct httprequest *)
348                         malloc(sizeof(struct httprequest));
349                 if (req == NULL)
350                         req = hptr;
351                 else
352                         last->next = hptr;
353                 hptr->next = NULL;
354                 last = hptr;
355
356                 safestrncpy(hptr->line, buf, sizeof hptr->line);
357
358         } while (!IsEmptyStr(buf));
359
360         /**
361          * If the request is prefixed by "/webcit" then chop that off.  This
362          * allows a front end web server to forward all /webcit requests to us
363          * while still using the same web server port for other things.
364          */
365         
366         ptr = strstr(req->line, " /webcit ");   /*< Handle "/webcit" */
367         if (ptr != NULL) {
368                 strcpy(ptr+2, ptr+8);
369         }
370
371         ptr = strstr(req->line, " /webcit");    /*< Handle "/webcit/" */
372         if (ptr != NULL) {
373                 strcpy(ptr+1, ptr+8);
374         }
375
376         /** Begin parsing the request. */
377
378         safestrncpy(buf, req->line, sizeof buf);
379         lprintf(5, "HTTP: %s\n", buf);
380
381         /** Check for bogus requests */
382         if (is_bogus(buf)) {
383                 strcpy(req->line, "GET /404 HTTP/1.1");
384                 strcpy(buf, "GET /404 HTTP/1.1");
385         }
386
387         /**
388          * Strip out the method, leaving the URL up front...
389          */
390         remove_token(buf, 0, ' ');
391         if (buf[1]==' ') buf[1]=0;
392
393         /**
394          * While we're at it, gracefully handle requests for the
395          * robots.txt and favicon.ico files.
396          */
397         if (!strncasecmp(buf, "/robots.txt", 11)) {
398                 strcpy(req->line, "GET /static/robots.txt"
399                                 "?force_close_session=yes HTTP/1.1");
400         }
401         else if (!strncasecmp(buf, "/favicon.ico", 12)) {
402                 strcpy(req->line, "GET /static/favicon.ico");
403         }
404
405         /**
406          * These are the URL's which may be executed without a
407          * session cookie already set.  If it's not one of these,
408          * force the session to close because cookies are
409          * probably disabled on the client browser.
410          */
411         else if ( (strcmp(buf, "/"))
412                 && (strncasecmp(buf, "/listsub", 8))
413                 && (strncasecmp(buf, "/freebusy", 9))
414                 && (strncasecmp(buf, "/do_logout", 10))
415                 && (strncasecmp(buf, "/groupdav", 9))
416                 && (strncasecmp(buf, "/static", 7))
417                 && (strncasecmp(buf, "/rss", 4))
418                 && (strncasecmp(buf, "/404", 4))
419                 && (got_cookie == 0)) {
420                 strcpy(req->line, "GET /static/nocookies.html"
421                                 "?force_close_session=yes HTTP/1.1");
422         }
423
424         /**
425          * See if there's an existing session open with the desired ID or user/pass
426          */
427         TheSession = NULL;
428
429         if (TheSession == NULL) {
430                 pthread_mutex_lock(&SessionListMutex);
431                 for (sptr = SessionList; sptr != NULL; sptr = sptr->next) {
432
433                         /** If HTTP-AUTH, look for a session with matching credentials */
434                         if ( (!IsEmptyStr(httpauth_user))
435                            &&(!strcasecmp(sptr->httpauth_user, httpauth_user))
436                            &&(!strcasecmp(sptr->httpauth_pass, httpauth_pass)) ) {
437                                 TheSession = sptr;
438                         }
439
440                         /** If cookie-session, look for a session with matching session ID */
441                         if ( (desired_session != 0) && (sptr->wc_session == desired_session)) {
442                                 TheSession = sptr;
443                         }
444
445                 }
446                 pthread_mutex_unlock(&SessionListMutex);
447         }
448
449         /**
450          * Create a new session if we have to
451          */
452         if (TheSession == NULL) {
453                 lprintf(3, "Creating a new session\n");
454                 TheSession = (struct wcsession *)
455                         malloc(sizeof(struct wcsession));
456                 memset(TheSession, 0, sizeof(struct wcsession));
457                 TheSession->serv_sock = (-1);
458                 TheSession->chat_sock = (-1);
459         
460                 /* If we're recreating a session that expired, it's best to give it the same
461                  * session number that it had before.  The client browser ought to pick up
462                  * the new session number and start using it, but in some rare situations it
463                  * doesn't, and that's a Bad Thing because it causes lots of spurious sessions
464                  * to get created.
465                  */     
466                 if (desired_session == 0) {
467                         TheSession->wc_session = GenerateSessionID();
468                 }
469                 else {
470                         TheSession->wc_session = desired_session;
471                 }
472
473                 strcpy(TheSession->httpauth_user, httpauth_user);
474                 strcpy(TheSession->httpauth_pass, httpauth_pass);
475                 TheSession->hash_prefs = NewHash(1,NULL);       /* Get a hash table for the user preferences */
476                 pthread_mutex_init(&TheSession->SessionMutex, NULL);
477                 pthread_mutex_lock(&SessionListMutex);
478                 TheSession->urlstrings = NULL;
479                 TheSession->vars = NULL;
480                 TheSession->nonce = rand();
481                 TheSession->next = SessionList;
482                 SessionList = TheSession;
483                 pthread_mutex_unlock(&SessionListMutex);
484                 session_is_new = 1;
485         }
486
487         /*
488          * A future improvement might be to check the session integrity
489          * at this point before continuing.
490          */
491
492         /*
493          * Bind to the session and perform the transaction
494          */
495         pthread_mutex_lock(&TheSession->SessionMutex);          /* bind */
496         pthread_setspecific(MyConKey, (void *)TheSession);
497         
498         TheSession->urlstrings = NewHash(1,NULL);
499         TheSession->vars = NewHash(1,NULL);
500         TheSession->http_sock = sock;
501         TheSession->lastreq = time(NULL);                       /* log */
502         TheSession->gzip_ok = gzip_ok;
503 #ifdef ENABLE_NLS
504         if (session_is_new) {
505                 httplang_to_locale(accept_language);
506         }
507         go_selected_language();                                 /* set locale */
508 #endif
509         session_loop(req);                                      /* do transaction */
510 #ifdef ENABLE_NLS
511         stop_selected_language();                               /* unset locale */
512 #endif
513         DeleteHash(&TheSession->urlstrings);
514         DeleteHash(&TheSession->vars);
515
516         pthread_mutex_unlock(&TheSession->SessionMutex);        /* unbind */
517
518         /* Free the request buffer */
519         while (req != NULL) {
520                 hptr = req->next;
521                 free(req);
522                 req = hptr;
523         }
524
525         /*
526          * Free up any session-local substitution variables which
527          * were set during this transaction
528          */
529         
530         
531 }