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