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