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_attachments(struct wcsession *sess) {
26 struct wc_attachment *att;
28 while (sess->first_attachment != NULL) {
29 att = sess->first_attachment;
30 sess->first_attachment = sess->first_attachment->next;
37 void DestroySession(struct wcsession **sessions_to_kill)
39 close((*sessions_to_kill)->serv_sock);
40 close((*sessions_to_kill)->chat_sock);
41 // if ((*sessions_to_kill)->preferences != NULL) {
42 // free((*sessions_to_kill)->preferences);
44 if ((*sessions_to_kill)->cache_fold != NULL) {
45 free((*sessions_to_kill)->cache_fold);
47 free_attachments((*sessions_to_kill));
48 free_march_list((*sessions_to_kill));
49 DeleteHash(&((*sessions_to_kill)->hash_prefs));
50 DeleteHash(&((*sessions_to_kill)->IconBarSetttings));
51 DeleteHash(&((*sessions_to_kill)->ServCfg));
52 FreeStrBuf(&((*sessions_to_kill)->UrlFragment1));
53 FreeStrBuf(&((*sessions_to_kill)->UrlFragment2));
54 FreeStrBuf(&((*sessions_to_kill)->WBuf));
55 FreeStrBuf(&((*sessions_to_kill)->HBuf));
56 FreeStrBuf(&((*sessions_to_kill)->CLineBuf));
57 free((*sessions_to_kill));
58 (*sessions_to_kill) = NULL;
61 void shutdown_sessions(void)
63 struct wcsession *sptr;
65 for (sptr = SessionList; sptr != NULL; sptr = sptr->next) {
70 void do_housekeeping(void)
72 struct wcsession *sptr, *ss;
73 struct wcsession *sessions_to_kill = NULL;
75 static int num_threads = MIN_WORKER_THREADS;
78 * Lock the session list, moving any candidates for euthanasia into
81 pthread_mutex_lock(&SessionListMutex);
83 for (sptr = SessionList; sptr != NULL; sptr = sptr->next) {
86 /** Kill idle sessions */
87 if ((time(NULL) - (sptr->lastreq)) >
88 (time_t) WEBCIT_TIMEOUT) {
92 /** Remove sessions flagged for kill */
95 /** remove session from linked list */
96 if (sptr == SessionList) {
97 SessionList = SessionList->next;
99 else for (ss=SessionList;ss!=NULL;ss=ss->next) {
100 if (ss->next == sptr) {
101 ss->next = ss->next->next;
105 sptr->next = sessions_to_kill;
106 sessions_to_kill = sptr;
109 pthread_mutex_unlock(&SessionListMutex);
112 * Now free up and destroy the culled sessions.
114 while (sessions_to_kill != NULL) {
115 lprintf(3, "Destroying session %d\n", sessions_to_kill->wc_session);
116 pthread_mutex_lock(&sessions_to_kill->SessionMutex);
117 pthread_mutex_unlock(&sessions_to_kill->SessionMutex);
118 sptr = sessions_to_kill->next;
120 DestroySession(&sessions_to_kill);
121 sessions_to_kill = sptr;
126 * If there are more sessions than threads, then we should spawn
127 * more threads ... up to a predefined maximum.
129 while ( (num_sessions > num_threads)
130 && (num_threads <= MAX_WORKER_THREADS) ) {
131 spawn_another_worker_thread();
133 lprintf(3, "There are %d sessions and %d threads active.\n",
134 num_sessions, num_threads);
140 * \brief Wake up occasionally and clean house
142 void housekeeping_loop(void)
145 sleeeeeeeeeep(HOUSEKEEPING);
152 * \brief Create a Session id
153 * Generate a unique WebCit session ID (which is not the same thing as the
154 * Citadel session ID).
156 * \todo FIXME ... ensure that session number is truly unique
159 int GenerateSessionID(void)
161 static int seq = (-1);
164 seq = (int) time(NULL);
172 * Collapse multiple cookies on one line
174 ////int req_gets(int *sock, char *buf, char *hold, size_t hlen)
178 //// if (IsEmptyStr(hold)) {
179 //// strcpy(buf, "");
180 //// a = client_getln(sock, buf, SIZ);
181 //// if (a<1) return(-1);
183 //// safestrncpy(buf, hold, SIZ);
185 //// strcpy(hold, "");
187 //// if (!strncasecmp(buf, "Cookie: ", 8)) {
189 //// len = strlen(buf);
190 //// for (a = 0; a < len; ++a)
191 //// if (buf[a] == ';') {
192 //// // we don't refresh len, because of we
193 //// // only exit from here.
194 //// snprintf(hold, hlen, "Cookie: %s", &buf[a + 1]);
197 //// while (isspace(hold[b]))
200 //// memmove(&hold[8], &hold[b], len - b + 1);
210 * Collapse multiple cookies on one line
212 int ReqGetStrBuf(int *sock, StrBuf *Target, StrBuf *buf)
215 return ClientGetLine(sock, Target, buf);
221 * lingering_close() a`la Apache. see
222 * http://www.apache.org/docs/misc/fin_wait_2.html for rationale
224 int lingering_close(int fd)
229 struct timeval tv, start;
231 gettimeofday(&start, NULL);
235 gettimeofday(&tv, NULL);
236 tv.tv_sec = SLEEPING - (tv.tv_sec - start.tv_sec);
237 tv.tv_usec = start.tv_usec - tv.tv_usec;
238 if (tv.tv_usec < 0) {
240 tv.tv_usec += 1000000;
244 i = select(fd + 1, &set, NULL, NULL, &tv);
245 } while (i == -1 && errno == EINTR);
250 i = read(fd, buf, sizeof buf);
251 } while (i != 0 && (i != -1 || errno == EINTR));
259 * \brief sanity requests
260 * Check for bogus requests coming from brain-dead Windows boxes.
262 * \param http_cmd The HTTP request to check
264 int is_bogus(StrBuf *http_cmd) {
268 url = ChrPtr(http_cmd);
269 if (IsEmptyStr(url)) return(1);
272 char *bogus_prefixes[] = {
273 "/scripts/root.exe", /**< Worms and trojans and viruses, oh my! */
276 "/_vti", /**< Broken Microsoft DAV implementation */
277 "/MSOffice" /**< Stoopid MSOffice thinks everyone is IIS */
280 max = sizeof(bogus_prefixes) / sizeof(char *);
282 for (i=0; i<max; ++i) {
283 if (!strncasecmp(url, bogus_prefixes[i], strlen(bogus_prefixes[i]))) {
288 return(0); /* probably ok */
292 const char *nix(void *vptr) {return ChrPtr( (StrBuf*)vptr);}
295 * \brief handle one request
296 * This loop gets called once for every HTTP connection made to WebCit. At
297 * this entry point we have an HTTP socket with a browser allegedly on the
298 * other end, but we have not yet bound to a WebCit session.
300 * The job of this function is to locate the correct session and bind to it,
301 * or create a session if necessary and bind to it, then run the WebCit
302 * transaction loop. Afterwards, we unbind from the session. When this
303 * function returns, the worker thread is then free to handle another
305 * \param sock the socket we will put our answer to
307 void context_loop(int *sock)
310 int desired_session = 0;
313 struct wcsession *TheSession, *sptr;
314 char httpauth_string[1024];
315 char httpauth_user[1024];
316 char httpauth_pass[1024];
318 int session_is_new = 0;
322 StrBuf *Buf, *Line, *LastLine, *HeaderName, *ReqLine, *ReqType, *HTTPVersion;
323 StrBuf *accept_language = NULL;
324 const char *pch, *pchs, *pche;
325 HashList *HTTPHeaders;
327 strcpy(httpauth_string, "");
328 strcpy(httpauth_user, DEFAULT_HTTPAUTH_USER);
329 strcpy(httpauth_pass, DEFAULT_HTTPAUTH_PASS);
332 * Find out what it is that the web browser is asking for
334 HeaderName = NewStrBuf();
337 HTTPHeaders = NewHash(1, NULL);
339 * Read in the request
344 if (ReqGetStrBuf(sock, Line, Buf) < 0) return;
346 LineLen = StrLength(Line);
357 /** Do we need to Unfold? */
358 if ((LastLine != NULL) &&
359 (isspace(*ChrPtr(Line)))) {
360 pch = pchs = ChrPtr(Line);
361 pche = pchs + StrLength(Line);
362 while (isspace(pch) && (pch < pche))
364 StrBufCutLeft(Line, pch - pchs);
365 StrBufAppendBuf(LastLine, Line, 0);
370 StrBufExtract_token(HeaderName, Line, 0, ':');
371 //// TODO: filter bad chars!
374 pch = pchs + StrLength(HeaderName) + 1;
375 pche = pchs + StrLength(Line);
376 while (isspace(*pch) && (pch < pche))
378 StrBufCutLeft(Line, pch - pchs);
380 StrBufUpCase(HeaderName);
381 Put(HTTPHeaders, SKEY(HeaderName), Line, HFreeStrBuf);
383 } while (LineLen > 0);
384 FreeStrBuf(&HeaderName);
386 //// dbg_PrintHash(HTTPHeaders, nix, NULL);
392 if (GetHash(HTTPHeaders, HKEY("ACCEPT-ENCODING"), &vLine) &&
394 buf = ChrPtr((StrBuf*)vLine);
395 if (strstr(&buf[16], "gzip")) {
401 * Browser-based sessions use cookies for session authentication
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 ", 6)) {
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 sheme 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 ((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), "/wholist_section", 16) != 0)) {
462 lprintf(5, "HTTP: %s %s %s\n", ChrPtr(ReqType), ChrPtr(ReqLine), ChrPtr(HTTPVersion));
467 /** Check for bogus requests */
468 if ((StrLength(HTTPVersion) == 0) ||
469 (StrLength(ReqType) == 0) ||
471 StrBufPlain(ReqLine, HKEY("/404 HTTP/1.1"));
472 StrBufPlain(ReqType, HKEY("GET"));
474 FreeStrBuf(&HTTPVersion);
477 * While we're at it, gracefully handle requests for the
478 * robots.txt and favicon.ico files.
480 if (!strncasecmp(ChrPtr(ReqLine), "/robots.txt", 11)) {
482 HKEY("/static/robots.txt"
483 "?force_close_session=yes HTTP/1.1"));
484 StrBufPlain(ReqType, HKEY("GET"));
486 else if (!strncasecmp(ChrPtr(ReqLine), "/favicon.ico", 12)) {
487 StrBufPlain(ReqLine, HKEY("/static/favicon.ico"));
488 StrBufPlain(ReqType, HKEY("GET"));
492 * These are the URL's which may be executed without a
493 * session cookie already set. If it's not one of these,
494 * force the session to close because cookies are
495 * probably disabled on the client browser.
497 else if ( (StrLength(ReqLine) > 1 )
498 && (strncasecmp(ChrPtr(ReqLine), "/listsub", 8))
499 && (strncasecmp(ChrPtr(ReqLine), "/freebusy", 9))
500 && (strncasecmp(ChrPtr(ReqLine), "/do_logout", 10))
501 && (strncasecmp(ChrPtr(ReqLine), "/groupdav", 9))
502 && (strncasecmp(ChrPtr(ReqLine), "/static", 7))
503 && (strncasecmp(ChrPtr(ReqLine), "/rss", 4))
504 && (strncasecmp(ChrPtr(ReqLine), "/404", 4))
505 && (got_cookie == 0)) {
507 HKEY("/static/nocookies.html"
508 "?force_close_session=yes"));
512 * See if there's an existing session open with the desired ID or user/pass
516 if (TheSession == NULL) {
517 pthread_mutex_lock(&SessionListMutex);
518 for (sptr = SessionList; sptr != NULL; sptr = sptr->next) {
520 /** If HTTP-AUTH, look for a session with matching credentials */
521 if ( (!IsEmptyStr(httpauth_user))
522 &&(!strcasecmp(sptr->httpauth_user, httpauth_user))
523 &&(!strcasecmp(sptr->httpauth_pass, httpauth_pass)) ) {
527 /** If cookie-session, look for a session with matching session ID */
528 if ( (desired_session != 0) && (sptr->wc_session == desired_session)) {
533 pthread_mutex_unlock(&SessionListMutex);
537 * Create a new session if we have to
539 if (TheSession == NULL) {
540 lprintf(3, "Creating a new session\n");
541 TheSession = (struct wcsession *)
542 malloc(sizeof(struct wcsession));
543 memset(TheSession, 0, sizeof(struct wcsession));
544 TheSession->serv_sock = (-1);
545 TheSession->chat_sock = (-1);
547 /* If we're recreating a session that expired, it's best to give it the same
548 * session number that it had before. The client browser ought to pick up
549 * the new session number and start using it, but in some rare situations it
550 * doesn't, and that's a Bad Thing because it causes lots of spurious sessions
553 if (desired_session == 0) {
554 TheSession->wc_session = GenerateSessionID();
557 TheSession->wc_session = desired_session;
560 strcpy(TheSession->httpauth_user, httpauth_user);
561 strcpy(TheSession->httpauth_pass, httpauth_pass);
562 TheSession->hash_prefs = NewHash(1,NULL); /* Get a hash table for the user preferences */
563 pthread_mutex_init(&TheSession->SessionMutex, NULL);
564 pthread_mutex_lock(&SessionListMutex);
565 TheSession->urlstrings = NULL;
566 TheSession->vars = NULL;
567 TheSession->nonce = rand();
568 TheSession->WBuf = NULL;
569 TheSession->CLineBuf = NewStrBuf();
570 TheSession->next = SessionList;
571 TheSession->is_mobile = -1;
572 SessionList = TheSession;
573 pthread_mutex_unlock(&SessionListMutex);
578 * A future improvement might be to check the session integrity
579 * at this point before continuing.
583 * Bind to the session and perform the transaction
585 pthread_mutex_lock(&TheSession->SessionMutex); /* bind */
586 pthread_setspecific(MyConKey, (void *)TheSession);
588 TheSession->urlstrings = NewHash(1,NULL);
589 TheSession->vars = NewHash(1,NULL);
590 TheSession->http_sock = *sock;
591 TheSession->lastreq = time(NULL); /* log */
592 TheSession->gzip_ok = gzip_ok;
594 if (session_is_new) {
595 httplang_to_locale(accept_language);
597 go_selected_language(); /* set locale */
599 session_loop(HTTPHeaders, ReqLine, ReqType, Buf); /* do transaction */
601 stop_selected_language(); /* unset locale */
603 DeleteHash(&TheSession->summ);
604 DeleteHash(&TheSession->urlstrings);
605 DeleteHash(&TheSession->vars);
606 FreeStrBuf(&TheSession->WBuf);
607 FreeStrBuf(&TheSession->HBuf);
610 pthread_mutex_unlock(&TheSession->SessionMutex); /* unbind */
612 /* Free the request buffer */
613 DeleteHash(&HTTPHeaders);
614 FreeStrBuf(&ReqLine);
615 FreeStrBuf(&ReqType);
618 * Free up any session-local substitution variables which
619 * were set during this transaction
625 void tmpl_nonce(StrBuf *Target, int nArgs, WCTemplateToken *Tokens, void *Context, int ContextType)
627 struct wcsession *WCC = WC;
628 StrBufAppendPrintf(Target, "%ld",
629 (WCC != NULL)? WCC->nonce:0);
636 RegisterNamespace("NONCE", 0, 0, tmpl_nonce, 0);