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);
141 * lingering_close() a`la Apache. see
142 * http://www.apache.org/docs/misc/fin_wait_2.html for rationale
144 int lingering_close(int fd)
149 struct timeval tv, start;
151 gettimeofday(&start, NULL);
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) {
160 tv.tv_usec += 1000000;
164 i = select(fd + 1, &set, NULL, NULL, &tv);
165 } while (i == -1 && errno == EINTR);
170 i = read(fd, buf, sizeof buf);
171 } while (i != 0 && (i != -1 || errno == EINTR));
180 * \brief Detects a 'mobile' user agent
182 int is_mobile_ua(char *user_agent) {
183 if (strstr(user_agent,"iPhone OS") != NULL) {
185 } else if (strstr(user_agent,"Windows CE") != NULL) {
187 } else if (strstr(user_agent,"SymbianOS") != NULL) {
189 } else if (strstr(user_agent, "Opera Mobi") != NULL) {
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. */
198 /* If it's a "force 404" situation then display the error and bail. */
201 hprintf("HTTP/1.1 404 Not found\r\n");
202 hprintf("Content-Type: text/plain\r\n");
203 wprintf("Not found\r\n");
207 int ReadHttpSubject(ParsedHttpHdrs *Hdr, StrBuf *Line, StrBuf *Buf)
210 void *vLine, *vHandler;
211 const char *Pos = NULL;
215 /* The requesttype... GET, POST... */
216 StrBufExtract_token(Buf, Hdr->ReqLine, 0, ' ');
217 if (GetHash(HttpReqTypes, SKEY(Buf), &vLine) &&
220 Hdr->eReqType = *(long*)vLine;
223 Hdr->eReqType = eGET;
226 StrBufCutLeft(Hdr->ReqLine, StrLength(Buf) + 1);
228 /* the HTTP Version... */
229 StrBufExtract_token(Buf, Hdr->ReqLine, 1, ' ');
230 StrBufCutRight(Hdr->ReqLine, StrLength(Buf) + 1);
232 if (StrLength(Buf) == 0) {
233 Hdr->eReqType = eGET;
237 Hdr->this_page = NewStrBufDup(Hdr->ReqLine);
238 /* chop Filename / query arguments */
239 Args = strchr(ChrPtr(Hdr->ReqLine), '?');
240 if (Args == NULL) /* whe're not that picky about params... TODO: this will spoil '&' in filenames.*/
241 Args = strchr(ChrPtr(Hdr->ReqLine), '&');
243 Args ++; /* skip the ? */
244 Hdr->PlainArgs = NewStrBufPlain(
246 StrLength(Hdr->ReqLine) -
247 (Args - ChrPtr(Hdr->ReqLine)));
248 StrBufCutAt(Hdr->ReqLine, 0, Args - 1);
249 } /* don't parse them yet, maybe we don't even care... */
251 /* now lookup what we are going to do with this... */
252 /* skip first slash */
253 StrBufExtract_NextToken(Buf, Hdr->ReqLine, &Pos, '/');
255 StrBufExtract_NextToken(Buf, Hdr->ReqLine, &Pos, '/');
257 GetHash(HandlerHash, SKEY(Buf), &vHandler),
258 Hdr->Handler = (WebcitHandler*) vHandler;
259 if (Hdr->Handler == NULL)
262 * If the request is prefixed by "/webcit" then chop that off. This
263 * allows a front end web server to forward all /webcit requests to us
264 * while still using the same web server port for other things.
266 if ((Hdr->Handler->Flags & URLNAMESPACE) != 0)
270 /* remove the handlername from the URL */
272 StrBufCutLeft(Hdr->ReqLine,
273 Pos - ChrPtr(Hdr->ReqLine));
276 if (Hdr->Handler != NULL) {
277 if ((Hdr->Handler->Flags & BOGUS) != 0)
279 Hdr->DontNeedAuth = (Hdr->Handler->Flags & ISSTATIC) != 0;
282 Hdr->HTTPHeaders = NewHash(1, NULL);
286 int AnalyseHeaders(ParsedHttpHdrs *Hdr)
292 HashPos *at = GetNewHashPos(Hdr->HTTPHeaders, 0);
294 while (GetNextHashPos(Hdr->HTTPHeaders, at, &HKLen, &HashKey, &vHdr) &&
296 pHdr = (OneHttpHeader *)vHdr;
297 if (pHdr->HaveEvaluator)
298 pHdr->H(pHdr->Val, Hdr);
305 /*const char *nix(void *vptr) {return ChrPtr( (StrBuf*)vptr);}*/
308 * Read in the request
310 int ReadHTTPRequset (ParsedHttpHdrs *Hdr)
312 const char *pch, *pchs, *pche;
314 StrBuf *Line, *LastLine, *HeaderName;
319 HeaderName = NewStrBuf();
320 Hdr->ReadBuf = NewStrBuf();
326 if (ClientGetLine(&Hdr->http_sock, Line, Hdr->ReadBuf, &Hdr->Pos) < 0) return 1;
328 if (StrLength(Line) == 0) {
333 lprintf(9, "%s\n", ChrPtr(Line));
334 isbogus = ReadHttpSubject(Hdr, Line, HeaderName);
339 /* Do we need to Unfold? */
340 if ((LastLine != NULL) &&
341 (isspace(*ChrPtr(Line)))) {
342 pch = pchs = ChrPtr(Line);
343 pche = pchs + StrLength(Line);
344 while (isspace(*pch) && (pch < pche))
346 StrBufCutLeft(Line, pch - pchs);
347 StrBufAppendBuf(LastLine, Line, 0);
353 StrBufSanitizeAscii(Line, '§');
354 StrBufExtract_token(HeaderName, Line, 0, ':');
357 pch = pchs + StrLength(HeaderName) + 1;
358 pche = pchs + StrLength(Line);
359 while (isspace(*pch) && (pch < pche))
361 StrBufCutLeft(Line, pch - pchs);
363 StrBufUpCase(HeaderName);
365 pHdr = (OneHttpHeader*) malloc(sizeof(OneHttpHeader));
366 memset(pHdr, 0, sizeof(OneHttpHeader));
369 if (GetHash(HttpHeaderHandler, SKEY(HeaderName), &vF) &&
372 OneHttpHeader *FHdr = (OneHttpHeader*) vF;
374 pHdr->HaveEvaluator = 1;
376 Put(Hdr->HTTPHeaders, SKEY(HeaderName), pHdr, DestroyHttpHeaderHandler);
378 } while (Line != NULL);
380 FreeStrBuf(&HeaderName);
390 * This loop gets called once for every HTTP connection made to WebCit. At
391 * this entry point we have an HTTP socket with a browser allegedly on the
392 * other end, but we have not yet bound to a WebCit session.
394 * The job of this function is to locate the correct session and bind to it,
395 * or create a session if necessary and bind to it, then run the WebCit
396 * transaction loop. Afterwards, we unbind from the session. When this
397 * function returns, the worker thread is then free to handle another
400 void context_loop(int *sock)
404 wcsession *TheSession, *sptr;
405 struct timeval tx_start;
406 struct timeval tx_finish;
408 gettimeofday(&tx_start, NULL); /* start a stopwatch for performance timing */
410 memset(&Hdr, 0, sizeof(ParsedHttpHdrs));
412 Hdr.http_sock = *sock;
414 * Find out what it is that the web browser is asking for
416 isbogus = ReadHTTPRequset(&Hdr);
419 isbogus = AnalyseHeaders(&Hdr);
422 ((Hdr.Handler != NULL) &&
423 ((Hdr.Handler->Flags & BOGUS) != 0)))
426 Bogus = (wcsession *)
427 malloc(sizeof(wcsession));
428 memset(Bogus, 0, sizeof(wcsession));
429 pthread_setspecific(MyConKey, (void *)Bogus);
431 Bogus->WBuf = NewStrBuf();
432 Bogus->HBuf = NewStrBuf();
433 session_new_modules(Bogus);
435 session_detach_modules(Bogus);
436 http_destroy_modules(&Hdr);
437 session_destroy_modules(&Bogus);
441 if ((Hdr.Handler != NULL) &&
442 ((Hdr.Handler->Flags & ISSTATIC) != 0))
446 Static = (wcsession *)
447 malloc(sizeof(wcsession));
448 memset(Static, 0, sizeof(wcsession));
449 pthread_setspecific(MyConKey, (void *)Static);
451 Static->WBuf = NewStrBuf();
452 Static->HBuf = NewStrBuf();
453 Static->serv_sock = (-1);
454 Static->chat_sock = (-1);
455 Static->is_mobile = -1;
456 session_new_modules(Static);
460 /* How long did this transaction take? */
461 gettimeofday(&tx_finish, NULL);
463 lprintf(9, "SL: Transaction [%s] completed in %ld.%06ld seconds.\n",
464 ChrPtr(Hdr.this_page),
465 ((tx_finish.tv_sec*1000000 + tx_finish.tv_usec) - (tx_start.tv_sec*1000000 + tx_start.tv_usec)) / 1000000,
466 ((tx_finish.tv_sec*1000000 + tx_finish.tv_usec) - (tx_start.tv_sec*1000000 + tx_start.tv_usec)) % 1000000
469 session_detach_modules(Static);
470 http_destroy_modules(&Hdr);
471 session_destroy_modules(&Static);
475 if (Hdr.got_auth == AUTH_BASIC)
476 CheckAuthBasic(&Hdr);
479 TODO HKEY("/static/nocookies.html?force_close_session=yes"));
482 /* dbg_PrintHash(HTTPHeaders, nix, NULL); */
485 /* Begin parsing the request. * /
487 if ((strncmp(ChrPtr(ReqLine), "/sslg", 5) != 0) &&
488 (strncmp(ChrPtr(ReqLine), "/static/", 8) != 0) &&
489 (strncmp(ChrPtr(ReqLine), "/tiny_mce/", 10) != 0) &&
490 (strncmp(ChrPtr(ReqLine), "/wholist_section", 16) != 0) &&
491 (strstr(ChrPtr(ReqLine), "wholist_section") == NULL)) {
493 lprintf(5, "HTTP: %s %s\n", ReqStrs[Hdr.eReqType], ChrPtr(ReqLine));
501 * See if there's an existing session open with the desired ID or user/pass
505 if (TheSession == NULL) {
506 pthread_mutex_lock(&SessionListMutex);
507 for (sptr = SessionList;
508 ((sptr != NULL) && (TheSession == NULL));
511 /** If HTTP-AUTH, look for a session with matching credentials */
512 switch (Hdr.got_auth)
515 if ( (Hdr.SessionKey != sptr->SessionKey))
518 if ((!strcasecmp(ChrPtr(Hdr.c_username), ChrPtr(sptr->wc_username))) &&
519 (!strcasecmp(ChrPtr(Hdr.c_password), ChrPtr(sptr->wc_password))) )
523 /** If cookie-session, look for a session with matching session ID */
524 if ( (Hdr.desired_session != 0) &&
525 (sptr->wc_session == Hdr.desired_session))
532 pthread_mutex_unlock(&SessionListMutex);
536 * Create a new session if we have to
538 if (TheSession == NULL) {
539 lprintf(3, "Creating a new session\n");
540 TheSession = (wcsession *)
541 malloc(sizeof(wcsession));
542 memset(TheSession, 0, sizeof(wcsession));
543 TheSession->Hdr = &Hdr;
544 TheSession->SessionKey = Hdr.SessionKey;
545 TheSession->serv_sock = (-1);
546 TheSession->chat_sock = (-1);
548 /* If we're recreating a session that expired, it's best to give it the same
549 * session number that it had before. The client browser ought to pick up
550 * the new session number and start using it, but in some rare situations it
551 * doesn't, and that's a Bad Thing because it causes lots of spurious sessions
554 if (Hdr.desired_session == 0) {
555 TheSession->wc_session = GenerateSessionID();
558 TheSession->wc_session = Hdr.desired_session;
561 pthread_setspecific(MyConKey, (void *)TheSession);
562 session_new_modules(TheSession);
564 pthread_mutex_init(&TheSession->SessionMutex, NULL);
565 pthread_mutex_lock(&SessionListMutex);
566 TheSession->nonce = rand();
567 TheSession->next = SessionList;
568 TheSession->is_mobile = -1;
569 SessionList = TheSession;
570 pthread_mutex_unlock(&SessionListMutex);
572 if (StrLength(Hdr.c_language) > 0) {
573 lprintf(9, "Session cookie requests language '%s'\n", ChrPtr(Hdr.c_language));
574 set_selected_language(ChrPtr(Hdr.c_language));
575 go_selected_language();
580 * A future improvement might be to check the session integrity
581 * at this point before continuing.
585 * Bind to the session and perform the transaction
587 pthread_mutex_lock(&TheSession->SessionMutex); /* bind */
588 pthread_setspecific(MyConKey, (void *)TheSession);
590 TheSession->lastreq = time(NULL); /* log */
591 TheSession->Hdr = &Hdr;
593 session_attach_modules(TheSession);
594 session_loop(); /* do transaction */
597 /* How long did this transaction take? */
598 gettimeofday(&tx_finish, NULL);
600 lprintf(9, "Transaction [%s] completed in %ld.%06ld seconds.\n",
601 ChrPtr(Hdr.this_page),
602 ((tx_finish.tv_sec*1000000 + tx_finish.tv_usec) - (tx_start.tv_sec*1000000 + tx_start.tv_usec)) / 1000000,
603 ((tx_finish.tv_sec*1000000 + tx_finish.tv_usec) - (tx_start.tv_sec*1000000 + tx_start.tv_usec)) % 1000000
606 session_detach_modules(TheSession);
608 TheSession->Hdr = NULL;
609 pthread_mutex_unlock(&TheSession->SessionMutex); /* unbind */
611 http_destroy_modules(&Hdr);
614 void tmplput_nonce(StrBuf *Target, WCTemplputParams *TP)
617 StrBufAppendPrintf(Target, "%ld",
618 (WCC != NULL)? WCC->nonce:0);
621 void tmplput_current_user(StrBuf *Target, WCTemplputParams *TP)
623 StrBufAppendTemplate(Target, TP, WC->wc_fullname, 0);
626 void tmplput_current_room(StrBuf *Target, WCTemplputParams *TP)
628 StrBufAppendTemplate(Target, TP, WC->wc_roomname, 0);
631 void Header_HandleContentLength(StrBuf *Line, ParsedHttpHdrs *hdr)
633 hdr->ContentLength = StrToi(Line);
636 void Header_HandleContentType(StrBuf *Line, ParsedHttpHdrs *hdr)
638 hdr->ContentType = Line;
641 void Header_HandleUserAgent(StrBuf *Line, ParsedHttpHdrs *hdr)
643 hdr->user_agent = Line;
645 /* TODO: do this later on session creating
646 if ((WCC->is_mobile < 0) && is_mobile_ua(&buf[12])) {
657 void Header_HandleHost(StrBuf *Line, ParsedHttpHdrs *hdr)
659 if ((follow_xff) && (hdr->http_host != NULL))
662 hdr->http_host = Line;
665 void Header_HandleXFFHost(StrBuf *Line, ParsedHttpHdrs *hdr)
668 hdr->http_host = Line;
672 void Header_HandleXFF(StrBuf *Line, ParsedHttpHdrs *hdr)
674 hdr->browser_host = Line;
676 while (StrBufNum_tokens(hdr->browser_host, ',') > 1) {
677 StrBufRemove_token(hdr->browser_host, 0, ',');
679 StrBufTrim(hdr->browser_host);
682 void Header_HandleIfModSince(StrBuf *Line, ParsedHttpHdrs *hdr)
684 hdr->if_modified_since = httpdate_to_timestamp(Line);
687 void Header_HandleAcceptEncoding(StrBuf *Line, ParsedHttpHdrs *hdr)
692 if (strstr(&ChrPtr(Line)[16], "gzip")) {
696 const char *ReqStrs[eNONE] = {
709 ServerStartModule_CONTEXT
713 HttpReqTypes = NewHash(1, NULL);
714 HttpHeaderHandler = NewHash(1, NULL);
716 v = malloc(sizeof(long));
718 Put(HttpReqTypes, HKEY("GET"), v, NULL);
720 v = malloc(sizeof(long));
722 Put(HttpReqTypes, HKEY("POST"), v, NULL);
724 v = malloc(sizeof(long));
726 Put(HttpReqTypes, HKEY("OPTIONS"), v, NULL);
728 v = malloc(sizeof(long));
730 Put(HttpReqTypes, HKEY("PROPFIND"), v, NULL);
732 v = malloc(sizeof(long));
734 Put(HttpReqTypes, HKEY("PUT"), v, NULL);
736 v = malloc(sizeof(long));
738 Put(HttpReqTypes, HKEY("DELETE"), v, NULL);
740 v = malloc(sizeof(long));
742 Put(HttpReqTypes, HKEY("HEAD"), v, NULL);
744 v = malloc(sizeof(long));
746 Put(HttpReqTypes, HKEY("MOVE"), v, NULL);
748 v = malloc(sizeof(long));
750 Put(HttpReqTypes, HKEY("COPY"), v, NULL);
754 ServerShutdownModule_CONTEXT
757 DeleteHash(&HttpReqTypes);
758 DeleteHash(&HttpHeaderHandler);
761 void RegisterHeaderHandler(const char *Name, long Len, Header_Evaluator F)
764 pHdr = (OneHttpHeader*) malloc(sizeof(OneHttpHeader));
765 memset(pHdr, 0, sizeof(OneHttpHeader));
767 Put(HttpHeaderHandler, Name, Len, pHdr, DestroyHttpHeaderHandler);
775 RegisterHeaderHandler(HKEY("CONTENT-LENGTH"), Header_HandleContentLength);
776 RegisterHeaderHandler(HKEY("CONTENT-TYPE"), Header_HandleContentType);
777 RegisterHeaderHandler(HKEY("USER-AGENT"), Header_HandleUserAgent);
778 RegisterHeaderHandler(HKEY("X-FORWARDED-HOST"), Header_HandleXFFHost);
779 RegisterHeaderHandler(HKEY("HOST"), Header_HandleHost);
780 RegisterHeaderHandler(HKEY("X-FORWARDED-FOR"), Header_HandleXFF);
781 RegisterHeaderHandler(HKEY("ACCEPT-ENCODING"), Header_HandleAcceptEncoding);
782 RegisterHeaderHandler(HKEY("IF-MODIFIED-SINCE"), Header_HandleIfModSince);
784 RegisterNamespace("CURRENT_USER", 0, 1, tmplput_current_user, CTX_NONE);
785 RegisterNamespace("CURRENT_ROOM", 0, 1, tmplput_current_room, CTX_NONE);
786 RegisterNamespace("NONCE", 0, 0, tmplput_nonce, 0);
788 WebcitAddUrlHandler(HKEY("404"), do_404, ANONYMOUS|COOKIEUNNEEDED);
790 * Look for commonly-found probes of malware such as worms, viruses, trojans, and Microsoft Office.
791 * Short-circuit these requests so we don't have to send them through the full processing loop.
793 WebcitAddUrlHandler(HKEY("scripts"), do_404, ANONYMOUS|BOGUS); /* /root.exe /* Worms and trojans and viruses, oh my! */
794 WebcitAddUrlHandler(HKEY("c"), do_404, ANONYMOUS|BOGUS); /* /winnt */
795 WebcitAddUrlHandler(HKEY("MSADC"), do_404, ANONYMOUS|BOGUS);
796 WebcitAddUrlHandler(HKEY("_vti"), do_404, ANONYMOUS|BOGUS); /* Broken Microsoft DAV implementation */
797 WebcitAddUrlHandler(HKEY("MSOffice"), do_404, ANONYMOUS|BOGUS); /* Stoopid MSOffice thinks everyone is IIS */
798 WebcitAddUrlHandler(HKEY("nonexistenshit"), do_404, ANONYMOUS|BOGUS); /* Exploit found in the wild January 2009 */
804 HttpDestroyModule_CONTEXT
805 (ParsedHttpHdrs *httpreq)
807 FreeStrBuf(&httpreq->ReqLine);
808 FreeStrBuf(&httpreq->ReadBuf);
809 FreeStrBuf(&httpreq->PlainArgs);
810 FreeStrBuf(&httpreq->this_page);
811 DeleteHash(&httpreq->HTTPHeaders);