9c1dde0afe7f123332576b7f0aabbdf755661ccf
[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 = NULL;
142         wcsession *TheSession = NULL;   
143         
144         if (Hdr->HR.got_auth == AUTH_BASIC) {
145                 GetAuthBasic(Hdr);
146         }
147
148         pthread_mutex_lock(ListMutex);
149         for (sptr = *wclist; ((sptr != NULL) && (TheSession == NULL)); sptr = sptr->next) {
150                 
151                 /* If HTTP-AUTH, look for a session with matching credentials */
152                 switch (Hdr->HR.got_auth)
153                 {
154                 case AUTH_BASIC:
155                         if ( (Hdr->HR.SessionKey != sptr->SessionKey))
156                                 continue;
157                         if ((!strcasecmp(ChrPtr(Hdr->c_username), ChrPtr(sptr->wc_username))) &&
158                             (!strcasecmp(ChrPtr(Hdr->c_password), ChrPtr(sptr->wc_password))) ) {
159                                 TheSession = sptr;
160                         }
161                         if (TheSession == NULL)
162                                 lprintf(1, "found sessionkey [%ld], but credentials for [%s|%s] didn't match\n",
163                                         Hdr->HR.SessionKey,ChrPtr(Hdr->c_username), ChrPtr(sptr->wc_username));
164                         break;
165                 case AUTH_COOKIE:
166                         /* If cookie-session, look for a session with matching session ID */
167                         if ( (Hdr->HR.desired_session != 0) && 
168                              (sptr->wc_session == Hdr->HR.desired_session)) {
169                                 TheSession = sptr;
170                         }
171                         break;                       
172                 case NO_AUTH:
173                         break;
174                 }
175         }
176         pthread_mutex_unlock(ListMutex);
177         if (TheSession == NULL)
178                 lprintf(1, "didn't find sessionkey [%ld] for user [%s]\n",
179                         Hdr->HR.SessionKey,ChrPtr(Hdr->c_username));
180         return TheSession;
181 }
182
183 wcsession *CreateSession(int Lockable, wcsession **wclist, ParsedHttpHdrs *Hdr, pthread_mutex_t *ListMutex)
184 {
185         wcsession *TheSession;
186         lprintf(3, "Creating a new session\n");
187         TheSession = (wcsession *) malloc(sizeof(wcsession));
188         memset(TheSession, 0, sizeof(wcsession));
189         TheSession->Hdr = Hdr;
190         TheSession->SessionKey = Hdr->HR.SessionKey;
191         TheSession->serv_sock = (-1);
192         TheSession->chat_sock = (-1);
193         TheSession->is_mobile = -1;
194
195         pthread_setspecific(MyConKey, (void *)TheSession);
196         
197         /* If we're recreating a session that expired, it's best to give it the same
198          * session number that it had before.  The client browser ought to pick up
199          * the new session number and start using it, but in some rare situations it
200          * doesn't, and that's a Bad Thing because it causes lots of spurious sessions
201          * to get created.
202          */     
203         if (Hdr->HR.desired_session == 0) {
204                 TheSession->wc_session = GenerateSessionID();
205         }
206         else {
207                 TheSession->wc_session = Hdr->HR.desired_session;
208         }
209
210         session_new_modules(TheSession);
211
212         if (Lockable) {
213                 pthread_mutex_init(&TheSession->SessionMutex, NULL);
214
215                 if (ListMutex != NULL)
216                         pthread_mutex_lock(ListMutex);
217
218                 if (wclist != NULL) {
219                         TheSession->nonce = rand();
220                         TheSession->next = *wclist;
221                         *wclist = TheSession;
222                 }
223                 if (ListMutex != NULL)
224                         pthread_mutex_unlock(ListMutex);
225         }
226         return TheSession;
227 }
228
229
230 /**
231  * \brief Detects a 'mobile' user agent 
232  */
233 int is_mobile_ua(char *user_agent) {
234       if (strstr(user_agent,"iPhone OS") != NULL) {
235         return 1;
236       } else if (strstr(user_agent,"Windows CE") != NULL) {
237         return 1;
238       } else if (strstr(user_agent,"SymbianOS") != NULL) {
239         return 1;
240       } else if (strstr(user_agent, "Opera Mobi") != NULL) {
241         return 1;
242       } else if (strstr(user_agent, "Firefox/2.0.0 Opera 9.51 Beta") != NULL) {
243               /*  For some reason a new install of Opera 9.51beta decided to spoof. */
244           return 1;
245           }
246       return 0;
247 }
248
249 /* If it's a "force 404" situation then display the error and bail. */
250 void do_404(void)
251 {
252         hprintf("HTTP/1.1 404 Not found\r\n");
253         hprintf("Content-Type: text/plain\r\n");
254         wprintf("Not found\r\n");
255         end_burst();
256 }
257
258 int ReadHttpSubject(ParsedHttpHdrs *Hdr, StrBuf *Line, StrBuf *Buf)
259 {
260         const char *Args;
261         void *vLine, *vHandler;
262         const char *Pos = NULL;
263
264
265         Hdr->HR.ReqLine = Line;
266         /* The requesttype... GET, POST... */
267         StrBufExtract_token(Buf, Hdr->HR.ReqLine, 0, ' ');
268         if (GetHash(HttpReqTypes, SKEY(Buf), &vLine) &&
269             (vLine != NULL))
270         {
271                 Hdr->HR.eReqType = *(long*)vLine;
272         }
273         else {
274                 Hdr->HR.eReqType = eGET;
275                 return 1;
276         }
277         StrBufCutLeft(Hdr->HR.ReqLine, StrLength(Buf) + 1);
278
279         /* the HTTP Version... */
280         StrBufExtract_token(Buf, Hdr->HR.ReqLine, 1, ' ');
281         StrBufCutRight(Hdr->HR.ReqLine, StrLength(Buf) + 1);
282         
283         if (StrLength(Buf) == 0) {
284                 Hdr->HR.eReqType = eGET;
285                 return 1;
286         }
287
288         StrBufAppendBuf(Hdr->this_page, Hdr->HR.ReqLine, 0);
289         /* chop Filename / query arguments */
290         Args = strchr(ChrPtr(Hdr->HR.ReqLine), '?');
291         if (Args == NULL) /* whe're not that picky about params... TODO: this will spoil '&' in filenames.*/
292                 Args = strchr(ChrPtr(Hdr->HR.ReqLine), '&');
293         if (Args != NULL) {
294                 Args ++; /* skip the ? */
295                 StrBufPlain(Hdr->PlainArgs, 
296                             Args, 
297                             StrLength(Hdr->HR.ReqLine) -
298                             (Args - ChrPtr(Hdr->HR.ReqLine)));
299                 StrBufCutAt(Hdr->HR.ReqLine, 0, Args - 1);
300         } /* don't parse them yet, maybe we don't even care... */
301         
302         /* now lookup what we are going to do with this... */
303         /* skip first slash */
304         StrBufExtract_NextToken(Buf, Hdr->HR.ReqLine, &Pos, '/');
305         do {
306                 StrBufExtract_NextToken(Buf, Hdr->HR.ReqLine, &Pos, '/');
307
308                 GetHash(HandlerHash, SKEY(Buf), &vHandler),
309                 Hdr->HR.Handler = (WebcitHandler*) vHandler;
310                 if (Hdr->HR.Handler == NULL)
311                         break;
312                 /*
313                  * If the request is prefixed by "/webcit" then chop that off.  This
314                  * allows a front end web server to forward all /webcit requests to us
315                  * while still using the same web server port for other things.
316                  */
317                 if ((Hdr->HR.Handler->Flags & URLNAMESPACE) != 0)
318                         continue;
319                 break;
320         } while (1);
321         /* remove the handlername from the URL */
322         if ((Pos != NULL) && (Pos != StrBufNOTNULL)){
323                 StrBufCutLeft(Hdr->HR.ReqLine, 
324                               Pos - ChrPtr(Hdr->HR.ReqLine));
325         }
326
327         if (Hdr->HR.Handler != NULL) {
328                 if ((Hdr->HR.Handler->Flags & BOGUS) != 0)
329                         return 1;
330                 Hdr->HR.DontNeedAuth = (
331                         ((Hdr->HR.Handler->Flags & ISSTATIC) != 0) ||
332                         ((Hdr->HR.Handler->Flags & ANONYMOUS) != 0)
333                         );
334         }
335         else {
336                 Hdr->HR.DontNeedAuth = 1; /* Flat request? show him the login screen... */
337         }
338
339         return 0;
340 }
341
342 int AnalyseHeaders(ParsedHttpHdrs *Hdr)
343 {
344         OneHttpHeader *pHdr;
345         void *vHdr;
346         long HKLen;
347         const char *HashKey;
348         HashPos *at = GetNewHashPos(Hdr->HTTPHeaders, 0);
349         
350         while (GetNextHashPos(Hdr->HTTPHeaders, at, &HKLen, &HashKey, &vHdr) && 
351                (vHdr != NULL)) {
352                 pHdr = (OneHttpHeader *)vHdr;
353                 if (pHdr->HaveEvaluator)
354                         pHdr->H(pHdr->Val, Hdr);
355
356         }
357         DeleteHashPos(&at);
358         return 0;
359 }
360
361 /*const char *nix(void *vptr) {return ChrPtr( (StrBuf*)vptr);}*/
362
363 /*
364  * Read in the request
365  */
366 int ReadHTTPRequest (ParsedHttpHdrs *Hdr)
367 {
368         const char *pch, *pchs, *pche;
369         OneHttpHeader *pHdr;
370         StrBuf *Line, *LastLine, *HeaderName;
371         int nLine = 0;
372         void *vF;
373         int isbogus = 0;
374
375         HeaderName = NewStrBuf();
376         LastLine = NULL;
377         do {
378                 nLine ++;
379                 Line = NewStrBufPlain(NULL, SIZ / 4);
380
381                 if (ClientGetLine(Hdr, Line) < 0) return 1;
382
383                 if (StrLength(Line) == 0) {
384                         FreeStrBuf(&Line);
385                         continue;
386                 }
387                 if (nLine == 1) {
388                         Hdr->HTTPHeaders = NewHash(1, NULL);
389                         pHdr = (OneHttpHeader*) malloc(sizeof(OneHttpHeader));
390                         memset(pHdr, 0, sizeof(OneHttpHeader));
391                         pHdr->Val = Line;
392                         Put(Hdr->HTTPHeaders, HKEY("GET /"), pHdr, DestroyHttpHeaderHandler);
393                         lprintf(9, "%s\n", ChrPtr(Line));
394                         isbogus = ReadHttpSubject(Hdr, Line, HeaderName);
395                         if (isbogus) break;
396                         continue;
397                 }
398
399                 /* Do we need to Unfold? */
400                 if ((LastLine != NULL) && 
401                     (isspace(*ChrPtr(Line)))) {
402                         pch = pchs = ChrPtr(Line);
403                         pche = pchs + StrLength(Line);
404                         while (isspace(*pch) && (pch < pche))
405                                 pch ++;
406                         StrBufCutLeft(Line, pch - pchs);
407                         StrBufAppendBuf(LastLine, Line, 0);
408
409                         FreeStrBuf(&Line);
410                         continue;
411                 }
412
413                 StrBufSanitizeAscii(Line, '§');
414                 StrBufExtract_token(HeaderName, Line, 0, ':');
415
416                 pchs = ChrPtr(Line);
417                 pch = pchs + StrLength(HeaderName) + 1;
418                 pche = pchs + StrLength(Line);
419                 while (isspace(*pch) && (pch < pche))
420                         pch ++;
421                 StrBufCutLeft(Line, pch - pchs);
422
423                 StrBufUpCase(HeaderName);
424
425                 pHdr = (OneHttpHeader*) malloc(sizeof(OneHttpHeader));
426                 memset(pHdr, 0, sizeof(OneHttpHeader));
427                 pHdr->Val = Line;
428
429                 if (GetHash(HttpHeaderHandler, SKEY(HeaderName), &vF) &&
430                     (vF != NULL))
431                 {
432                         OneHttpHeader *FHdr = (OneHttpHeader*) vF;
433                         pHdr->H = FHdr->H;
434                         pHdr->HaveEvaluator = 1;
435                 }
436                 Put(Hdr->HTTPHeaders, SKEY(HeaderName), pHdr, DestroyHttpHeaderHandler);
437                 LastLine = Line;
438         } while (Line != NULL);
439
440         FreeStrBuf(&HeaderName);
441
442         return isbogus;
443 }
444
445 void OverrideRequest(ParsedHttpHdrs *Hdr, const char *Line, long len)
446 {
447         StrBuf *Buf = NewStrBuf();
448
449         FlushStrBuf(Hdr->HR.ReqLine);
450         StrBufPlain(Hdr->HR.ReqLine, Line, len);
451         ReadHttpSubject(Hdr, Hdr->HR.ReqLine, Buf);
452
453         FreeStrBuf(&Buf);
454 }
455
456 /*
457  * handle one request
458  *
459  * This loop gets called once for every HTTP connection made to WebCit.  At
460  * this entry point we have an HTTP socket with a browser allegedly on the
461  * other end, but we have not yet bound to a WebCit session.
462  *
463  * The job of this function is to locate the correct session and bind to it,
464  * or create a session if necessary and bind to it, then run the WebCit
465  * transaction loop.  Afterwards, we unbind from the session.  When this
466  * function returns, the worker thread is then free to handle another
467  * transaction.
468  */
469 void context_loop(ParsedHttpHdrs *Hdr)
470 {
471         int isbogus = 0;
472         wcsession *TheSession;
473         struct timeval tx_start;
474         struct timeval tx_finish;
475         
476         gettimeofday(&tx_start, NULL);          /* start a stopwatch for performance timing */
477
478         /*
479          * Find out what it is that the web browser is asking for
480          */
481         isbogus = ReadHTTPRequest(Hdr);
482
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, 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, 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, &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 tmplput_current_room(StrBuf *Target, WCTemplputParams *TP)
619 {
620         StrBufAppendTemplate(Target, TP, WC->wc_roomname, 0); 
621 }
622
623 void Header_HandleContentLength(StrBuf *Line, ParsedHttpHdrs *hdr)
624 {
625         hdr->HR.ContentLength = StrToi(Line);
626 }
627
628 void Header_HandleContentType(StrBuf *Line, ParsedHttpHdrs *hdr)
629 {
630         hdr->HR.ContentType = Line;
631 }
632
633 void Header_HandleUserAgent(StrBuf *Line, ParsedHttpHdrs *hdr)
634 {
635         hdr->HR.user_agent = Line;
636 #ifdef TECH_PREVIEW
637 /* TODO: do this later on session creating
638         if ((WCC->is_mobile < 0) && is_mobile_ua(&buf[12])) {                   
639                 WCC->is_mobile = 1;
640         }
641         else {
642                 WCC->is_mobile = 0;
643         }
644 */
645 #endif
646 }
647
648
649 void Header_HandleHost(StrBuf *Line, ParsedHttpHdrs *hdr)
650 {
651         if ((follow_xff) && (hdr->HR.http_host != NULL))
652                 return;
653         else
654                 hdr->HR.http_host = Line;
655 }
656
657 void Header_HandleXFFHost(StrBuf *Line, ParsedHttpHdrs *hdr)
658 {
659         if (follow_xff)
660                 hdr->HR.http_host = Line;
661 }
662
663
664 void Header_HandleXFF(StrBuf *Line, ParsedHttpHdrs *hdr)
665 {
666         hdr->HR.browser_host = Line;
667
668         while (StrBufNum_tokens(hdr->HR.browser_host, ',') > 1) {
669                 StrBufRemove_token(hdr->HR.browser_host, 0, ',');
670         }
671         StrBufTrim(hdr->HR.browser_host);
672 }
673
674 void Header_HandleIfModSince(StrBuf *Line, ParsedHttpHdrs *hdr)
675 {
676         hdr->HR.if_modified_since = httpdate_to_timestamp(Line);
677 }
678
679 void Header_HandleAcceptEncoding(StrBuf *Line, ParsedHttpHdrs *hdr)
680 {
681         /*
682          * Can we compress?
683          */
684         if (strstr(&ChrPtr(Line)[16], "gzip")) {
685                 hdr->HR.gzip_ok = 1;
686         }
687 }
688 const char *ReqStrs[eNONE] = {
689         "GET",
690         "POST",
691         "OPTIONS",
692         "PROPFIND",
693         "PUT",
694         "DELETE",
695         "HEAD",
696         "MOVE",
697         "COPY"
698 };
699
700 void
701 ServerStartModule_CONTEXT
702 (void)
703 {
704         long *v;
705         HttpReqTypes = NewHash(1, NULL);
706         HttpHeaderHandler = NewHash(1, NULL);
707
708         v = malloc(sizeof(long));
709         *v = eGET;
710         Put(HttpReqTypes, HKEY("GET"), v, NULL);
711
712         v = malloc(sizeof(long));
713         *v = ePOST;
714         Put(HttpReqTypes, HKEY("POST"), v, NULL);
715
716         v = malloc(sizeof(long));
717         *v = eOPTIONS;
718         Put(HttpReqTypes, HKEY("OPTIONS"), v, NULL);
719
720         v = malloc(sizeof(long));
721         *v = ePROPFIND;
722         Put(HttpReqTypes, HKEY("PROPFIND"), v, NULL);
723
724         v = malloc(sizeof(long));
725         *v = ePUT;
726         Put(HttpReqTypes, HKEY("PUT"), v, NULL);
727
728         v = malloc(sizeof(long));
729         *v = eDELETE;
730         Put(HttpReqTypes, HKEY("DELETE"), v, NULL);
731
732         v = malloc(sizeof(long));
733         *v = eHEAD;
734         Put(HttpReqTypes, HKEY("HEAD"), v, NULL);
735
736         v = malloc(sizeof(long));
737         *v = eMOVE;
738         Put(HttpReqTypes, HKEY("MOVE"), v, NULL);
739
740         v = malloc(sizeof(long));
741         *v = eCOPY;
742         Put(HttpReqTypes, HKEY("COPY"), v, NULL);
743 }
744
745 void 
746 ServerShutdownModule_CONTEXT
747 (void)
748 {
749         DeleteHash(&HttpReqTypes);
750         DeleteHash(&HttpHeaderHandler);
751 }
752
753 void RegisterHeaderHandler(const char *Name, long Len, Header_Evaluator F)
754 {
755         OneHttpHeader *pHdr;
756         pHdr = (OneHttpHeader*) malloc(sizeof(OneHttpHeader));
757         memset(pHdr, 0, sizeof(OneHttpHeader));
758         pHdr->H = F;
759         Put(HttpHeaderHandler, Name, Len, pHdr, DestroyHttpHeaderHandler);
760 }
761
762
763 void 
764 InitModule_CONTEXT
765 (void)
766 {
767         RegisterHeaderHandler(HKEY("CONTENT-LENGTH"), Header_HandleContentLength);
768         RegisterHeaderHandler(HKEY("CONTENT-TYPE"), Header_HandleContentType);
769         RegisterHeaderHandler(HKEY("USER-AGENT"), Header_HandleUserAgent);
770         RegisterHeaderHandler(HKEY("X-FORWARDED-HOST"), Header_HandleXFFHost);
771         RegisterHeaderHandler(HKEY("HOST"), Header_HandleHost);
772         RegisterHeaderHandler(HKEY("X-FORWARDED-FOR"), Header_HandleXFF);
773         RegisterHeaderHandler(HKEY("ACCEPT-ENCODING"), Header_HandleAcceptEncoding);
774         RegisterHeaderHandler(HKEY("IF-MODIFIED-SINCE"), Header_HandleIfModSince);
775
776         RegisterNamespace("CURRENT_USER", 0, 1, tmplput_current_user, CTX_NONE);
777         RegisterNamespace("CURRENT_ROOM", 0, 1, tmplput_current_room, CTX_NONE);
778         RegisterNamespace("NONCE", 0, 0, tmplput_nonce, 0);
779
780         WebcitAddUrlHandler(HKEY("404"), do_404, ANONYMOUS|COOKIEUNNEEDED);
781 /*
782  * Look for commonly-found probes of malware such as worms, viruses, trojans, and Microsoft Office.
783  * Short-circuit these requests so we don't have to send them through the full processing loop.
784  */
785         WebcitAddUrlHandler(HKEY("scripts"), do_404, ANONYMOUS|BOGUS);          /* /root.exe - Worms and trojans and viruses, oh my! */
786         WebcitAddUrlHandler(HKEY("c"), do_404, ANONYMOUS|BOGUS);                /* /winnt */
787         WebcitAddUrlHandler(HKEY("MSADC"), do_404, ANONYMOUS|BOGUS);
788         WebcitAddUrlHandler(HKEY("_vti"), do_404, ANONYMOUS|BOGUS);             /* Broken Microsoft DAV implementation */
789         WebcitAddUrlHandler(HKEY("MSOffice"), do_404, ANONYMOUS|BOGUS);         /* Stoopid MSOffice thinks everyone is IIS */
790         WebcitAddUrlHandler(HKEY("nonexistenshit"), do_404, ANONYMOUS|BOGUS);   /* Exploit found in the wild January 2009 */
791 }
792         
793
794 void 
795 HttpNewModule_CONTEXT
796 (ParsedHttpHdrs *httpreq)
797 {
798         httpreq->PlainArgs = NewStrBufPlain(NULL, SIZ);
799         httpreq->this_page = NewStrBufPlain(NULL, SIZ);
800 }
801
802 void 
803 HttpDetachModule_CONTEXT
804 (ParsedHttpHdrs *httpreq)
805 {
806         FlushStrBuf(httpreq->PlainArgs);
807         FlushStrBuf(httpreq->this_page);
808         FlushStrBuf(httpreq->PlainArgs);
809         DeleteHash(&httpreq->HTTPHeaders);
810         memset(&httpreq->HR, 0, sizeof(HdrRefs));
811 }
812
813 void 
814 HttpDestroyModule_CONTEXT
815 (ParsedHttpHdrs *httpreq)
816 {
817         FreeStrBuf(&httpreq->this_page);
818         FreeStrBuf(&httpreq->PlainArgs);
819         FreeStrBuf(&httpreq->this_page);
820         FreeStrBuf(&httpreq->PlainArgs);
821         DeleteHash(&httpreq->HTTPHeaders);
822
823 }