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.
12 #include "webserver.h"
13 #include "modules_init.h"
15 /* Only one thread may manipulate SessionList at a time... */
16 pthread_mutex_t SessionListMutex;
18 wcsession *SessionList = NULL; /**< our sessions ????*/
20 pthread_key_t MyConKey; /**< TSD key for MySession() */
21 HashList *HttpReqTypes = NULL;
22 HashList *HttpHeaderHandler = NULL;
23 extern HashList *HandlerHash;
25 void DestroyHttpHeaderHandler(void *V)
28 pHdr = (OneHttpHeader*) V;
29 FreeStrBuf(&pHdr->Val);
33 void shutdown_sessions(void)
37 for (sptr = SessionList; sptr != NULL; sptr = sptr->next) {
42 void do_housekeeping(void)
45 wcsession *sessions_to_kill = NULL;
47 static int num_threads = MIN_WORKER_THREADS;
50 * Lock the session list, moving any candidates for euthanasia into
53 pthread_mutex_lock(&SessionListMutex);
55 for (sptr = SessionList; sptr != NULL; sptr = sptr->next) {
58 /** Kill idle sessions */
59 if ((time(NULL) - (sptr->lastreq)) >
60 (time_t) WEBCIT_TIMEOUT) {
64 /** Remove sessions flagged for kill */
67 /** remove session from linked list */
68 if (sptr == SessionList) {
69 SessionList = SessionList->next;
71 else for (ss=SessionList;ss!=NULL;ss=ss->next) {
72 if (ss->next == sptr) {
73 ss->next = ss->next->next;
77 sptr->next = sessions_to_kill;
78 sessions_to_kill = sptr;
81 pthread_mutex_unlock(&SessionListMutex);
84 * Now free up and destroy the culled sessions.
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;
92 session_destroy_modules(&sessions_to_kill);
93 sessions_to_kill = sptr;
98 * If there are more sessions than threads, then we should spawn
99 * more threads ... up to a predefined maximum.
101 while ( (num_sessions > num_threads)
102 && (num_threads <= MAX_WORKER_THREADS) ) {
103 spawn_another_worker_thread();
105 lprintf(3, "There are %d sessions and %d threads active.\n",
106 num_sessions, num_threads);
112 * Wake up occasionally and clean house
114 void housekeeping_loop(void)
117 sleeeeeeeeeep(HOUSEKEEPING);
124 * Create a Session id
125 * Generate a unique WebCit session ID (which is not the same thing as the
126 * Citadel session ID).
128 int GenerateSessionID(void)
130 static int seq = (-1);
133 seq = (int) time(NULL);
144 * \brief Detects a 'mobile' user agent
146 int is_mobile_ua(char *user_agent) {
147 if (strstr(user_agent,"iPhone OS") != NULL) {
149 } else if (strstr(user_agent,"Windows CE") != NULL) {
151 } else if (strstr(user_agent,"SymbianOS") != NULL) {
153 } else if (strstr(user_agent, "Opera Mobi") != NULL) {
155 } else if (strstr(user_agent, "Firefox/2.0.0 Opera 9.51 Beta") != NULL) {
156 /* For some reason a new install of Opera 9.51beta decided to spoof. */
162 /* If it's a "force 404" situation then display the error and bail. */
165 hprintf("HTTP/1.1 404 Not found\r\n");
166 hprintf("Content-Type: text/plain\r\n");
167 wprintf("Not found\r\n");
171 int ReadHttpSubject(ParsedHttpHdrs *Hdr, StrBuf *Line, StrBuf *Buf)
174 void *vLine, *vHandler;
175 const char *Pos = NULL;
178 Hdr->HR.ReqLine = Line;
179 /* The requesttype... GET, POST... */
180 StrBufExtract_token(Buf, Hdr->HR.ReqLine, 0, ' ');
181 if (GetHash(HttpReqTypes, SKEY(Buf), &vLine) &&
184 Hdr->HR.eReqType = *(long*)vLine;
187 Hdr->HR.eReqType = eGET;
190 StrBufCutLeft(Hdr->HR.ReqLine, StrLength(Buf) + 1);
192 /* the HTTP Version... */
193 StrBufExtract_token(Buf, Hdr->HR.ReqLine, 1, ' ');
194 StrBufCutRight(Hdr->HR.ReqLine, StrLength(Buf) + 1);
196 if (StrLength(Buf) == 0) {
197 Hdr->HR.eReqType = eGET;
201 Hdr->this_page = NewStrBufDup(Hdr->HR.ReqLine);
202 /* chop Filename / query arguments */
203 Args = strchr(ChrPtr(Hdr->HR.ReqLine), '?');
204 if (Args == NULL) /* whe're not that picky about params... TODO: this will spoil '&' in filenames.*/
205 Args = strchr(ChrPtr(Hdr->HR.ReqLine), '&');
207 Args ++; /* skip the ? */
208 Hdr->PlainArgs = NewStrBufPlain(
210 StrLength(Hdr->HR.ReqLine) -
211 (Args - ChrPtr(Hdr->HR.ReqLine)));
212 StrBufCutAt(Hdr->HR.ReqLine, 0, Args - 1);
213 } /* don't parse them yet, maybe we don't even care... */
215 /* now lookup what we are going to do with this... */
216 /* skip first slash */
217 StrBufExtract_NextToken(Buf, Hdr->HR.ReqLine, &Pos, '/');
219 StrBufExtract_NextToken(Buf, Hdr->HR.ReqLine, &Pos, '/');
221 GetHash(HandlerHash, SKEY(Buf), &vHandler),
222 Hdr->HR.Handler = (WebcitHandler*) vHandler;
223 if (Hdr->HR.Handler == NULL)
226 * If the request is prefixed by "/webcit" then chop that off. This
227 * allows a front end web server to forward all /webcit requests to us
228 * while still using the same web server port for other things.
230 if ((Hdr->HR.Handler->Flags & URLNAMESPACE) != 0)
234 /* remove the handlername from the URL */
236 StrBufCutLeft(Hdr->HR.ReqLine,
237 Pos - ChrPtr(Hdr->HR.ReqLine));
240 if (Hdr->HR.Handler != NULL) {
241 if ((Hdr->HR.Handler->Flags & BOGUS) != 0)
243 Hdr->HR.DontNeedAuth = (Hdr->HR.Handler->Flags & ISSTATIC) != 0;
246 Hdr->HTTPHeaders = NewHash(1, NULL);
250 int AnalyseHeaders(ParsedHttpHdrs *Hdr)
256 HashPos *at = GetNewHashPos(Hdr->HTTPHeaders, 0);
258 while (GetNextHashPos(Hdr->HTTPHeaders, at, &HKLen, &HashKey, &vHdr) &&
260 pHdr = (OneHttpHeader *)vHdr;
261 if (pHdr->HaveEvaluator)
262 pHdr->H(pHdr->Val, Hdr);
269 /*const char *nix(void *vptr) {return ChrPtr( (StrBuf*)vptr);}*/
272 * Read in the request
274 int ReadHTTPRequset (ParsedHttpHdrs *Hdr)
276 const char *pch, *pchs, *pche;
278 StrBuf *Line, *LastLine, *HeaderName;
283 HeaderName = NewStrBuf();
284 Hdr->ReadBuf = NewStrBuf();
290 if (ClientGetLine(Hdr, Line) < 0) return 1;
292 if (StrLength(Line) == 0) {
297 pHdr = (OneHttpHeader*) malloc(sizeof(OneHttpHeader));
298 memset(pHdr, 0, sizeof(OneHttpHeader));
300 Put(Hdr->HTTPHeaders, HKEY("GET /"), pHdr, DestroyHttpHeaderHandler);
301 lprintf(9, "%s\n", ChrPtr(Line));
302 isbogus = ReadHttpSubject(Hdr, Line, HeaderName);
307 /* Do we need to Unfold? */
308 if ((LastLine != NULL) &&
309 (isspace(*ChrPtr(Line)))) {
310 pch = pchs = ChrPtr(Line);
311 pche = pchs + StrLength(Line);
312 while (isspace(*pch) && (pch < pche))
314 StrBufCutLeft(Line, pch - pchs);
315 StrBufAppendBuf(LastLine, Line, 0);
321 StrBufSanitizeAscii(Line, '§');
322 StrBufExtract_token(HeaderName, Line, 0, ':');
325 pch = pchs + StrLength(HeaderName) + 1;
326 pche = pchs + StrLength(Line);
327 while (isspace(*pch) && (pch < pche))
329 StrBufCutLeft(Line, pch - pchs);
331 StrBufUpCase(HeaderName);
333 pHdr = (OneHttpHeader*) malloc(sizeof(OneHttpHeader));
334 memset(pHdr, 0, sizeof(OneHttpHeader));
337 if (GetHash(HttpHeaderHandler, SKEY(HeaderName), &vF) &&
340 OneHttpHeader *FHdr = (OneHttpHeader*) vF;
342 pHdr->HaveEvaluator = 1;
344 Put(Hdr->HTTPHeaders, SKEY(HeaderName), pHdr, DestroyHttpHeaderHandler);
346 } while (Line != NULL);
348 FreeStrBuf(&HeaderName);
358 * This loop gets called once for every HTTP connection made to WebCit. At
359 * this entry point we have an HTTP socket with a browser allegedly on the
360 * other end, but we have not yet bound to a WebCit session.
362 * The job of this function is to locate the correct session and bind to it,
363 * or create a session if necessary and bind to it, then run the WebCit
364 * transaction loop. Afterwards, we unbind from the session. When this
365 * function returns, the worker thread is then free to handle another
368 void context_loop(ParsedHttpHdrs *Hdr)
371 wcsession *TheSession, *sptr;
372 struct timeval tx_start;
373 struct timeval tx_finish;
375 gettimeofday(&tx_start, NULL); /* start a stopwatch for performance timing */
378 * Find out what it is that the web browser is asking for
380 isbogus = ReadHTTPRequset(Hdr);
383 isbogus = AnalyseHeaders(Hdr);
386 ((Hdr->HR.Handler != NULL) &&
387 ((Hdr->HR.Handler->Flags & BOGUS) != 0)))
390 Bogus = (wcsession *)
391 malloc(sizeof(wcsession));
392 memset(Bogus, 0, sizeof(wcsession));
393 pthread_setspecific(MyConKey, (void *)Bogus);
395 session_new_modules(Bogus);
397 session_detach_modules(Bogus);
398 http_destroy_modules(Hdr);
399 session_destroy_modules(&Bogus);
403 if ((Hdr->HR.Handler != NULL) &&
404 ((Hdr->HR.Handler->Flags & ISSTATIC) != 0))
408 Static = (wcsession *)
409 malloc(sizeof(wcsession));
410 memset(Static, 0, sizeof(wcsession));
411 pthread_setspecific(MyConKey, (void *)Static);
413 Static->serv_sock = (-1);
414 Static->chat_sock = (-1);
415 Static->is_mobile = -1;
416 session_new_modules(Static);
418 Hdr->HR.Handler->F();
420 /* How long did this transaction take? */
421 gettimeofday(&tx_finish, NULL);
423 lprintf(9, "SL: Transaction [%s] completed in %ld.%06ld seconds.\n",
424 ChrPtr(Hdr->this_page),
425 ((tx_finish.tv_sec*1000000 + tx_finish.tv_usec) - (tx_start.tv_sec*1000000 + tx_start.tv_usec)) / 1000000,
426 ((tx_finish.tv_sec*1000000 + tx_finish.tv_usec) - (tx_start.tv_sec*1000000 + tx_start.tv_usec)) % 1000000
429 session_detach_modules(Static);
430 http_destroy_modules(Hdr);
431 session_destroy_modules(&Static);
435 if (Hdr->HR.got_auth == AUTH_BASIC)
439 TODO HKEY("/static/nocookies.html?force_close_session=yes"));
442 /* dbg_PrintHash(HTTPHeaders, nix, NULL); */
445 /* Begin parsing the request. * /
447 if ((strncmp(ChrPtr(ReqLine), "/sslg", 5) != 0) &&
448 (strncmp(ChrPtr(ReqLine), "/static/", 8) != 0) &&
449 (strncmp(ChrPtr(ReqLine), "/tiny_mce/", 10) != 0) &&
450 (strncmp(ChrPtr(ReqLine), "/wholist_section", 16) != 0) &&
451 (strstr(ChrPtr(ReqLine), "wholist_section") == NULL)) {
453 lprintf(5, "HTTP: %s %s\n", ReqStrs[Hdr.eReqType], ChrPtr(ReqLine));
461 * See if there's an existing session open with the desired ID or user/pass
465 if (TheSession == NULL) {
466 pthread_mutex_lock(&SessionListMutex);
467 for (sptr = SessionList;
468 ((sptr != NULL) && (TheSession == NULL));
471 /** If HTTP-AUTH, look for a session with matching credentials */
472 switch (Hdr->HR.got_auth)
475 if ( (Hdr->HR.SessionKey != sptr->SessionKey))
478 if ((!strcasecmp(ChrPtr(Hdr->c_username), ChrPtr(sptr->wc_username))) &&
479 (!strcasecmp(ChrPtr(Hdr->c_password), ChrPtr(sptr->wc_password))) )
483 /** If cookie-session, look for a session with matching session ID */
484 if ( (Hdr->HR.desired_session != 0) &&
485 (sptr->wc_session == Hdr->HR.desired_session))
492 pthread_mutex_unlock(&SessionListMutex);
496 * Create a new session if we have to
498 if (TheSession == NULL) {
499 lprintf(3, "Creating a new session\n");
500 TheSession = (wcsession *)
501 malloc(sizeof(wcsession));
502 memset(TheSession, 0, sizeof(wcsession));
503 TheSession->Hdr = Hdr;
504 TheSession->SessionKey = Hdr->HR.SessionKey;
505 TheSession->serv_sock = (-1);
506 TheSession->chat_sock = (-1);
508 /* If we're recreating a session that expired, it's best to give it the same
509 * session number that it had before. The client browser ought to pick up
510 * the new session number and start using it, but in some rare situations it
511 * doesn't, and that's a Bad Thing because it causes lots of spurious sessions
514 if (Hdr->HR.desired_session == 0) {
515 TheSession->wc_session = GenerateSessionID();
518 TheSession->wc_session = Hdr->HR.desired_session;
521 pthread_setspecific(MyConKey, (void *)TheSession);
522 session_new_modules(TheSession);
524 pthread_mutex_init(&TheSession->SessionMutex, NULL);
525 pthread_mutex_lock(&SessionListMutex);
526 TheSession->nonce = rand();
527 TheSession->next = SessionList;
528 TheSession->is_mobile = -1;
529 SessionList = TheSession;
530 pthread_mutex_unlock(&SessionListMutex);
532 if (StrLength(Hdr->c_language) > 0) {
533 lprintf(9, "Session cookie requests language '%s'\n", ChrPtr(Hdr->c_language));
534 set_selected_language(ChrPtr(Hdr->c_language));
535 go_selected_language();
540 * A future improvement might be to check the session integrity
541 * at this point before continuing.
545 * Bind to the session and perform the transaction
547 pthread_mutex_lock(&TheSession->SessionMutex); /* bind */
548 pthread_setspecific(MyConKey, (void *)TheSession);
550 TheSession->lastreq = time(NULL); /* log */
551 TheSession->Hdr = Hdr;
553 session_attach_modules(TheSession);
554 session_loop(); /* do transaction */
557 /* How long did this transaction take? */
558 gettimeofday(&tx_finish, NULL);
560 lprintf(9, "Transaction [%s] completed in %ld.%06ld seconds.\n",
561 ChrPtr(Hdr->this_page),
562 ((tx_finish.tv_sec*1000000 + tx_finish.tv_usec) - (tx_start.tv_sec*1000000 + tx_start.tv_usec)) / 1000000,
563 ((tx_finish.tv_sec*1000000 + tx_finish.tv_usec) - (tx_start.tv_sec*1000000 + tx_start.tv_usec)) % 1000000
566 session_detach_modules(TheSession);
568 TheSession->Hdr = NULL;
569 pthread_mutex_unlock(&TheSession->SessionMutex); /* unbind */
571 http_destroy_modules(Hdr);
574 void tmplput_nonce(StrBuf *Target, WCTemplputParams *TP)
577 StrBufAppendPrintf(Target, "%ld",
578 (WCC != NULL)? WCC->nonce:0);
581 void tmplput_current_user(StrBuf *Target, WCTemplputParams *TP)
583 StrBufAppendTemplate(Target, TP, WC->wc_fullname, 0);
586 void tmplput_current_room(StrBuf *Target, WCTemplputParams *TP)
588 StrBufAppendTemplate(Target, TP, WC->wc_roomname, 0);
591 void Header_HandleContentLength(StrBuf *Line, ParsedHttpHdrs *hdr)
593 hdr->HR.ContentLength = StrToi(Line);
596 void Header_HandleContentType(StrBuf *Line, ParsedHttpHdrs *hdr)
598 hdr->HR.ContentType = Line;
601 void Header_HandleUserAgent(StrBuf *Line, ParsedHttpHdrs *hdr)
603 hdr->HR.user_agent = Line;
605 /* TODO: do this later on session creating
606 if ((WCC->is_mobile < 0) && is_mobile_ua(&buf[12])) {
617 void Header_HandleHost(StrBuf *Line, ParsedHttpHdrs *hdr)
619 if ((follow_xff) && (hdr->HR.http_host != NULL))
622 hdr->HR.http_host = Line;
625 void Header_HandleXFFHost(StrBuf *Line, ParsedHttpHdrs *hdr)
628 hdr->HR.http_host = Line;
632 void Header_HandleXFF(StrBuf *Line, ParsedHttpHdrs *hdr)
634 hdr->HR.browser_host = Line;
636 while (StrBufNum_tokens(hdr->HR.browser_host, ',') > 1) {
637 StrBufRemove_token(hdr->HR.browser_host, 0, ',');
639 StrBufTrim(hdr->HR.browser_host);
642 void Header_HandleIfModSince(StrBuf *Line, ParsedHttpHdrs *hdr)
644 hdr->HR.if_modified_since = httpdate_to_timestamp(Line);
647 void Header_HandleAcceptEncoding(StrBuf *Line, ParsedHttpHdrs *hdr)
652 if (strstr(&ChrPtr(Line)[16], "gzip")) {
656 const char *ReqStrs[eNONE] = {
669 ServerStartModule_CONTEXT
673 HttpReqTypes = NewHash(1, NULL);
674 HttpHeaderHandler = NewHash(1, NULL);
676 v = malloc(sizeof(long));
678 Put(HttpReqTypes, HKEY("GET"), v, NULL);
680 v = malloc(sizeof(long));
682 Put(HttpReqTypes, HKEY("POST"), v, NULL);
684 v = malloc(sizeof(long));
686 Put(HttpReqTypes, HKEY("OPTIONS"), v, NULL);
688 v = malloc(sizeof(long));
690 Put(HttpReqTypes, HKEY("PROPFIND"), v, NULL);
692 v = malloc(sizeof(long));
694 Put(HttpReqTypes, HKEY("PUT"), v, NULL);
696 v = malloc(sizeof(long));
698 Put(HttpReqTypes, HKEY("DELETE"), v, NULL);
700 v = malloc(sizeof(long));
702 Put(HttpReqTypes, HKEY("HEAD"), v, NULL);
704 v = malloc(sizeof(long));
706 Put(HttpReqTypes, HKEY("MOVE"), v, NULL);
708 v = malloc(sizeof(long));
710 Put(HttpReqTypes, HKEY("COPY"), v, NULL);
714 ServerShutdownModule_CONTEXT
717 DeleteHash(&HttpReqTypes);
718 DeleteHash(&HttpHeaderHandler);
721 void RegisterHeaderHandler(const char *Name, long Len, Header_Evaluator F)
724 pHdr = (OneHttpHeader*) malloc(sizeof(OneHttpHeader));
725 memset(pHdr, 0, sizeof(OneHttpHeader));
727 Put(HttpHeaderHandler, Name, Len, pHdr, DestroyHttpHeaderHandler);
735 RegisterHeaderHandler(HKEY("CONTENT-LENGTH"), Header_HandleContentLength);
736 RegisterHeaderHandler(HKEY("CONTENT-TYPE"), Header_HandleContentType);
737 RegisterHeaderHandler(HKEY("USER-AGENT"), Header_HandleUserAgent);
738 RegisterHeaderHandler(HKEY("X-FORWARDED-HOST"), Header_HandleXFFHost);
739 RegisterHeaderHandler(HKEY("HOST"), Header_HandleHost);
740 RegisterHeaderHandler(HKEY("X-FORWARDED-FOR"), Header_HandleXFF);
741 RegisterHeaderHandler(HKEY("ACCEPT-ENCODING"), Header_HandleAcceptEncoding);
742 RegisterHeaderHandler(HKEY("IF-MODIFIED-SINCE"), Header_HandleIfModSince);
744 RegisterNamespace("CURRENT_USER", 0, 1, tmplput_current_user, CTX_NONE);
745 RegisterNamespace("CURRENT_ROOM", 0, 1, tmplput_current_room, CTX_NONE);
746 RegisterNamespace("NONCE", 0, 0, tmplput_nonce, 0);
748 WebcitAddUrlHandler(HKEY("404"), do_404, ANONYMOUS|COOKIEUNNEEDED);
750 * Look for commonly-found probes of malware such as worms, viruses, trojans, and Microsoft Office.
751 * Short-circuit these requests so we don't have to send them through the full processing loop.
753 WebcitAddUrlHandler(HKEY("scripts"), do_404, ANONYMOUS|BOGUS); /* /root.exe /* Worms and trojans and viruses, oh my! */
754 WebcitAddUrlHandler(HKEY("c"), do_404, ANONYMOUS|BOGUS); /* /winnt */
755 WebcitAddUrlHandler(HKEY("MSADC"), do_404, ANONYMOUS|BOGUS);
756 WebcitAddUrlHandler(HKEY("_vti"), do_404, ANONYMOUS|BOGUS); /* Broken Microsoft DAV implementation */
757 WebcitAddUrlHandler(HKEY("MSOffice"), do_404, ANONYMOUS|BOGUS); /* Stoopid MSOffice thinks everyone is IIS */
758 WebcitAddUrlHandler(HKEY("nonexistenshit"), do_404, ANONYMOUS|BOGUS); /* Exploit found in the wild January 2009 */
764 HttpDestroyModule_CONTEXT
765 (ParsedHttpHdrs *httpreq)
767 FreeStrBuf(&httpreq->ReadBuf);
768 FreeStrBuf(&httpreq->PlainArgs);
769 FreeStrBuf(&httpreq->this_page);
770 DeleteHash(&httpreq->HTTPHeaders);