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