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