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