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 * Wake up occasionally and clean house
137 void housekeeping_loop(void)
140 sleeeeeeeeeep(HOUSEKEEPING);
147 * Create a Session id
148 * Generate a unique WebCit session ID (which is not the same thing as the
149 * Citadel session ID).
151 int GenerateSessionID(void)
153 static int seq = (-1);
156 seq = (int) time(NULL);
163 * Collapse multiple cookies on one line
165 int ReqGetStrBuf(int *sock, StrBuf *Target, StrBuf *buf)
168 return ClientGetLine(sock, Target, buf);
174 * lingering_close() a`la Apache. see
175 * http://www.apache.org/docs/misc/fin_wait_2.html for rationale
177 int lingering_close(int fd)
182 struct timeval tv, start;
184 gettimeofday(&start, NULL);
188 gettimeofday(&tv, NULL);
189 tv.tv_sec = SLEEPING - (tv.tv_sec - start.tv_sec);
190 tv.tv_usec = start.tv_usec - tv.tv_usec;
191 if (tv.tv_usec < 0) {
193 tv.tv_usec += 1000000;
197 i = select(fd + 1, &set, NULL, NULL, &tv);
198 } while (i == -1 && errno == EINTR);
203 i = read(fd, buf, sizeof buf);
204 } while (i != 0 && (i != -1 || errno == EINTR));
212 * Look for commonly-found probes of malware such as worms, viruses, trojans, and Microsoft Office.
213 * Short-circuit these requests so we don't have to send them through the full processing loop.
215 int is_bogus(StrBuf *http_cmd) {
218 const char *bogus_prefixes[] = {
219 "/scripts/root.exe", /* Worms and trojans and viruses, oh my! */
222 "/_vti", /* Broken Microsoft DAV implementation */
223 "/MSOffice", /* Stoopid MSOffice thinks everyone is IIS */
224 "/nonexistenshit" /* Exploit found in the wild January 2009 */
227 url = ChrPtr(http_cmd);
228 if (IsEmptyStr(url)) return(1);
231 max = sizeof(bogus_prefixes) / sizeof(char *);
233 for (i=0; i<max; ++i) {
234 if (!strncasecmp(url, bogus_prefixes[i], strlen(bogus_prefixes[i]))) {
239 return(0); /* probably ok */
243 const char *nix(void *vptr) {return ChrPtr( (StrBuf*)vptr);}
248 * This loop gets called once for every HTTP connection made to WebCit. At
249 * this entry point we have an HTTP socket with a browser allegedly on the
250 * other end, but we have not yet bound to a WebCit session.
252 * The job of this function is to locate the correct session and bind to it,
253 * or create a session if necessary and bind to it, then run the WebCit
254 * transaction loop. Afterwards, we unbind from the session. When this
255 * function returns, the worker thread is then free to handle another
258 void context_loop(int *sock)
261 int desired_session = 0;
264 wcsession *TheSession, *sptr;
265 char httpauth_string[1024];
266 char httpauth_user[1024];
267 char httpauth_pass[1024];
268 int session_is_new = 0;
272 StrBuf *Buf, *Line, *LastLine, *HeaderName, *ReqLine, *ReqType, *HTTPVersion;
273 StrBuf *accept_language = NULL;
274 const char *pch, *pchs, *pche;
275 HashList *HTTPHeaders;
277 strcpy(httpauth_string, "");
278 strcpy(httpauth_user, DEFAULT_HTTPAUTH_USER);
279 strcpy(httpauth_pass, DEFAULT_HTTPAUTH_PASS);
282 * Find out what it is that the web browser is asking for
284 HeaderName = NewStrBuf();
287 HTTPHeaders = NewHash(1, NULL);
290 * Read in the request
295 if (ReqGetStrBuf(sock, Line, Buf) < 0) return;
297 LineLen = StrLength(Line);
308 /* Do we need to Unfold? */
309 if ((LastLine != NULL) &&
310 (isspace(*ChrPtr(Line)))) {
311 pch = pchs = ChrPtr(Line);
312 pche = pchs + StrLength(Line);
313 while (isspace(*pch) && (pch < pche))
315 StrBufCutLeft(Line, pch - pchs);
316 StrBufAppendBuf(LastLine, Line, 0);
321 StrBufExtract_token(HeaderName, Line, 0, ':');
322 /*/// TODO: filter bad chars! */
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);
332 Put(HTTPHeaders, SKEY(HeaderName), Line, HFreeStrBuf);
334 } while (LineLen > 0);
335 FreeStrBuf(&HeaderName);
337 /*/// dbg_PrintHash(HTTPHeaders, nix, NULL); */
343 if (GetHash(HTTPHeaders, HKEY("ACCEPT-ENCODING"), &vLine) &&
345 buf = ChrPtr((StrBuf*)vLine);
346 if (strstr(&buf[16], "gzip")) {
352 * Browser-based sessions use cookies for session authentication
354 if (GetHash(HTTPHeaders, HKEY("COOKIE"), &vLine) &&
356 cookie_to_stuff(vLine, &desired_session,
362 * GroupDAV-based sessions use HTTP authentication
364 if (GetHash(HTTPHeaders, HKEY("AUTHORIZATION"), &vLine) &&
366 Line = (StrBuf*)vLine;
367 if (strncasecmp(ChrPtr(Line), "Basic", 5) == 0) {
368 StrBufCutLeft(Line, 6);
369 CtdlDecodeBase64(httpauth_string, ChrPtr(Line), StrLength(Line));
370 extract_token(httpauth_user, httpauth_string, 0, ':', sizeof httpauth_user);
371 extract_token(httpauth_pass, httpauth_string, 1, ':', sizeof httpauth_pass);
374 lprintf(1, "Authentication scheme not supported! [%s]\n", ChrPtr(Line));
377 if (GetHash(HTTPHeaders, HKEY("IF-MODIFIED-SINCE"), &vLine) &&
379 if_modified_since = httpdate_to_timestamp((StrBuf*)vLine);
382 if (GetHash(HTTPHeaders, HKEY("ACCEPT-LANGUAGE"), &vLine) &&
384 accept_language = (StrBuf*) vLine;
388 ReqType = NewStrBuf();
389 HTTPVersion = NewStrBuf();
390 StrBufExtract_token(HTTPVersion, ReqLine, 2, ' ');
391 StrBufExtract_token(ReqType, ReqLine, 0, ' ');
392 StrBufCutLeft(ReqLine, StrLength(ReqType) + 1);
393 StrBufCutRight(ReqLine, StrLength(HTTPVersion) + 1);
396 * If the request is prefixed by "/webcit" then chop that off. This
397 * allows a front end web server to forward all /webcit requests to us
398 * while still using the same web server port for other things.
400 if ( (StrLength(ReqLine) >= 8) && (strstr(ChrPtr(ReqLine), "/webcit/")) ) {
401 StrBufCutLeft(ReqLine, 7);
404 /* Begin parsing the request. */
406 if ((strncmp(ChrPtr(ReqLine), "/sslg", 5) != 0) &&
407 (strncmp(ChrPtr(ReqLine), "/static/", 8) != 0) &&
408 (strncmp(ChrPtr(ReqLine), "/tiny_mce/", 10) != 0) &&
409 (strncmp(ChrPtr(ReqLine), "/wholist_section", 16) != 0) &&
410 (strstr(ChrPtr(ReqLine), "wholist_section") == NULL)) {
412 lprintf(5, "HTTP: %s %s %s\n", ChrPtr(ReqType), ChrPtr(ReqLine), ChrPtr(HTTPVersion));
417 /** Check for bogus requests */
418 if ((StrLength(HTTPVersion) == 0) ||
419 (StrLength(ReqType) == 0) ||
421 StrBufPlain(ReqLine, HKEY("/404 HTTP/1.1"));
422 StrBufPlain(ReqType, HKEY("GET"));
424 FreeStrBuf(&HTTPVersion);
427 * While we're at it, gracefully handle requests for the
428 * robots.txt and favicon.ico files.
430 if (!strncasecmp(ChrPtr(ReqLine), "/robots.txt", 11)) {
432 HKEY("/static/robots.txt"
433 "?force_close_session=yes HTTP/1.1"));
434 StrBufPlain(ReqType, HKEY("GET"));
436 else if (!strncasecmp(ChrPtr(ReqLine), "/favicon.ico", 12)) {
437 StrBufPlain(ReqLine, HKEY("/static/favicon.ico"));
438 StrBufPlain(ReqType, HKEY("GET"));
442 * These are the URL's which may be executed without a
443 * session cookie already set. If it's not one of these,
444 * force the session to close because cookies are
445 * probably disabled on the client browser.
447 else if ( (StrLength(ReqLine) > 1 )
448 && (strncasecmp(ChrPtr(ReqLine), "/listsub", 8))
449 && (strncasecmp(ChrPtr(ReqLine), "/freebusy", 9))
450 && (strncasecmp(ChrPtr(ReqLine), "/do_logout", 10))
451 && (strncasecmp(ChrPtr(ReqLine), "/groupdav", 9))
452 && (strncasecmp(ChrPtr(ReqLine), "/static", 7))
453 && (strncasecmp(ChrPtr(ReqLine), "/rss", 4))
454 && (strncasecmp(ChrPtr(ReqLine), "/404", 4))
455 && (got_cookie == 0)) {
457 HKEY("/static/nocookies.html"
458 "?force_close_session=yes"));
462 * See if there's an existing session open with the desired ID or user/pass
466 if (TheSession == NULL) {
467 pthread_mutex_lock(&SessionListMutex);
468 for (sptr = SessionList; sptr != NULL; sptr = sptr->next) {
470 /** If HTTP-AUTH, look for a session with matching credentials */
471 if ( (!IsEmptyStr(httpauth_user))
472 &&(!strcasecmp(ChrPtr(sptr->httpauth_user), httpauth_user))
473 &&(!strcasecmp(ChrPtr(sptr->httpauth_pass), httpauth_pass)) ) {
477 /** If cookie-session, look for a session with matching session ID */
478 if ( (desired_session != 0) && (sptr->wc_session == desired_session)) {
483 pthread_mutex_unlock(&SessionListMutex);
487 * Create a new session if we have to
489 if (TheSession == NULL) {
490 lprintf(3, "Creating a new session\n");
491 TheSession = (wcsession *)
492 malloc(sizeof(wcsession));
493 memset(TheSession, 0, sizeof(wcsession));
494 TheSession->serv_sock = (-1);
495 TheSession->chat_sock = (-1);
497 /* If we're recreating a session that expired, it's best to give it the same
498 * session number that it had before. The client browser ought to pick up
499 * the new session number and start using it, but in some rare situations it
500 * doesn't, and that's a Bad Thing because it causes lots of spurious sessions
503 if (desired_session == 0) {
504 TheSession->wc_session = GenerateSessionID();
507 TheSession->wc_session = desired_session;
510 if (TheSession->httpauth_user != NULL){
511 FlushStrBuf(TheSession->httpauth_user);
512 StrBufAppendBufPlain(TheSession->httpauth_user, httpauth_user, -1, 0);
514 else TheSession->httpauth_user = NewStrBufPlain(httpauth_user, -1);
515 if (TheSession->httpauth_user != NULL){
516 FlushStrBuf(TheSession->httpauth_pass);
517 StrBufAppendBufPlain(TheSession->httpauth_pass, httpauth_user, -1, 0);
519 else TheSession->httpauth_pass = NewStrBufPlain(httpauth_user, -1);
521 TheSession->hash_prefs = NewHash(1,NULL); /* Get a hash table for the user preferences */
522 pthread_mutex_init(&TheSession->SessionMutex, NULL);
523 pthread_mutex_lock(&SessionListMutex);
524 TheSession->urlstrings = NULL;
525 TheSession->vars = NULL;
526 TheSession->nonce = rand();
527 TheSession->WBuf = NULL;
528 TheSession->CLineBuf = NewStrBuf();
529 TheSession->next = SessionList;
530 TheSession->is_mobile = -1;
531 SessionList = TheSession;
532 pthread_mutex_unlock(&SessionListMutex);
537 * A future improvement might be to check the session integrity
538 * at this point before continuing.
542 * Bind to the session and perform the transaction
544 pthread_mutex_lock(&TheSession->SessionMutex); /* bind */
545 pthread_setspecific(MyConKey, (void *)TheSession);
547 TheSession->urlstrings = NewHash(1,NULL);
548 TheSession->vars = NewHash(1,NULL);
549 TheSession->http_sock = *sock;
550 TheSession->lastreq = time(NULL); /* log */
551 TheSession->gzip_ok = gzip_ok;
553 if (session_is_new) {
554 httplang_to_locale(accept_language);
556 go_selected_language(); /* set locale */
558 session_loop(HTTPHeaders, ReqLine, ReqType, Buf); /* do transaction */
560 stop_selected_language(); /* unset locale */
562 DeleteHash(&TheSession->summ);
563 DeleteHash(&TheSession->urlstrings);
564 DeleteHash(&TheSession->vars);
565 FreeStrBuf(&TheSession->WBuf);
566 FreeStrBuf(&TheSession->HBuf);
569 pthread_mutex_unlock(&TheSession->SessionMutex); /* unbind */
571 /* Free the request buffer */
572 DeleteHash(&HTTPHeaders);
573 FreeStrBuf(&ReqLine);
574 FreeStrBuf(&ReqType);
577 * Free up any session-local substitution variables which
578 * were set during this transaction
584 void tmplput_nonce(StrBuf *Target, WCTemplputParams *TP)
587 StrBufAppendPrintf(Target, "%ld",
588 (WCC != NULL)? WCC->nonce:0);
591 void tmplput_current_user(StrBuf *Target, WCTemplputParams *TP)
593 StrBufAppendTemplate(Target, TP, WC->wc_fullname, 0);
596 void tmplput_current_room(StrBuf *Target, WCTemplputParams *TP)
598 StrBufAppendTemplate(Target, TP, WC->wc_roomname, 0);
607 RegisterNamespace("CURRENT_USER", 0, 1, tmplput_current_user, CTX_NONE);
608 RegisterNamespace("CURRENT_ROOM", 0, 1, tmplput_current_room, CTX_NONE);
609 RegisterNamespace("NONCE", 0, 0, tmplput_nonce, 0);