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)->IconBarSetttings));
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 free((*sessions_to_kill));
47 (*sessions_to_kill) = NULL;
50 void shutdown_sessions(void)
54 for (sptr = SessionList; sptr != NULL; sptr = sptr->next) {
59 void do_housekeeping(void)
62 wcsession *sessions_to_kill = NULL;
64 static int num_threads = MIN_WORKER_THREADS;
67 * Lock the session list, moving any candidates for euthanasia into
70 pthread_mutex_lock(&SessionListMutex);
72 for (sptr = SessionList; sptr != NULL; sptr = sptr->next) {
75 /** Kill idle sessions */
76 if ((time(NULL) - (sptr->lastreq)) >
77 (time_t) WEBCIT_TIMEOUT) {
81 /** Remove sessions flagged for kill */
84 /** remove session from linked list */
85 if (sptr == SessionList) {
86 SessionList = SessionList->next;
88 else for (ss=SessionList;ss!=NULL;ss=ss->next) {
89 if (ss->next == sptr) {
90 ss->next = ss->next->next;
94 sptr->next = sessions_to_kill;
95 sessions_to_kill = sptr;
98 pthread_mutex_unlock(&SessionListMutex);
101 * Now free up and destroy the culled sessions.
103 while (sessions_to_kill != NULL) {
104 lprintf(3, "Destroying session %d\n", sessions_to_kill->wc_session);
105 pthread_mutex_lock(&sessions_to_kill->SessionMutex);
106 pthread_mutex_unlock(&sessions_to_kill->SessionMutex);
107 sptr = sessions_to_kill->next;
109 DestroySession(&sessions_to_kill);
110 sessions_to_kill = sptr;
115 * If there are more sessions than threads, then we should spawn
116 * more threads ... up to a predefined maximum.
118 while ( (num_sessions > num_threads)
119 && (num_threads <= MAX_WORKER_THREADS) ) {
120 spawn_another_worker_thread();
122 lprintf(3, "There are %d sessions and %d threads active.\n",
123 num_sessions, num_threads);
129 * \brief Wake up occasionally and clean house
131 void housekeeping_loop(void)
134 sleeeeeeeeeep(HOUSEKEEPING);
141 * \brief Create a Session id
142 * Generate a unique WebCit session ID (which is not the same thing as the
143 * Citadel session ID).
145 * \todo FIXME ... ensure that session number is truly unique
148 int GenerateSessionID(void)
150 static int seq = (-1);
153 seq = (int) time(NULL);
160 * Collapse multiple cookies on one line
162 int ReqGetStrBuf(int *sock, StrBuf *Target, StrBuf *buf)
165 return ClientGetLine(sock, Target, buf);
171 * lingering_close() a`la Apache. see
172 * http://www.apache.org/docs/misc/fin_wait_2.html for rationale
174 int lingering_close(int fd)
179 struct timeval tv, start;
181 gettimeofday(&start, NULL);
185 gettimeofday(&tv, NULL);
186 tv.tv_sec = SLEEPING - (tv.tv_sec - start.tv_sec);
187 tv.tv_usec = start.tv_usec - tv.tv_usec;
188 if (tv.tv_usec < 0) {
190 tv.tv_usec += 1000000;
194 i = select(fd + 1, &set, NULL, NULL, &tv);
195 } while (i == -1 && errno == EINTR);
200 i = read(fd, buf, sizeof buf);
201 } while (i != 0 && (i != -1 || errno == EINTR));
209 * Look for commonly-found probes of malware such as worms, viruses, trojans, and Microsoft Office.
210 * Short-circuit these requests so we don't have to send them through the full processing loop.
212 int is_bogus(StrBuf *http_cmd) {
215 const char *bogus_prefixes[] = {
216 "/scripts/root.exe", /* Worms and trojans and viruses, oh my! */
219 "/_vti", /* Broken Microsoft DAV implementation */
220 "/MSOffice", /* Stoopid MSOffice thinks everyone is IIS */
221 "/nonexistenshit" /* Exploit found in the wild January 2009 */
224 url = ChrPtr(http_cmd);
225 if (IsEmptyStr(url)) return(1);
228 max = sizeof(bogus_prefixes) / sizeof(char *);
230 for (i=0; i<max; ++i) {
231 if (!strncasecmp(url, bogus_prefixes[i], strlen(bogus_prefixes[i]))) {
236 return(0); /* probably ok */
240 const char *nix(void *vptr) {return ChrPtr( (StrBuf*)vptr);}
243 * \brief handle one request
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
253 * \param sock the socket we will put our answer to
255 void context_loop(int *sock)
258 int desired_session = 0;
261 wcsession *TheSession, *sptr;
262 char httpauth_string[1024];
263 char httpauth_user[1024];
264 char httpauth_pass[1024];
266 int session_is_new = 0;
270 StrBuf *Buf, *Line, *LastLine, *HeaderName, *ReqLine, *ReqType, *HTTPVersion;
271 StrBuf *accept_language = NULL;
272 const char *pch, *pchs, *pche;
273 HashList *HTTPHeaders;
275 strcpy(httpauth_string, "");
276 strcpy(httpauth_user, DEFAULT_HTTPAUTH_USER);
277 strcpy(httpauth_pass, DEFAULT_HTTPAUTH_PASS);
280 * Find out what it is that the web browser is asking for
282 HeaderName = NewStrBuf();
285 HTTPHeaders = NewHash(1, NULL);
287 * Read in the request
292 if (ReqGetStrBuf(sock, Line, Buf) < 0) return;
294 LineLen = StrLength(Line);
305 /** Do we need to Unfold? */
306 if ((LastLine != NULL) &&
307 (isspace(*ChrPtr(Line)))) {
308 pch = pchs = ChrPtr(Line);
309 pche = pchs + StrLength(Line);
310 while (isspace(*pch) && (pch < pche))
312 StrBufCutLeft(Line, pch - pchs);
313 StrBufAppendBuf(LastLine, Line, 0);
318 StrBufExtract_token(HeaderName, Line, 0, ':');
319 /*/// TODO: filter bad chars! */
322 pch = pchs + StrLength(HeaderName) + 1;
323 pche = pchs + StrLength(Line);
324 while (isspace(*pch) && (pch < pche))
326 StrBufCutLeft(Line, pch - pchs);
328 StrBufUpCase(HeaderName);
329 Put(HTTPHeaders, SKEY(HeaderName), Line, HFreeStrBuf);
331 } while (LineLen > 0);
332 FreeStrBuf(&HeaderName);
334 /*/// dbg_PrintHash(HTTPHeaders, nix, NULL); */
340 if (GetHash(HTTPHeaders, HKEY("ACCEPT-ENCODING"), &vLine) &&
342 buf = ChrPtr((StrBuf*)vLine);
343 if (strstr(&buf[16], "gzip")) {
349 * Browser-based sessions use cookies for session
353 if (GetHash(HTTPHeaders, HKEY("COOKIE"), &vLine) &&
355 cookie_to_stuff(vLine, &desired_session,
356 NULL, 0, NULL, 0, NULL, 0);
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;
388 * If the request is prefixed by "/webcit" then chop that off. This
389 * allows a front end web server to forward all /webcit requests to us
390 * while still using the same web server port for other things.
393 ReqType = NewStrBuf();
394 HTTPVersion = NewStrBuf();
395 StrBufExtract_token(HTTPVersion, ReqLine, 2, ' ');
396 StrBufExtract_token(ReqType, ReqLine, 0, ' ');
397 StrBufCutLeft(ReqLine, StrLength(ReqType) + 1);
398 StrBufCutRight(ReqLine, StrLength(HTTPVersion) + 1);
400 if ((follow_xff == 1) && (StrLength(ReqLine) >= 8) &&
401 (ptr = strstr(ChrPtr(ReqLine), "/webcit/"), /*< Handle "/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(sptr->httpauth_user, httpauth_user))
475 &&(!strcasecmp(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 strcpy(TheSession->httpauth_user, httpauth_user);
513 strcpy(TheSession->httpauth_pass, httpauth_pass);
514 TheSession->hash_prefs = NewHash(1,NULL); /* Get a hash table for the user preferences */
515 pthread_mutex_init(&TheSession->SessionMutex, NULL);
516 pthread_mutex_lock(&SessionListMutex);
517 TheSession->urlstrings = NULL;
518 TheSession->vars = NULL;
519 TheSession->nonce = rand();
520 TheSession->WBuf = NULL;
521 TheSession->CLineBuf = NewStrBuf();
522 TheSession->next = SessionList;
523 TheSession->is_mobile = -1;
524 SessionList = TheSession;
525 pthread_mutex_unlock(&SessionListMutex);
530 * A future improvement might be to check the session integrity
531 * at this point before continuing.
535 * Bind to the session and perform the transaction
537 pthread_mutex_lock(&TheSession->SessionMutex); /* bind */
538 pthread_setspecific(MyConKey, (void *)TheSession);
540 TheSession->urlstrings = NewHash(1,NULL);
541 TheSession->vars = NewHash(1,NULL);
542 TheSession->http_sock = *sock;
543 TheSession->lastreq = time(NULL); /* log */
544 TheSession->gzip_ok = gzip_ok;
546 if (session_is_new) {
547 httplang_to_locale(accept_language);
549 go_selected_language(); /* set locale */
551 session_loop(HTTPHeaders, ReqLine, ReqType, Buf); /* do transaction */
553 stop_selected_language(); /* unset locale */
555 DeleteHash(&TheSession->summ);
556 DeleteHash(&TheSession->urlstrings);
557 DeleteHash(&TheSession->vars);
558 FreeStrBuf(&TheSession->WBuf);
559 FreeStrBuf(&TheSession->HBuf);
562 pthread_mutex_unlock(&TheSession->SessionMutex); /* unbind */
564 /* Free the request buffer */
565 DeleteHash(&HTTPHeaders);
566 FreeStrBuf(&ReqLine);
567 FreeStrBuf(&ReqType);
570 * Free up any session-local substitution variables which
571 * were set during this transaction
577 void tmpl_nonce(StrBuf *Target, int nArgs, WCTemplateToken *Tokens, void *Context, int ContextType)
580 StrBufAppendPrintf(Target, "%ld",
581 (WCC != NULL)? WCC->nonce:0);
588 RegisterNamespace("NONCE", 0, 0, tmpl_nonce, 0);