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 DeleteServInfo(&((*sessions_to_kill)->serv_info));
36 DeleteHash(&((*sessions_to_kill)->attachments));
37 free_march_list((*sessions_to_kill));
38 DeleteHash(&((*sessions_to_kill)->hash_prefs));
39 DeleteHash(&((*sessions_to_kill)->IconBarSettings));
40 DeleteHash(&((*sessions_to_kill)->ServCfg));
41 FreeStrBuf(&((*sessions_to_kill)->ReadBuf));
42 FreeStrBuf(&((*sessions_to_kill)->UrlFragment1));
43 FreeStrBuf(&((*sessions_to_kill)->UrlFragment2));
44 FreeStrBuf(&((*sessions_to_kill)->UrlFragment3));
45 FreeStrBuf(&((*sessions_to_kill)->WBuf));
46 FreeStrBuf(&((*sessions_to_kill)->HBuf));
47 FreeStrBuf(&((*sessions_to_kill)->CLineBuf));
48 FreeStrBuf(&((*sessions_to_kill)->wc_username));
49 FreeStrBuf(&((*sessions_to_kill)->wc_fullname));
50 FreeStrBuf(&((*sessions_to_kill)->wc_password));
51 FreeStrBuf(&((*sessions_to_kill)->wc_roomname));
52 FreeStrBuf(&((*sessions_to_kill)->httpauth_user));
53 FreeStrBuf(&((*sessions_to_kill)->httpauth_pass));
54 free((*sessions_to_kill));
55 (*sessions_to_kill) = NULL;
58 void shutdown_sessions(void)
62 for (sptr = SessionList; sptr != NULL; sptr = sptr->next) {
67 void do_housekeeping(void)
70 wcsession *sessions_to_kill = NULL;
72 static int num_threads = MIN_WORKER_THREADS;
75 * Lock the session list, moving any candidates for euthanasia into
78 pthread_mutex_lock(&SessionListMutex);
80 for (sptr = SessionList; sptr != NULL; sptr = sptr->next) {
83 /** Kill idle sessions */
84 if ((time(NULL) - (sptr->lastreq)) >
85 (time_t) WEBCIT_TIMEOUT) {
89 /** Remove sessions flagged for kill */
92 /** remove session from linked list */
93 if (sptr == SessionList) {
94 SessionList = SessionList->next;
96 else for (ss=SessionList;ss!=NULL;ss=ss->next) {
97 if (ss->next == sptr) {
98 ss->next = ss->next->next;
102 sptr->next = sessions_to_kill;
103 sessions_to_kill = sptr;
106 pthread_mutex_unlock(&SessionListMutex);
109 * Now free up and destroy the culled sessions.
111 while (sessions_to_kill != NULL) {
112 lprintf(3, "Destroying session %d\n", sessions_to_kill->wc_session);
113 pthread_mutex_lock(&sessions_to_kill->SessionMutex);
114 pthread_mutex_unlock(&sessions_to_kill->SessionMutex);
115 sptr = sessions_to_kill->next;
117 DestroySession(&sessions_to_kill);
118 sessions_to_kill = sptr;
123 * If there are more sessions than threads, then we should spawn
124 * more threads ... up to a predefined maximum.
126 while ( (num_sessions > num_threads)
127 && (num_threads <= MAX_WORKER_THREADS) ) {
128 spawn_another_worker_thread();
130 lprintf(3, "There are %d sessions and %d threads active.\n",
131 num_sessions, num_threads);
137 * Wake up occasionally and clean house
139 void housekeeping_loop(void)
142 sleeeeeeeeeep(HOUSEKEEPING);
149 * Create a Session id
150 * Generate a unique WebCit session ID (which is not the same thing as the
151 * Citadel session ID).
153 int GenerateSessionID(void)
155 static int seq = (-1);
158 seq = (int) time(NULL);
165 * Collapse multiple cookies on one line
167 int ReqGetStrBuf(int *sock, StrBuf *Target, StrBuf *buf)
170 return ClientGetLine(sock, Target, buf);
176 * lingering_close() a`la Apache. see
177 * http://www.apache.org/docs/misc/fin_wait_2.html for rationale
179 int lingering_close(int fd)
184 struct timeval tv, start;
186 gettimeofday(&start, NULL);
190 gettimeofday(&tv, NULL);
191 tv.tv_sec = SLEEPING - (tv.tv_sec - start.tv_sec);
192 tv.tv_usec = start.tv_usec - tv.tv_usec;
193 if (tv.tv_usec < 0) {
195 tv.tv_usec += 1000000;
199 i = select(fd + 1, &set, NULL, NULL, &tv);
200 } while (i == -1 && errno == EINTR);
205 i = read(fd, buf, sizeof buf);
206 } while (i != 0 && (i != -1 || errno == EINTR));
214 * Look for commonly-found probes of malware such as worms, viruses, trojans, and Microsoft Office.
215 * Short-circuit these requests so we don't have to send them through the full processing loop.
217 int is_bogus(StrBuf *http_cmd) {
220 const char *bogus_prefixes[] = {
221 "/scripts/root.exe", /* Worms and trojans and viruses, oh my! */
224 "/_vti", /* Broken Microsoft DAV implementation */
225 "/MSOffice", /* Stoopid MSOffice thinks everyone is IIS */
226 "/nonexistenshit" /* Exploit found in the wild January 2009 */
229 url = ChrPtr(http_cmd);
230 if (IsEmptyStr(url)) return(1);
233 max = sizeof(bogus_prefixes) / sizeof(char *);
235 for (i=0; i<max; ++i) {
236 if (!strncasecmp(url, bogus_prefixes[i], strlen(bogus_prefixes[i]))) {
241 return(0); /* probably ok */
245 const char *nix(void *vptr) {return ChrPtr( (StrBuf*)vptr);}
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
260 void context_loop(int *sock)
263 int desired_session = 0;
266 wcsession *TheSession, *sptr;
267 char httpauth_string[1024];
268 char httpauth_user[1024];
269 char httpauth_pass[1024];
270 int session_is_new = 0;
274 StrBuf *Buf, *Line, *LastLine, *HeaderName, *ReqLine, *ReqType, *HTTPVersion;
275 StrBuf *accept_language = NULL;
276 const char *pch, *pchs, *pche;
277 HashList *HTTPHeaders;
279 strcpy(httpauth_string, "");
280 strcpy(httpauth_user, DEFAULT_HTTPAUTH_USER);
281 strcpy(httpauth_pass, DEFAULT_HTTPAUTH_PASS);
284 * Find out what it is that the web browser is asking for
286 HeaderName = NewStrBuf();
289 HTTPHeaders = NewHash(1, NULL);
292 * Read in the request
297 if (ReqGetStrBuf(sock, Line, Buf) < 0) return;
299 LineLen = StrLength(Line);
310 /* Do we need to Unfold? */
311 if ((LastLine != NULL) &&
312 (isspace(*ChrPtr(Line)))) {
313 pch = pchs = ChrPtr(Line);
314 pche = pchs + StrLength(Line);
315 while (isspace(*pch) && (pch < pche))
317 StrBufCutLeft(Line, pch - pchs);
318 StrBufAppendBuf(LastLine, Line, 0);
323 StrBufSanitizeAscii(Line, '§');
324 StrBufExtract_token(HeaderName, Line, 0, ':');
327 pch = pchs + StrLength(HeaderName) + 1;
328 pche = pchs + StrLength(Line);
329 while (isspace(*pch) && (pch < pche))
331 StrBufCutLeft(Line, pch - pchs);
333 StrBufUpCase(HeaderName);
334 Put(HTTPHeaders, SKEY(HeaderName), Line, HFreeStrBuf);
336 } while (LineLen > 0);
337 FreeStrBuf(&HeaderName);
339 /*/// dbg_PrintHash(HTTPHeaders, nix, NULL); */
345 if (GetHash(HTTPHeaders, HKEY("ACCEPT-ENCODING"), &vLine) &&
347 buf = ChrPtr((StrBuf*)vLine);
348 if (strstr(&buf[16], "gzip")) {
354 * Browser-based sessions use cookies for session authentication
356 if (GetHash(HTTPHeaders, HKEY("COOKIE"), &vLine) &&
358 cookie_to_stuff(vLine, &desired_session,
364 * GroupDAV-based sessions use HTTP authentication
366 if (GetHash(HTTPHeaders, HKEY("AUTHORIZATION"), &vLine) &&
368 Line = (StrBuf*)vLine;
369 if (strncasecmp(ChrPtr(Line), "Basic", 5) == 0) {
370 StrBufCutLeft(Line, 6);
371 CtdlDecodeBase64(httpauth_string, ChrPtr(Line), StrLength(Line));
372 extract_token(httpauth_user, httpauth_string, 0, ':', sizeof httpauth_user);
373 extract_token(httpauth_pass, httpauth_string, 1, ':', sizeof httpauth_pass);
376 lprintf(1, "Authentication scheme not supported! [%s]\n", ChrPtr(Line));
379 if (GetHash(HTTPHeaders, HKEY("IF-MODIFIED-SINCE"), &vLine) &&
381 if_modified_since = httpdate_to_timestamp((StrBuf*)vLine);
384 if (GetHash(HTTPHeaders, HKEY("ACCEPT-LANGUAGE"), &vLine) &&
386 accept_language = (StrBuf*) vLine;
390 ReqType = NewStrBuf();
391 HTTPVersion = NewStrBuf();
392 StrBufExtract_token(HTTPVersion, ReqLine, 2, ' ');
393 StrBufExtract_token(ReqType, ReqLine, 0, ' ');
394 StrBufCutLeft(ReqLine, StrLength(ReqType) + 1);
395 StrBufCutRight(ReqLine, StrLength(HTTPVersion) + 1);
398 * If the request is prefixed by "/webcit" then chop that off. This
399 * allows a front end web server to forward all /webcit requests to us
400 * while still using the same web server port for other things.
402 if ( (StrLength(ReqLine) >= 8) && (strstr(ChrPtr(ReqLine), "/webcit/")) ) {
403 StrBufCutLeft(ReqLine, 7);
406 /* Begin parsing the request. */
408 if ((strncmp(ChrPtr(ReqLine), "/sslg", 5) != 0) &&
409 (strncmp(ChrPtr(ReqLine), "/static/", 8) != 0) &&
410 (strncmp(ChrPtr(ReqLine), "/tiny_mce/", 10) != 0) &&
411 (strncmp(ChrPtr(ReqLine), "/wholist_section", 16) != 0) &&
412 (strstr(ChrPtr(ReqLine), "wholist_section") == NULL)) {
414 lprintf(5, "HTTP: %s %s %s\n", ChrPtr(ReqType), ChrPtr(ReqLine), ChrPtr(HTTPVersion));
419 /** Check for bogus requests */
420 if ((StrLength(HTTPVersion) == 0) ||
421 (StrLength(ReqType) == 0) ||
423 StrBufPlain(ReqLine, HKEY("/404 HTTP/1.1"));
424 StrBufPlain(ReqType, HKEY("GET"));
426 FreeStrBuf(&HTTPVersion);
429 * While we're at it, gracefully handle requests for the
430 * robots.txt and favicon.ico files.
432 if (!strncasecmp(ChrPtr(ReqLine), "/robots.txt", 11)) {
434 HKEY("/static/robots.txt"
435 "?force_close_session=yes HTTP/1.1"));
436 StrBufPlain(ReqType, HKEY("GET"));
438 else if (!strncasecmp(ChrPtr(ReqLine), "/favicon.ico", 12)) {
439 StrBufPlain(ReqLine, HKEY("/static/favicon.ico"));
440 StrBufPlain(ReqType, HKEY("GET"));
444 * These are the URL's which may be executed without a
445 * session cookie already set. If it's not one of these,
446 * force the session to close because cookies are
447 * probably disabled on the client browser.
449 else if ( (StrLength(ReqLine) > 1 )
450 && (strncasecmp(ChrPtr(ReqLine), "/listsub", 8))
451 && (strncasecmp(ChrPtr(ReqLine), "/freebusy", 9))
452 && (strncasecmp(ChrPtr(ReqLine), "/do_logout", 10))
453 && (strncasecmp(ChrPtr(ReqLine), "/groupdav", 9))
454 && (strncasecmp(ChrPtr(ReqLine), "/static", 7))
455 && (strncasecmp(ChrPtr(ReqLine), "/rss", 4))
456 && (strncasecmp(ChrPtr(ReqLine), "/404", 4))
457 && (got_cookie == 0)) {
459 HKEY("/static/nocookies.html"
460 "?force_close_session=yes"));
464 * See if there's an existing session open with the desired ID or user/pass
468 if (TheSession == NULL) {
469 pthread_mutex_lock(&SessionListMutex);
470 for (sptr = SessionList; sptr != NULL; sptr = sptr->next) {
472 /** If HTTP-AUTH, look for a session with matching credentials */
473 if ( (!IsEmptyStr(httpauth_user))
474 &&(!strcasecmp(ChrPtr(sptr->httpauth_user), httpauth_user))
475 &&(!strcasecmp(ChrPtr(sptr->httpauth_pass), httpauth_pass)) ) {
479 /** If cookie-session, look for a session with matching session ID */
480 if ( (desired_session != 0) && (sptr->wc_session == desired_session)) {
485 pthread_mutex_unlock(&SessionListMutex);
489 * Create a new session if we have to
491 if (TheSession == NULL) {
492 lprintf(3, "Creating a new session\n");
493 TheSession = (wcsession *)
494 malloc(sizeof(wcsession));
495 memset(TheSession, 0, sizeof(wcsession));
496 TheSession->serv_sock = (-1);
497 TheSession->chat_sock = (-1);
499 /* If we're recreating a session that expired, it's best to give it the same
500 * session number that it had before. The client browser ought to pick up
501 * the new session number and start using it, but in some rare situations it
502 * doesn't, and that's a Bad Thing because it causes lots of spurious sessions
505 if (desired_session == 0) {
506 TheSession->wc_session = GenerateSessionID();
509 TheSession->wc_session = desired_session;
512 if (TheSession->httpauth_user != NULL){
513 FlushStrBuf(TheSession->httpauth_user);
514 StrBufAppendBufPlain(TheSession->httpauth_user, httpauth_user, -1, 0);
516 else TheSession->httpauth_user = NewStrBufPlain(httpauth_user, -1);
517 if (TheSession->httpauth_user != NULL){
518 FlushStrBuf(TheSession->httpauth_pass);
519 StrBufAppendBufPlain(TheSession->httpauth_pass, httpauth_user, -1, 0);
521 else TheSession->httpauth_pass = NewStrBufPlain(httpauth_user, -1);
523 TheSession->CLineBuf = NewStrBuf();
524 TheSession->hash_prefs = NewHash(1,NULL); /* Get a hash table for the user preferences */
525 pthread_mutex_init(&TheSession->SessionMutex, NULL);
526 pthread_mutex_lock(&SessionListMutex);
527 TheSession->nonce = rand();
528 TheSession->next = SessionList;
529 TheSession->is_mobile = -1;
530 SessionList = TheSession;
531 pthread_mutex_unlock(&SessionListMutex);
536 * A future improvement might be to check the session integrity
537 * at this point before continuing.
541 * Bind to the session and perform the transaction
543 pthread_mutex_lock(&TheSession->SessionMutex); /* bind */
544 pthread_setspecific(MyConKey, (void *)TheSession);
546 TheSession->urlstrings = NewHash(1,NULL);
547 TheSession->vars = NewHash(1,NULL);
548 TheSession->http_sock = *sock;
549 TheSession->lastreq = time(NULL); /* log */
550 TheSession->gzip_ok = gzip_ok;
552 if (session_is_new) {
553 httplang_to_locale(accept_language);
555 go_selected_language(); /* set locale */
557 session_loop(HTTPHeaders, ReqLine, ReqType, Buf); /* do transaction */
559 stop_selected_language(); /* unset locale */
561 DeleteHash(&TheSession->summ);
562 DeleteHash(&TheSession->urlstrings);
563 DeleteHash(&TheSession->vars);
564 FreeStrBuf(&TheSession->WBuf);
565 FreeStrBuf(&TheSession->HBuf);
568 pthread_mutex_unlock(&TheSession->SessionMutex); /* unbind */
570 /* Free the request buffer */
571 DeleteHash(&HTTPHeaders);
572 FreeStrBuf(&ReqLine);
573 FreeStrBuf(&ReqType);
576 * Free up any session-local substitution variables which
577 * were set during this transaction
583 void tmplput_nonce(StrBuf *Target, WCTemplputParams *TP)
586 StrBufAppendPrintf(Target, "%ld",
587 (WCC != NULL)? WCC->nonce:0);
590 void tmplput_current_user(StrBuf *Target, WCTemplputParams *TP)
592 StrBufAppendTemplate(Target, TP, WC->wc_fullname, 0);
595 void tmplput_current_room(StrBuf *Target, WCTemplputParams *TP)
597 StrBufAppendTemplate(Target, TP, WC->wc_roomname, 0);
606 RegisterNamespace("CURRENT_USER", 0, 1, tmplput_current_user, CTX_NONE);
607 RegisterNamespace("CURRENT_ROOM", 0, 1, tmplput_current_room, CTX_NONE);
608 RegisterNamespace("NONCE", 0, 0, tmplput_nonce, 0);