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