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"
14 /* Only one thread may manipulate SessionList at a time... */
15 pthread_mutex_t SessionListMutex;
17 wcsession *SessionList = NULL; /**< our sessions ????*/
19 pthread_key_t MyConKey; /**< TSD key for MySession() */
23 void DestroySession(wcsession **sessions_to_kill)
25 close((*sessions_to_kill)->serv_sock);
26 close((*sessions_to_kill)->chat_sock);
28 // if ((*sessions_to_kill)->preferences != NULL) {
29 // free((*sessions_to_kill)->preferences);
32 if ((*sessions_to_kill)->cache_fold != NULL) {
33 free((*sessions_to_kill)->cache_fold);
35 DeleteHash(&((*sessions_to_kill)->attachments));
36 free_march_list((*sessions_to_kill));
37 DeleteHash(&((*sessions_to_kill)->hash_prefs));
38 DeleteHash(&((*sessions_to_kill)->IconBarSettings));
39 DeleteHash(&((*sessions_to_kill)->ServCfg));
40 FreeStrBuf(&((*sessions_to_kill)->UrlFragment1));
41 FreeStrBuf(&((*sessions_to_kill)->UrlFragment2));
42 FreeStrBuf(&((*sessions_to_kill)->UrlFragment3));
43 FreeStrBuf(&((*sessions_to_kill)->WBuf));
44 FreeStrBuf(&((*sessions_to_kill)->HBuf));
45 FreeStrBuf(&((*sessions_to_kill)->CLineBuf));
46 FreeStrBuf(&((*sessions_to_kill)->wc_username));
47 FreeStrBuf(&((*sessions_to_kill)->wc_fullname));
48 FreeStrBuf(&((*sessions_to_kill)->wc_password));
49 FreeStrBuf(&((*sessions_to_kill)->wc_roomname));
50 FreeStrBuf(&((*sessions_to_kill)->httpauth_user));
51 FreeStrBuf(&((*sessions_to_kill)->httpauth_pass));
52 free((*sessions_to_kill));
53 (*sessions_to_kill) = NULL;
56 void shutdown_sessions(void)
60 for (sptr = SessionList; sptr != NULL; sptr = sptr->next) {
65 void do_housekeeping(void)
68 wcsession *sessions_to_kill = NULL;
70 static int num_threads = MIN_WORKER_THREADS;
73 * Lock the session list, moving any candidates for euthanasia into
76 pthread_mutex_lock(&SessionListMutex);
78 for (sptr = SessionList; sptr != NULL; sptr = sptr->next) {
81 /** Kill idle sessions */
82 if ((time(NULL) - (sptr->lastreq)) >
83 (time_t) WEBCIT_TIMEOUT) {
87 /** Remove sessions flagged for kill */
90 /** remove session from linked list */
91 if (sptr == SessionList) {
92 SessionList = SessionList->next;
94 else for (ss=SessionList;ss!=NULL;ss=ss->next) {
95 if (ss->next == sptr) {
96 ss->next = ss->next->next;
100 sptr->next = sessions_to_kill;
101 sessions_to_kill = sptr;
104 pthread_mutex_unlock(&SessionListMutex);
107 * Now free up and destroy the culled sessions.
109 while (sessions_to_kill != NULL) {
110 lprintf(3, "Destroying session %d\n", sessions_to_kill->wc_session);
111 pthread_mutex_lock(&sessions_to_kill->SessionMutex);
112 pthread_mutex_unlock(&sessions_to_kill->SessionMutex);
113 sptr = sessions_to_kill->next;
115 DestroySession(&sessions_to_kill);
116 sessions_to_kill = sptr;
121 * If there are more sessions than threads, then we should spawn
122 * more threads ... up to a predefined maximum.
124 while ( (num_sessions > num_threads)
125 && (num_threads <= MAX_WORKER_THREADS) ) {
126 spawn_another_worker_thread();
128 lprintf(3, "There are %d sessions and %d threads active.\n",
129 num_sessions, num_threads);
135 * \brief Wake up occasionally and clean house
137 void housekeeping_loop(void)
140 sleeeeeeeeeep(HOUSEKEEPING);
147 * \brief Create a Session id
148 * Generate a unique WebCit session ID (which is not the same thing as the
149 * Citadel session ID).
151 * \todo FIXME ... ensure that session number is truly unique
154 int GenerateSessionID(void)
156 static int seq = (-1);
159 seq = (int) time(NULL);
166 * Collapse multiple cookies on one line
168 int ReqGetStrBuf(int *sock, StrBuf *Target, StrBuf *buf)
171 return ClientGetLine(sock, Target, buf);
177 * lingering_close() a`la Apache. see
178 * http://www.apache.org/docs/misc/fin_wait_2.html for rationale
180 int lingering_close(int fd)
185 struct timeval tv, start;
187 gettimeofday(&start, NULL);
191 gettimeofday(&tv, NULL);
192 tv.tv_sec = SLEEPING - (tv.tv_sec - start.tv_sec);
193 tv.tv_usec = start.tv_usec - tv.tv_usec;
194 if (tv.tv_usec < 0) {
196 tv.tv_usec += 1000000;
200 i = select(fd + 1, &set, NULL, NULL, &tv);
201 } while (i == -1 && errno == EINTR);
206 i = read(fd, buf, sizeof buf);
207 } while (i != 0 && (i != -1 || errno == EINTR));
215 * Look for commonly-found probes of malware such as worms, viruses, trojans, and Microsoft Office.
216 * Short-circuit these requests so we don't have to send them through the full processing loop.
218 int is_bogus(StrBuf *http_cmd) {
221 const char *bogus_prefixes[] = {
222 "/scripts/root.exe", /* Worms and trojans and viruses, oh my! */
225 "/_vti", /* Broken Microsoft DAV implementation */
226 "/MSOffice", /* Stoopid MSOffice thinks everyone is IIS */
227 "/nonexistenshit" /* Exploit found in the wild January 2009 */
230 url = ChrPtr(http_cmd);
231 if (IsEmptyStr(url)) return(1);
234 max = sizeof(bogus_prefixes) / sizeof(char *);
236 for (i=0; i<max; ++i) {
237 if (!strncasecmp(url, bogus_prefixes[i], strlen(bogus_prefixes[i]))) {
242 return(0); /* probably ok */
246 const char *nix(void *vptr) {return ChrPtr( (StrBuf*)vptr);}
249 * \brief handle one request
250 * This loop gets called once for every HTTP connection made to WebCit. At
251 * this entry point we have an HTTP socket with a browser allegedly on the
252 * other end, but we have not yet bound to a WebCit session.
254 * The job of this function is to locate the correct session and bind to it,
255 * or create a session if necessary and bind to it, then run the WebCit
256 * transaction loop. Afterwards, we unbind from the session. When this
257 * function returns, the worker thread is then free to handle another
259 * \param sock the socket we will put our answer to
261 void context_loop(int *sock)
264 int desired_session = 0;
267 wcsession *TheSession, *sptr;
268 char httpauth_string[1024];
269 char httpauth_user[1024];
270 char httpauth_pass[1024];
272 int session_is_new = 0;
276 StrBuf *Buf, *Line, *LastLine, *HeaderName, *ReqLine, *ReqType, *HTTPVersion;
277 StrBuf *accept_language = NULL;
278 const char *pch, *pchs, *pche;
279 HashList *HTTPHeaders;
281 strcpy(httpauth_string, "");
282 strcpy(httpauth_user, DEFAULT_HTTPAUTH_USER);
283 strcpy(httpauth_pass, DEFAULT_HTTPAUTH_PASS);
286 * Find out what it is that the web browser is asking for
288 HeaderName = NewStrBuf();
291 HTTPHeaders = NewHash(1, NULL);
293 * Read in the request
298 if (ReqGetStrBuf(sock, Line, Buf) < 0) return;
300 LineLen = StrLength(Line);
311 /** Do we need to Unfold? */
312 if ((LastLine != NULL) &&
313 (isspace(*ChrPtr(Line)))) {
314 pch = pchs = ChrPtr(Line);
315 pche = pchs + StrLength(Line);
316 while (isspace(*pch) && (pch < pche))
318 StrBufCutLeft(Line, pch - pchs);
319 StrBufAppendBuf(LastLine, Line, 0);
324 StrBufExtract_token(HeaderName, Line, 0, ':');
325 /*/// TODO: filter bad chars! */
328 pch = pchs + StrLength(HeaderName) + 1;
329 pche = pchs + StrLength(Line);
330 while (isspace(*pch) && (pch < pche))
332 StrBufCutLeft(Line, pch - pchs);
334 StrBufUpCase(HeaderName);
335 Put(HTTPHeaders, SKEY(HeaderName), Line, HFreeStrBuf);
337 } while (LineLen > 0);
338 FreeStrBuf(&HeaderName);
340 /*/// dbg_PrintHash(HTTPHeaders, nix, NULL); */
346 if (GetHash(HTTPHeaders, HKEY("ACCEPT-ENCODING"), &vLine) &&
348 buf = ChrPtr((StrBuf*)vLine);
349 if (strstr(&buf[16], "gzip")) {
355 * Browser-based sessions use cookies for session
359 if (GetHash(HTTPHeaders, HKEY("COOKIE"), &vLine) &&
361 cookie_to_stuff(vLine, &desired_session,
367 * GroupDAV-based sessions use HTTP authentication
369 if (GetHash(HTTPHeaders, HKEY("AUTHORIZATION"), &vLine) &&
371 Line = (StrBuf*)vLine;
372 if (strncasecmp(ChrPtr(Line), "Basic", 5) == 0) {
373 StrBufCutLeft(Line, 6);
374 CtdlDecodeBase64(httpauth_string, ChrPtr(Line), StrLength(Line));
375 extract_token(httpauth_user, httpauth_string, 0, ':', sizeof httpauth_user);
376 extract_token(httpauth_pass, httpauth_string, 1, ':', sizeof httpauth_pass);
379 lprintf(1, "Authentication scheme not supported! [%s]\n", ChrPtr(Line));
382 if (GetHash(HTTPHeaders, HKEY("IF-MODIFIED-SINCE"), &vLine) &&
384 if_modified_since = httpdate_to_timestamp((StrBuf*)vLine);
387 if (GetHash(HTTPHeaders, HKEY("ACCEPT-LANGUAGE"), &vLine) &&
389 accept_language = (StrBuf*) vLine;
394 * If the request is prefixed by "/webcit" then chop that off. This
395 * allows a front end web server to forward all /webcit requests to us
396 * while still using the same web server port for other things.
399 ReqType = NewStrBuf();
400 HTTPVersion = NewStrBuf();
401 StrBufExtract_token(HTTPVersion, ReqLine, 2, ' ');
402 StrBufExtract_token(ReqType, ReqLine, 0, ' ');
403 StrBufCutLeft(ReqLine, StrLength(ReqType) + 1);
404 StrBufCutRight(ReqLine, StrLength(HTTPVersion) + 1);
406 if ((follow_xff == 1) && (StrLength(ReqLine) >= 8) &&
407 (ptr = strstr(ChrPtr(ReqLine), "/webcit/"), /*< Handle "/webcit/" */
409 StrBufCutLeft(ReqLine, 7);
412 /** Begin parsing the request. */
414 if ((strncmp(ChrPtr(ReqLine), "/sslg", 5) != 0) &&
415 (strncmp(ChrPtr(ReqLine), "/static/", 8) != 0) &&
416 (strncmp(ChrPtr(ReqLine), "/tiny_mce/", 10) != 0) &&
417 (strncmp(ChrPtr(ReqLine), "/wholist_section", 16) != 0) &&
418 (strstr(ChrPtr(ReqLine), "wholist_section") == NULL)) {
420 lprintf(5, "HTTP: %s %s %s\n", ChrPtr(ReqType), ChrPtr(ReqLine), ChrPtr(HTTPVersion));
425 /** Check for bogus requests */
426 if ((StrLength(HTTPVersion) == 0) ||
427 (StrLength(ReqType) == 0) ||
429 StrBufPlain(ReqLine, HKEY("/404 HTTP/1.1"));
430 StrBufPlain(ReqType, HKEY("GET"));
432 FreeStrBuf(&HTTPVersion);
435 * While we're at it, gracefully handle requests for the
436 * robots.txt and favicon.ico files.
438 if (!strncasecmp(ChrPtr(ReqLine), "/robots.txt", 11)) {
440 HKEY("/static/robots.txt"
441 "?force_close_session=yes HTTP/1.1"));
442 StrBufPlain(ReqType, HKEY("GET"));
444 else if (!strncasecmp(ChrPtr(ReqLine), "/favicon.ico", 12)) {
445 StrBufPlain(ReqLine, HKEY("/static/favicon.ico"));
446 StrBufPlain(ReqType, HKEY("GET"));
450 * These are the URL's which may be executed without a
451 * session cookie already set. If it's not one of these,
452 * force the session to close because cookies are
453 * probably disabled on the client browser.
455 else if ( (StrLength(ReqLine) > 1 )
456 && (strncasecmp(ChrPtr(ReqLine), "/listsub", 8))
457 && (strncasecmp(ChrPtr(ReqLine), "/freebusy", 9))
458 && (strncasecmp(ChrPtr(ReqLine), "/do_logout", 10))
459 && (strncasecmp(ChrPtr(ReqLine), "/groupdav", 9))
460 && (strncasecmp(ChrPtr(ReqLine), "/static", 7))
461 && (strncasecmp(ChrPtr(ReqLine), "/rss", 4))
462 && (strncasecmp(ChrPtr(ReqLine), "/404", 4))
463 && (got_cookie == 0)) {
465 HKEY("/static/nocookies.html"
466 "?force_close_session=yes"));
470 * See if there's an existing session open with the desired ID or user/pass
474 if (TheSession == NULL) {
475 pthread_mutex_lock(&SessionListMutex);
476 for (sptr = SessionList; sptr != NULL; sptr = sptr->next) {
478 /** If HTTP-AUTH, look for a session with matching credentials */
479 if ( (!IsEmptyStr(httpauth_user))
480 &&(!strcasecmp(ChrPtr(sptr->httpauth_user), httpauth_user))
481 &&(!strcasecmp(ChrPtr(sptr->httpauth_pass), httpauth_pass)) ) {
485 /** If cookie-session, look for a session with matching session ID */
486 if ( (desired_session != 0) && (sptr->wc_session == desired_session)) {
491 pthread_mutex_unlock(&SessionListMutex);
495 * Create a new session if we have to
497 if (TheSession == NULL) {
498 lprintf(3, "Creating a new session\n");
499 TheSession = (wcsession *)
500 malloc(sizeof(wcsession));
501 memset(TheSession, 0, sizeof(wcsession));
502 TheSession->serv_sock = (-1);
503 TheSession->chat_sock = (-1);
505 /* If we're recreating a session that expired, it's best to give it the same
506 * session number that it had before. The client browser ought to pick up
507 * the new session number and start using it, but in some rare situations it
508 * doesn't, and that's a Bad Thing because it causes lots of spurious sessions
511 if (desired_session == 0) {
512 TheSession->wc_session = GenerateSessionID();
515 TheSession->wc_session = desired_session;
518 if (TheSession->httpauth_user != NULL){
519 FlushStrBuf(TheSession->httpauth_user);
520 StrBufAppendBufPlain(TheSession->httpauth_user, httpauth_user, -1, 0);
522 else TheSession->httpauth_user = NewStrBufPlain(httpauth_user, -1);
523 if (TheSession->httpauth_user != NULL){
524 FlushStrBuf(TheSession->httpauth_pass);
525 StrBufAppendBufPlain(TheSession->httpauth_pass, httpauth_user, -1, 0);
527 else TheSession->httpauth_pass = NewStrBufPlain(httpauth_user, -1);
529 TheSession->hash_prefs = NewHash(1,NULL); /* Get a hash table for the user preferences */
530 pthread_mutex_init(&TheSession->SessionMutex, NULL);
531 pthread_mutex_lock(&SessionListMutex);
532 TheSession->urlstrings = NULL;
533 TheSession->vars = NULL;
534 TheSession->nonce = rand();
535 TheSession->WBuf = NULL;
536 TheSession->CLineBuf = NewStrBuf();
537 TheSession->next = SessionList;
538 TheSession->is_mobile = -1;
539 SessionList = TheSession;
540 pthread_mutex_unlock(&SessionListMutex);
545 * A future improvement might be to check the session integrity
546 * at this point before continuing.
550 * Bind to the session and perform the transaction
552 pthread_mutex_lock(&TheSession->SessionMutex); /* bind */
553 pthread_setspecific(MyConKey, (void *)TheSession);
555 TheSession->urlstrings = NewHash(1,NULL);
556 TheSession->vars = NewHash(1,NULL);
557 TheSession->http_sock = *sock;
558 TheSession->lastreq = time(NULL); /* log */
559 TheSession->gzip_ok = gzip_ok;
561 if (session_is_new) {
562 httplang_to_locale(accept_language);
564 go_selected_language(); /* set locale */
566 session_loop(HTTPHeaders, ReqLine, ReqType, Buf); /* do transaction */
568 stop_selected_language(); /* unset locale */
570 DeleteHash(&TheSession->summ);
571 DeleteHash(&TheSession->urlstrings);
572 DeleteHash(&TheSession->vars);
573 FreeStrBuf(&TheSession->WBuf);
574 FreeStrBuf(&TheSession->HBuf);
577 pthread_mutex_unlock(&TheSession->SessionMutex); /* unbind */
579 /* Free the request buffer */
580 DeleteHash(&HTTPHeaders);
581 FreeStrBuf(&ReqLine);
582 FreeStrBuf(&ReqType);
585 * Free up any session-local substitution variables which
586 * were set during this transaction
592 void tmplput_nonce(StrBuf *Target, WCTemplputParams *TP)
595 StrBufAppendPrintf(Target, "%ld",
596 (WCC != NULL)? WCC->nonce:0);
599 void tmplput_current_user(StrBuf *Target, WCTemplputParams *TP)
601 StrBufAppendTemplate(Target, TP, WC->wc_fullname, 0);
604 void tmplput_current_room(StrBuf *Target, WCTemplputParams *TP)
606 StrBufAppendTemplate(Target, TP, WC->wc_roomname, 0);
615 RegisterNamespace("CURRENT_USER", 0, 1, tmplput_current_user, CTX_NONE);
616 RegisterNamespace("CURRENT_ROOM", 0, 1, tmplput_current_room, CTX_NONE);
617 RegisterNamespace("NONCE", 0, 0, tmplput_nonce, 0);