* BIG rewrite of header handling and slimming of context_loop and session_loop; shuff...
[citadel.git] / webcit / context_loop.c
1 /*
2  * $Id$
3  *
4  * This is the other half of the webserver.  It handles the task of hooking
5  * up HTTP requests with the sessions they belong to, using HTTP cookies to
6  * keep track of things.  If the HTTP request doesn't belong to any currently
7  * active session, a new session is started.
8  *
9  */
10
11 #include "webcit.h"
12 #include "webserver.h"
13 #include "modules_init.h"
14
15 /* Only one thread may manipulate SessionList at a time... */
16 pthread_mutex_t SessionListMutex;
17
18 wcsession *SessionList = NULL; /**< our sessions ????*/
19
20 pthread_key_t MyConKey;         /**< TSD key for MySession() */
21 HashList *HttpReqTypes = NULL;
22 HashList *HttpHeaderHandler = NULL;
23 extern HashList *HandlerHash;
24
25 void DestroyHttpHeaderHandler(void *V)
26 {
27         OneHttpHeader *pHdr;
28         pHdr = (OneHttpHeader*) V;
29         FreeStrBuf(&pHdr->Val);
30         free(pHdr);
31 }
32
33 void shutdown_sessions(void)
34 {
35         wcsession *sptr;
36         
37         for (sptr = SessionList; sptr != NULL; sptr = sptr->next) {
38                         sptr->killthis = 1;
39         }
40 }
41
42 void do_housekeeping(void)
43 {
44         wcsession *sptr, *ss;
45         wcsession *sessions_to_kill = NULL;
46         int num_sessions = 0;
47         static int num_threads = MIN_WORKER_THREADS;
48
49         /**
50          * Lock the session list, moving any candidates for euthanasia into
51          * a separate list.
52          */
53         pthread_mutex_lock(&SessionListMutex);
54         num_sessions = 0;
55         for (sptr = SessionList; sptr != NULL; sptr = sptr->next) {
56                 ++num_sessions;
57
58                 /** Kill idle sessions */
59                 if ((time(NULL) - (sptr->lastreq)) >
60                    (time_t) WEBCIT_TIMEOUT) {
61                         sptr->killthis = 1;
62                 }
63
64                 /** Remove sessions flagged for kill */
65                 if (sptr->killthis) {
66
67                         /** remove session from linked list */
68                         if (sptr == SessionList) {
69                                 SessionList = SessionList->next;
70                         }
71                         else for (ss=SessionList;ss!=NULL;ss=ss->next) {
72                                 if (ss->next == sptr) {
73                                         ss->next = ss->next->next;
74                                 }
75                         }
76
77                         sptr->next = sessions_to_kill;
78                         sessions_to_kill = sptr;
79                 }
80         }
81         pthread_mutex_unlock(&SessionListMutex);
82
83         /**
84          * Now free up and destroy the culled sessions.
85          */
86         while (sessions_to_kill != NULL) {
87                 lprintf(3, "Destroying session %d\n", sessions_to_kill->wc_session);
88                 pthread_mutex_lock(&sessions_to_kill->SessionMutex);
89                 pthread_mutex_unlock(&sessions_to_kill->SessionMutex);
90                 sptr = sessions_to_kill->next;
91
92                 session_destroy_modules(&sessions_to_kill);
93                 sessions_to_kill = sptr;
94                 --num_sessions;
95         }
96
97         /**
98          * If there are more sessions than threads, then we should spawn
99          * more threads ... up to a predefined maximum.
100          */
101         while ( (num_sessions > num_threads)
102               && (num_threads <= MAX_WORKER_THREADS) ) {
103                 spawn_another_worker_thread();
104                 ++num_threads;
105                 lprintf(3, "There are %d sessions and %d threads active.\n",
106                         num_sessions, num_threads);
107         }
108 }
109
110
111 /*
112  * Wake up occasionally and clean house
113  */
114 void housekeeping_loop(void)
115 {
116         while (1) {
117                 sleeeeeeeeeep(HOUSEKEEPING);
118                 do_housekeeping();
119         }
120 }
121
122
123 /*
124  * Create a Session id
125  * Generate a unique WebCit session ID (which is not the same thing as the
126  * Citadel session ID).
127  */
128 int GenerateSessionID(void)
129 {
130         static int seq = (-1);
131
132         if (seq < 0) {
133                 seq = (int) time(NULL);
134         }
135                 
136         return ++seq;
137 }
138
139
140 /*
141  * lingering_close() a`la Apache. see
142  * http://www.apache.org/docs/misc/fin_wait_2.html for rationale
143  */
144 int lingering_close(int fd)
145 {
146         char buf[SIZ];
147         int i;
148         fd_set set;
149         struct timeval tv, start;
150
151         gettimeofday(&start, NULL);
152         shutdown(fd, 1);
153         do {
154                 do {
155                         gettimeofday(&tv, NULL);
156                         tv.tv_sec = SLEEPING - (tv.tv_sec - start.tv_sec);
157                         tv.tv_usec = start.tv_usec - tv.tv_usec;
158                         if (tv.tv_usec < 0) {
159                                 tv.tv_sec--;
160                                 tv.tv_usec += 1000000;
161                         }
162                         FD_ZERO(&set);
163                         FD_SET(fd, &set);
164                         i = select(fd + 1, &set, NULL, NULL, &tv);
165                 } while (i == -1 && errno == EINTR);
166
167                 if (i <= 0)
168                         break;
169
170                 i = read(fd, buf, sizeof buf);
171         } while (i != 0 && (i != -1 || errno == EINTR));
172
173         return close(fd);
174 }
175
176
177
178
179 /**
180  * \brief Detects a 'mobile' user agent 
181  */
182 int is_mobile_ua(char *user_agent) {
183       if (strstr(user_agent,"iPhone OS") != NULL) {
184         return 1;
185       } else if (strstr(user_agent,"Windows CE") != NULL) {
186         return 1;
187       } else if (strstr(user_agent,"SymbianOS") != NULL) {
188         return 1;
189       } else if (strstr(user_agent, "Opera Mobi") != NULL) {
190         return 1;
191       } else if (strstr(user_agent, "Firefox/2.0.0 Opera 9.51 Beta") != NULL) {
192               /*  For some reason a new install of Opera 9.51beta decided to spoof. */
193           return 1;
194           }
195       return 0;
196 }
197
198
199
200 /*
201  * Look for commonly-found probes of malware such as worms, viruses, trojans, and Microsoft Office.
202  * Short-circuit these requests so we don't have to send them through the full processing loop.
203  */
204 int is_bogus(StrBuf *http_cmd) {////TODO!
205         const char *url;
206         int i, max;
207         const char *bogus_prefixes[] = {
208                 "/scripts/root.exe",    /* Worms and trojans and viruses, oh my! */
209                 "/c/winnt",
210                 "/MSADC/",
211                 "/_vti",                /* Broken Microsoft DAV implementation */
212                 "/MSOffice",            /* Stoopid MSOffice thinks everyone is IIS */
213                 "/nonexistenshit"       /* Exploit found in the wild January 2009 */
214         };
215
216         url = ChrPtr(http_cmd);
217         if (IsEmptyStr(url)) return(1);
218         ++url;
219
220         max = sizeof(bogus_prefixes) / sizeof(char *);
221
222         for (i=0; i<max; ++i) {
223                 if (!strncasecmp(url, bogus_prefixes[i], strlen(bogus_prefixes[i]))) {
224                         return(2);
225                 }
226         }
227
228         return(0);      /* probably ok */
229 }
230
231
232 int ReadHttpSubject(ParsedHttpHdrs *Hdr, StrBuf *Line, StrBuf *Buf)
233 {
234         const char *Args;
235         void *vLine, *vHandler;
236         const char *Pos = NULL;
237
238
239         Hdr->ReqLine = Line;
240         /* The requesttype... GET, POST... */
241         StrBufExtract_token(Buf, Hdr->ReqLine, 0, ' ');
242         if (GetHash(HttpReqTypes, SKEY(Buf), &vLine) &&
243             (vLine != NULL))
244         {
245                 Hdr->eReqType = *(long*)vLine;
246         }
247         else {
248                 Hdr->eReqType = eGET;
249                 return 1;
250         }
251         StrBufCutLeft(Hdr->ReqLine, StrLength(Buf) + 1);
252
253         /* the HTTP Version... */
254         StrBufExtract_token(Buf, Hdr->ReqLine, 1, ' ');
255         StrBufCutRight(Hdr->ReqLine, StrLength(Buf) + 1);
256         if ((StrLength(Buf) == 0) ||
257             is_bogus(Hdr->ReqLine)) {
258                 Hdr->eReqType = eGET;
259                 return 1;
260         }
261
262         Hdr->this_page = NewStrBufDup(Hdr->ReqLine);
263         /* chop Filename / query arguments */
264         Args = strchr(ChrPtr(Hdr->ReqLine), '?');
265         if (Args == NULL) /* whe're not that picky about params... TODO: this will spoil '&' in filenames.*/
266                 Args = strchr(ChrPtr(Hdr->ReqLine), '&');
267         if (Args != NULL) {
268                 Hdr->PlainArgs = NewStrBufPlain(
269                         Args, 
270                         StrLength(Hdr->ReqLine) -
271                         (Args - ChrPtr(Hdr->ReqLine)));
272                 StrBufCutAt(Hdr->ReqLine, 0, Args);
273         } /* don't parse them yet, maybe we don't even care... */
274         
275         /* now lookup what we are going to do with this... */
276         /* skip first slash */
277         StrBufExtract_NextToken(Buf, Hdr->ReqLine, &Pos, '/');
278         do {
279                 StrBufExtract_NextToken(Buf, Hdr->ReqLine, &Pos, '/');
280
281                 GetHash(HandlerHash, SKEY(Buf), &vHandler),
282                 Hdr->Handler = (WebcitHandler*) vHandler;
283                 if (Hdr->Handler == NULL)
284                         break;
285                 /* are we about to ignore some prefix like webcit/ ? */
286                 if ((Hdr->Handler->Flags & URLNAMESPACE) == 0)
287                         break;
288         } while (1);
289         /* remove the handlername from the URL */
290         if (Pos != NULL) {
291                 StrBufCutLeft(Hdr->ReqLine, 
292                               Pos - ChrPtr(Hdr->ReqLine));
293         }
294 /*
295         if (Hdr->Handler == NULL)
296                 return 1;
297 */
298         Hdr->HTTPHeaders = NewHash(1, NULL);
299
300         return 0;
301 }
302
303 int AnalyseHeaders(ParsedHttpHdrs *Hdr)
304 {
305         OneHttpHeader *pHdr;
306         void *vHdr;
307         long HKLen;
308         const char *HashKey;
309         HashPos *at = GetNewHashPos(Hdr->HTTPHeaders, 0);
310         
311         while (GetNextHashPos(Hdr->HTTPHeaders, at, &HKLen, &HashKey, &vHdr) && 
312                (vHdr != NULL)) {
313                 pHdr = (OneHttpHeader *)vHdr;
314                 if (pHdr->HaveEvaluator)
315                         pHdr->H(pHdr->Val, Hdr);
316
317         }
318         DeleteHashPos(&at);
319         return 0;
320 }
321
322 /*const char *nix(void *vptr) {return ChrPtr( (StrBuf*)vptr);}*/
323
324 /*
325  * Read in the request
326  */
327 int ReadHTTPRequset (ParsedHttpHdrs *Hdr)
328 {
329         const char *pch, *pchs, *pche;
330         OneHttpHeader *pHdr;
331         StrBuf *Line, *LastLine, *HeaderName;
332         int nLine = 0;
333         void *vF;
334         int isbogus = 0;
335
336         HeaderName = NewStrBuf();
337         Hdr->ReadBuf = NewStrBuf();
338         LastLine = NULL;
339         do {
340                 nLine ++;
341                 Line = NewStrBuf();
342
343                 if (ClientGetLine(&Hdr->http_sock, Line, Hdr->ReadBuf, &Hdr->Pos) < 0) return 1;
344
345                 if (StrLength(Line) == 0) {
346                         FreeStrBuf(&Line);
347                         continue;
348                 }
349                 if (nLine == 1) {
350                         isbogus = ReadHttpSubject(Hdr, Line, HeaderName);
351                         if (isbogus) break;
352                         continue;
353                 }
354
355                 /* Do we need to Unfold? */
356                 if ((LastLine != NULL) && 
357                     (isspace(*ChrPtr(Line)))) {
358                         pch = pchs = ChrPtr(Line);
359                         pche = pchs + StrLength(Line);
360                         while (isspace(*pch) && (pch < pche))
361                                 pch ++;
362                         StrBufCutLeft(Line, pch - pchs);
363                         StrBufAppendBuf(LastLine, Line, 0);
364                         FreeStrBuf(&Line);
365                         continue;
366                 }
367
368                 StrBufSanitizeAscii(Line, '§');
369                 StrBufExtract_token(HeaderName, Line, 0, ':');
370
371                 pchs = ChrPtr(Line);
372                 pch = pchs + StrLength(HeaderName) + 1;
373                 pche = pchs + StrLength(Line);
374                 while (isspace(*pch) && (pch < pche))
375                         pch ++;
376                 StrBufCutLeft(Line, pch - pchs);
377
378                 StrBufUpCase(HeaderName);
379
380                 pHdr = (OneHttpHeader*) malloc(sizeof(OneHttpHeader));
381                 memset(pHdr, 0, sizeof(OneHttpHeader));
382                 pHdr->Val = Line;
383
384                 if (GetHash(HttpHeaderHandler, SKEY(HeaderName), &vF) &&
385                     (vF != NULL))
386                 {
387                         OneHttpHeader *FHdr = (OneHttpHeader*) vF;
388                         pHdr->H = FHdr->H;
389                         pHdr->HaveEvaluator = 1;
390                 }
391                 Put(Hdr->HTTPHeaders, SKEY(HeaderName), pHdr, DestroyHttpHeaderHandler);
392                 LastLine = Line;
393         } while (Line != NULL);
394
395         FreeStrBuf(&HeaderName);
396
397         return isbogus;
398 }
399
400
401
402 /*
403  * handle one request
404  *
405  * This loop gets called once for every HTTP connection made to WebCit.  At
406  * this entry point we have an HTTP socket with a browser allegedly on the
407  * other end, but we have not yet bound to a WebCit session.
408  *
409  * The job of this function is to locate the correct session and bind to it,
410  * or create a session if necessary and bind to it, then run the WebCit
411  * transaction loop.  Afterwards, we unbind from the session.  When this
412  * function returns, the worker thread is then free to handle another
413  * transaction.
414  */
415 void context_loop(int *sock)
416 {
417         ParsedHttpHdrs Hdr;
418         int isbogus = 0;
419         wcsession *TheSession, *sptr;
420         struct timeval tx_start;
421         struct timeval tx_finish;
422         
423         gettimeofday(&tx_start, NULL);          /* start a stopwatch for performance timing */
424
425         memset(&Hdr, 0, sizeof(ParsedHttpHdrs));
426         Hdr.eReqType = eGET;
427         Hdr.http_sock = *sock;
428         /*
429          * Find out what it is that the web browser is asking for
430          */
431         isbogus = ReadHTTPRequset(&Hdr);
432
433         if (!isbogus)
434                 isbogus = AnalyseHeaders(&Hdr);
435 /*
436         if (isbogus)
437                 StrBufPlain(ReqLine, HKEY("/404"));
438 */
439
440 /*      dbg_PrintHash(HTTPHeaders, nix, NULL);  */
441
442
443 ///HttpHeaderHandler
444
445
446
447
448
449         /*
450          * If the request is prefixed by "/webcit" then chop that off.  This
451          * allows a front end web server to forward all /webcit requests to us
452          * while still using the same web server port for other things.
453          * /
454         if (!isbogus &&
455             (StrLength(ReqLine) >= 8) && 
456             (strstr(ChrPtr(ReqLine), "/webcit/")) ) {
457                 StrBufCutLeft(ReqLine, 7);
458         }
459
460         /* Begin parsing the request. * /
461 #ifdef TECH_PREVIEW
462         if ((strncmp(ChrPtr(ReqLine), "/sslg", 5) != 0) &&
463             (strncmp(ChrPtr(ReqLine), "/static/", 8) != 0) &&
464             (strncmp(ChrPtr(ReqLine), "/tiny_mce/", 10) != 0) &&
465             (strncmp(ChrPtr(ReqLine), "/wholist_section", 16) != 0) &&
466             (strstr(ChrPtr(ReqLine), "wholist_section") == NULL)) {
467 #endif
468                 lprintf(5, "HTTP: %s %s\n", ReqStrs[Hdr.eReqType], ChrPtr(ReqLine));
469 #ifdef TECH_PREVIEW
470         }
471 #endif
472
473 */
474
475         /**
476          * See if there's an existing session open with the desired ID or user/pass
477          */
478         TheSession = NULL;
479
480         if (TheSession == NULL) {
481                 pthread_mutex_lock(&SessionListMutex);
482                 for (sptr = SessionList; 
483                      ((sptr != NULL) && (TheSession == NULL)); 
484                       sptr = sptr->next) {
485
486                         /** If HTTP-AUTH, look for a session with matching credentials * /
487                         if ( (////TODO check auth type here...
488                              &&(!strcasecmp(ChrPtr(sptr->httpauth_user), httpauth_user))
489                              &&(!strcasecmp(ChrPtr(sptr->httpauth_pass), httpauth_pass)) ) {
490                                 TheSession = sptr;
491                         }
492
493                         /** If cookie-session, look for a session with matching session ID */
494                         if ( (Hdr.desired_session != 0) && (sptr->wc_session == Hdr.desired_session)) {
495                                 TheSession = sptr;
496                         }
497
498                 }
499                 pthread_mutex_unlock(&SessionListMutex);
500         }
501
502         /**
503          * Create a new session if we have to
504          */
505         if (TheSession == NULL) {
506                 lprintf(3, "Creating a new session\n");
507                 TheSession = (wcsession *)
508                         malloc(sizeof(wcsession));
509                 memset(TheSession, 0, sizeof(wcsession));
510                 TheSession->Hdr = &Hdr;
511                 TheSession->serv_sock = (-1);
512                 TheSession->chat_sock = (-1);
513         
514                 /* If we're recreating a session that expired, it's best to give it the same
515                  * session number that it had before.  The client browser ought to pick up
516                  * the new session number and start using it, but in some rare situations it
517                  * doesn't, and that's a Bad Thing because it causes lots of spurious sessions
518                  * to get created.
519                  */     
520                 if (Hdr.desired_session == 0) {
521                         TheSession->wc_session = GenerateSessionID();
522                 }
523                 else {
524                         TheSession->wc_session = Hdr.desired_session;
525                 }
526 /*
527                 TheSession->httpauth_user = NewStrBufPlain(httpauth_user, -1);
528                         TheSession->httpauth_pass = NewStrBufPlain(httpauth_user, -1);
529 */
530                 pthread_setspecific(MyConKey, (void *)TheSession);
531                 session_new_modules(TheSession);
532
533                 pthread_mutex_init(&TheSession->SessionMutex, NULL);
534                 pthread_mutex_lock(&SessionListMutex);
535                 TheSession->nonce = rand();
536                 TheSession->next = SessionList;
537                 TheSession->is_mobile = -1;
538                 SessionList = TheSession;
539                 pthread_mutex_unlock(&SessionListMutex);
540         }
541
542         /*
543          * A future improvement might be to check the session integrity
544          * at this point before continuing.
545          */
546
547         /*
548          * Bind to the session and perform the transaction
549          */
550         pthread_mutex_lock(&TheSession->SessionMutex);          /* bind */
551         pthread_setspecific(MyConKey, (void *)TheSession);
552         
553         TheSession->lastreq = time(NULL);                       /* log */
554         TheSession->Hdr = &Hdr;
555
556         session_attach_modules(TheSession);
557         session_loop();                         /* do transaction */
558         session_detach_modules(TheSession);
559
560         TheSession->Hdr = NULL;
561         pthread_mutex_unlock(&TheSession->SessionMutex);        /* unbind */
562 /* TODO
563
564         FreeStrBuf(&c_username);
565         FreeStrBuf(&c_password);
566         FreeStrBuf(&c_roomname);
567         FreeStrBuf(&c_httpauth_user);
568         FreeStrBuf(&c_httpauth_pass);
569 */
570         /* Free the request buffer */
571         ///DeleteHash(&HTTPHeaders);
572         ///FreeStrBuf(&ReqLine);
573         
574         /* How long did this transaction take? */
575         gettimeofday(&tx_finish, NULL);
576         
577         lprintf(9, "Transaction completed in %ld.%06ld seconds.\n",
578                 ((tx_finish.tv_sec*1000000 + tx_finish.tv_usec) - (tx_start.tv_sec*1000000 + tx_start.tv_usec)) / 1000000,
579                 ((tx_finish.tv_sec*1000000 + tx_finish.tv_usec) - (tx_start.tv_sec*1000000 + tx_start.tv_usec)) % 1000000
580         );
581 }
582
583 void tmplput_nonce(StrBuf *Target, WCTemplputParams *TP)
584 {
585         wcsession *WCC = WC;
586         StrBufAppendPrintf(Target, "%ld",
587                            (WCC != NULL)? WCC->nonce:0);                   
588 }
589
590 void tmplput_current_user(StrBuf *Target, WCTemplputParams *TP)
591 {
592         StrBufAppendTemplate(Target, TP, WC->wc_fullname, 0);
593 }
594
595 void tmplput_current_room(StrBuf *Target, WCTemplputParams *TP)
596 {
597         StrBufAppendTemplate(Target, TP, WC->wc_roomname, 0); 
598 }
599
600
601 void Header_HandleCookie(StrBuf *Line, ParsedHttpHdrs *hdr)
602 {
603         hdr->RawCookie = Line;
604         if (hdr->DontNeedAuth)
605                 return;
606 /*
607         c_username = NewStrBuf();
608         c_password = NewStrBuf();
609         c_roomname = NewStrBuf();
610         safestrncpy(c_httpauth_string, "", sizeof c_httpauth_string);
611         c_httpauth_user = NewStrBufPlain(HKEY(DEFAULT_HTTPAUTH_USER));
612         c_httpauth_pass = NewStrBufPlain(HKEY(DEFAULT_HTTPAUTH_PASS));
613 */
614         cookie_to_stuff(Line, &hdr->desired_session,
615                         hdr->c_username,
616                         hdr->c_password,
617                         hdr->c_roomname);
618         hdr->got_cookie = 1;
619 }
620
621
622         /*
623          * Browser-based sessions use cookies for session authentication
624          * /
625         if (!isbogus &&
626             GetHash(HTTPHeaders, HKEY("COOKIE"), &vLine) && 
627             (vLine != NULL)) {
628                 cookie_to_stuff(vLine, &desired_session,
629                                 NULL, NULL, NULL);
630                 got_cookie = 1;
631         }
632         */
633         /*
634          * GroupDAV-based sessions use HTTP authentication
635          */
636 /*
637         if (!isbogus &&
638             GetHash(HTTPHeaders, HKEY("AUTHORIZATION"), &vLine) && 
639             (vLine != NULL)) {
640                 Line = (StrBuf*)vLine;
641                 if (strncasecmp(ChrPtr(Line), "Basic", 5) == 0) {
642                         StrBufCutLeft(Line, 6);
643                         CtdlDecodeBase64(httpauth_string, ChrPtr(Line), StrLength(Line));
644                         extract_token(httpauth_user, httpauth_string, 0, ':', sizeof httpauth_user);
645                         extract_token(httpauth_pass, httpauth_string, 1, ':', sizeof httpauth_pass);
646                 }
647                 else 
648                         lprintf(1, "Authentication scheme not supported! [%s]\n", ChrPtr(Line));
649         }
650
651 */
652 void Header_HandleAuth(StrBuf *Line, ParsedHttpHdrs *hdr)
653 {
654         const char *Pos = NULL;
655         StrBufDecodeBase64(Line);
656         StrBufExtract_NextToken(hdr->c_username, Line, &Pos, ':');
657         StrBufExtract_NextToken(hdr->c_password, Line, &Pos, ':');
658 }
659
660 void Header_HandleContentLength(StrBuf *Line, ParsedHttpHdrs *hdr)
661 {
662         hdr->ContentLength = StrToi(Line);
663 }
664
665 void Header_HandleContentType(StrBuf *Line, ParsedHttpHdrs *hdr)
666 {
667         hdr->ContentType = Line;
668 }
669
670 void Header_HandleUserAgent(StrBuf *Line, ParsedHttpHdrs *hdr)
671 {
672         hdr->user_agent = Line;
673 #ifdef TECH_PREVIEW
674 /* TODO: do this later on session creating
675         if ((WCC->is_mobile < 0) && is_mobile_ua(&buf[12])) {                   
676                 WCC->is_mobile = 1;
677         }
678         else {
679                 WCC->is_mobile = 0;
680         }
681 */
682 #endif
683 }
684
685
686 void Header_HandleHost(StrBuf *Line, ParsedHttpHdrs *hdr)
687 {
688         if ((follow_xff) && (hdr->http_host != NULL))
689                 return;
690         else
691                 hdr->http_host = Line;
692 }
693
694 void Header_HandleXFFHost(StrBuf *Line, ParsedHttpHdrs *hdr)
695 {
696         if (follow_xff)
697                 hdr->http_host = Line;
698 }
699
700
701 void Header_HandleXFF(StrBuf *Line, ParsedHttpHdrs *hdr)
702 {
703         hdr->browser_host = Line;
704
705         while (StrBufNum_tokens(hdr->browser_host, ',') > 1) {
706                 StrBufRemove_token(hdr->browser_host, 0, ',');
707         }
708         StrBufTrim(hdr->browser_host);
709 }
710
711 void Header_HandleIfModSince(StrBuf *Line, ParsedHttpHdrs *hdr)
712 {
713         hdr->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->gzip_ok = 1;
723         }
724 }
725
726 /*
727 {
728         c_username = NewStrBuf();
729         c_password = NewStrBuf();
730         c_roomname = NewStrBuf();
731         safestrncpy(c_httpauth_string, "", sizeof c_httpauth_string);
732         c_httpauth_user = NewStrBufPlain(HKEY(DEFAULT_HTTPAUTH_USER));
733         c_httpauth_pass = NewStrBufPlain(HKEY(DEFAULT_HTTPAUTH_PASS));
734 }
735 */
736         /* *
737          * These are the URL's which may be executed without a
738          * session cookie already set.  If it's not one of these,
739          * force the session to close because cookies are
740          * probably disabled on the client browser.
741          * /
742         else if ( (StrLength(ReqLine) > 1 )
743                 && (strncasecmp(ChrPtr(ReqLine), "/404", 4))
744                 && (Hdr.got_cookie == 0)) {
745                 StrBufPlain(ReqLine, 
746                             HKEY("/static/nocookies.html"
747                                  "?force_close_session=yes"));
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 };
761
762 void
763 ServerStartModule_CONTEXT
764 (void)
765 {
766         long *v;
767         HttpReqTypes = NewHash(1, NULL);
768         HttpHeaderHandler = NewHash(1, NULL);
769
770         v = malloc(sizeof(long));
771         *v = eGET;
772         Put(HttpReqTypes, HKEY("GET"), v, NULL);
773
774         v = malloc(sizeof(long));
775         *v = ePOST;
776         Put(HttpReqTypes, HKEY("POST"), v, NULL);
777
778         v = malloc(sizeof(long));
779         *v = eOPTIONS;
780         Put(HttpReqTypes, HKEY("OPTIONS"), v, NULL);
781
782         v = malloc(sizeof(long));
783         *v = ePROPFIND;
784         Put(HttpReqTypes, HKEY("PROPFIND"), v, NULL);
785
786         v = malloc(sizeof(long));
787         *v = ePUT;
788         Put(HttpReqTypes, HKEY("PUT"), v, NULL);
789
790         v = malloc(sizeof(long));
791         *v = eDELETE;
792         Put(HttpReqTypes, HKEY("DELETE"), v, NULL);
793
794         v = malloc(sizeof(long));
795         *v = eHEAD;
796         Put(HttpReqTypes, HKEY("HEAD"), v, NULL);
797
798         v = malloc(sizeof(long));
799         *v = eMOVE;
800         Put(HttpReqTypes, HKEY("MOVE"), v, NULL);
801
802         v = malloc(sizeof(long));
803         *v = eCOPY;
804         Put(HttpReqTypes, HKEY("COPY"), v, NULL);
805 }
806
807 void 
808 ServerShutdownModule_CONTEXT
809 (void)
810 {
811         DeleteHash(&HttpReqTypes);
812         DeleteHash(&HttpHeaderHandler);
813 }
814
815 void RegisterHeaderHandler(const char *Name, long Len, Header_Evaluator F)
816 {
817         OneHttpHeader *pHdr;
818         pHdr = (OneHttpHeader*) malloc(sizeof(OneHttpHeader));
819         memset(pHdr, 0, sizeof(OneHttpHeader));
820         pHdr->H = F;
821         Put(HttpHeaderHandler, Name, Len, pHdr, DestroyHttpHeaderHandler);
822 }
823 extern void blank_page(void); ///TODO: remove me
824 void 
825 InitModule_CONTEXT
826 (void)
827 {
828         RegisterHeaderHandler(HKEY("COOKIE"), Header_HandleCookie);
829         RegisterHeaderHandler(HKEY("AUTHORIZATION"), Header_HandleAuth);
830         RegisterHeaderHandler(HKEY("CONTENT-LENGTH"), Header_HandleContentLength);
831         RegisterHeaderHandler(HKEY("CONTENT-TYPE"), Header_HandleContentType);
832         RegisterHeaderHandler(HKEY("USER-AGENT"), Header_HandleUserAgent);
833         RegisterHeaderHandler(HKEY("X-FORWARDED-HOST"), Header_HandleXFFHost);
834         RegisterHeaderHandler(HKEY("HOST"), Header_HandleHost);
835         RegisterHeaderHandler(HKEY("X-FORWARDED-FOR"), Header_HandleXFF);
836         RegisterHeaderHandler(HKEY("ACCEPT-ENCODING"), Header_HandleAcceptEncoding);
837         RegisterHeaderHandler(HKEY("IF-MODIFIED-SINCE"), Header_HandleIfModSince);
838
839         RegisterNamespace("CURRENT_USER", 0, 1, tmplput_current_user, CTX_NONE);
840         RegisterNamespace("CURRENT_ROOM", 0, 1, tmplput_current_room, CTX_NONE);
841         RegisterNamespace("NONCE", 0, 0, tmplput_nonce, 0);
842
843
844
845         WebcitAddUrlHandler(HKEY("blank"), blank_page, ANONYMOUS|BOGUS);
846
847         WebcitAddUrlHandler(HKEY("blank"), blank_page, URLNAMESPACE);
848 }
849 //FreeStrBuf(&WCC->this_page);
850