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));
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)) {
180 a = client_getln(sock, buf, SIZ);
183 safestrncpy(buf, hold, SIZ);
187 if (!strncasecmp(buf, "Cookie: ", 8)) {
190 for (a = 0; a < len; ++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);
209 * lingering_close() a`la Apache. see
210 * http://www.apache.org/docs/misc/fin_wait_2.html for rationale
212 int lingering_close(int fd)
217 struct timeval tv, start;
219 gettimeofday(&start, NULL);
223 gettimeofday(&tv, NULL);
224 tv.tv_sec = SLEEPING - (tv.tv_sec - start.tv_sec);
225 tv.tv_usec = start.tv_usec - tv.tv_usec;
226 if (tv.tv_usec < 0) {
228 tv.tv_usec += 1000000;
232 i = select(fd + 1, &set, NULL, NULL, &tv);
233 } while (i == -1 && errno == EINTR);
238 i = read(fd, buf, sizeof buf);
239 } while (i != 0 && (i != -1 || errno == EINTR));
247 * \brief sanity requests
248 * Check for bogus requests coming from brain-dead Windows boxes.
250 * \param http_cmd The HTTP request to check
252 int is_bogus(char *http_cmd) {
256 url = strstr(http_cmd, " ");
257 if (url == NULL) return(1);
260 char *bogus_prefixes[] = {
261 "/scripts/root.exe", /**< Worms and trojans and viruses, oh my! */
264 "/_vti", /**< Broken Microsoft DAV implementation */
265 "/MSOffice" /**< Stoopid MSOffice thinks everyone is IIS */
268 max = sizeof(bogus_prefixes) / sizeof(char *);
270 for (i=0; i<max; ++i) {
271 if (!strncasecmp(url, bogus_prefixes[i], strlen(bogus_prefixes[i]))) {
276 return(0); /* probably ok */
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)
296 struct httprequest *req = NULL;
297 struct httprequest *last = NULL;
298 struct httprequest *hptr;
299 char buf[SIZ], hold[SIZ];
300 int desired_session = 0;
303 struct wcsession *TheSession, *sptr;
304 char httpauth_string[1024];
305 char httpauth_user[1024];
306 char httpauth_pass[1024];
307 char accept_language[256];
309 int session_is_new = 0;
311 strcpy(httpauth_string, "");
312 strcpy(httpauth_user, DEFAULT_HTTPAUTH_USER);
313 strcpy(httpauth_pass, DEFAULT_HTTPAUTH_PASS);
316 * Find out what it is that the web browser is asking for
318 memset(hold, 0, sizeof(hold));
320 if (req_gets(sock, buf, hold, SIZ) < 0) return;
325 if (!strncasecmp(buf, "Accept-encoding:", 16)) {
326 if (strstr(&buf[16], "gzip")) {
332 * Browser-based sessions use cookies for session authentication
334 if (!strncasecmp(buf, "Cookie: webcit=", 15)) {
335 cookie_to_stuff(&buf[15], &desired_session,
336 NULL, 0, NULL, 0, NULL, 0);
341 * GroupDAV-based sessions use HTTP authentication
343 if (!strncasecmp(buf, "Authorization: Basic ", 21)) {
344 CtdlDecodeBase64(httpauth_string, &buf[21], strlen(&buf[21]));
345 extract_token(httpauth_user, httpauth_string, 0, ':', sizeof httpauth_user);
346 extract_token(httpauth_pass, httpauth_string, 1, ':', sizeof httpauth_pass);
349 if (!strncasecmp(buf, "If-Modified-Since: ", 19)) {
350 if_modified_since = httpdate_to_timestamp(&buf[19]);
353 if (!strncasecmp(buf, "Accept-Language: ", 17)) {
354 safestrncpy(accept_language, &buf[17], sizeof accept_language);
358 * Read in the request
360 hptr = (struct httprequest *)
361 malloc(sizeof(struct httprequest));
369 safestrncpy(hptr->line, buf, sizeof hptr->line);
371 } while (!IsEmptyStr(buf));
374 * If the request is prefixed by "/webcit" then chop that off. This
375 * allows a front end web server to forward all /webcit requests to us
376 * while still using the same web server port for other things.
379 ptr = strstr(req->line, " /webcit "); /*< Handle "/webcit" */
381 strcpy(ptr+2, ptr+8);
384 ptr = strstr(req->line, " /webcit"); /*< Handle "/webcit/" */
386 strcpy(ptr+1, ptr+8);
389 safestrncpy(buf, req->line, sizeof buf);
390 /** Begin parsing the request. */
392 if ((strncmp(req->line+4, "/sslg", 5) != 0) &&
393 (strncmp(req->line+4, "/static/", 8) != 0) &&
394 (strncmp(req->line+4, "/wholist_section", 16) != 0)) {
396 lprintf(5, "HTTP: %s\n", buf);
401 /** Check for bogus requests */
403 strcpy(req->line, "GET /404 HTTP/1.1");
404 strcpy(buf, "GET /404 HTTP/1.1");
408 * Strip out the method, leaving the URL up front...
410 remove_token(buf, 0, ' ');
411 if (buf[1]==' ') buf[1]=0;
414 * While we're at it, gracefully handle requests for the
415 * robots.txt and favicon.ico files.
417 if (!strncasecmp(buf, "/robots.txt", 11)) {
418 strcpy(req->line, "GET /static/robots.txt"
419 "?force_close_session=yes HTTP/1.1");
421 else if (!strncasecmp(buf, "/favicon.ico", 12)) {
422 strcpy(req->line, "GET /static/favicon.ico");
426 * These are the URL's which may be executed without a
427 * session cookie already set. If it's not one of these,
428 * force the session to close because cookies are
429 * probably disabled on the client browser.
431 else if ( (strcmp(buf, "/"))
432 && (strncasecmp(buf, "/listsub", 8))
433 && (strncasecmp(buf, "/freebusy", 9))
434 && (strncasecmp(buf, "/do_logout", 10))
435 && (strncasecmp(buf, "/groupdav", 9))
436 && (strncasecmp(buf, "/static", 7))
437 && (strncasecmp(buf, "/rss", 4))
438 && (strncasecmp(buf, "/404", 4))
439 && (got_cookie == 0)) {
440 strcpy(req->line, "GET /static/nocookies.html"
441 "?force_close_session=yes HTTP/1.1");
445 * See if there's an existing session open with the desired ID or user/pass
449 if (TheSession == NULL) {
450 pthread_mutex_lock(&SessionListMutex);
451 for (sptr = SessionList; sptr != NULL; sptr = sptr->next) {
453 /** If HTTP-AUTH, look for a session with matching credentials */
454 if ( (!IsEmptyStr(httpauth_user))
455 &&(!strcasecmp(sptr->httpauth_user, httpauth_user))
456 &&(!strcasecmp(sptr->httpauth_pass, httpauth_pass)) ) {
460 /** If cookie-session, look for a session with matching session ID */
461 if ( (desired_session != 0) && (sptr->wc_session == desired_session)) {
466 pthread_mutex_unlock(&SessionListMutex);
470 * Create a new session if we have to
472 if (TheSession == NULL) {
473 lprintf(3, "Creating a new session\n");
474 TheSession = (struct wcsession *)
475 malloc(sizeof(struct wcsession));
476 memset(TheSession, 0, sizeof(struct wcsession));
477 TheSession->serv_sock = (-1);
478 TheSession->chat_sock = (-1);
480 /* If we're recreating a session that expired, it's best to give it the same
481 * session number that it had before. The client browser ought to pick up
482 * the new session number and start using it, but in some rare situations it
483 * doesn't, and that's a Bad Thing because it causes lots of spurious sessions
486 if (desired_session == 0) {
487 TheSession->wc_session = GenerateSessionID();
490 TheSession->wc_session = desired_session;
493 strcpy(TheSession->httpauth_user, httpauth_user);
494 strcpy(TheSession->httpauth_pass, httpauth_pass);
495 TheSession->hash_prefs = NewHash(1,NULL); /* Get a hash table for the user preferences */
496 pthread_mutex_init(&TheSession->SessionMutex, NULL);
497 pthread_mutex_lock(&SessionListMutex);
498 TheSession->urlstrings = NULL;
499 TheSession->vars = NULL;
500 TheSession->nonce = rand();
501 TheSession->WBuf = NULL;
502 TheSession->next = SessionList;
503 SessionList = TheSession;
504 pthread_mutex_unlock(&SessionListMutex);
509 * A future improvement might be to check the session integrity
510 * at this point before continuing.
514 * Bind to the session and perform the transaction
516 pthread_mutex_lock(&TheSession->SessionMutex); /* bind */
517 pthread_setspecific(MyConKey, (void *)TheSession);
519 TheSession->urlstrings = NewHash(1,NULL);
520 TheSession->vars = NewHash(1,NULL);
521 TheSession->http_sock = *sock;
522 TheSession->lastreq = time(NULL); /* log */
523 TheSession->gzip_ok = gzip_ok;
525 if (session_is_new) {
526 httplang_to_locale(accept_language);
528 go_selected_language(); /* set locale */
530 session_loop(req); /* do transaction */
532 stop_selected_language(); /* unset locale */
534 DeleteHash(&TheSession->urlstrings);
535 DeleteHash(&TheSession->vars);
536 FreeStrBuf(&TheSession->WBuf);
537 FreeStrBuf(&TheSession->HBuf);
540 pthread_mutex_unlock(&TheSession->SessionMutex); /* unbind */
542 /* Free the request buffer */
543 while (req != NULL) {
550 * Free up any session-local substitution variables which
551 * were set during this transaction
557 void tmpl_nonce(StrBuf *Target, int nArgs, WCTemplateToken *Tokens, void *Context)
559 struct wcsession *WCC = WC;
560 StrBufAppendPrintf(Target, "%ld",
561 (WCC != NULL)? WCC->nonce:0);
568 RegisterNamespace("NONCE", 0, 0, tmpl_nonce);