0248c384f29d8e6c168aad5dbb60e90d54bad830
[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 wcsession *SessionList = NULL; /**< our sessions ????*/
18
19 pthread_key_t MyConKey;         /**< TSD key for MySession() */
20
21
22
23 void DestroySession(wcsession **sessions_to_kill)
24 {
25         close((*sessions_to_kill)->serv_sock);
26         close((*sessions_to_kill)->chat_sock);
27 /*
28 //              if ((*sessions_to_kill)->preferences != NULL) {
29 //                      free((*sessions_to_kill)->preferences);
30 //              }
31 */
32         if ((*sessions_to_kill)->cache_fold != NULL) {
33                 free((*sessions_to_kill)->cache_fold);
34         }
35         DeleteHash(&((*sessions_to_kill)->attachments));
36         free_march_list((*sessions_to_kill));
37         DeleteHash(&((*sessions_to_kill)->hash_prefs));
38         DeleteHash(&((*sessions_to_kill)->IconBarSetttings));
39         DeleteHash(&((*sessions_to_kill)->ServCfg));
40         FreeStrBuf(&((*sessions_to_kill)->UrlFragment1));
41         FreeStrBuf(&((*sessions_to_kill)->UrlFragment2));
42         FreeStrBuf(&((*sessions_to_kill)->UrlFragment3));
43         FreeStrBuf(&((*sessions_to_kill)->WBuf));
44         FreeStrBuf(&((*sessions_to_kill)->HBuf));
45         FreeStrBuf(&((*sessions_to_kill)->CLineBuf));
46         free((*sessions_to_kill));
47         (*sessions_to_kill) = NULL;
48 }
49
50 void shutdown_sessions(void)
51 {
52         wcsession *sptr;
53         
54         for (sptr = SessionList; sptr != NULL; sptr = sptr->next) {
55                         sptr->killthis = 1;
56         }
57 }
58
59 void do_housekeeping(void)
60 {
61         wcsession *sptr, *ss;
62         wcsession *sessions_to_kill = NULL;
63         int num_sessions = 0;
64         static int num_threads = MIN_WORKER_THREADS;
65
66         /**
67          * Lock the session list, moving any candidates for euthanasia into
68          * a separate list.
69          */
70         pthread_mutex_lock(&SessionListMutex);
71         num_sessions = 0;
72         for (sptr = SessionList; sptr != NULL; sptr = sptr->next) {
73                 ++num_sessions;
74
75                 /** Kill idle sessions */
76                 if ((time(NULL) - (sptr->lastreq)) >
77                    (time_t) WEBCIT_TIMEOUT) {
78                         sptr->killthis = 1;
79                 }
80
81                 /** Remove sessions flagged for kill */
82                 if (sptr->killthis) {
83
84                         /** remove session from linked list */
85                         if (sptr == SessionList) {
86                                 SessionList = SessionList->next;
87                         }
88                         else for (ss=SessionList;ss!=NULL;ss=ss->next) {
89                                 if (ss->next == sptr) {
90                                         ss->next = ss->next->next;
91                                 }
92                         }
93
94                         sptr->next = sessions_to_kill;
95                         sessions_to_kill = sptr;
96                 }
97         }
98         pthread_mutex_unlock(&SessionListMutex);
99
100         /**
101          * Now free up and destroy the culled sessions.
102          */
103         while (sessions_to_kill != NULL) {
104                 lprintf(3, "Destroying session %d\n", sessions_to_kill->wc_session);
105                 pthread_mutex_lock(&sessions_to_kill->SessionMutex);
106                 pthread_mutex_unlock(&sessions_to_kill->SessionMutex);
107                 sptr = sessions_to_kill->next;
108
109                 DestroySession(&sessions_to_kill);
110                 sessions_to_kill = sptr;
111                 --num_sessions;
112         }
113
114         /**
115          * If there are more sessions than threads, then we should spawn
116          * more threads ... up to a predefined maximum.
117          */
118         while ( (num_sessions > num_threads)
119               && (num_threads <= MAX_WORKER_THREADS) ) {
120                 spawn_another_worker_thread();
121                 ++num_threads;
122                 lprintf(3, "There are %d sessions and %d threads active.\n",
123                         num_sessions, num_threads);
124         }
125 }
126
127
128 /**
129  * \brief Wake up occasionally and clean house
130  */
131 void housekeeping_loop(void)
132 {
133         while (1) {
134                 sleeeeeeeeeep(HOUSEKEEPING);
135                 do_housekeeping();
136         }
137 }
138
139
140 /**
141  * \brief Create a Session id
142  * Generate a unique WebCit session ID (which is not the same thing as the
143  * Citadel session ID).
144  *
145  * \todo FIXME ... ensure that session number is truly unique
146  *
147  */
148 int GenerateSessionID(void)
149 {
150         static int seq = (-1);
151
152         if (seq < 0) {
153                 seq = (int) time(NULL);
154         }
155                 
156         return ++seq;
157 }
158
159 /*
160  * Collapse multiple cookies on one line
161  */
162 int ReqGetStrBuf(int *sock, StrBuf *Target, StrBuf *buf)
163 {
164         
165         return ClientGetLine(sock, Target, buf);
166 }
167
168
169
170 /*
171  * lingering_close() a`la Apache. see
172  * http://www.apache.org/docs/misc/fin_wait_2.html for rationale
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  * Look for commonly-found probes of malware such as worms, viruses, trojans, and Microsoft Office.
210  * Short-circuit these requests so we don't have to send them through the full processing loop.
211  */
212 int is_bogus(StrBuf *http_cmd) {
213         const char *url;
214         int i, max;
215         const char *bogus_prefixes[] = {
216                 "/scripts/root.exe",    /* Worms and trojans and viruses, oh my! */
217                 "/c/winnt",
218                 "/MSADC/",
219                 "/_vti",                /* Broken Microsoft DAV implementation */
220                 "/MSOffice",            /* Stoopid MSOffice thinks everyone is IIS */
221                 "/nonexistenshit"       /* Exploit found in the wild January 2009 */
222         };
223
224         url = ChrPtr(http_cmd);
225         if (IsEmptyStr(url)) return(1);
226         ++url;
227
228         max = sizeof(bogus_prefixes) / sizeof(char *);
229
230         for (i=0; i<max; ++i) {
231                 if (!strncasecmp(url, bogus_prefixes[i], strlen(bogus_prefixes[i]))) {
232                         return(2);
233                 }
234         }
235
236         return(0);      /* probably ok */
237 }
238
239
240 const char *nix(void *vptr) {return ChrPtr( (StrBuf*)vptr);}
241
242 /**
243  * \brief handle one request
244  * This loop gets called once for every HTTP connection made to WebCit.  At
245  * this entry point we have an HTTP socket with a browser allegedly on the
246  * other end, but we have not yet bound to a WebCit session.
247  *
248  * The job of this function is to locate the correct session and bind to it,
249  * or create a session if necessary and bind to it, then run the WebCit
250  * transaction loop.  Afterwards, we unbind from the session.  When this
251  * function returns, the worker thread is then free to handle another
252  * transaction.
253  * \param sock the socket we will put our answer to
254  */
255 void context_loop(int *sock)
256 {
257         const char *buf;
258         int desired_session = 0;
259         int got_cookie = 0;
260         int gzip_ok = 0;
261         wcsession *TheSession, *sptr;
262         char httpauth_string[1024];
263         char httpauth_user[1024];
264         char httpauth_pass[1024];
265         char *ptr = NULL;
266         int session_is_new = 0;
267         int nLine = 0;
268         int LineLen;
269         void *vLine;
270         StrBuf *Buf, *Line, *LastLine, *HeaderName, *ReqLine, *ReqType, *HTTPVersion;
271         StrBuf *accept_language = NULL;
272         const char *pch, *pchs, *pche;
273         HashList *HTTPHeaders;
274
275         strcpy(httpauth_string, "");
276         strcpy(httpauth_user, DEFAULT_HTTPAUTH_USER);
277         strcpy(httpauth_pass, DEFAULT_HTTPAUTH_PASS);
278
279         /**
280          * Find out what it is that the web browser is asking for
281          */
282         HeaderName = NewStrBuf();
283         Buf = NewStrBuf();
284         LastLine = NULL;
285         HTTPHeaders = NewHash(1, NULL);
286         /**
287          * Read in the request
288          */
289         do {
290                 nLine ++;
291                 Line = NewStrBuf();
292                 if (ReqGetStrBuf(sock, Line, Buf) < 0) return;
293
294                 LineLen = StrLength(Line);
295
296                 if (nLine == 1) {
297                         ReqLine = Line;
298                         continue;
299                 }
300                 if (LineLen == 0) {
301                         FreeStrBuf(&Line);
302                         continue;
303                 }
304
305                 /** Do we need to Unfold? */
306                 if ((LastLine != NULL) && 
307                     (isspace(*ChrPtr(Line)))) {
308                         pch = pchs = ChrPtr(Line);
309                         pche = pchs + StrLength(Line);
310                         while (isspace(*pch) && (pch < pche))
311                                 pch ++;
312                         StrBufCutLeft(Line, pch - pchs);
313                         StrBufAppendBuf(LastLine, Line, 0);
314                         FreeStrBuf(&Line);
315                         continue;
316                 }
317
318                 StrBufExtract_token(HeaderName, Line, 0, ':');
319                 /*/// TODO: filter bad chars! */
320
321                 pchs = ChrPtr(Line);
322                 pch = pchs + StrLength(HeaderName) + 1;
323                 pche = pchs + StrLength(Line);
324                 while (isspace(*pch) && (pch < pche))
325                         pch ++;
326                 StrBufCutLeft(Line, pch - pchs);
327
328                 StrBufUpCase(HeaderName);
329                 Put(HTTPHeaders, SKEY(HeaderName), Line, HFreeStrBuf);
330                 LastLine = Line;
331         } while (LineLen > 0);
332         FreeStrBuf(&HeaderName);
333
334 /*///   dbg_PrintHash(HTTPHeaders, nix, NULL); */
335
336
337         /**
338          * Can we compress?
339          */
340         if (GetHash(HTTPHeaders, HKEY("ACCEPT-ENCODING"), &vLine) && 
341             (vLine != NULL)) {
342                 buf = ChrPtr((StrBuf*)vLine);
343                 if (strstr(&buf[16], "gzip")) {
344                         gzip_ok = 1;
345                 }
346         }
347
348         /**
349          * Browser-based sessions use cookies for session 
350
351 authentication
352          */
353         if (GetHash(HTTPHeaders, HKEY("COOKIE"), &vLine) && 
354             (vLine != NULL)) {
355                 cookie_to_stuff(vLine, &desired_session,
356                                 NULL, 0, NULL, 0, NULL, 0);
357                 got_cookie = 1;
358         }
359
360         /**
361          * GroupDAV-based sessions use HTTP authentication
362          */
363         if (GetHash(HTTPHeaders, HKEY("AUTHORIZATION"), &vLine) && 
364             (vLine != NULL)) {
365                 Line = (StrBuf*)vLine;
366                 if (strncasecmp(ChrPtr(Line), "Basic", 5) == 0) {
367                         StrBufCutLeft(Line, 6);
368                         CtdlDecodeBase64(httpauth_string, ChrPtr(Line), StrLength(Line));
369                         extract_token(httpauth_user, httpauth_string, 0, ':', sizeof httpauth_user);
370                         extract_token(httpauth_pass, httpauth_string, 1, ':', sizeof httpauth_pass);
371                 }
372                 else 
373                         lprintf(1, "Authentication scheme not supported! [%s]\n", ChrPtr(Line));
374         }
375
376         if (GetHash(HTTPHeaders, HKEY("IF-MODIFIED-SINCE"), &vLine) && 
377             (vLine != NULL)) {
378                 if_modified_since = httpdate_to_timestamp((StrBuf*)vLine);
379         }
380
381         if (GetHash(HTTPHeaders, HKEY("ACCEPT-LANGUAGE"), &vLine) && 
382             (vLine != NULL)) {
383                 accept_language = (StrBuf*) vLine;
384         }
385
386
387         /**
388          * If the request is prefixed by "/webcit" then chop that off.  This
389          * allows a front end web server to forward all /webcit requests to us
390          * while still using the same web server port for other things.
391          */
392
393         ReqType = NewStrBuf();
394         HTTPVersion = NewStrBuf();
395         StrBufExtract_token(HTTPVersion, ReqLine, 2, ' ');
396         StrBufExtract_token(ReqType, ReqLine, 0, ' ');
397         StrBufCutLeft(ReqLine, StrLength(ReqType) + 1);
398         StrBufCutRight(ReqLine, StrLength(HTTPVersion) + 1);
399
400         if ((follow_xff == 1) && (StrLength(ReqLine) >= 8) &&
401             (ptr = strstr(ChrPtr(ReqLine), "/webcit/"), /*< Handle "/webcit/" */
402              (ptr != NULL))) {
403                 StrBufCutLeft(ReqLine, 7);
404         }
405
406         /** Begin parsing the request. */
407 #ifdef TECH_PREVIEW
408         if ((strncmp(ChrPtr(ReqLine), "/sslg", 5) != 0) &&
409             (strncmp(ChrPtr(ReqLine), "/static/", 8) != 0) &&
410             (strncmp(ChrPtr(ReqLine), "/tiny_mce/", 10) != 0) &&
411             (strncmp(ChrPtr(ReqLine), "/wholist_section", 16) != 0) &&
412             (strstr(ChrPtr(ReqLine), "wholist_section") == NULL)) {
413 #endif
414                 lprintf(5, "HTTP: %s %s %s\n", ChrPtr(ReqType), ChrPtr(ReqLine), ChrPtr(HTTPVersion));
415 #ifdef TECH_PREVIEW
416         }
417 #endif
418
419         /** Check for bogus requests */
420         if ((StrLength(HTTPVersion) == 0) ||
421             (StrLength(ReqType) == 0) || 
422             is_bogus(ReqLine)) {
423                 StrBufPlain(ReqLine, HKEY("/404 HTTP/1.1"));
424                 StrBufPlain(ReqType, HKEY("GET"));
425         }
426         FreeStrBuf(&HTTPVersion);
427
428         /**
429          * While we're at it, gracefully handle requests for the
430          * robots.txt and favicon.ico files.
431          */
432         if (!strncasecmp(ChrPtr(ReqLine), "/robots.txt", 11)) {
433                 StrBufPlain(ReqLine, 
434                             HKEY("/static/robots.txt"
435                                  "?force_close_session=yes HTTP/1.1"));
436                 StrBufPlain(ReqType, HKEY("GET"));
437         }
438         else if (!strncasecmp(ChrPtr(ReqLine), "/favicon.ico", 12)) {
439                 StrBufPlain(ReqLine, HKEY("/static/favicon.ico"));
440                 StrBufPlain(ReqType, HKEY("GET"));
441         }
442
443         /**
444          * These are the URL's which may be executed without a
445          * session cookie already set.  If it's not one of these,
446          * force the session to close because cookies are
447          * probably disabled on the client browser.
448          */
449         else if ( (StrLength(ReqLine) > 1 )
450                 && (strncasecmp(ChrPtr(ReqLine), "/listsub", 8))
451                 && (strncasecmp(ChrPtr(ReqLine), "/freebusy", 9))
452                 && (strncasecmp(ChrPtr(ReqLine), "/do_logout", 10))
453                 && (strncasecmp(ChrPtr(ReqLine), "/groupdav", 9))
454                 && (strncasecmp(ChrPtr(ReqLine), "/static", 7))
455                 && (strncasecmp(ChrPtr(ReqLine), "/rss", 4))
456                 && (strncasecmp(ChrPtr(ReqLine), "/404", 4))
457                 && (got_cookie == 0)) {
458                 StrBufPlain(ReqLine, 
459                             HKEY("/static/nocookies.html"
460                                  "?force_close_session=yes"));
461         }
462
463         /**
464          * See if there's an existing session open with the desired ID or user/pass
465          */
466         TheSession = NULL;
467
468         if (TheSession == NULL) {
469                 pthread_mutex_lock(&SessionListMutex);
470                 for (sptr = SessionList; sptr != NULL; sptr = sptr->next) {
471
472                         /** If HTTP-AUTH, look for a session with matching credentials */
473                         if ( (!IsEmptyStr(httpauth_user))
474                            &&(!strcasecmp(sptr->httpauth_user, httpauth_user))
475                            &&(!strcasecmp(sptr->httpauth_pass, httpauth_pass)) ) {
476                                 TheSession = sptr;
477                         }
478
479                         /** If cookie-session, look for a session with matching session ID */
480                         if ( (desired_session != 0) && (sptr->wc_session == desired_session)) {
481                                 TheSession = sptr;
482                         }
483
484                 }
485                 pthread_mutex_unlock(&SessionListMutex);
486         }
487
488         /**
489          * Create a new session if we have to
490          */
491         if (TheSession == NULL) {
492                 lprintf(3, "Creating a new session\n");
493                 TheSession = (wcsession *)
494                         malloc(sizeof(wcsession));
495                 memset(TheSession, 0, sizeof(wcsession));
496                 TheSession->serv_sock = (-1);
497                 TheSession->chat_sock = (-1);
498         
499                 /* If we're recreating a session that expired, it's best to give it the same
500                  * session number that it had before.  The client browser ought to pick up
501                  * the new session number and start using it, but in some rare situations it
502                  * doesn't, and that's a Bad Thing because it causes lots of spurious sessions
503                  * to get created.
504                  */     
505                 if (desired_session == 0) {
506                         TheSession->wc_session = GenerateSessionID();
507                 }
508                 else {
509                         TheSession->wc_session = desired_session;
510                 }
511
512                 strcpy(TheSession->httpauth_user, httpauth_user);
513                 strcpy(TheSession->httpauth_pass, httpauth_pass);
514                 TheSession->hash_prefs = NewHash(1,NULL);       /* Get a hash table for the user preferences */
515                 pthread_mutex_init(&TheSession->SessionMutex, NULL);
516                 pthread_mutex_lock(&SessionListMutex);
517                 TheSession->urlstrings = NULL;
518                 TheSession->vars = NULL;
519                 TheSession->nonce = rand();
520                 TheSession->WBuf = NULL;
521                 TheSession->CLineBuf = NewStrBuf();
522                 TheSession->next = SessionList;
523                 TheSession->is_mobile = -1;
524                 SessionList = TheSession;
525                 pthread_mutex_unlock(&SessionListMutex);
526                 session_is_new = 1;
527         }
528
529         /*
530          * A future improvement might be to check the session integrity
531          * at this point before continuing.
532          */
533
534         /*
535          * Bind to the session and perform the transaction
536          */
537         pthread_mutex_lock(&TheSession->SessionMutex);          /* bind */
538         pthread_setspecific(MyConKey, (void *)TheSession);
539         
540         TheSession->urlstrings = NewHash(1,NULL);
541         TheSession->vars = NewHash(1,NULL);
542         TheSession->http_sock = *sock;
543         TheSession->lastreq = time(NULL);                       /* log */
544         TheSession->gzip_ok = gzip_ok;
545 #ifdef ENABLE_NLS
546         if (session_is_new) {
547                 httplang_to_locale(accept_language);
548         }
549         go_selected_language();                                 /* set locale */
550 #endif
551         session_loop(HTTPHeaders, ReqLine, ReqType, Buf);                               /* do transaction */
552 #ifdef ENABLE_NLS
553         stop_selected_language();                               /* unset locale */
554 #endif
555         DeleteHash(&TheSession->summ);
556         DeleteHash(&TheSession->urlstrings);
557         DeleteHash(&TheSession->vars);
558         FreeStrBuf(&TheSession->WBuf);
559         FreeStrBuf(&TheSession->HBuf);
560         
561         
562         pthread_mutex_unlock(&TheSession->SessionMutex);        /* unbind */
563
564         /* Free the request buffer */
565         DeleteHash(&HTTPHeaders);
566         FreeStrBuf(&ReqLine);
567         FreeStrBuf(&ReqType);
568         FreeStrBuf(&Buf);
569         /*
570          * Free up any session-local substitution variables which
571          * were set during this transaction
572          */
573         
574         
575 }
576
577 void tmpl_nonce(StrBuf *Target, int nArgs, WCTemplateToken *Tokens, void *Context, int ContextType)
578 {
579         wcsession *WCC = WC;
580         StrBufAppendPrintf(Target, "%ld",
581                            (WCC != NULL)? WCC->nonce:0);                   
582 }
583
584 void 
585 InitModule_CONTEXT
586 (void)
587 {
588         RegisterNamespace("NONCE", 0, 0, tmpl_nonce, 0);
589 }