aa8a467a9287908a531f16b71de13799dadffc40
[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 #include "modules_init.h"
14
15 /* Only one thread may manipulate SessionList at a time... */
16 pthread_mutex_t SessionListMutex;
17
18 wcsession *SessionList = NULL;  /* Linked list of all webcit sessions */
19
20 pthread_key_t MyConKey;         /* TSD key for MySession() */
21 HashList *HttpReqTypes = NULL;
22 HashList *HttpHeaderHandler = NULL;
23 extern HashList *HandlerHash;
24 int num_threads = 1;            /* Number of worker threads.  Start at 1 because the parent counts. */
25
26 void DestroyHttpHeaderHandler(void *V)
27 {
28         OneHttpHeader *pHdr;
29         pHdr = (OneHttpHeader*) V;
30         FreeStrBuf(&pHdr->Val);
31         free(pHdr);
32 }
33
34 void shutdown_sessions(void)
35 {
36         wcsession *sptr;
37         
38         for (sptr = SessionList; sptr != NULL; sptr = sptr->next) {
39                         sptr->killthis = 1;
40         }
41 }
42
43 void do_housekeeping(void)
44 {
45         wcsession *sptr, *ss;
46         wcsession *sessions_to_kill = NULL;
47         int num_sessions = 0;
48
49         /*
50          * Lock the session list, moving any candidates for euthanasia into
51          * a separate list.
52          */
53         pthread_mutex_lock(&SessionListMutex);
54         num_sessions = 0;
55         for (sptr = SessionList; sptr != NULL; sptr = sptr->next) {
56                 ++num_sessions;
57
58                 /* Kill idle sessions */
59                 if ((time(NULL) - (sptr->lastreq)) > (time_t) WEBCIT_TIMEOUT) {
60                         sptr->killthis = 1;
61                 }
62
63                 /* Remove sessions flagged for kill */
64                 if (sptr->killthis) {
65
66                         /** remove session from linked list */
67                         if (sptr == SessionList) {
68                                 SessionList = SessionList->next;
69                         }
70                         else for (ss=SessionList;ss!=NULL;ss=ss->next) {
71                                 if (ss->next == sptr) {
72                                         ss->next = ss->next->next;
73                                 }
74                         }
75
76                         sptr->next = sessions_to_kill;
77                         sessions_to_kill = sptr;
78                 }
79         }
80         pthread_mutex_unlock(&SessionListMutex);
81
82         /*
83          * Now free up and destroy the culled sessions.
84          */
85         while (sessions_to_kill != NULL) {
86                 lprintf(3, "Destroying session %d\n", sessions_to_kill->wc_session);
87                 pthread_mutex_lock(&sessions_to_kill->SessionMutex);
88                 pthread_mutex_unlock(&sessions_to_kill->SessionMutex);
89                 sptr = sessions_to_kill->next;
90
91                 session_destroy_modules(&sessions_to_kill);
92                 sessions_to_kill = sptr;
93                 --num_sessions;
94         }
95
96         /*
97          * If there are more sessions than threads, then we should spawn
98          * more threads ... up to a predefined maximum.
99          */
100         while ( (num_sessions > num_threads) && (num_threads <= MAX_WORKER_THREADS) ) {
101                 spawn_another_worker_thread();
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  * Create a Session id
122  * Generate a unique WebCit session ID (which is not the same thing as the
123  * Citadel session ID).
124  */
125 int GenerateSessionID(void)
126 {
127         static int seq = (-1);
128
129         if (seq < 0) {
130                 seq = (int) time(NULL);
131         }
132                 
133         return ++seq;
134 }
135
136 wcsession *FindSession(wcsession **wclist, ParsedHttpHdrs *Hdr, pthread_mutex_t *ListMutex)
137 {
138         wcsession *sptr = NULL;
139         wcsession *TheSession = NULL;   
140         
141         if (Hdr->HR.got_auth == AUTH_BASIC) {
142                 GetAuthBasic(Hdr);
143         }
144
145         pthread_mutex_lock(ListMutex);
146         for (sptr = *wclist; ((sptr != NULL) && (TheSession == NULL)); sptr = sptr->next) {
147                 
148                 /* If HTTP-AUTH, look for a session with matching credentials */
149                 switch (Hdr->HR.got_auth)
150                 {
151                 case AUTH_BASIC:
152                         if ( (Hdr->HR.SessionKey != sptr->SessionKey))
153                                 continue;
154                         if ((!strcasecmp(ChrPtr(Hdr->c_username), ChrPtr(sptr->wc_username))) &&
155                             (!strcasecmp(ChrPtr(Hdr->c_password), ChrPtr(sptr->wc_password))) ) {
156                                 TheSession = sptr;
157                         }
158                         if (TheSession == NULL)
159                                 lprintf(1, "found sessionkey [%ld], but credentials for [%s|%s] didn't match\n",
160                                         Hdr->HR.SessionKey,ChrPtr(Hdr->c_username), ChrPtr(sptr->wc_username));
161                         break;
162                 case AUTH_COOKIE:
163                         /* If cookie-session, look for a session with matching session ID */
164                         if ( (Hdr->HR.desired_session != 0) && 
165                              (sptr->wc_session == Hdr->HR.desired_session)) {
166                                 TheSession = sptr;
167                         }
168                         break;                       
169                 case NO_AUTH:
170                         break;
171                 }
172         }
173         pthread_mutex_unlock(ListMutex);
174         if (TheSession == NULL)
175                 lprintf(1, "didn't find sessionkey [%ld] for user [%s]\n",
176                         Hdr->HR.SessionKey,ChrPtr(Hdr->c_username));
177         return TheSession;
178 }
179
180 wcsession *CreateSession(int Lockable, wcsession **wclist, ParsedHttpHdrs *Hdr, pthread_mutex_t *ListMutex)
181 {
182         wcsession *TheSession;
183         lprintf(3, "Creating a new session\n");
184         TheSession = (wcsession *) malloc(sizeof(wcsession));
185         memset(TheSession, 0, sizeof(wcsession));
186         TheSession->Hdr = Hdr;
187         TheSession->SessionKey = Hdr->HR.SessionKey;
188         TheSession->serv_sock = (-1);
189         TheSession->chat_sock = (-1);
190         TheSession->is_mobile = -1;
191
192         pthread_setspecific(MyConKey, (void *)TheSession);
193         
194         /* If we're recreating a session that expired, it's best to give it the same
195          * session number that it had before.  The client browser ought to pick up
196          * the new session number and start using it, but in some rare situations it
197          * doesn't, and that's a Bad Thing because it causes lots of spurious sessions
198          * to get created.
199          */     
200         if (Hdr->HR.desired_session == 0) {
201                 TheSession->wc_session = GenerateSessionID();
202         }
203         else {
204                 TheSession->wc_session = Hdr->HR.desired_session;
205         }
206
207         session_new_modules(TheSession);
208
209         if (Lockable) {
210                 pthread_mutex_init(&TheSession->SessionMutex, NULL);
211
212                 if (ListMutex != NULL)
213                         pthread_mutex_lock(ListMutex);
214
215                 if (wclist != NULL) {
216                         TheSession->nonce = rand();
217                         TheSession->next = *wclist;
218                         *wclist = TheSession;
219                 }
220                 if (ListMutex != NULL)
221                         pthread_mutex_unlock(ListMutex);
222         }
223         return TheSession;
224 }
225
226
227 /*
228  * Detects a 'mobile' user agent 
229  */
230 int is_mobile_ua(char *user_agent) {
231       if (strstr(user_agent,"iPhone OS") != NULL) {
232         return 1;
233       } else if (strstr(user_agent,"Windows CE") != NULL) {
234         return 1;
235       } else if (strstr(user_agent,"SymbianOS") != NULL) {
236         return 1;
237       } else if (strstr(user_agent, "Opera Mobi") != NULL) {
238         return 1;
239       } else if (strstr(user_agent, "Firefox/2.0.0 Opera 9.51 Beta") != NULL) {
240               /*  For some reason a new install of Opera 9.51beta decided to spoof. */
241           return 1;
242           }
243       return 0;
244 }
245
246 /* If it's a "force 404" situation then display the error and bail. */
247 void do_404(void)
248 {
249         hprintf("HTTP/1.1 404 Not found\r\n");
250         hprintf("Content-Type: text/plain\r\n");
251         wprintf("Not found\r\n");
252         end_burst();
253 }
254
255 int ReadHttpSubject(ParsedHttpHdrs *Hdr, StrBuf *Line, StrBuf *Buf)
256 {
257         const char *Args;
258         void *vLine, *vHandler;
259         const char *Pos = NULL;
260
261
262         Hdr->HR.ReqLine = Line;
263         /* The requesttype... GET, POST... */
264         StrBufExtract_token(Buf, Hdr->HR.ReqLine, 0, ' ');
265         if (GetHash(HttpReqTypes, SKEY(Buf), &vLine) &&
266             (vLine != NULL))
267         {
268                 Hdr->HR.eReqType = *(long*)vLine;
269         }
270         else {
271                 Hdr->HR.eReqType = eGET;
272                 return 1;
273         }
274         StrBufCutLeft(Hdr->HR.ReqLine, StrLength(Buf) + 1);
275
276         /* the HTTP Version... */
277         StrBufExtract_token(Buf, Hdr->HR.ReqLine, 1, ' ');
278         StrBufCutRight(Hdr->HR.ReqLine, StrLength(Buf) + 1);
279         
280         if (StrLength(Buf) == 0) {
281                 Hdr->HR.eReqType = eGET;
282                 return 1;
283         }
284
285         StrBufAppendBuf(Hdr->this_page, Hdr->HR.ReqLine, 0);
286         /* chop Filename / query arguments */
287         Args = strchr(ChrPtr(Hdr->HR.ReqLine), '?');
288         if (Args == NULL) /* whe're not that picky about params... TODO: this will spoil '&' in filenames.*/
289                 Args = strchr(ChrPtr(Hdr->HR.ReqLine), '&');
290         if (Args != NULL) {
291                 Args ++; /* skip the ? */
292                 StrBufPlain(Hdr->PlainArgs, 
293                             Args, 
294                             StrLength(Hdr->HR.ReqLine) -
295                             (Args - ChrPtr(Hdr->HR.ReqLine)));
296                 StrBufCutAt(Hdr->HR.ReqLine, 0, Args - 1);
297         } /* don't parse them yet, maybe we don't even care... */
298         
299         /* now lookup what we are going to do with this... */
300         /* skip first slash */
301         StrBufExtract_NextToken(Buf, Hdr->HR.ReqLine, &Pos, '/');
302         do {
303                 StrBufExtract_NextToken(Buf, Hdr->HR.ReqLine, &Pos, '/');
304
305                 GetHash(HandlerHash, SKEY(Buf), &vHandler),
306                 Hdr->HR.Handler = (WebcitHandler*) vHandler;
307                 if (Hdr->HR.Handler == NULL)
308                         break;
309                 /*
310                  * If the request is prefixed by "/webcit" then chop that off.  This
311                  * allows a front end web server to forward all /webcit requests to us
312                  * while still using the same web server port for other things.
313                  */
314                 if ((Hdr->HR.Handler->Flags & URLNAMESPACE) != 0)
315                         continue;
316                 break;
317         } while (1);
318         /* remove the handlername from the URL */
319         if ((Pos != NULL) && (Pos != StrBufNOTNULL)){
320                 StrBufCutLeft(Hdr->HR.ReqLine, 
321                               Pos - ChrPtr(Hdr->HR.ReqLine));
322         }
323
324         if (Hdr->HR.Handler != NULL) {
325                 if ((Hdr->HR.Handler->Flags & BOGUS) != 0)
326                         return 1;
327                 Hdr->HR.DontNeedAuth = (
328                         ((Hdr->HR.Handler->Flags & ISSTATIC) != 0) ||
329                         ((Hdr->HR.Handler->Flags & ANONYMOUS) != 0)
330                         );
331         }
332         else {
333                 Hdr->HR.DontNeedAuth = 1; /* Flat request? show him the login screen... */
334         }
335
336         return 0;
337 }
338
339 int AnalyseHeaders(ParsedHttpHdrs *Hdr)
340 {
341         OneHttpHeader *pHdr;
342         void *vHdr;
343         long HKLen;
344         const char *HashKey;
345         HashPos *at = GetNewHashPos(Hdr->HTTPHeaders, 0);
346         
347         while (GetNextHashPos(Hdr->HTTPHeaders, at, &HKLen, &HashKey, &vHdr) && 
348                (vHdr != NULL)) {
349                 pHdr = (OneHttpHeader *)vHdr;
350                 if (pHdr->HaveEvaluator)
351                         pHdr->H(pHdr->Val, Hdr);
352
353         }
354         DeleteHashPos(&at);
355         return 0;
356 }
357
358 /*const char *nix(void *vptr) {return ChrPtr( (StrBuf*)vptr);}*/
359
360 /*
361  * Read in the request
362  */
363 int ReadHTTPRequest (ParsedHttpHdrs *Hdr)
364 {
365         const char *pch, *pchs, *pche;
366         OneHttpHeader *pHdr;
367         StrBuf *Line, *LastLine, *HeaderName;
368         int nLine = 0;
369         void *vF;
370         int isbogus = 0;
371
372         HeaderName = NewStrBuf();
373         LastLine = NULL;
374         do {
375                 nLine ++;
376                 Line = NewStrBufPlain(NULL, SIZ / 4);
377
378                 if (ClientGetLine(Hdr, Line) < 0) return 1;
379
380                 if (StrLength(Line) == 0) {
381                         FreeStrBuf(&Line);
382                         continue;
383                 }
384                 if (nLine == 1) {
385                         Hdr->HTTPHeaders = NewHash(1, NULL);
386                         pHdr = (OneHttpHeader*) malloc(sizeof(OneHttpHeader));
387                         memset(pHdr, 0, sizeof(OneHttpHeader));
388                         pHdr->Val = Line;
389                         Put(Hdr->HTTPHeaders, HKEY("GET /"), pHdr, DestroyHttpHeaderHandler);
390                         lprintf(9, "%s\n", ChrPtr(Line));
391                         isbogus = ReadHttpSubject(Hdr, Line, HeaderName);
392                         if (isbogus) break;
393                         continue;
394                 }
395
396                 /* Do we need to Unfold? */
397                 if ((LastLine != NULL) && 
398                     (isspace(*ChrPtr(Line)))) {
399                         pch = pchs = ChrPtr(Line);
400                         pche = pchs + StrLength(Line);
401                         while (isspace(*pch) && (pch < pche))
402                                 pch ++;
403                         StrBufCutLeft(Line, pch - pchs);
404                         StrBufAppendBuf(LastLine, Line, 0);
405
406                         FreeStrBuf(&Line);
407                         continue;
408                 }
409
410                 StrBufSanitizeAscii(Line, '§');
411                 StrBufExtract_token(HeaderName, Line, 0, ':');
412
413                 pchs = ChrPtr(Line);
414                 pch = pchs + StrLength(HeaderName) + 1;
415                 pche = pchs + StrLength(Line);
416                 while (isspace(*pch) && (pch < pche))
417                         pch ++;
418                 StrBufCutLeft(Line, pch - pchs);
419
420                 StrBufUpCase(HeaderName);
421
422                 pHdr = (OneHttpHeader*) malloc(sizeof(OneHttpHeader));
423                 memset(pHdr, 0, sizeof(OneHttpHeader));
424                 pHdr->Val = Line;
425
426                 if (GetHash(HttpHeaderHandler, SKEY(HeaderName), &vF) &&
427                     (vF != NULL))
428                 {
429                         OneHttpHeader *FHdr = (OneHttpHeader*) vF;
430                         pHdr->H = FHdr->H;
431                         pHdr->HaveEvaluator = 1;
432                 }
433                 Put(Hdr->HTTPHeaders, SKEY(HeaderName), pHdr, DestroyHttpHeaderHandler);
434                 LastLine = Line;
435         } while (Line != NULL);
436
437         FreeStrBuf(&HeaderName);
438
439         return isbogus;
440 }
441
442 void OverrideRequest(ParsedHttpHdrs *Hdr, const char *Line, long len)
443 {
444         StrBuf *Buf = NewStrBuf();
445
446         FlushStrBuf(Hdr->HR.ReqLine);
447         StrBufPlain(Hdr->HR.ReqLine, Line, len);
448         ReadHttpSubject(Hdr, Hdr->HR.ReqLine, Buf);
449
450         FreeStrBuf(&Buf);
451 }
452
453 /*
454  * handle one request
455  *
456  * This loop gets called once for every HTTP connection made to WebCit.  At
457  * this entry point we have an HTTP socket with a browser allegedly on the
458  * other end, but we have not yet bound to a WebCit session.
459  *
460  * The job of this function is to locate the correct session and bind to it,
461  * or create a session if necessary and bind to it, then run the WebCit
462  * transaction loop.  Afterwards, we unbind from the session.  When this
463  * function returns, the worker thread is then free to handle another
464  * transaction.
465  */
466 void context_loop(ParsedHttpHdrs *Hdr)
467 {
468         int isbogus = 0;
469         wcsession *TheSession;
470         struct timeval tx_start;
471         struct timeval tx_finish;
472         
473         gettimeofday(&tx_start, NULL);          /* start a stopwatch for performance timing */
474
475         /*
476          * Find out what it is that the web browser is asking for
477          */
478         isbogus = ReadHTTPRequest(Hdr);
479
480         Hdr->HR.dav_depth = 32767; /* TODO: find a general way to have non-0 defaults */
481         if (!isbogus)
482                 isbogus = AnalyseHeaders(Hdr);
483
484         if ((isbogus) ||
485             ((Hdr->HR.Handler != NULL) &&
486              ((Hdr->HR.Handler->Flags & BOGUS) != 0)))
487         {
488                 wcsession *Bogus;
489
490                 Bogus = CreateSession(0, NULL, Hdr, NULL);
491
492                 do_404();
493
494                 lprintf(9, "HTTP: 404 [%ld.%06ld] %s %s \n",
495                         ((tx_finish.tv_sec*1000000 + tx_finish.tv_usec) - (tx_start.tv_sec*1000000 + tx_start.tv_usec)) / 1000000,
496                         ((tx_finish.tv_sec*1000000 + tx_finish.tv_usec) - (tx_start.tv_sec*1000000 + tx_start.tv_usec)) % 1000000,
497                         ReqStrs[Hdr->HR.eReqType],
498                         ChrPtr(Hdr->this_page)
499                         );
500                 session_detach_modules(Bogus);
501                 session_destroy_modules(&Bogus);
502                 return;
503         }
504
505         if ((Hdr->HR.Handler != NULL) && ((Hdr->HR.Handler->Flags & ISSTATIC) != 0))
506         {
507                 wcsession *Static;
508                 Static = CreateSession(0, NULL, Hdr, NULL);
509                 
510                 Hdr->HR.Handler->F();
511
512                 /* How long did this transaction take? */
513                 gettimeofday(&tx_finish, NULL);
514                 
515 #ifdef TECH_PREVIEW
516                 if ((Hdr->HR.Handler != NULL) ||
517                     ((Hdr->HR.Handler->Flags & LOGCHATTY) == 0))
518 #endif
519                         lprintf(9, "HTTP: 200 [%ld.%06ld] %s %s \n",
520                                 ((tx_finish.tv_sec*1000000 + tx_finish.tv_usec) - (tx_start.tv_sec*1000000 + tx_start.tv_usec)) / 1000000,
521                                 ((tx_finish.tv_sec*1000000 + tx_finish.tv_usec) - (tx_start.tv_sec*1000000 + tx_start.tv_usec)) % 1000000,
522                                 ReqStrs[Hdr->HR.eReqType],
523                                 ChrPtr(Hdr->this_page)
524                                 );
525                 session_detach_modules(Static);
526                 session_destroy_modules(&Static);
527                 return;
528         }
529
530         if (Hdr->HR.got_auth == AUTH_BASIC) {
531                 CheckAuthBasic(Hdr);
532         }
533
534         /*
535          * See if there's an existing session open with the desired ID or user/pass
536          */
537         TheSession = FindSession(&SessionList, Hdr, &SessionListMutex);
538
539         /*
540          * Create a new session if we have to
541          */
542         if (TheSession == NULL) {
543                 TheSession = CreateSession(1, &SessionList, Hdr, &SessionListMutex);
544
545                 if ((StrLength(Hdr->c_username) == 0) && (!Hdr->HR.DontNeedAuth)) {
546
547                         if ((Hdr->HR.Handler != NULL) && 
548                             (XHTTP_COMMANDS & Hdr->HR.Handler->Flags) == XHTTP_COMMANDS) {
549                                 OverrideRequest(Hdr, HKEY("GET /401 HTTP/1.0"));
550                                 Hdr->HR.prohibit_caching = 1;                           
551                         }
552                         else {
553                                 OverrideRequest(Hdr, HKEY("GET /static/nocookies.html?force_close_session=yes HTTP/1.0"));
554                                 Hdr->HR.prohibit_caching = 1;
555                         }
556                 }
557                 
558                 if (StrLength(Hdr->c_language) > 0) {
559                         lprintf(9, "Session cookie requests language '%s'\n", ChrPtr(Hdr->c_language));
560                         set_selected_language(ChrPtr(Hdr->c_language));
561                         go_selected_language();
562                 }
563         }
564
565         /*
566          * A future improvement might be to check the session integrity
567          * at this point before continuing.
568          */
569
570         /*
571          * Bind to the session and perform the transaction
572          */
573         pthread_mutex_lock(&TheSession->SessionMutex);          /* bind */
574         pthread_setspecific(MyConKey, (void *)TheSession);
575         
576         TheSession->lastreq = time(NULL);                       /* log */
577         TheSession->Hdr = Hdr;
578
579         session_attach_modules(TheSession);
580         session_loop();                         /* do transaction */
581
582
583         /* How long did this transaction take? */
584         gettimeofday(&tx_finish, NULL);
585         
586
587 #ifdef TECH_PREVIEW
588         if ((Hdr->HR.Handler != NULL) &&
589             ((Hdr->HR.Handler->Flags & LOGCHATTY) == 0))
590 #endif
591                 lprintf(9, "HTTP: 200 [%ld.%06ld] %s %s \n",
592                         ((tx_finish.tv_sec*1000000 + tx_finish.tv_usec) - (tx_start.tv_sec*1000000 + tx_start.tv_usec)) / 1000000,
593                         ((tx_finish.tv_sec*1000000 + tx_finish.tv_usec) - (tx_start.tv_sec*1000000 + tx_start.tv_usec)) % 1000000,
594                         ReqStrs[Hdr->HR.eReqType],
595                         ChrPtr(Hdr->this_page)
596                         );
597
598         session_detach_modules(TheSession);
599
600         TheSession->Hdr = NULL;
601         pthread_mutex_unlock(&TheSession->SessionMutex);        /* unbind */
602 }
603
604 void tmplput_nonce(StrBuf *Target, WCTemplputParams *TP)
605 {
606         wcsession *WCC = WC;
607         StrBufAppendPrintf(Target, "%ld",
608                            (WCC != NULL)? WCC->nonce:0);                   
609 }
610
611 void tmplput_current_user(StrBuf *Target, WCTemplputParams *TP)
612 {
613         StrBufAppendTemplate(Target, TP, WC->wc_fullname, 0);
614 }
615
616 void tmplput_current_room(StrBuf *Target, WCTemplputParams *TP)
617 {
618         StrBufAppendTemplate(Target, TP, WC->wc_roomname, 0); 
619 }
620
621 void Header_HandleContentLength(StrBuf *Line, ParsedHttpHdrs *hdr)
622 {
623         hdr->HR.ContentLength = StrToi(Line);
624 }
625
626 void Header_HandleContentType(StrBuf *Line, ParsedHttpHdrs *hdr)
627 {
628         hdr->HR.ContentType = Line;
629 }
630
631 void Header_HandleUserAgent(StrBuf *Line, ParsedHttpHdrs *hdr)
632 {
633         hdr->HR.user_agent = Line;
634 #ifdef TECH_PREVIEW
635 /* TODO: do this later on session creating
636         if ((WCC->is_mobile < 0) && is_mobile_ua(&buf[12])) {                   
637                 WCC->is_mobile = 1;
638         }
639         else {
640                 WCC->is_mobile = 0;
641         }
642 */
643 #endif
644 }
645
646
647 void Header_HandleHost(StrBuf *Line, ParsedHttpHdrs *hdr)
648 {
649         if ((follow_xff) && (hdr->HR.http_host != NULL))
650                 return;
651         else
652                 hdr->HR.http_host = Line;
653 }
654
655 void Header_HandleXFFHost(StrBuf *Line, ParsedHttpHdrs *hdr)
656 {
657         if (follow_xff)
658                 hdr->HR.http_host = Line;
659 }
660
661
662 void Header_HandleXFF(StrBuf *Line, ParsedHttpHdrs *hdr)
663 {
664         hdr->HR.browser_host = Line;
665
666         while (StrBufNum_tokens(hdr->HR.browser_host, ',') > 1) {
667                 StrBufRemove_token(hdr->HR.browser_host, 0, ',');
668         }
669         StrBufTrim(hdr->HR.browser_host);
670 }
671
672 void Header_HandleIfModSince(StrBuf *Line, ParsedHttpHdrs *hdr)
673 {
674         hdr->HR.if_modified_since = httpdate_to_timestamp(Line);
675 }
676
677 void Header_HandleAcceptEncoding(StrBuf *Line, ParsedHttpHdrs *hdr)
678 {
679         /*
680          * Can we compress?
681          */
682         if (strstr(&ChrPtr(Line)[16], "gzip")) {
683                 hdr->HR.gzip_ok = 1;
684         }
685 }
686 const char *ReqStrs[eNONE] = {
687         "GET",
688         "POST",
689         "OPTIONS",
690         "PROPFIND",
691         "PUT",
692         "DELETE",
693         "HEAD",
694         "MOVE",
695         "COPY"
696 };
697
698 void
699 ServerStartModule_CONTEXT
700 (void)
701 {
702         long *v;
703         HttpReqTypes = NewHash(1, NULL);
704         HttpHeaderHandler = NewHash(1, NULL);
705
706         v = malloc(sizeof(long));
707         *v = eGET;
708         Put(HttpReqTypes, HKEY("GET"), v, NULL);
709
710         v = malloc(sizeof(long));
711         *v = ePOST;
712         Put(HttpReqTypes, HKEY("POST"), v, NULL);
713
714         v = malloc(sizeof(long));
715         *v = eOPTIONS;
716         Put(HttpReqTypes, HKEY("OPTIONS"), v, NULL);
717
718         v = malloc(sizeof(long));
719         *v = ePROPFIND;
720         Put(HttpReqTypes, HKEY("PROPFIND"), v, NULL);
721
722         v = malloc(sizeof(long));
723         *v = ePUT;
724         Put(HttpReqTypes, HKEY("PUT"), v, NULL);
725
726         v = malloc(sizeof(long));
727         *v = eDELETE;
728         Put(HttpReqTypes, HKEY("DELETE"), v, NULL);
729
730         v = malloc(sizeof(long));
731         *v = eHEAD;
732         Put(HttpReqTypes, HKEY("HEAD"), v, NULL);
733
734         v = malloc(sizeof(long));
735         *v = eMOVE;
736         Put(HttpReqTypes, HKEY("MOVE"), v, NULL);
737
738         v = malloc(sizeof(long));
739         *v = eCOPY;
740         Put(HttpReqTypes, HKEY("COPY"), v, NULL);
741 }
742
743 void 
744 ServerShutdownModule_CONTEXT
745 (void)
746 {
747         DeleteHash(&HttpReqTypes);
748         DeleteHash(&HttpHeaderHandler);
749 }
750
751 void RegisterHeaderHandler(const char *Name, long Len, Header_Evaluator F)
752 {
753         OneHttpHeader *pHdr;
754         pHdr = (OneHttpHeader*) malloc(sizeof(OneHttpHeader));
755         memset(pHdr, 0, sizeof(OneHttpHeader));
756         pHdr->H = F;
757         Put(HttpHeaderHandler, Name, Len, pHdr, DestroyHttpHeaderHandler);
758 }
759
760
761 void 
762 InitModule_CONTEXT
763 (void)
764 {
765         RegisterHeaderHandler(HKEY("CONTENT-LENGTH"), Header_HandleContentLength);
766         RegisterHeaderHandler(HKEY("CONTENT-TYPE"), Header_HandleContentType);
767         RegisterHeaderHandler(HKEY("USER-AGENT"), Header_HandleUserAgent);
768         RegisterHeaderHandler(HKEY("X-FORWARDED-HOST"), Header_HandleXFFHost); /* Apache way... */
769         RegisterHeaderHandler(HKEY("X-REAL-IP"), Header_HandleXFFHost);        /* NGinX way... */
770         RegisterHeaderHandler(HKEY("HOST"), Header_HandleHost);
771         RegisterHeaderHandler(HKEY("X-FORWARDED-FOR"), Header_HandleXFF);
772         RegisterHeaderHandler(HKEY("ACCEPT-ENCODING"), Header_HandleAcceptEncoding);
773         RegisterHeaderHandler(HKEY("IF-MODIFIED-SINCE"), Header_HandleIfModSince);
774
775         RegisterNamespace("CURRENT_USER", 0, 1, tmplput_current_user, NULL, CTX_NONE);
776         RegisterNamespace("CURRENT_ROOM", 0, 1, tmplput_current_room, NULL, CTX_NONE);
777         RegisterNamespace("NONCE", 0, 0, tmplput_nonce, NULL, 0);
778
779         WebcitAddUrlHandler(HKEY("404"), do_404, ANONYMOUS|COOKIEUNNEEDED);
780 /*
781  * Look for commonly-found probes of malware such as worms, viruses, trojans, and Microsoft Office.
782  * Short-circuit these requests so we don't have to send them through the full processing loop.
783  */
784         WebcitAddUrlHandler(HKEY("scripts"), do_404, ANONYMOUS|BOGUS);          /* /root.exe - Worms and trojans and viruses, oh my! */
785         WebcitAddUrlHandler(HKEY("c"), do_404, ANONYMOUS|BOGUS);                /* /winnt */
786         WebcitAddUrlHandler(HKEY("MSADC"), do_404, ANONYMOUS|BOGUS);
787         WebcitAddUrlHandler(HKEY("_vti"), do_404, ANONYMOUS|BOGUS);             /* Broken Microsoft DAV implementation */
788         WebcitAddUrlHandler(HKEY("MSOffice"), do_404, ANONYMOUS|BOGUS);         /* Stoopid MSOffice thinks everyone is IIS */
789         WebcitAddUrlHandler(HKEY("nonexistenshit"), do_404, ANONYMOUS|BOGUS);   /* Exploit found in the wild January 2009 */
790 }
791         
792
793 void 
794 HttpNewModule_CONTEXT
795 (ParsedHttpHdrs *httpreq)
796 {
797         httpreq->PlainArgs = NewStrBufPlain(NULL, SIZ);
798         httpreq->this_page = NewStrBufPlain(NULL, SIZ);
799 }
800
801 void 
802 HttpDetachModule_CONTEXT
803 (ParsedHttpHdrs *httpreq)
804 {
805         FlushStrBuf(httpreq->PlainArgs);
806         FlushStrBuf(httpreq->this_page);
807         FlushStrBuf(httpreq->PlainArgs);
808         DeleteHash(&httpreq->HTTPHeaders);
809         memset(&httpreq->HR, 0, sizeof(HdrRefs));
810 }
811
812 void 
813 HttpDestroyModule_CONTEXT
814 (ParsedHttpHdrs *httpreq)
815 {
816         FreeStrBuf(&httpreq->this_page);
817         FreeStrBuf(&httpreq->PlainArgs);
818         FreeStrBuf(&httpreq->this_page);
819         FreeStrBuf(&httpreq->PlainArgs);
820         DeleteHash(&httpreq->HTTPHeaders);
821
822 }