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"
13 #include "modules_init.h"
15 /* Only one thread may manipulate SessionList at a time... */
16 pthread_mutex_t SessionListMutex;
18 wcsession *SessionList = NULL; /**< our sessions ????*/
20 pthread_key_t MyConKey; /**< TSD key for MySession() */
21 HashList *HttpReqTypes = NULL;
23 void shutdown_sessions(void)
27 for (sptr = SessionList; sptr != NULL; sptr = sptr->next) {
32 void do_housekeeping(void)
35 wcsession *sessions_to_kill = NULL;
37 static int num_threads = MIN_WORKER_THREADS;
40 * Lock the session list, moving any candidates for euthanasia into
43 pthread_mutex_lock(&SessionListMutex);
45 for (sptr = SessionList; sptr != NULL; sptr = sptr->next) {
48 /** Kill idle sessions */
49 if ((time(NULL) - (sptr->lastreq)) >
50 (time_t) WEBCIT_TIMEOUT) {
54 /** Remove sessions flagged for kill */
57 /** remove session from linked list */
58 if (sptr == SessionList) {
59 SessionList = SessionList->next;
61 else for (ss=SessionList;ss!=NULL;ss=ss->next) {
62 if (ss->next == sptr) {
63 ss->next = ss->next->next;
67 sptr->next = sessions_to_kill;
68 sessions_to_kill = sptr;
71 pthread_mutex_unlock(&SessionListMutex);
74 * Now free up and destroy the culled sessions.
76 while (sessions_to_kill != NULL) {
77 lprintf(3, "Destroying session %d\n", sessions_to_kill->wc_session);
78 pthread_mutex_lock(&sessions_to_kill->SessionMutex);
79 pthread_mutex_unlock(&sessions_to_kill->SessionMutex);
80 sptr = sessions_to_kill->next;
82 session_destroy_modules(&sessions_to_kill);
83 sessions_to_kill = sptr;
88 * If there are more sessions than threads, then we should spawn
89 * more threads ... up to a predefined maximum.
91 while ( (num_sessions > num_threads)
92 && (num_threads <= MAX_WORKER_THREADS) ) {
93 spawn_another_worker_thread();
95 lprintf(3, "There are %d sessions and %d threads active.\n",
96 num_sessions, num_threads);
102 * Wake up occasionally and clean house
104 void housekeeping_loop(void)
107 sleeeeeeeeeep(HOUSEKEEPING);
114 * Create a Session id
115 * Generate a unique WebCit session ID (which is not the same thing as the
116 * Citadel session ID).
118 int GenerateSessionID(void)
120 static int seq = (-1);
123 seq = (int) time(NULL);
131 * lingering_close() a`la Apache. see
132 * http://www.apache.org/docs/misc/fin_wait_2.html for rationale
134 int lingering_close(int fd)
139 struct timeval tv, start;
141 gettimeofday(&start, NULL);
145 gettimeofday(&tv, NULL);
146 tv.tv_sec = SLEEPING - (tv.tv_sec - start.tv_sec);
147 tv.tv_usec = start.tv_usec - tv.tv_usec;
148 if (tv.tv_usec < 0) {
150 tv.tv_usec += 1000000;
154 i = select(fd + 1, &set, NULL, NULL, &tv);
155 } while (i == -1 && errno == EINTR);
160 i = read(fd, buf, sizeof buf);
161 } while (i != 0 && (i != -1 || errno == EINTR));
169 * Look for commonly-found probes of malware such as worms, viruses, trojans, and Microsoft Office.
170 * Short-circuit these requests so we don't have to send them through the full processing loop.
172 int is_bogus(StrBuf *http_cmd) {
175 const char *bogus_prefixes[] = {
176 "/scripts/root.exe", /* Worms and trojans and viruses, oh my! */
179 "/_vti", /* Broken Microsoft DAV implementation */
180 "/MSOffice", /* Stoopid MSOffice thinks everyone is IIS */
181 "/nonexistenshit" /* Exploit found in the wild January 2009 */
184 url = ChrPtr(http_cmd);
185 if (IsEmptyStr(url)) return(1);
188 max = sizeof(bogus_prefixes) / sizeof(char *);
190 for (i=0; i<max; ++i) {
191 if (!strncasecmp(url, bogus_prefixes[i], strlen(bogus_prefixes[i]))) {
196 return(0); /* probably ok */
200 /*const char *nix(void *vptr) {return ChrPtr( (StrBuf*)vptr);}*/
205 * This loop gets called once for every HTTP connection made to WebCit. At
206 * this entry point we have an HTTP socket with a browser allegedly on the
207 * other end, but we have not yet bound to a WebCit session.
209 * The job of this function is to locate the correct session and bind to it,
210 * or create a session if necessary and bind to it, then run the WebCit
211 * transaction loop. Afterwards, we unbind from the session. When this
212 * function returns, the worker thread is then free to handle another
215 void context_loop(int *sock)
217 long eReqType = eGET;
219 const char *Pos = NULL;
221 int desired_session = 0;
224 wcsession *TheSession, *sptr;
225 char httpauth_string[1024];
226 char httpauth_user[1024];
227 char httpauth_pass[1024];
231 StrBuf *Buf, *Line, *LastLine, *HeaderName, *ReqLine;
232 const char *pch, *pchs, *pche;
233 HashList *HTTPHeaders;
235 strcpy(httpauth_string, "");
236 strcpy(httpauth_user, DEFAULT_HTTPAUTH_USER);
237 strcpy(httpauth_pass, DEFAULT_HTTPAUTH_PASS);
240 * Find out what it is that the web browser is asking for
242 HeaderName = NewStrBuf();
245 HTTPHeaders = NewHash(1, NULL);
248 * Read in the request
255 if (ClientGetLine(sock, Line, Buf, &Pos) < 0) return;
257 LineLen = StrLength(Line);
261 /* The requesttype... GET, POST... */
262 StrBufExtract_token(HeaderName, ReqLine, 0, ' ');
263 if (GetHash(HttpReqTypes, SKEY(HeaderName), &vLine) &&
266 eReqType = *(long*)vLine;
273 StrBufCutLeft(ReqLine, StrLength(HeaderName) + 1);
274 /* the HTTP Version... */
275 StrBufExtract_token(HeaderName, ReqLine, 1, ' ');
276 StrBufCutRight(ReqLine, StrLength(HeaderName) + 1);
277 if ((StrLength(HeaderName) == 0) ||
290 /* Do we need to Unfold? */
291 if ((LastLine != NULL) &&
292 (isspace(*ChrPtr(Line)))) {
293 pch = pchs = ChrPtr(Line);
294 pche = pchs + StrLength(Line);
295 while (isspace(*pch) && (pch < pche))
297 StrBufCutLeft(Line, pch - pchs);
298 StrBufAppendBuf(LastLine, Line, 0);
303 StrBufSanitizeAscii(Line, '§');
304 StrBufExtract_token(HeaderName, Line, 0, ':');
307 pch = pchs + StrLength(HeaderName) + 1;
308 pche = pchs + StrLength(Line);
309 while (isspace(*pch) && (pch < pche))
311 StrBufCutLeft(Line, pch - pchs);
313 StrBufUpCase(HeaderName);
314 Put(HTTPHeaders, SKEY(HeaderName), Line, HFreeStrBuf);
316 } while (LineLen > 0);
318 FreeStrBuf(&HeaderName);
321 StrBufPlain(ReqLine, HKEY("/404"));
324 /* dbg_PrintHash(HTTPHeaders, nix, NULL); */
331 GetHash(HTTPHeaders, HKEY("ACCEPT-ENCODING"), &vLine) &&
333 buf = ChrPtr((StrBuf*)vLine);
334 if (strstr(&buf[16], "gzip")) {
340 * Browser-based sessions use cookies for session authentication
343 GetHash(HTTPHeaders, HKEY("COOKIE"), &vLine) &&
345 cookie_to_stuff(vLine, &desired_session,
351 * GroupDAV-based sessions use HTTP authentication
354 GetHash(HTTPHeaders, HKEY("AUTHORIZATION"), &vLine) &&
356 Line = (StrBuf*)vLine;
357 if (strncasecmp(ChrPtr(Line), "Basic", 5) == 0) {
358 StrBufCutLeft(Line, 6);
359 CtdlDecodeBase64(httpauth_string, ChrPtr(Line), StrLength(Line));
360 extract_token(httpauth_user, httpauth_string, 0, ':', sizeof httpauth_user);
361 extract_token(httpauth_pass, httpauth_string, 1, ':', sizeof httpauth_pass);
364 lprintf(1, "Authentication scheme not supported! [%s]\n", ChrPtr(Line));
368 GetHash(HTTPHeaders, HKEY("IF-MODIFIED-SINCE"), &vLine) &&
370 if_modified_since = httpdate_to_timestamp((StrBuf*)vLine);
377 * If the request is prefixed by "/webcit" then chop that off. This
378 * allows a front end web server to forward all /webcit requests to us
379 * while still using the same web server port for other things.
382 (StrLength(ReqLine) >= 8) &&
383 (strstr(ChrPtr(ReqLine), "/webcit/")) ) {
384 StrBufCutLeft(ReqLine, 7);
387 /* Begin parsing the request. */
389 if ((strncmp(ChrPtr(ReqLine), "/sslg", 5) != 0) &&
390 (strncmp(ChrPtr(ReqLine), "/static/", 8) != 0) &&
391 (strncmp(ChrPtr(ReqLine), "/tiny_mce/", 10) != 0) &&
392 (strncmp(ChrPtr(ReqLine), "/wholist_section", 16) != 0) &&
393 (strstr(ChrPtr(ReqLine), "wholist_section") == NULL)) {
395 lprintf(5, "HTTP: %s %s\n", ReqStrs[eReqType], ChrPtr(ReqLine));
402 * While we're at it, gracefully handle requests for the
403 * robots.txt and favicon.ico files.
405 if ((StrLength(ReqLine) >= 11) &&
406 !strncasecmp(ChrPtr(ReqLine), "/robots.txt", 11)) {
408 HKEY("/static/robots.txt"
409 "?force_close_session=yes HTTP/1.1"));
412 else if ((StrLength(ReqLine) >= 11) &&
413 !strncasecmp(ChrPtr(ReqLine), "/favicon.ico", 12)) {
414 StrBufPlain(ReqLine, HKEY("/static/favicon.ico"));
419 * These are the URL's which may be executed without a
420 * session cookie already set. If it's not one of these,
421 * force the session to close because cookies are
422 * probably disabled on the client browser.
424 else if ( (StrLength(ReqLine) > 1 )
425 && (strncasecmp(ChrPtr(ReqLine), "/listsub", 8))
426 && (strncasecmp(ChrPtr(ReqLine), "/freebusy", 9))
427 && (strncasecmp(ChrPtr(ReqLine), "/do_logout", 10))
428 && (strncasecmp(ChrPtr(ReqLine), "/groupdav", 9))
429 && (strncasecmp(ChrPtr(ReqLine), "/static", 7))
430 && (strncasecmp(ChrPtr(ReqLine), "/rss", 4))
431 && (strncasecmp(ChrPtr(ReqLine), "/404", 4))
432 && (got_cookie == 0)) {
434 HKEY("/static/nocookies.html"
435 "?force_close_session=yes"));
439 * See if there's an existing session open with the desired ID or user/pass
443 if (TheSession == NULL) {
444 pthread_mutex_lock(&SessionListMutex);
445 for (sptr = SessionList;
446 ((sptr != NULL) && (TheSession == NULL));
449 /** If HTTP-AUTH, look for a session with matching credentials */
450 if ( (!IsEmptyStr(httpauth_user))
451 &&(!strcasecmp(ChrPtr(sptr->httpauth_user), httpauth_user))
452 &&(!strcasecmp(ChrPtr(sptr->httpauth_pass), httpauth_pass)) ) {
456 /** If cookie-session, look for a session with matching session ID */
457 if ( (desired_session != 0) && (sptr->wc_session == desired_session)) {
462 pthread_mutex_unlock(&SessionListMutex);
466 * Create a new session if we have to
468 if (TheSession == NULL) {
469 lprintf(3, "Creating a new session\n");
470 TheSession = (wcsession *)
471 malloc(sizeof(wcsession));
472 memset(TheSession, 0, sizeof(wcsession));
473 TheSession->headers = HTTPHeaders;
474 TheSession->serv_sock = (-1);
475 TheSession->chat_sock = (-1);
477 /* If we're recreating a session that expired, it's best to give it the same
478 * session number that it had before. The client browser ought to pick up
479 * the new session number and start using it, but in some rare situations it
480 * doesn't, and that's a Bad Thing because it causes lots of spurious sessions
483 if (desired_session == 0) {
484 TheSession->wc_session = GenerateSessionID();
487 TheSession->wc_session = desired_session;
490 TheSession->httpauth_user = NewStrBufPlain(httpauth_user, -1);
491 TheSession->httpauth_pass = NewStrBufPlain(httpauth_user, -1);
493 pthread_setspecific(MyConKey, (void *)TheSession);
494 session_new_modules(TheSession);
496 pthread_mutex_init(&TheSession->SessionMutex, NULL);
497 pthread_mutex_lock(&SessionListMutex);
498 TheSession->nonce = rand();
499 TheSession->next = SessionList;
500 TheSession->is_mobile = -1;
501 SessionList = TheSession;
502 pthread_mutex_unlock(&SessionListMutex);
506 * A future improvement might be to check the session integrity
507 * at this point before continuing.
511 * Bind to the session and perform the transaction
513 pthread_mutex_lock(&TheSession->SessionMutex); /* bind */
514 pthread_setspecific(MyConKey, (void *)TheSession);
516 TheSession->eReqType = eReqType;
517 TheSession->headers = HTTPHeaders;
518 TheSession->lastreq = time(NULL); /* log */
519 TheSession->http_sock = *sock;
520 TheSession->gzip_ok = gzip_ok;
522 session_attach_modules(TheSession);
523 session_loop(ReqLine, Buf, &Pos); /* do transaction */
524 session_detach_modules(TheSession);
526 TheSession->headers = NULL;
527 pthread_mutex_unlock(&TheSession->SessionMutex); /* unbind */
529 /* Free the request buffer */
530 DeleteHash(&HTTPHeaders);
531 FreeStrBuf(&ReqLine);
535 void tmplput_nonce(StrBuf *Target, WCTemplputParams *TP)
538 StrBufAppendPrintf(Target, "%ld",
539 (WCC != NULL)? WCC->nonce:0);
542 void tmplput_current_user(StrBuf *Target, WCTemplputParams *TP)
544 StrBufAppendTemplate(Target, TP, WC->wc_fullname, 0);
547 void tmplput_current_room(StrBuf *Target, WCTemplputParams *TP)
549 StrBufAppendTemplate(Target, TP, WC->wc_roomname, 0);
552 const char *ReqStrs[eNONE] = {
565 ServerStartModule_CONTEXT
569 HttpReqTypes = NewHash(1, NULL);
572 v = malloc(sizeof(long));
574 Put(HttpReqTypes, HKEY("GET"), v, NULL);
576 v = malloc(sizeof(long));
578 Put(HttpReqTypes, HKEY("POST"), v, NULL);
580 v = malloc(sizeof(long));
582 Put(HttpReqTypes, HKEY("OPTIONS"), v, NULL);
584 v = malloc(sizeof(long));
586 Put(HttpReqTypes, HKEY("PROPFIND"), v, NULL);
588 v = malloc(sizeof(long));
590 Put(HttpReqTypes, HKEY("PUT"), v, NULL);
592 v = malloc(sizeof(long));
594 Put(HttpReqTypes, HKEY("DELETE"), v, NULL);
596 v = malloc(sizeof(long));
598 Put(HttpReqTypes, HKEY("HEAD"), v, NULL);
600 v = malloc(sizeof(long));
602 Put(HttpReqTypes, HKEY("MOVE"), v, NULL);
604 v = malloc(sizeof(long));
606 Put(HttpReqTypes, HKEY("COPY"), v, NULL);
610 ServerShutdownModule_CONTEXT
613 DeleteHash(&HttpReqTypes);
621 RegisterNamespace("CURRENT_USER", 0, 1, tmplput_current_user, CTX_NONE);
622 RegisterNamespace("CURRENT_ROOM", 0, 1, tmplput_current_room, CTX_NONE);
623 RegisterNamespace("NONCE", 0, 0, tmplput_nonce, 0);