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);
27 // if ((*sessions_to_kill)->preferences != NULL) {
28 // free((*sessions_to_kill)->preferences);
30 if ((*sessions_to_kill)->cache_fold != NULL) {
31 free((*sessions_to_kill)->cache_fold);
33 DeleteHash(&((*sessions_to_kill)->attachments));
34 free_march_list((*sessions_to_kill));
35 DeleteHash(&((*sessions_to_kill)->hash_prefs));
36 DeleteHash(&((*sessions_to_kill)->IconBarSetttings));
37 DeleteHash(&((*sessions_to_kill)->ServCfg));
38 FreeStrBuf(&((*sessions_to_kill)->UrlFragment1));
39 FreeStrBuf(&((*sessions_to_kill)->UrlFragment2));
40 FreeStrBuf(&((*sessions_to_kill)->UrlFragment3));
41 FreeStrBuf(&((*sessions_to_kill)->WBuf));
42 FreeStrBuf(&((*sessions_to_kill)->HBuf));
43 FreeStrBuf(&((*sessions_to_kill)->CLineBuf));
44 free((*sessions_to_kill));
45 (*sessions_to_kill) = NULL;
48 void shutdown_sessions(void)
52 for (sptr = SessionList; sptr != NULL; sptr = sptr->next) {
57 void do_housekeeping(void)
60 wcsession *sessions_to_kill = NULL;
62 static int num_threads = MIN_WORKER_THREADS;
65 * Lock the session list, moving any candidates for euthanasia into
68 pthread_mutex_lock(&SessionListMutex);
70 for (sptr = SessionList; sptr != NULL; sptr = sptr->next) {
73 /** Kill idle sessions */
74 if ((time(NULL) - (sptr->lastreq)) >
75 (time_t) WEBCIT_TIMEOUT) {
79 /** Remove sessions flagged for kill */
82 /** remove session from linked list */
83 if (sptr == SessionList) {
84 SessionList = SessionList->next;
86 else for (ss=SessionList;ss!=NULL;ss=ss->next) {
87 if (ss->next == sptr) {
88 ss->next = ss->next->next;
92 sptr->next = sessions_to_kill;
93 sessions_to_kill = sptr;
96 pthread_mutex_unlock(&SessionListMutex);
99 * Now free up and destroy the culled sessions.
101 while (sessions_to_kill != NULL) {
102 lprintf(3, "Destroying session %d\n", sessions_to_kill->wc_session);
103 pthread_mutex_lock(&sessions_to_kill->SessionMutex);
104 pthread_mutex_unlock(&sessions_to_kill->SessionMutex);
105 sptr = sessions_to_kill->next;
107 DestroySession(&sessions_to_kill);
108 sessions_to_kill = sptr;
113 * If there are more sessions than threads, then we should spawn
114 * more threads ... up to a predefined maximum.
116 while ( (num_sessions > num_threads)
117 && (num_threads <= MAX_WORKER_THREADS) ) {
118 spawn_another_worker_thread();
120 lprintf(3, "There are %d sessions and %d threads active.\n",
121 num_sessions, num_threads);
127 * \brief Wake up occasionally and clean house
129 void housekeeping_loop(void)
132 sleeeeeeeeeep(HOUSEKEEPING);
139 * \brief Create a Session id
140 * Generate a unique WebCit session ID (which is not the same thing as the
141 * Citadel session ID).
143 * \todo FIXME ... ensure that session number is truly unique
146 int GenerateSessionID(void)
148 static int seq = (-1);
151 seq = (int) time(NULL);
159 * Collapse multiple cookies on one line
161 ////int req_gets(int *sock, char *buf, char *hold, size_t hlen)
165 //// if (IsEmptyStr(hold)) {
166 //// strcpy(buf, "");
167 //// a = client_getln(sock, buf, SIZ);
168 //// if (a<1) return(-1);
170 //// safestrncpy(buf, hold, SIZ);
172 //// strcpy(hold, "");
174 //// if (!strncasecmp(buf, "Cookie: ", 8)) {
176 //// len = strlen(buf);
177 //// for (a = 0; a < len; ++a)
178 //// if (buf[a] == ';') {
179 //// // we don't refresh len, because of we
180 //// // only exit from here.
181 //// snprintf(hold, hlen, "Cookie: %s", &buf[a + 1]);
184 //// while (isspace(hold[b]))
187 //// memmove(&hold[8], &hold[b], len - b + 1);
197 * Collapse multiple cookies on one line
199 int ReqGetStrBuf(int *sock, StrBuf *Target, StrBuf *buf)
202 return ClientGetLine(sock, Target, buf);
208 * lingering_close() a`la Apache. see
209 * http://www.apache.org/docs/misc/fin_wait_2.html for rationale
211 int lingering_close(int fd)
216 struct timeval tv, start;
218 gettimeofday(&start, NULL);
222 gettimeofday(&tv, NULL);
223 tv.tv_sec = SLEEPING - (tv.tv_sec - start.tv_sec);
224 tv.tv_usec = start.tv_usec - tv.tv_usec;
225 if (tv.tv_usec < 0) {
227 tv.tv_usec += 1000000;
231 i = select(fd + 1, &set, NULL, NULL, &tv);
232 } while (i == -1 && errno == EINTR);
237 i = read(fd, buf, sizeof buf);
238 } while (i != 0 && (i != -1 || errno == EINTR));
246 * \brief sanity requests
247 * Check for bogus requests coming from brain-dead Windows boxes.
249 * \param http_cmd The HTTP request to check
251 int is_bogus(StrBuf *http_cmd) {
255 url = ChrPtr(http_cmd);
256 if (IsEmptyStr(url)) return(1);
259 char *bogus_prefixes[] = {
260 "/scripts/root.exe", /**< Worms and trojans and viruses, oh my! */
263 "/_vti", /**< Broken Microsoft DAV implementation */
264 "/MSOffice" /**< Stoopid MSOffice thinks everyone is IIS */
267 max = sizeof(bogus_prefixes) / sizeof(char *);
269 for (i=0; i<max; ++i) {
270 if (!strncasecmp(url, bogus_prefixes[i], strlen(bogus_prefixes[i]))) {
275 return(0); /* probably ok */
279 const char *nix(void *vptr) {return ChrPtr( (StrBuf*)vptr);}
282 * \brief handle one request
283 * This loop gets called once for every HTTP connection made to WebCit. At
284 * this entry point we have an HTTP socket with a browser allegedly on the
285 * other end, but we have not yet bound to a WebCit session.
287 * The job of this function is to locate the correct session and bind to it,
288 * or create a session if necessary and bind to it, then run the WebCit
289 * transaction loop. Afterwards, we unbind from the session. When this
290 * function returns, the worker thread is then free to handle another
292 * \param sock the socket we will put our answer to
294 void context_loop(int *sock)
297 int desired_session = 0;
300 wcsession *TheSession, *sptr;
301 char httpauth_string[1024];
302 char httpauth_user[1024];
303 char httpauth_pass[1024];
305 int session_is_new = 0;
309 StrBuf *Buf, *Line, *LastLine, *HeaderName, *ReqLine, *ReqType, *HTTPVersion;
310 StrBuf *accept_language = NULL;
311 const char *pch, *pchs, *pche;
312 HashList *HTTPHeaders;
314 strcpy(httpauth_string, "");
315 strcpy(httpauth_user, DEFAULT_HTTPAUTH_USER);
316 strcpy(httpauth_pass, DEFAULT_HTTPAUTH_PASS);
319 * Find out what it is that the web browser is asking for
321 HeaderName = NewStrBuf();
324 HTTPHeaders = NewHash(1, NULL);
326 * Read in the request
331 if (ReqGetStrBuf(sock, Line, Buf) < 0) return;
333 LineLen = StrLength(Line);
344 /** Do we need to Unfold? */
345 if ((LastLine != NULL) &&
346 (isspace(*ChrPtr(Line)))) {
347 pch = pchs = ChrPtr(Line);
348 pche = pchs + StrLength(Line);
349 while (isspace(*pch) && (pch < pche))
351 StrBufCutLeft(Line, pch - pchs);
352 StrBufAppendBuf(LastLine, Line, 0);
357 StrBufExtract_token(HeaderName, Line, 0, ':');
358 //// TODO: filter bad chars!
361 pch = pchs + StrLength(HeaderName) + 1;
362 pche = pchs + StrLength(Line);
363 while (isspace(*pch) && (pch < pche))
365 StrBufCutLeft(Line, pch - pchs);
367 StrBufUpCase(HeaderName);
368 Put(HTTPHeaders, SKEY(HeaderName), Line, HFreeStrBuf);
370 } while (LineLen > 0);
371 FreeStrBuf(&HeaderName);
373 //// dbg_PrintHash(HTTPHeaders, nix, NULL);
379 if (GetHash(HTTPHeaders, HKEY("ACCEPT-ENCODING"), &vLine) &&
381 buf = ChrPtr((StrBuf*)vLine);
382 if (strstr(&buf[16], "gzip")) {
388 * Browser-based sessions use cookies for session
392 if (GetHash(HTTPHeaders, HKEY("COOKIE"), &vLine) &&
394 cookie_to_stuff(vLine, &desired_session,
395 NULL, 0, NULL, 0, NULL, 0);
400 * GroupDAV-based sessions use HTTP authentication
402 if (GetHash(HTTPHeaders, HKEY("AUTHORIZATION"), &vLine) &&
404 Line = (StrBuf*)vLine;
405 if (strncasecmp(ChrPtr(Line), "Basic", 5) == 0) {
406 StrBufCutLeft(Line, 6);
407 CtdlDecodeBase64(httpauth_string, ChrPtr(Line), StrLength(Line));
408 extract_token(httpauth_user, httpauth_string, 0, ':', sizeof httpauth_user);
409 extract_token(httpauth_pass, httpauth_string, 1, ':', sizeof httpauth_pass);
412 lprintf(1, "Authentication scheme not supported! [%s]\n", ChrPtr(Line));
415 if (GetHash(HTTPHeaders, HKEY("IF-MODIFIED-SINCE"), &vLine) &&
417 if_modified_since = httpdate_to_timestamp((StrBuf*)vLine);
420 if (GetHash(HTTPHeaders, HKEY("ACCEPT-LANGUAGE"), &vLine) &&
422 accept_language = (StrBuf*) vLine;
427 * If the request is prefixed by "/webcit" then chop that off. This
428 * allows a front end web server to forward all /webcit requests to us
429 * while still using the same web server port for other things.
432 ReqType = NewStrBuf();
433 HTTPVersion = NewStrBuf();
434 StrBufExtract_token(HTTPVersion, ReqLine, 2, ' ');
435 StrBufExtract_token(ReqType, ReqLine, 0, ' ');
436 StrBufCutLeft(ReqLine, StrLength(ReqType) + 1);
437 StrBufCutRight(ReqLine, StrLength(HTTPVersion) + 1);
439 if ((follow_xff == 1) && (StrLength(ReqLine) >= 8) &&
440 (ptr = strstr(ChrPtr(ReqLine), "/webcit/"), /*< Handle "/webcit/" */
442 StrBufCutLeft(ReqLine, 7);
445 /** Begin parsing the request. */
447 if ((strncmp(ChrPtr(ReqLine), "/sslg", 5) != 0) &&
448 (strncmp(ChrPtr(ReqLine), "/static/", 8) != 0) &&
449 (strncmp(ChrPtr(ReqLine), "/tiny_mce/", 10) != 0) &&
450 (strncmp(ChrPtr(ReqLine), "/wholist_section", 16) != 0) &&
451 (strstr(ChrPtr(ReqLine), "wholist_section") == NULL)) {
453 lprintf(5, "HTTP: %s %s %s\n", ChrPtr(ReqType), ChrPtr(ReqLine), ChrPtr(HTTPVersion));
458 /** Check for bogus requests */
459 if ((StrLength(HTTPVersion) == 0) ||
460 (StrLength(ReqType) == 0) ||
462 StrBufPlain(ReqLine, HKEY("/404 HTTP/1.1"));
463 StrBufPlain(ReqType, HKEY("GET"));
465 FreeStrBuf(&HTTPVersion);
468 * While we're at it, gracefully handle requests for the
469 * robots.txt and favicon.ico files.
471 if (!strncasecmp(ChrPtr(ReqLine), "/robots.txt", 11)) {
473 HKEY("/static/robots.txt"
474 "?force_close_session=yes HTTP/1.1"));
475 StrBufPlain(ReqType, HKEY("GET"));
477 else if (!strncasecmp(ChrPtr(ReqLine), "/favicon.ico", 12)) {
478 StrBufPlain(ReqLine, HKEY("/static/favicon.ico"));
479 StrBufPlain(ReqType, HKEY("GET"));
483 * These are the URL's which may be executed without a
484 * session cookie already set. If it's not one of these,
485 * force the session to close because cookies are
486 * probably disabled on the client browser.
488 else if ( (StrLength(ReqLine) > 1 )
489 && (strncasecmp(ChrPtr(ReqLine), "/listsub", 8))
490 && (strncasecmp(ChrPtr(ReqLine), "/freebusy", 9))
491 && (strncasecmp(ChrPtr(ReqLine), "/do_logout", 10))
492 && (strncasecmp(ChrPtr(ReqLine), "/groupdav", 9))
493 && (strncasecmp(ChrPtr(ReqLine), "/static", 7))
494 && (strncasecmp(ChrPtr(ReqLine), "/rss", 4))
495 && (strncasecmp(ChrPtr(ReqLine), "/404", 4))
496 && (got_cookie == 0)) {
498 HKEY("/static/nocookies.html"
499 "?force_close_session=yes"));
503 * See if there's an existing session open with the desired ID or user/pass
507 if (TheSession == NULL) {
508 pthread_mutex_lock(&SessionListMutex);
509 for (sptr = SessionList; sptr != NULL; sptr = sptr->next) {
511 /** If HTTP-AUTH, look for a session with matching credentials */
512 if ( (!IsEmptyStr(httpauth_user))
513 &&(!strcasecmp(sptr->httpauth_user, httpauth_user))
514 &&(!strcasecmp(sptr->httpauth_pass, httpauth_pass)) ) {
518 /** If cookie-session, look for a session with matching session ID */
519 if ( (desired_session != 0) && (sptr->wc_session == desired_session)) {
524 pthread_mutex_unlock(&SessionListMutex);
528 * Create a new session if we have to
530 if (TheSession == NULL) {
531 lprintf(3, "Creating a new session\n");
532 TheSession = (wcsession *)
533 malloc(sizeof(wcsession));
534 memset(TheSession, 0, sizeof(wcsession));
535 TheSession->serv_sock = (-1);
536 TheSession->chat_sock = (-1);
538 /* If we're recreating a session that expired, it's best to give it the same
539 * session number that it had before. The client browser ought to pick up
540 * the new session number and start using it, but in some rare situations it
541 * doesn't, and that's a Bad Thing because it causes lots of spurious sessions
544 if (desired_session == 0) {
545 TheSession->wc_session = GenerateSessionID();
548 TheSession->wc_session = desired_session;
551 strcpy(TheSession->httpauth_user, httpauth_user);
552 strcpy(TheSession->httpauth_pass, httpauth_pass);
553 TheSession->hash_prefs = NewHash(1,NULL); /* Get a hash table for the user preferences */
554 pthread_mutex_init(&TheSession->SessionMutex, NULL);
555 pthread_mutex_lock(&SessionListMutex);
556 TheSession->urlstrings = NULL;
557 TheSession->vars = NULL;
558 TheSession->nonce = rand();
559 TheSession->WBuf = NULL;
560 TheSession->CLineBuf = NewStrBuf();
561 TheSession->next = SessionList;
562 TheSession->is_mobile = -1;
563 SessionList = TheSession;
564 pthread_mutex_unlock(&SessionListMutex);
569 * A future improvement might be to check the session integrity
570 * at this point before continuing.
574 * Bind to the session and perform the transaction
576 pthread_mutex_lock(&TheSession->SessionMutex); /* bind */
577 pthread_setspecific(MyConKey, (void *)TheSession);
579 TheSession->urlstrings = NewHash(1,NULL);
580 TheSession->vars = NewHash(1,NULL);
581 TheSession->http_sock = *sock;
582 TheSession->lastreq = time(NULL); /* log */
583 TheSession->gzip_ok = gzip_ok;
585 if (session_is_new) {
586 httplang_to_locale(accept_language);
588 go_selected_language(); /* set locale */
590 session_loop(HTTPHeaders, ReqLine, ReqType, Buf); /* do transaction */
592 stop_selected_language(); /* unset locale */
594 DeleteHash(&TheSession->summ);
595 DeleteHash(&TheSession->urlstrings);
596 DeleteHash(&TheSession->vars);
597 FreeStrBuf(&TheSession->WBuf);
598 FreeStrBuf(&TheSession->HBuf);
601 pthread_mutex_unlock(&TheSession->SessionMutex); /* unbind */
603 /* Free the request buffer */
604 DeleteHash(&HTTPHeaders);
605 FreeStrBuf(&ReqLine);
606 FreeStrBuf(&ReqType);
609 * Free up any session-local substitution variables which
610 * were set during this transaction
616 void tmpl_nonce(StrBuf *Target, int nArgs, WCTemplateToken *Tokens, void *Context, int ContextType)
619 StrBufAppendPrintf(Target, "%ld",
620 (WCC != NULL)? WCC->nonce:0);
627 RegisterNamespace("NONCE", 0, 0, tmpl_nonce, 0);