1d1cbb821a39640173b2c9ddf4fcf287a35fe353
[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                 Args ++; /* skip the ? */
269                 Hdr->PlainArgs = NewStrBufPlain(
270                         Args, 
271                         StrLength(Hdr->ReqLine) -
272                         (Args - ChrPtr(Hdr->ReqLine)));
273                 StrBufCutAt(Hdr->ReqLine, 0, Args);
274         } /* don't parse them yet, maybe we don't even care... */
275         
276         /* now lookup what we are going to do with this... */
277         /* skip first slash */
278         StrBufExtract_NextToken(Buf, Hdr->ReqLine, &Pos, '/');
279         do {
280                 StrBufExtract_NextToken(Buf, Hdr->ReqLine, &Pos, '/');
281
282                 GetHash(HandlerHash, SKEY(Buf), &vHandler),
283                 Hdr->Handler = (WebcitHandler*) vHandler;
284                 if (Hdr->Handler == NULL)
285                         break;
286                 /* are we about to ignore some prefix like webcit/ ? */
287                 if ((Hdr->Handler->Flags & URLNAMESPACE) == 0)
288                         break;
289         } while (1);
290         /* remove the handlername from the URL */
291         if (Pos != NULL) {
292                 StrBufCutLeft(Hdr->ReqLine, 
293                               Pos - ChrPtr(Hdr->ReqLine));
294         }
295 /*
296         if (Hdr->Handler == NULL)
297                 return 1;
298 */
299         Hdr->HTTPHeaders = NewHash(1, NULL);
300
301         return 0;
302 }
303
304 int AnalyseHeaders(ParsedHttpHdrs *Hdr)
305 {
306         OneHttpHeader *pHdr;
307         void *vHdr;
308         long HKLen;
309         const char *HashKey;
310         HashPos *at = GetNewHashPos(Hdr->HTTPHeaders, 0);
311         
312         while (GetNextHashPos(Hdr->HTTPHeaders, at, &HKLen, &HashKey, &vHdr) && 
313                (vHdr != NULL)) {
314                 pHdr = (OneHttpHeader *)vHdr;
315                 if (pHdr->HaveEvaluator)
316                         pHdr->H(pHdr->Val, Hdr);
317
318         }
319         DeleteHashPos(&at);
320         return 0;
321 }
322
323 /*const char *nix(void *vptr) {return ChrPtr( (StrBuf*)vptr);}*/
324
325 /*
326  * Read in the request
327  */
328 int ReadHTTPRequset (ParsedHttpHdrs *Hdr)
329 {
330         const char *pch, *pchs, *pche;
331         OneHttpHeader *pHdr;
332         StrBuf *Line, *LastLine, *HeaderName;
333         int nLine = 0;
334         void *vF;
335         int isbogus = 0;
336
337         HeaderName = NewStrBuf();
338         Hdr->ReadBuf = NewStrBuf();
339         LastLine = NULL;
340         do {
341                 nLine ++;
342                 Line = NewStrBuf();
343
344                 if (ClientGetLine(&Hdr->http_sock, Line, Hdr->ReadBuf, &Hdr->Pos) < 0) return 1;
345
346                 if (StrLength(Line) == 0) {
347                         FreeStrBuf(&Line);
348                         continue;
349                 }
350                 if (nLine == 1) {
351                         isbogus = ReadHttpSubject(Hdr, Line, HeaderName);
352                         if (isbogus) break;
353                         continue;
354                 }
355
356                 /* Do we need to Unfold? */
357                 if ((LastLine != NULL) && 
358                     (isspace(*ChrPtr(Line)))) {
359                         pch = pchs = ChrPtr(Line);
360                         pche = pchs + StrLength(Line);
361                         while (isspace(*pch) && (pch < pche))
362                                 pch ++;
363                         StrBufCutLeft(Line, pch - pchs);
364                         StrBufAppendBuf(LastLine, Line, 0);
365
366                         FreeStrBuf(&Line);
367                         continue;
368                 }
369
370                 StrBufSanitizeAscii(Line, '§');
371                 StrBufExtract_token(HeaderName, Line, 0, ':');
372
373                 pchs = ChrPtr(Line);
374                 pch = pchs + StrLength(HeaderName) + 1;
375                 pche = pchs + StrLength(Line);
376                 while (isspace(*pch) && (pch < pche))
377                         pch ++;
378                 StrBufCutLeft(Line, pch - pchs);
379
380                 StrBufUpCase(HeaderName);
381
382                 pHdr = (OneHttpHeader*) malloc(sizeof(OneHttpHeader));
383                 memset(pHdr, 0, sizeof(OneHttpHeader));
384                 pHdr->Val = Line;
385
386                 if (GetHash(HttpHeaderHandler, SKEY(HeaderName), &vF) &&
387                     (vF != NULL))
388                 {
389                         OneHttpHeader *FHdr = (OneHttpHeader*) vF;
390                         pHdr->H = FHdr->H;
391                         pHdr->HaveEvaluator = 1;
392                 }
393                 Put(Hdr->HTTPHeaders, SKEY(HeaderName), pHdr, DestroyHttpHeaderHandler);
394                 LastLine = Line;
395         } while (Line != NULL);
396
397         FreeStrBuf(&HeaderName);
398
399         return isbogus;
400 }
401
402
403
404 /*
405  * handle one request
406  *
407  * This loop gets called once for every HTTP connection made to WebCit.  At
408  * this entry point we have an HTTP socket with a browser allegedly on the
409  * other end, but we have not yet bound to a WebCit session.
410  *
411  * The job of this function is to locate the correct session and bind to it,
412  * or create a session if necessary and bind to it, then run the WebCit
413  * transaction loop.  Afterwards, we unbind from the session.  When this
414  * function returns, the worker thread is then free to handle another
415  * transaction.
416  */
417 void context_loop(int *sock)
418 {
419         ParsedHttpHdrs Hdr;
420         int isbogus = 0;
421         wcsession *TheSession, *sptr;
422         struct timeval tx_start;
423         struct timeval tx_finish;
424         
425         gettimeofday(&tx_start, NULL);          /* start a stopwatch for performance timing */
426
427         memset(&Hdr, 0, sizeof(ParsedHttpHdrs));
428         Hdr.eReqType = eGET;
429         Hdr.http_sock = *sock;
430         /*
431          * Find out what it is that the web browser is asking for
432          */
433         isbogus = ReadHTTPRequset(&Hdr);
434
435         if (!isbogus)
436                 isbogus = AnalyseHeaders(&Hdr);
437 /*
438         if (isbogus)
439                 StrBufPlain(ReqLine, HKEY("/404"));
440 */
441
442 /*      dbg_PrintHash(HTTPHeaders, nix, NULL);  */
443
444
445 ///HttpHeaderHandler
446
447
448
449
450
451         /*
452          * If the request is prefixed by "/webcit" then chop that off.  This
453          * allows a front end web server to forward all /webcit requests to us
454          * while still using the same web server port for other things.
455          * /
456         if (!isbogus &&
457             (StrLength(ReqLine) >= 8) && 
458             (strstr(ChrPtr(ReqLine), "/webcit/")) ) {
459                 StrBufCutLeft(ReqLine, 7);
460         }
461
462         /* Begin parsing the request. * /
463 #ifdef TECH_PREVIEW
464         if ((strncmp(ChrPtr(ReqLine), "/sslg", 5) != 0) &&
465             (strncmp(ChrPtr(ReqLine), "/static/", 8) != 0) &&
466             (strncmp(ChrPtr(ReqLine), "/tiny_mce/", 10) != 0) &&
467             (strncmp(ChrPtr(ReqLine), "/wholist_section", 16) != 0) &&
468             (strstr(ChrPtr(ReqLine), "wholist_section") == NULL)) {
469 #endif
470                 lprintf(5, "HTTP: %s %s\n", ReqStrs[Hdr.eReqType], ChrPtr(ReqLine));
471 #ifdef TECH_PREVIEW
472         }
473 #endif
474
475 */
476
477         /**
478          * See if there's an existing session open with the desired ID or user/pass
479          */
480         TheSession = NULL;
481
482         if (TheSession == NULL) {
483                 pthread_mutex_lock(&SessionListMutex);
484                 for (sptr = SessionList; 
485                      ((sptr != NULL) && (TheSession == NULL)); 
486                       sptr = sptr->next) {
487
488                         /** If HTTP-AUTH, look for a session with matching credentials * /
489                         if ( (////TODO check auth type here...
490                              &&(!strcasecmp(ChrPtr(sptr->httpauth_user), httpauth_user))
491                              &&(!strcasecmp(ChrPtr(sptr->httpauth_pass), httpauth_pass)) ) {
492                                 TheSession = sptr;
493                         }
494
495                         /** If cookie-session, look for a session with matching session ID */
496                         if ( (Hdr.desired_session != 0) && (sptr->wc_session == Hdr.desired_session)) {
497                                 TheSession = sptr;
498                         }
499
500                 }
501                 pthread_mutex_unlock(&SessionListMutex);
502         }
503
504         /**
505          * Create a new session if we have to
506          */
507         if (TheSession == NULL) {
508                 lprintf(3, "Creating a new session\n");
509                 TheSession = (wcsession *)
510                         malloc(sizeof(wcsession));
511                 memset(TheSession, 0, sizeof(wcsession));
512                 TheSession->Hdr = &Hdr;
513                 TheSession->serv_sock = (-1);
514                 TheSession->chat_sock = (-1);
515         
516                 /* If we're recreating a session that expired, it's best to give it the same
517                  * session number that it had before.  The client browser ought to pick up
518                  * the new session number and start using it, but in some rare situations it
519                  * doesn't, and that's a Bad Thing because it causes lots of spurious sessions
520                  * to get created.
521                  */     
522                 if (Hdr.desired_session == 0) {
523                         TheSession->wc_session = GenerateSessionID();
524                 }
525                 else {
526                         TheSession->wc_session = Hdr.desired_session;
527                 }
528 /*
529                 TheSession->httpauth_user = NewStrBufPlain(httpauth_user, -1);
530                         TheSession->httpauth_pass = NewStrBufPlain(httpauth_user, -1);
531 */
532                 pthread_setspecific(MyConKey, (void *)TheSession);
533                 session_new_modules(TheSession);
534
535                 pthread_mutex_init(&TheSession->SessionMutex, NULL);
536                 pthread_mutex_lock(&SessionListMutex);
537                 TheSession->nonce = rand();
538                 TheSession->next = SessionList;
539                 TheSession->is_mobile = -1;
540                 SessionList = TheSession;
541                 pthread_mutex_unlock(&SessionListMutex);
542         }
543
544         /*
545          * A future improvement might be to check the session integrity
546          * at this point before continuing.
547          */
548
549         /*
550          * Bind to the session and perform the transaction
551          */
552         pthread_mutex_lock(&TheSession->SessionMutex);          /* bind */
553         pthread_setspecific(MyConKey, (void *)TheSession);
554         
555         TheSession->lastreq = time(NULL);                       /* log */
556         TheSession->Hdr = &Hdr;
557
558         session_attach_modules(TheSession);
559         session_loop();                         /* do transaction */
560
561
562         /* How long did this transaction take? */
563         gettimeofday(&tx_finish, NULL);
564         
565         lprintf(9, "Transaction [%s] completed in %ld.%06ld seconds.\n",
566                 ChrPtr(Hdr.this_page),
567                 ((tx_finish.tv_sec*1000000 + tx_finish.tv_usec) - (tx_start.tv_sec*1000000 + tx_start.tv_usec)) / 1000000,
568                 ((tx_finish.tv_sec*1000000 + tx_finish.tv_usec) - (tx_start.tv_sec*1000000 + tx_start.tv_usec)) % 1000000
569         );
570
571         session_detach_modules(TheSession);
572
573         TheSession->Hdr = NULL;
574         pthread_mutex_unlock(&TheSession->SessionMutex);        /* unbind */
575
576
577         http_destroy_modules(&Hdr);
578 /* TODO
579
580         FreeStrBuf(&c_username);
581         FreeStrBuf(&c_password);
582         FreeStrBuf(&c_roomname);
583         FreeStrBuf(&c_httpauth_user);
584         FreeStrBuf(&c_httpauth_pass);
585 */
586         /* Free the request buffer */
587         ///FreeStrBuf(&ReqLine);
588         
589 }
590
591 void tmplput_nonce(StrBuf *Target, WCTemplputParams *TP)
592 {
593         wcsession *WCC = WC;
594         StrBufAppendPrintf(Target, "%ld",
595                            (WCC != NULL)? WCC->nonce:0);                   
596 }
597
598 void tmplput_current_user(StrBuf *Target, WCTemplputParams *TP)
599 {
600         StrBufAppendTemplate(Target, TP, WC->wc_fullname, 0);
601 }
602
603 void tmplput_current_room(StrBuf *Target, WCTemplputParams *TP)
604 {
605         StrBufAppendTemplate(Target, TP, WC->wc_roomname, 0); 
606 }
607
608
609 void Header_HandleCookie(StrBuf *Line, ParsedHttpHdrs *hdr)
610 {
611         hdr->RawCookie = Line;
612         if (hdr->DontNeedAuth)
613                 return;
614 /*
615         c_username = NewStrBuf();
616         c_password = NewStrBuf();
617         c_roomname = NewStrBuf();
618         safestrncpy(c_httpauth_string, "", sizeof c_httpauth_string);
619         c_httpauth_user = NewStrBufPlain(HKEY(DEFAULT_HTTPAUTH_USER));
620         c_httpauth_pass = NewStrBufPlain(HKEY(DEFAULT_HTTPAUTH_PASS));
621 */
622         cookie_to_stuff(Line, &hdr->desired_session,
623                         hdr->c_username,
624                         hdr->c_password,
625                         hdr->c_roomname);
626         hdr->got_cookie = 1;
627 }
628
629
630         /*
631          * Browser-based sessions use cookies for session authentication
632          * /
633         if (!isbogus &&
634             GetHash(HTTPHeaders, HKEY("COOKIE"), &vLine) && 
635             (vLine != NULL)) {
636                 cookie_to_stuff(vLine, &desired_session,
637                                 NULL, NULL, NULL);
638                 got_cookie = 1;
639         }
640         */
641         /*
642          * GroupDAV-based sessions use HTTP authentication
643          */
644 /*
645         if (!isbogus &&
646             GetHash(HTTPHeaders, HKEY("AUTHORIZATION"), &vLine) && 
647             (vLine != NULL)) {
648                 Line = (StrBuf*)vLine;
649                 if (strncasecmp(ChrPtr(Line), "Basic", 5) == 0) {
650                         StrBufCutLeft(Line, 6);
651                         CtdlDecodeBase64(httpauth_string, ChrPtr(Line), StrLength(Line));
652                         extract_token(httpauth_user, httpauth_string, 0, ':', sizeof httpauth_user);
653                         extract_token(httpauth_pass, httpauth_string, 1, ':', sizeof httpauth_pass);
654                 }
655                 else 
656                         lprintf(1, "Authentication scheme not supported! [%s]\n", ChrPtr(Line));
657         }
658
659 */
660 void Header_HandleAuth(StrBuf *Line, ParsedHttpHdrs *hdr)
661 {
662         const char *Pos = NULL;
663         StrBufDecodeBase64(Line);
664         StrBufExtract_NextToken(hdr->c_username, Line, &Pos, ':');
665         StrBufExtract_NextToken(hdr->c_password, Line, &Pos, ':');
666 }
667
668 void Header_HandleContentLength(StrBuf *Line, ParsedHttpHdrs *hdr)
669 {
670         hdr->ContentLength = StrToi(Line);
671 }
672
673 void Header_HandleContentType(StrBuf *Line, ParsedHttpHdrs *hdr)
674 {
675         hdr->ContentType = Line;
676 }
677
678 void Header_HandleUserAgent(StrBuf *Line, ParsedHttpHdrs *hdr)
679 {
680         hdr->user_agent = Line;
681 #ifdef TECH_PREVIEW
682 /* TODO: do this later on session creating
683         if ((WCC->is_mobile < 0) && is_mobile_ua(&buf[12])) {                   
684                 WCC->is_mobile = 1;
685         }
686         else {
687                 WCC->is_mobile = 0;
688         }
689 */
690 #endif
691 }
692
693
694 void Header_HandleHost(StrBuf *Line, ParsedHttpHdrs *hdr)
695 {
696         if ((follow_xff) && (hdr->http_host != NULL))
697                 return;
698         else
699                 hdr->http_host = Line;
700 }
701
702 void Header_HandleXFFHost(StrBuf *Line, ParsedHttpHdrs *hdr)
703 {
704         if (follow_xff)
705                 hdr->http_host = Line;
706 }
707
708
709 void Header_HandleXFF(StrBuf *Line, ParsedHttpHdrs *hdr)
710 {
711         hdr->browser_host = Line;
712
713         while (StrBufNum_tokens(hdr->browser_host, ',') > 1) {
714                 StrBufRemove_token(hdr->browser_host, 0, ',');
715         }
716         StrBufTrim(hdr->browser_host);
717 }
718
719 void Header_HandleIfModSince(StrBuf *Line, ParsedHttpHdrs *hdr)
720 {
721         hdr->if_modified_since = httpdate_to_timestamp(Line);
722 }
723
724 void Header_HandleAcceptEncoding(StrBuf *Line, ParsedHttpHdrs *hdr)
725 {
726         /*
727          * Can we compress?
728          */
729         if (strstr(&ChrPtr(Line)[16], "gzip")) {
730                 hdr->gzip_ok = 1;
731         }
732 }
733
734 /*
735 {
736         c_username = NewStrBuf();
737         c_password = NewStrBuf();
738         c_roomname = NewStrBuf();
739         safestrncpy(c_httpauth_string, "", sizeof c_httpauth_string);
740         c_httpauth_user = NewStrBufPlain(HKEY(DEFAULT_HTTPAUTH_USER));
741         c_httpauth_pass = NewStrBufPlain(HKEY(DEFAULT_HTTPAUTH_PASS));
742 }
743 */
744         /* *
745          * These are the URL's which may be executed without a
746          * session cookie already set.  If it's not one of these,
747          * force the session to close because cookies are
748          * probably disabled on the client browser.
749          * /
750         else if ( (StrLength(ReqLine) > 1 )
751                 && (strncasecmp(ChrPtr(ReqLine), "/404", 4))
752                 && (Hdr.got_cookie == 0)) {
753                 StrBufPlain(ReqLine, 
754                             HKEY("/static/nocookies.html"
755                                  "?force_close_session=yes"));
756         }
757 */
758 const char *ReqStrs[eNONE] = {
759         "GET",
760         "POST",
761         "OPTIONS",
762         "PROPFIND",
763         "PUT",
764         "DELETE",
765         "HEAD",
766         "MOVE",
767         "COPY"
768 };
769
770 void
771 ServerStartModule_CONTEXT
772 (void)
773 {
774         long *v;
775         HttpReqTypes = NewHash(1, NULL);
776         HttpHeaderHandler = NewHash(1, NULL);
777
778         v = malloc(sizeof(long));
779         *v = eGET;
780         Put(HttpReqTypes, HKEY("GET"), v, NULL);
781
782         v = malloc(sizeof(long));
783         *v = ePOST;
784         Put(HttpReqTypes, HKEY("POST"), v, NULL);
785
786         v = malloc(sizeof(long));
787         *v = eOPTIONS;
788         Put(HttpReqTypes, HKEY("OPTIONS"), v, NULL);
789
790         v = malloc(sizeof(long));
791         *v = ePROPFIND;
792         Put(HttpReqTypes, HKEY("PROPFIND"), v, NULL);
793
794         v = malloc(sizeof(long));
795         *v = ePUT;
796         Put(HttpReqTypes, HKEY("PUT"), v, NULL);
797
798         v = malloc(sizeof(long));
799         *v = eDELETE;
800         Put(HttpReqTypes, HKEY("DELETE"), v, NULL);
801
802         v = malloc(sizeof(long));
803         *v = eHEAD;
804         Put(HttpReqTypes, HKEY("HEAD"), v, NULL);
805
806         v = malloc(sizeof(long));
807         *v = eMOVE;
808         Put(HttpReqTypes, HKEY("MOVE"), v, NULL);
809
810         v = malloc(sizeof(long));
811         *v = eCOPY;
812         Put(HttpReqTypes, HKEY("COPY"), v, NULL);
813 }
814
815 void 
816 ServerShutdownModule_CONTEXT
817 (void)
818 {
819         DeleteHash(&HttpReqTypes);
820         DeleteHash(&HttpHeaderHandler);
821 }
822
823 void RegisterHeaderHandler(const char *Name, long Len, Header_Evaluator F)
824 {
825         OneHttpHeader *pHdr;
826         pHdr = (OneHttpHeader*) malloc(sizeof(OneHttpHeader));
827         memset(pHdr, 0, sizeof(OneHttpHeader));
828         pHdr->H = F;
829         Put(HttpHeaderHandler, Name, Len, pHdr, DestroyHttpHeaderHandler);
830 }
831 extern void blank_page(void); ///TODO: remove me
832 void 
833 InitModule_CONTEXT
834 (void)
835 {
836         RegisterHeaderHandler(HKEY("COOKIE"), Header_HandleCookie);
837         RegisterHeaderHandler(HKEY("AUTHORIZATION"), Header_HandleAuth);
838         RegisterHeaderHandler(HKEY("CONTENT-LENGTH"), Header_HandleContentLength);
839         RegisterHeaderHandler(HKEY("CONTENT-TYPE"), Header_HandleContentType);
840         RegisterHeaderHandler(HKEY("USER-AGENT"), Header_HandleUserAgent);
841         RegisterHeaderHandler(HKEY("X-FORWARDED-HOST"), Header_HandleXFFHost);
842         RegisterHeaderHandler(HKEY("HOST"), Header_HandleHost);
843         RegisterHeaderHandler(HKEY("X-FORWARDED-FOR"), Header_HandleXFF);
844         RegisterHeaderHandler(HKEY("ACCEPT-ENCODING"), Header_HandleAcceptEncoding);
845         RegisterHeaderHandler(HKEY("IF-MODIFIED-SINCE"), Header_HandleIfModSince);
846
847         RegisterNamespace("CURRENT_USER", 0, 1, tmplput_current_user, CTX_NONE);
848         RegisterNamespace("CURRENT_ROOM", 0, 1, tmplput_current_room, CTX_NONE);
849         RegisterNamespace("NONCE", 0, 0, tmplput_nonce, 0);
850
851
852
853         WebcitAddUrlHandler(HKEY("blank"), blank_page, ANONYMOUS|BOGUS);
854
855         WebcitAddUrlHandler(HKEY("webcit"), blank_page, URLNAMESPACE);
856 }
857         
858
859
860 void 
861 HttpDestroyModule_CONTEXT
862 (ParsedHttpHdrs *httpreq)
863 {
864         FreeStrBuf(&httpreq->ReqLine);
865         FreeStrBuf(&httpreq->ReadBuf);
866         FreeStrBuf(&httpreq->PlainArgs);
867         FreeStrBuf(&httpreq->this_page);
868         DeleteHash(&httpreq->HTTPHeaders);
869
870 }