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