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 struct wcsession *SessionList = NULL; /**< our sessions ????*/
19 pthread_key_t MyConKey; /**< TSD key for MySession() */
23 * free the memory used for viewing atachments
25 void free_attachment(void *vattach) {
26 wc_attachment *att = (wc_attachment*) vattach;
27 FreeStrBuf(&att->content_type);
28 FreeStrBuf(&att->filename);
34 void DestroySession(struct wcsession **sessions_to_kill)
36 close((*sessions_to_kill)->serv_sock);
37 close((*sessions_to_kill)->chat_sock);
38 // if ((*sessions_to_kill)->preferences != NULL) {
39 // free((*sessions_to_kill)->preferences);
41 if ((*sessions_to_kill)->cache_fold != NULL) {
42 free((*sessions_to_kill)->cache_fold);
44 DeleteHash(&((*sessions_to_kill)->attachments));
45 free_march_list((*sessions_to_kill));
46 DeleteHash(&((*sessions_to_kill)->hash_prefs));
47 DeleteHash(&((*sessions_to_kill)->IconBarSetttings));
48 DeleteHash(&((*sessions_to_kill)->ServCfg));
49 FreeStrBuf(&((*sessions_to_kill)->UrlFragment1));
50 FreeStrBuf(&((*sessions_to_kill)->UrlFragment2));
51 FreeStrBuf(&((*sessions_to_kill)->UrlFragment3));
52 FreeStrBuf(&((*sessions_to_kill)->WBuf));
53 FreeStrBuf(&((*sessions_to_kill)->HBuf));
54 FreeStrBuf(&((*sessions_to_kill)->CLineBuf));
55 free((*sessions_to_kill));
56 (*sessions_to_kill) = NULL;
59 void shutdown_sessions(void)
61 struct wcsession *sptr;
63 for (sptr = SessionList; sptr != NULL; sptr = sptr->next) {
68 void do_housekeeping(void)
70 struct wcsession *sptr, *ss;
71 struct wcsession *sessions_to_kill = NULL;
73 static int num_threads = MIN_WORKER_THREADS;
76 * Lock the session list, moving any candidates for euthanasia into
79 pthread_mutex_lock(&SessionListMutex);
81 for (sptr = SessionList; sptr != NULL; sptr = sptr->next) {
84 /** Kill idle sessions */
85 if ((time(NULL) - (sptr->lastreq)) >
86 (time_t) WEBCIT_TIMEOUT) {
90 /** Remove sessions flagged for kill */
93 /** remove session from linked list */
94 if (sptr == SessionList) {
95 SessionList = SessionList->next;
97 else for (ss=SessionList;ss!=NULL;ss=ss->next) {
98 if (ss->next == sptr) {
99 ss->next = ss->next->next;
103 sptr->next = sessions_to_kill;
104 sessions_to_kill = sptr;
107 pthread_mutex_unlock(&SessionListMutex);
110 * Now free up and destroy the culled sessions.
112 while (sessions_to_kill != NULL) {
113 lprintf(3, "Destroying session %d\n", sessions_to_kill->wc_session);
114 pthread_mutex_lock(&sessions_to_kill->SessionMutex);
115 pthread_mutex_unlock(&sessions_to_kill->SessionMutex);
116 sptr = sessions_to_kill->next;
118 DestroySession(&sessions_to_kill);
119 sessions_to_kill = sptr;
124 * If there are more sessions than threads, then we should spawn
125 * more threads ... up to a predefined maximum.
127 while ( (num_sessions > num_threads)
128 && (num_threads <= MAX_WORKER_THREADS) ) {
129 spawn_another_worker_thread();
131 lprintf(3, "There are %d sessions and %d threads active.\n",
132 num_sessions, num_threads);
138 * \brief Wake up occasionally and clean house
140 void housekeeping_loop(void)
143 sleeeeeeeeeep(HOUSEKEEPING);
150 * \brief Create a Session id
151 * Generate a unique WebCit session ID (which is not the same thing as the
152 * Citadel session ID).
154 * \todo FIXME ... ensure that session number is truly unique
157 int GenerateSessionID(void)
159 static int seq = (-1);
162 seq = (int) time(NULL);
170 * Collapse multiple cookies on one line
172 ////int req_gets(int *sock, char *buf, char *hold, size_t hlen)
176 //// if (IsEmptyStr(hold)) {
177 //// strcpy(buf, "");
178 //// a = client_getln(sock, buf, SIZ);
179 //// if (a<1) return(-1);
181 //// safestrncpy(buf, hold, SIZ);
183 //// strcpy(hold, "");
185 //// if (!strncasecmp(buf, "Cookie: ", 8)) {
187 //// len = strlen(buf);
188 //// for (a = 0; a < len; ++a)
189 //// if (buf[a] == ';') {
190 //// // we don't refresh len, because of we
191 //// // only exit from here.
192 //// snprintf(hold, hlen, "Cookie: %s", &buf[a + 1]);
195 //// while (isspace(hold[b]))
198 //// memmove(&hold[8], &hold[b], len - b + 1);
208 * Collapse multiple cookies on one line
210 int ReqGetStrBuf(int *sock, StrBuf *Target, StrBuf *buf)
213 return ClientGetLine(sock, Target, buf);
219 * lingering_close() a`la Apache. see
220 * http://www.apache.org/docs/misc/fin_wait_2.html for rationale
222 int lingering_close(int fd)
227 struct timeval tv, start;
229 gettimeofday(&start, NULL);
233 gettimeofday(&tv, NULL);
234 tv.tv_sec = SLEEPING - (tv.tv_sec - start.tv_sec);
235 tv.tv_usec = start.tv_usec - tv.tv_usec;
236 if (tv.tv_usec < 0) {
238 tv.tv_usec += 1000000;
242 i = select(fd + 1, &set, NULL, NULL, &tv);
243 } while (i == -1 && errno == EINTR);
248 i = read(fd, buf, sizeof buf);
249 } while (i != 0 && (i != -1 || errno == EINTR));
257 * \brief sanity requests
258 * Check for bogus requests coming from brain-dead Windows boxes.
260 * \param http_cmd The HTTP request to check
262 int is_bogus(StrBuf *http_cmd) {
266 url = ChrPtr(http_cmd);
267 if (IsEmptyStr(url)) return(1);
270 char *bogus_prefixes[] = {
271 "/scripts/root.exe", /**< Worms and trojans and viruses, oh my! */
274 "/_vti", /**< Broken Microsoft DAV implementation */
275 "/MSOffice" /**< Stoopid MSOffice thinks everyone is IIS */
278 max = sizeof(bogus_prefixes) / sizeof(char *);
280 for (i=0; i<max; ++i) {
281 if (!strncasecmp(url, bogus_prefixes[i], strlen(bogus_prefixes[i]))) {
286 return(0); /* probably ok */
290 const char *nix(void *vptr) {return ChrPtr( (StrBuf*)vptr);}
293 * \brief handle one request
294 * This loop gets called once for every HTTP connection made to WebCit. At
295 * this entry point we have an HTTP socket with a browser allegedly on the
296 * other end, but we have not yet bound to a WebCit session.
298 * The job of this function is to locate the correct session and bind to it,
299 * or create a session if necessary and bind to it, then run the WebCit
300 * transaction loop. Afterwards, we unbind from the session. When this
301 * function returns, the worker thread is then free to handle another
303 * \param sock the socket we will put our answer to
305 void context_loop(int *sock)
308 int desired_session = 0;
311 struct wcsession *TheSession, *sptr;
312 char httpauth_string[1024];
313 char httpauth_user[1024];
314 char httpauth_pass[1024];
316 int session_is_new = 0;
320 StrBuf *Buf, *Line, *LastLine, *HeaderName, *ReqLine, *ReqType, *HTTPVersion;
321 StrBuf *accept_language = NULL;
322 const char *pch, *pchs, *pche;
323 HashList *HTTPHeaders;
325 strcpy(httpauth_string, "");
326 strcpy(httpauth_user, DEFAULT_HTTPAUTH_USER);
327 strcpy(httpauth_pass, DEFAULT_HTTPAUTH_PASS);
330 * Find out what it is that the web browser is asking for
332 HeaderName = NewStrBuf();
335 HTTPHeaders = NewHash(1, NULL);
337 * Read in the request
342 if (ReqGetStrBuf(sock, Line, Buf) < 0) return;
344 LineLen = StrLength(Line);
355 /** Do we need to Unfold? */
356 if ((LastLine != NULL) &&
357 (isspace(*ChrPtr(Line)))) {
358 pch = pchs = ChrPtr(Line);
359 pche = pchs + StrLength(Line);
360 while (isspace(*pch) && (pch < pche))
362 StrBufCutLeft(Line, pch - pchs);
363 StrBufAppendBuf(LastLine, Line, 0);
368 StrBufExtract_token(HeaderName, Line, 0, ':');
369 //// TODO: filter bad chars!
372 pch = pchs + StrLength(HeaderName) + 1;
373 pche = pchs + StrLength(Line);
374 while (isspace(*pch) && (pch < pche))
376 StrBufCutLeft(Line, pch - pchs);
378 StrBufUpCase(HeaderName);
379 Put(HTTPHeaders, SKEY(HeaderName), Line, HFreeStrBuf);
381 } while (LineLen > 0);
382 FreeStrBuf(&HeaderName);
384 //// dbg_PrintHash(HTTPHeaders, nix, NULL);
390 if (GetHash(HTTPHeaders, HKEY("ACCEPT-ENCODING"), &vLine) &&
392 buf = ChrPtr((StrBuf*)vLine);
393 if (strstr(&buf[16], "gzip")) {
399 * Browser-based sessions use cookies for session
403 if (GetHash(HTTPHeaders, HKEY("COOKIE"), &vLine) &&
405 cookie_to_stuff(vLine, &desired_session,
406 NULL, 0, NULL, 0, NULL, 0);
411 * GroupDAV-based sessions use HTTP authentication
413 if (GetHash(HTTPHeaders, HKEY("AUTHORIZATION"), &vLine) &&
415 Line = (StrBuf*)vLine;
416 if (strncasecmp(ChrPtr(Line), "Basic", 5) == 0) {
417 StrBufCutLeft(Line, 6);
418 CtdlDecodeBase64(httpauth_string, ChrPtr(Line), StrLength(Line));
419 extract_token(httpauth_user, httpauth_string, 0, ':', sizeof httpauth_user);
420 extract_token(httpauth_pass, httpauth_string, 1, ':', sizeof httpauth_pass);
423 lprintf(1, "Authentication scheme not supported! [%s]\n", ChrPtr(Line));
426 if (GetHash(HTTPHeaders, HKEY("IF-MODIFIED-SINCE"), &vLine) &&
428 if_modified_since = httpdate_to_timestamp((StrBuf*)vLine);
431 if (GetHash(HTTPHeaders, HKEY("ACCEPT-LANGUAGE"), &vLine) &&
433 accept_language = (StrBuf*) vLine;
438 * If the request is prefixed by "/webcit" then chop that off. This
439 * allows a front end web server to forward all /webcit requests to us
440 * while still using the same web server port for other things.
443 ReqType = NewStrBuf();
444 HTTPVersion = NewStrBuf();
445 StrBufExtract_token(HTTPVersion, ReqLine, 2, ' ');
446 StrBufExtract_token(ReqType, ReqLine, 0, ' ');
447 StrBufCutLeft(ReqLine, StrLength(ReqType) + 1);
448 StrBufCutRight(ReqLine, StrLength(HTTPVersion) + 1);
450 if ((follow_xff == 1) && (StrLength(ReqLine) >= 8) &&
451 (ptr = strstr(ChrPtr(ReqLine), "/webcit/"), /*< Handle "/webcit/" */
453 StrBufCutLeft(ReqLine, 7);
456 /** Begin parsing the request. */
458 if ((strncmp(ChrPtr(ReqLine), "/sslg", 5) != 0) &&
459 (strncmp(ChrPtr(ReqLine), "/static/", 8) != 0) &&
460 (strncmp(ChrPtr(ReqLine), "/tiny_mce/", 10) != 0) &&
461 (strncmp(ChrPtr(ReqLine), "/wholist_section", 16) != 0) &&
462 (strstr(ChrPtr(ReqLine), "wholist_section") == NULL)) {
464 lprintf(5, "HTTP: %s %s %s\n", ChrPtr(ReqType), ChrPtr(ReqLine), ChrPtr(HTTPVersion));
469 /** Check for bogus requests */
470 if ((StrLength(HTTPVersion) == 0) ||
471 (StrLength(ReqType) == 0) ||
473 StrBufPlain(ReqLine, HKEY("/404 HTTP/1.1"));
474 StrBufPlain(ReqType, HKEY("GET"));
476 FreeStrBuf(&HTTPVersion);
479 * While we're at it, gracefully handle requests for the
480 * robots.txt and favicon.ico files.
482 if (!strncasecmp(ChrPtr(ReqLine), "/robots.txt", 11)) {
484 HKEY("/static/robots.txt"
485 "?force_close_session=yes HTTP/1.1"));
486 StrBufPlain(ReqType, HKEY("GET"));
488 else if (!strncasecmp(ChrPtr(ReqLine), "/favicon.ico", 12)) {
489 StrBufPlain(ReqLine, HKEY("/static/favicon.ico"));
490 StrBufPlain(ReqType, HKEY("GET"));
494 * These are the URL's which may be executed without a
495 * session cookie already set. If it's not one of these,
496 * force the session to close because cookies are
497 * probably disabled on the client browser.
499 else if ( (StrLength(ReqLine) > 1 )
500 && (strncasecmp(ChrPtr(ReqLine), "/listsub", 8))
501 && (strncasecmp(ChrPtr(ReqLine), "/freebusy", 9))
502 && (strncasecmp(ChrPtr(ReqLine), "/do_logout", 10))
503 && (strncasecmp(ChrPtr(ReqLine), "/groupdav", 9))
504 && (strncasecmp(ChrPtr(ReqLine), "/static", 7))
505 && (strncasecmp(ChrPtr(ReqLine), "/rss", 4))
506 && (strncasecmp(ChrPtr(ReqLine), "/404", 4))
507 && (got_cookie == 0)) {
509 HKEY("/static/nocookies.html"
510 "?force_close_session=yes"));
514 * See if there's an existing session open with the desired ID or user/pass
518 if (TheSession == NULL) {
519 pthread_mutex_lock(&SessionListMutex);
520 for (sptr = SessionList; sptr != NULL; sptr = sptr->next) {
522 /** If HTTP-AUTH, look for a session with matching credentials */
523 if ( (!IsEmptyStr(httpauth_user))
524 &&(!strcasecmp(sptr->httpauth_user, httpauth_user))
525 &&(!strcasecmp(sptr->httpauth_pass, httpauth_pass)) ) {
529 /** If cookie-session, look for a session with matching session ID */
530 if ( (desired_session != 0) && (sptr->wc_session == desired_session)) {
535 pthread_mutex_unlock(&SessionListMutex);
539 * Create a new session if we have to
541 if (TheSession == NULL) {
542 lprintf(3, "Creating a new session\n");
543 TheSession = (struct wcsession *)
544 malloc(sizeof(struct wcsession));
545 memset(TheSession, 0, sizeof(struct wcsession));
546 TheSession->serv_sock = (-1);
547 TheSession->chat_sock = (-1);
549 /* If we're recreating a session that expired, it's best to give it the same
550 * session number that it had before. The client browser ought to pick up
551 * the new session number and start using it, but in some rare situations it
552 * doesn't, and that's a Bad Thing because it causes lots of spurious sessions
555 if (desired_session == 0) {
556 TheSession->wc_session = GenerateSessionID();
559 TheSession->wc_session = desired_session;
562 strcpy(TheSession->httpauth_user, httpauth_user);
563 strcpy(TheSession->httpauth_pass, httpauth_pass);
564 TheSession->hash_prefs = NewHash(1,NULL); /* Get a hash table for the user preferences */
565 pthread_mutex_init(&TheSession->SessionMutex, NULL);
566 pthread_mutex_lock(&SessionListMutex);
567 TheSession->urlstrings = NULL;
568 TheSession->vars = NULL;
569 TheSession->nonce = rand();
570 TheSession->WBuf = NULL;
571 TheSession->CLineBuf = NewStrBuf();
572 TheSession->next = SessionList;
573 TheSession->is_mobile = -1;
574 SessionList = TheSession;
575 pthread_mutex_unlock(&SessionListMutex);
580 * A future improvement might be to check the session integrity
581 * at this point before continuing.
585 * Bind to the session and perform the transaction
587 pthread_mutex_lock(&TheSession->SessionMutex); /* bind */
588 pthread_setspecific(MyConKey, (void *)TheSession);
590 TheSession->urlstrings = NewHash(1,NULL);
591 TheSession->vars = NewHash(1,NULL);
592 TheSession->http_sock = *sock;
593 TheSession->lastreq = time(NULL); /* log */
594 TheSession->gzip_ok = gzip_ok;
596 if (session_is_new) {
597 httplang_to_locale(accept_language);
599 go_selected_language(); /* set locale */
601 session_loop(HTTPHeaders, ReqLine, ReqType, Buf); /* do transaction */
603 stop_selected_language(); /* unset locale */
605 DeleteHash(&TheSession->summ);
606 DeleteHash(&TheSession->urlstrings);
607 DeleteHash(&TheSession->vars);
608 FreeStrBuf(&TheSession->WBuf);
609 FreeStrBuf(&TheSession->HBuf);
612 pthread_mutex_unlock(&TheSession->SessionMutex); /* unbind */
614 /* Free the request buffer */
615 DeleteHash(&HTTPHeaders);
616 FreeStrBuf(&ReqLine);
617 FreeStrBuf(&ReqType);
620 * Free up any session-local substitution variables which
621 * were set during this transaction
627 void tmpl_nonce(StrBuf *Target, int nArgs, WCTemplateToken *Tokens, void *Context, int ContextType)
629 struct wcsession *WCC = WC;
630 StrBufAppendPrintf(Target, "%ld",
631 (WCC != NULL)? WCC->nonce:0);
638 RegisterNamespace("NONCE", 0, 0, tmpl_nonce, 0);