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