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)->WBuf));
52 FreeStrBuf(&((*sessions_to_kill)->HBuf));
53 FreeStrBuf(&((*sessions_to_kill)->CLineBuf));
54 free((*sessions_to_kill));
55 (*sessions_to_kill) = NULL;
58 void shutdown_sessions(void)
60 struct wcsession *sptr;
62 for (sptr = SessionList; sptr != NULL; sptr = sptr->next) {
67 void do_housekeeping(void)
69 struct wcsession *sptr, *ss;
70 struct 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 * \brief Wake up occasionally and clean house
139 void housekeeping_loop(void)
142 sleeeeeeeeeep(HOUSEKEEPING);
149 * \brief Create a Session id
150 * Generate a unique WebCit session ID (which is not the same thing as the
151 * Citadel session ID).
153 * \todo FIXME ... ensure that session number is truly unique
156 int GenerateSessionID(void)
158 static int seq = (-1);
161 seq = (int) time(NULL);
169 * Collapse multiple cookies on one line
171 ////int req_gets(int *sock, char *buf, char *hold, size_t hlen)
175 //// if (IsEmptyStr(hold)) {
176 //// strcpy(buf, "");
177 //// a = client_getln(sock, buf, SIZ);
178 //// if (a<1) return(-1);
180 //// safestrncpy(buf, hold, SIZ);
182 //// strcpy(hold, "");
184 //// if (!strncasecmp(buf, "Cookie: ", 8)) {
186 //// len = strlen(buf);
187 //// for (a = 0; a < len; ++a)
188 //// if (buf[a] == ';') {
189 //// // we don't refresh len, because of we
190 //// // only exit from here.
191 //// snprintf(hold, hlen, "Cookie: %s", &buf[a + 1]);
194 //// while (isspace(hold[b]))
197 //// memmove(&hold[8], &hold[b], len - b + 1);
207 * Collapse multiple cookies on one line
209 int ReqGetStrBuf(int *sock, StrBuf *Target, StrBuf *buf)
212 return ClientGetLine(sock, Target, buf);
218 * lingering_close() a`la Apache. see
219 * http://www.apache.org/docs/misc/fin_wait_2.html for rationale
221 int lingering_close(int fd)
226 struct timeval tv, start;
228 gettimeofday(&start, NULL);
232 gettimeofday(&tv, NULL);
233 tv.tv_sec = SLEEPING - (tv.tv_sec - start.tv_sec);
234 tv.tv_usec = start.tv_usec - tv.tv_usec;
235 if (tv.tv_usec < 0) {
237 tv.tv_usec += 1000000;
241 i = select(fd + 1, &set, NULL, NULL, &tv);
242 } while (i == -1 && errno == EINTR);
247 i = read(fd, buf, sizeof buf);
248 } while (i != 0 && (i != -1 || errno == EINTR));
256 * \brief sanity requests
257 * Check for bogus requests coming from brain-dead Windows boxes.
259 * \param http_cmd The HTTP request to check
261 int is_bogus(StrBuf *http_cmd) {
265 url = ChrPtr(http_cmd);
266 if (IsEmptyStr(url)) return(1);
269 char *bogus_prefixes[] = {
270 "/scripts/root.exe", /**< Worms and trojans and viruses, oh my! */
273 "/_vti", /**< Broken Microsoft DAV implementation */
274 "/MSOffice" /**< Stoopid MSOffice thinks everyone is IIS */
277 max = sizeof(bogus_prefixes) / sizeof(char *);
279 for (i=0; i<max; ++i) {
280 if (!strncasecmp(url, bogus_prefixes[i], strlen(bogus_prefixes[i]))) {
285 return(0); /* probably ok */
289 const char *nix(void *vptr) {return ChrPtr( (StrBuf*)vptr);}
292 * \brief handle one request
293 * This loop gets called once for every HTTP connection made to WebCit. At
294 * this entry point we have an HTTP socket with a browser allegedly on the
295 * other end, but we have not yet bound to a WebCit session.
297 * The job of this function is to locate the correct session and bind to it,
298 * or create a session if necessary and bind to it, then run the WebCit
299 * transaction loop. Afterwards, we unbind from the session. When this
300 * function returns, the worker thread is then free to handle another
302 * \param sock the socket we will put our answer to
304 void context_loop(int *sock)
307 int desired_session = 0;
310 struct wcsession *TheSession, *sptr;
311 char httpauth_string[1024];
312 char httpauth_user[1024];
313 char httpauth_pass[1024];
315 int session_is_new = 0;
319 StrBuf *Buf, *Line, *LastLine, *HeaderName, *ReqLine, *ReqType, *HTTPVersion;
320 StrBuf *accept_language = NULL;
321 const char *pch, *pchs, *pche;
322 HashList *HTTPHeaders;
324 strcpy(httpauth_string, "");
325 strcpy(httpauth_user, DEFAULT_HTTPAUTH_USER);
326 strcpy(httpauth_pass, DEFAULT_HTTPAUTH_PASS);
329 * Find out what it is that the web browser is asking for
331 HeaderName = NewStrBuf();
334 HTTPHeaders = NewHash(1, NULL);
336 * Read in the request
341 if (ReqGetStrBuf(sock, Line, Buf) < 0) return;
343 LineLen = StrLength(Line);
354 /** Do we need to Unfold? */
355 if ((LastLine != NULL) &&
356 (isspace(*ChrPtr(Line)))) {
357 pch = pchs = ChrPtr(Line);
358 pche = pchs + StrLength(Line);
359 while (isspace(*pch) && (pch < pche))
361 StrBufCutLeft(Line, pch - pchs);
362 StrBufAppendBuf(LastLine, Line, 0);
367 StrBufExtract_token(HeaderName, Line, 0, ':');
368 //// TODO: filter bad chars!
371 pch = pchs + StrLength(HeaderName) + 1;
372 pche = pchs + StrLength(Line);
373 while (isspace(*pch) && (pch < pche))
375 StrBufCutLeft(Line, pch - pchs);
377 StrBufUpCase(HeaderName);
378 Put(HTTPHeaders, SKEY(HeaderName), Line, HFreeStrBuf);
380 } while (LineLen > 0);
381 FreeStrBuf(&HeaderName);
383 //// dbg_PrintHash(HTTPHeaders, nix, NULL);
389 if (GetHash(HTTPHeaders, HKEY("ACCEPT-ENCODING"), &vLine) &&
391 buf = ChrPtr((StrBuf*)vLine);
392 if (strstr(&buf[16], "gzip")) {
398 * Browser-based sessions use cookies for session
402 if (GetHash(HTTPHeaders, HKEY("COOKIE"), &vLine) &&
404 cookie_to_stuff(vLine, &desired_session,
405 NULL, 0, NULL, 0, NULL, 0);
410 * GroupDAV-based sessions use HTTP authentication
412 if (GetHash(HTTPHeaders, HKEY("AUTHORIZATION"), &vLine) &&
414 Line = (StrBuf*)vLine;
415 if (strncasecmp(ChrPtr(Line), "Basic", 5) == 0) {
416 StrBufCutLeft(Line, 6);
417 CtdlDecodeBase64(httpauth_string, ChrPtr(Line), StrLength(Line));
418 extract_token(httpauth_user, httpauth_string, 0, ':', sizeof httpauth_user);
419 extract_token(httpauth_pass, httpauth_string, 1, ':', sizeof httpauth_pass);
422 lprintf(1, "Authentication scheme not supported! [%s]\n", ChrPtr(Line));
425 if (GetHash(HTTPHeaders, HKEY("IF-MODIFIED-SINCE"), &vLine) &&
427 if_modified_since = httpdate_to_timestamp((StrBuf*)vLine);
430 if (GetHash(HTTPHeaders, HKEY("ACCEPT-LANGUAGE"), &vLine) &&
432 accept_language = (StrBuf*) vLine;
437 * If the request is prefixed by "/webcit" then chop that off. This
438 * allows a front end web server to forward all /webcit requests to us
439 * while still using the same web server port for other things.
442 ReqType = NewStrBuf();
443 HTTPVersion = NewStrBuf();
444 StrBufExtract_token(HTTPVersion, ReqLine, 2, ' ');
445 StrBufExtract_token(ReqType, ReqLine, 0, ' ');
446 StrBufCutLeft(ReqLine, StrLength(ReqType) + 1);
447 StrBufCutRight(ReqLine, StrLength(HTTPVersion) + 1);
449 if ((follow_xff == 1) && (StrLength(ReqLine) >= 8) &&
450 (ptr = strstr(ChrPtr(ReqLine), "/webcit/"), /*< Handle "/webcit/" */
452 StrBufCutLeft(ReqLine, 7);
455 /** Begin parsing the request. */
457 if ((strncmp(ChrPtr(ReqLine), "/sslg", 5) != 0) &&
458 (strncmp(ChrPtr(ReqLine), "/static/", 8) != 0) &&
459 (strncmp(ChrPtr(ReqLine), "/tiny_mce/", 10) != 0) &&
460 (strncmp(ChrPtr(ReqLine), "/wholist_section", 16) != 0) &&
461 (strstr(ChrPtr(ReqLine), "wholist_section") == NULL)) {
463 lprintf(5, "HTTP: %s %s %s\n", ChrPtr(ReqType), ChrPtr(ReqLine), ChrPtr(HTTPVersion));
468 /** Check for bogus requests */
469 if ((StrLength(HTTPVersion) == 0) ||
470 (StrLength(ReqType) == 0) ||
472 StrBufPlain(ReqLine, HKEY("/404 HTTP/1.1"));
473 StrBufPlain(ReqType, HKEY("GET"));
475 FreeStrBuf(&HTTPVersion);
478 * While we're at it, gracefully handle requests for the
479 * robots.txt and favicon.ico files.
481 if (!strncasecmp(ChrPtr(ReqLine), "/robots.txt", 11)) {
483 HKEY("/static/robots.txt"
484 "?force_close_session=yes HTTP/1.1"));
485 StrBufPlain(ReqType, HKEY("GET"));
487 else if (!strncasecmp(ChrPtr(ReqLine), "/favicon.ico", 12)) {
488 StrBufPlain(ReqLine, HKEY("/static/favicon.ico"));
489 StrBufPlain(ReqType, HKEY("GET"));
493 * These are the URL's which may be executed without a
494 * session cookie already set. If it's not one of these,
495 * force the session to close because cookies are
496 * probably disabled on the client browser.
498 else if ( (StrLength(ReqLine) > 1 )
499 && (strncasecmp(ChrPtr(ReqLine), "/listsub", 8))
500 && (strncasecmp(ChrPtr(ReqLine), "/freebusy", 9))
501 && (strncasecmp(ChrPtr(ReqLine), "/do_logout", 10))
502 && (strncasecmp(ChrPtr(ReqLine), "/groupdav", 9))
503 && (strncasecmp(ChrPtr(ReqLine), "/static", 7))
504 && (strncasecmp(ChrPtr(ReqLine), "/rss", 4))
505 && (strncasecmp(ChrPtr(ReqLine), "/404", 4))
506 && (got_cookie == 0)) {
508 HKEY("/static/nocookies.html"
509 "?force_close_session=yes"));
513 * See if there's an existing session open with the desired ID or user/pass
517 if (TheSession == NULL) {
518 pthread_mutex_lock(&SessionListMutex);
519 for (sptr = SessionList; sptr != NULL; sptr = sptr->next) {
521 /** If HTTP-AUTH, look for a session with matching credentials */
522 if ( (!IsEmptyStr(httpauth_user))
523 &&(!strcasecmp(sptr->httpauth_user, httpauth_user))
524 &&(!strcasecmp(sptr->httpauth_pass, httpauth_pass)) ) {
528 /** If cookie-session, look for a session with matching session ID */
529 if ( (desired_session != 0) && (sptr->wc_session == desired_session)) {
534 pthread_mutex_unlock(&SessionListMutex);
538 * Create a new session if we have to
540 if (TheSession == NULL) {
541 lprintf(3, "Creating a new session\n");
542 TheSession = (struct wcsession *)
543 malloc(sizeof(struct wcsession));
544 memset(TheSession, 0, sizeof(struct wcsession));
545 TheSession->serv_sock = (-1);
546 TheSession->chat_sock = (-1);
548 /* If we're recreating a session that expired, it's best to give it the same
549 * session number that it had before. The client browser ought to pick up
550 * the new session number and start using it, but in some rare situations it
551 * doesn't, and that's a Bad Thing because it causes lots of spurious sessions
554 if (desired_session == 0) {
555 TheSession->wc_session = GenerateSessionID();
558 TheSession->wc_session = desired_session;
561 strcpy(TheSession->httpauth_user, httpauth_user);
562 strcpy(TheSession->httpauth_pass, httpauth_pass);
563 TheSession->hash_prefs = NewHash(1,NULL); /* Get a hash table for the user preferences */
564 pthread_mutex_init(&TheSession->SessionMutex, NULL);
565 pthread_mutex_lock(&SessionListMutex);
566 TheSession->urlstrings = NULL;
567 TheSession->vars = NULL;
568 TheSession->nonce = rand();
569 TheSession->WBuf = NULL;
570 TheSession->CLineBuf = NewStrBuf();
571 TheSession->next = SessionList;
572 TheSession->is_mobile = -1;
573 SessionList = TheSession;
574 pthread_mutex_unlock(&SessionListMutex);
579 * A future improvement might be to check the session integrity
580 * at this point before continuing.
584 * Bind to the session and perform the transaction
586 pthread_mutex_lock(&TheSession->SessionMutex); /* bind */
587 pthread_setspecific(MyConKey, (void *)TheSession);
589 TheSession->urlstrings = NewHash(1,NULL);
590 TheSession->vars = NewHash(1,NULL);
591 TheSession->http_sock = *sock;
592 TheSession->lastreq = time(NULL); /* log */
593 TheSession->gzip_ok = gzip_ok;
595 if (session_is_new) {
596 httplang_to_locale(accept_language);
598 go_selected_language(); /* set locale */
600 session_loop(HTTPHeaders, ReqLine, ReqType, Buf); /* do transaction */
602 stop_selected_language(); /* unset locale */
604 DeleteHash(&TheSession->summ);
605 DeleteHash(&TheSession->urlstrings);
606 DeleteHash(&TheSession->vars);
607 FreeStrBuf(&TheSession->WBuf);
608 FreeStrBuf(&TheSession->HBuf);
611 pthread_mutex_unlock(&TheSession->SessionMutex); /* unbind */
613 /* Free the request buffer */
614 DeleteHash(&HTTPHeaders);
615 FreeStrBuf(&ReqLine);
616 FreeStrBuf(&ReqType);
619 * Free up any session-local substitution variables which
620 * were set during this transaction
626 void tmpl_nonce(StrBuf *Target, int nArgs, WCTemplateToken *Tokens, void *Context, int ContextType)
628 struct wcsession *WCC = WC;
629 StrBufAppendPrintf(Target, "%ld",
630 (WCC != NULL)? WCC->nonce:0);
637 RegisterNamespace("NONCE", 0, 0, tmpl_nonce, 0);