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)->UrlFragment4));
46 FreeStrBuf(&((*sessions_to_kill)->WBuf));
47 FreeStrBuf(&((*sessions_to_kill)->HBuf));
48 FreeStrBuf(&((*sessions_to_kill)->CLineBuf));
49 FreeStrBuf(&((*sessions_to_kill)->wc_username));
50 FreeStrBuf(&((*sessions_to_kill)->wc_fullname));
51 FreeStrBuf(&((*sessions_to_kill)->wc_password));
52 FreeStrBuf(&((*sessions_to_kill)->wc_roomname));
53 FreeStrBuf(&((*sessions_to_kill)->httpauth_user));
54 FreeStrBuf(&((*sessions_to_kill)->httpauth_pass));
55 FreeStrBuf(&((*sessions_to_kill)->ImportantMsg));
56 FreeStrBuf(&((*sessions_to_kill)->cs_inet_email));
57 FreeStrBuf(&((*sessions_to_kill)->MigrateReadLineBuf));
58 free((*sessions_to_kill));
59 (*sessions_to_kill) = NULL;
62 void shutdown_sessions(void)
66 for (sptr = SessionList; sptr != NULL; sptr = sptr->next) {
71 void do_housekeeping(void)
74 wcsession *sessions_to_kill = NULL;
76 static int num_threads = MIN_WORKER_THREADS;
79 * Lock the session list, moving any candidates for euthanasia into
82 pthread_mutex_lock(&SessionListMutex);
84 for (sptr = SessionList; sptr != NULL; sptr = sptr->next) {
87 /** Kill idle sessions */
88 if ((time(NULL) - (sptr->lastreq)) >
89 (time_t) WEBCIT_TIMEOUT) {
93 /** Remove sessions flagged for kill */
96 /** remove session from linked list */
97 if (sptr == SessionList) {
98 SessionList = SessionList->next;
100 else for (ss=SessionList;ss!=NULL;ss=ss->next) {
101 if (ss->next == sptr) {
102 ss->next = ss->next->next;
106 sptr->next = sessions_to_kill;
107 sessions_to_kill = sptr;
110 pthread_mutex_unlock(&SessionListMutex);
113 * Now free up and destroy the culled sessions.
115 while (sessions_to_kill != NULL) {
116 lprintf(3, "Destroying session %d\n", sessions_to_kill->wc_session);
117 pthread_mutex_lock(&sessions_to_kill->SessionMutex);
118 pthread_mutex_unlock(&sessions_to_kill->SessionMutex);
119 sptr = sessions_to_kill->next;
121 DestroySession(&sessions_to_kill);
122 sessions_to_kill = sptr;
127 * If there are more sessions than threads, then we should spawn
128 * more threads ... up to a predefined maximum.
130 while ( (num_sessions > num_threads)
131 && (num_threads <= MAX_WORKER_THREADS) ) {
132 spawn_another_worker_thread();
134 lprintf(3, "There are %d sessions and %d threads active.\n",
135 num_sessions, num_threads);
141 * Wake up occasionally and clean house
143 void housekeeping_loop(void)
146 sleeeeeeeeeep(HOUSEKEEPING);
153 * Create a Session id
154 * Generate a unique WebCit session ID (which is not the same thing as the
155 * Citadel session ID).
157 int GenerateSessionID(void)
159 static int seq = (-1);
162 seq = (int) time(NULL);
170 * lingering_close() a`la Apache. see
171 * http://www.apache.org/docs/misc/fin_wait_2.html for rationale
173 int lingering_close(int fd)
178 struct timeval tv, start;
180 gettimeofday(&start, NULL);
184 gettimeofday(&tv, NULL);
185 tv.tv_sec = SLEEPING - (tv.tv_sec - start.tv_sec);
186 tv.tv_usec = start.tv_usec - tv.tv_usec;
187 if (tv.tv_usec < 0) {
189 tv.tv_usec += 1000000;
193 i = select(fd + 1, &set, NULL, NULL, &tv);
194 } while (i == -1 && errno == EINTR);
199 i = read(fd, buf, sizeof buf);
200 } while (i != 0 && (i != -1 || errno == EINTR));
208 * Look for commonly-found probes of malware such as worms, viruses, trojans, and Microsoft Office.
209 * Short-circuit these requests so we don't have to send them through the full processing loop.
211 int is_bogus(StrBuf *http_cmd) {
214 const char *bogus_prefixes[] = {
215 "/scripts/root.exe", /* Worms and trojans and viruses, oh my! */
218 "/_vti", /* Broken Microsoft DAV implementation */
219 "/MSOffice", /* Stoopid MSOffice thinks everyone is IIS */
220 "/nonexistenshit" /* Exploit found in the wild January 2009 */
223 url = ChrPtr(http_cmd);
224 if (IsEmptyStr(url)) return(1);
227 max = sizeof(bogus_prefixes) / sizeof(char *);
229 for (i=0; i<max; ++i) {
230 if (!strncasecmp(url, bogus_prefixes[i], strlen(bogus_prefixes[i]))) {
235 return(0); /* probably ok */
239 const char *nix(void *vptr) {return ChrPtr( (StrBuf*)vptr);}
244 * This loop gets called once for every HTTP connection made to WebCit. At
245 * this entry point we have an HTTP socket with a browser allegedly on the
246 * other end, but we have not yet bound to a WebCit session.
248 * The job of this function is to locate the correct session and bind to it,
249 * or create a session if necessary and bind to it, then run the WebCit
250 * transaction loop. Afterwards, we unbind from the session. When this
251 * function returns, the worker thread is then free to handle another
254 void context_loop(int *sock)
256 const char *Pos = NULL;
258 int desired_session = 0;
261 wcsession *TheSession, *sptr;
262 char httpauth_string[1024];
263 char httpauth_user[1024];
264 char httpauth_pass[1024];
265 int session_is_new = 0;
269 StrBuf *Buf, *Line, *LastLine, *HeaderName, *ReqLine, *ReqType, *HTTPVersion;
270 StrBuf *accept_language = NULL;
271 const char *pch, *pchs, *pche;
272 HashList *HTTPHeaders;
274 strcpy(httpauth_string, "");
275 strcpy(httpauth_user, DEFAULT_HTTPAUTH_USER);
276 strcpy(httpauth_pass, DEFAULT_HTTPAUTH_PASS);
279 * Find out what it is that the web browser is asking for
281 HeaderName = NewStrBuf();
284 HTTPHeaders = NewHash(1, NULL);
287 * Read in the request
294 if (ClientGetLine(sock, Line, Buf, &Pos) < 0) return;
296 LineLen = StrLength(Line);
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);
320 StrBufSanitizeAscii(Line, '§');
321 StrBufExtract_token(HeaderName, Line, 0, ':');
324 pch = pchs + StrLength(HeaderName) + 1;
325 pche = pchs + StrLength(Line);
326 while (isspace(*pch) && (pch < pche))
328 StrBufCutLeft(Line, pch - pchs);
330 StrBufUpCase(HeaderName);
331 Put(HTTPHeaders, SKEY(HeaderName), Line, HFreeStrBuf);
333 } while (LineLen > 0);
334 FreeStrBuf(&HeaderName);
336 /* dbg_PrintHash(HTTPHeaders, nix, NULL); */
342 if (GetHash(HTTPHeaders, HKEY("ACCEPT-ENCODING"), &vLine) &&
344 buf = ChrPtr((StrBuf*)vLine);
345 if (strstr(&buf[16], "gzip")) {
351 * Browser-based sessions use cookies for session authentication
353 if (GetHash(HTTPHeaders, HKEY("COOKIE"), &vLine) &&
355 cookie_to_stuff(vLine, &desired_session,
361 * GroupDAV-based sessions use HTTP authentication
363 if (GetHash(HTTPHeaders, HKEY("AUTHORIZATION"), &vLine) &&
365 Line = (StrBuf*)vLine;
366 if (strncasecmp(ChrPtr(Line), "Basic", 5) == 0) {
367 StrBufCutLeft(Line, 6);
368 CtdlDecodeBase64(httpauth_string, ChrPtr(Line), StrLength(Line));
369 extract_token(httpauth_user, httpauth_string, 0, ':', sizeof httpauth_user);
370 extract_token(httpauth_pass, httpauth_string, 1, ':', sizeof httpauth_pass);
373 lprintf(1, "Authentication scheme not supported! [%s]\n", ChrPtr(Line));
376 if (GetHash(HTTPHeaders, HKEY("IF-MODIFIED-SINCE"), &vLine) &&
378 if_modified_since = httpdate_to_timestamp((StrBuf*)vLine);
381 if (GetHash(HTTPHeaders, HKEY("ACCEPT-LANGUAGE"), &vLine) &&
383 accept_language = (StrBuf*) vLine;
387 ReqType = NewStrBuf();
388 HTTPVersion = NewStrBuf();
389 StrBufExtract_token(HTTPVersion, ReqLine, 2, ' ');
390 StrBufExtract_token(ReqType, ReqLine, 0, ' ');
391 StrBufCutLeft(ReqLine, StrLength(ReqType) + 1);
392 StrBufCutRight(ReqLine, StrLength(HTTPVersion) + 1);
395 * If the request is prefixed by "/webcit" then chop that off. This
396 * allows a front end web server to forward all /webcit requests to us
397 * while still using the same web server port for other things.
399 if ( (StrLength(ReqLine) >= 8) && (strstr(ChrPtr(ReqLine), "/webcit/")) ) {
400 StrBufCutLeft(ReqLine, 7);
403 /* Begin parsing the request. */
405 if ((strncmp(ChrPtr(ReqLine), "/sslg", 5) != 0) &&
406 (strncmp(ChrPtr(ReqLine), "/static/", 8) != 0) &&
407 (strncmp(ChrPtr(ReqLine), "/tiny_mce/", 10) != 0) &&
408 (strncmp(ChrPtr(ReqLine), "/wholist_section", 16) != 0) &&
409 (strstr(ChrPtr(ReqLine), "wholist_section") == NULL)) {
411 lprintf(5, "HTTP: %s %s %s\n", ChrPtr(ReqType), ChrPtr(ReqLine), ChrPtr(HTTPVersion));
416 /** Check for bogus requests */
417 if ((StrLength(HTTPVersion) == 0) ||
418 (StrLength(ReqType) == 0) ||
420 StrBufPlain(ReqLine, HKEY("/404 HTTP/1.1"));
421 StrBufPlain(ReqType, HKEY("GET"));
423 FreeStrBuf(&HTTPVersion);
426 * While we're at it, gracefully handle requests for the
427 * robots.txt and favicon.ico files.
429 if (!strncasecmp(ChrPtr(ReqLine), "/robots.txt", 11)) {
431 HKEY("/static/robots.txt"
432 "?force_close_session=yes HTTP/1.1"));
433 StrBufPlain(ReqType, HKEY("GET"));
435 else if (!strncasecmp(ChrPtr(ReqLine), "/favicon.ico", 12)) {
436 StrBufPlain(ReqLine, HKEY("/static/favicon.ico"));
437 StrBufPlain(ReqType, HKEY("GET"));
441 * These are the URL's which may be executed without a
442 * session cookie already set. If it's not one of these,
443 * force the session to close because cookies are
444 * probably disabled on the client browser.
446 else if ( (StrLength(ReqLine) > 1 )
447 && (strncasecmp(ChrPtr(ReqLine), "/listsub", 8))
448 && (strncasecmp(ChrPtr(ReqLine), "/freebusy", 9))
449 && (strncasecmp(ChrPtr(ReqLine), "/do_logout", 10))
450 && (strncasecmp(ChrPtr(ReqLine), "/groupdav", 9))
451 && (strncasecmp(ChrPtr(ReqLine), "/static", 7))
452 && (strncasecmp(ChrPtr(ReqLine), "/rss", 4))
453 && (strncasecmp(ChrPtr(ReqLine), "/404", 4))
454 && (got_cookie == 0)) {
456 HKEY("/static/nocookies.html"
457 "?force_close_session=yes"));
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; sptr != NULL; sptr = sptr->next) {
469 /** If HTTP-AUTH, look for a session with matching credentials */
470 if ( (!IsEmptyStr(httpauth_user))
471 &&(!strcasecmp(ChrPtr(sptr->httpauth_user), httpauth_user))
472 &&(!strcasecmp(ChrPtr(sptr->httpauth_pass), httpauth_pass)) ) {
476 /** If cookie-session, look for a session with matching session ID */
477 if ( (desired_session != 0) && (sptr->wc_session == desired_session)) {
482 pthread_mutex_unlock(&SessionListMutex);
486 * Create a new session if we have to
488 if (TheSession == NULL) {
489 lprintf(3, "Creating a new session\n");
490 TheSession = (wcsession *)
491 malloc(sizeof(wcsession));
492 memset(TheSession, 0, sizeof(wcsession));
493 TheSession->serv_sock = (-1);
494 TheSession->chat_sock = (-1);
496 /* If we're recreating a session that expired, it's best to give it the same
497 * session number that it had before. The client browser ought to pick up
498 * the new session number and start using it, but in some rare situations it
499 * doesn't, and that's a Bad Thing because it causes lots of spurious sessions
502 if (desired_session == 0) {
503 TheSession->wc_session = GenerateSessionID();
506 TheSession->wc_session = desired_session;
509 if (TheSession->httpauth_user != NULL){
510 FlushStrBuf(TheSession->httpauth_user);
511 StrBufAppendBufPlain(TheSession->httpauth_user, httpauth_user, -1, 0);
513 else TheSession->httpauth_user = NewStrBufPlain(httpauth_user, -1);
514 if (TheSession->httpauth_user != NULL){
515 FlushStrBuf(TheSession->httpauth_pass);
516 StrBufAppendBufPlain(TheSession->httpauth_pass, httpauth_user, -1, 0);
518 else TheSession->httpauth_pass = NewStrBufPlain(httpauth_user, -1);
520 if (TheSession->MigrateReadLineBuf != NULL)
521 FlushStrBuf(TheSession->MigrateReadLineBuf);
522 else TheSession->MigrateReadLineBuf = NewStrBuf();
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 if (TheSession->ImportantMsg == NULL)
547 TheSession->ImportantMsg = NewStrBuf();
548 TheSession->urlstrings = NewHash(1,NULL);
549 TheSession->vars = NewHash(1,NULL);
550 TheSession->http_sock = *sock;
551 TheSession->lastreq = time(NULL); /* log */
552 TheSession->gzip_ok = gzip_ok;
554 if (session_is_new) {
555 httplang_to_locale(accept_language);
557 go_selected_language(); /* set locale */
559 session_loop(HTTPHeaders, ReqLine, ReqType, Buf, &Pos); /* do transaction */
561 stop_selected_language(); /* unset locale */
563 DeleteHash(&TheSession->summ);
564 DeleteHash(&TheSession->urlstrings);
565 DeleteHash(&TheSession->vars);
566 FreeStrBuf(&TheSession->WBuf);
567 FreeStrBuf(&TheSession->HBuf);
570 pthread_mutex_unlock(&TheSession->SessionMutex); /* unbind */
572 /* Free the request buffer */
573 DeleteHash(&HTTPHeaders);
574 FreeStrBuf(&ReqLine);
575 FreeStrBuf(&ReqType);
578 * Free up any session-local substitution variables which
579 * were set during this transaction
585 void tmplput_nonce(StrBuf *Target, WCTemplputParams *TP)
588 StrBufAppendPrintf(Target, "%ld",
589 (WCC != NULL)? WCC->nonce:0);
592 void tmplput_current_user(StrBuf *Target, WCTemplputParams *TP)
594 StrBufAppendTemplate(Target, TP, WC->wc_fullname, 0);
597 void tmplput_current_room(StrBuf *Target, WCTemplputParams *TP)
599 StrBufAppendTemplate(Target, TP, WC->wc_roomname, 0);
608 RegisterNamespace("CURRENT_USER", 0, 1, tmplput_current_user, CTX_NONE);
609 RegisterNamespace("CURRENT_ROOM", 0, 1, tmplput_current_room, CTX_NONE);
610 RegisterNamespace("NONCE", 0, 0, tmplput_nonce, 0);