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 shutdown_sessions(void)
39 struct wcsession *sptr;
41 for (sptr = SessionList; sptr != NULL; sptr = sptr->next) {
46 void do_housekeeping(void)
48 struct wcsession *sptr, *ss;
49 struct wcsession *sessions_to_kill = NULL;
51 static int num_threads = MIN_WORKER_THREADS;
54 * Lock the session list, moving any candidates for euthanasia into
57 pthread_mutex_lock(&SessionListMutex);
59 for (sptr = SessionList; sptr != NULL; sptr = sptr->next) {
62 /** Kill idle sessions */
63 if ((time(NULL) - (sptr->lastreq)) >
64 (time_t) WEBCIT_TIMEOUT) {
68 /** Remove sessions flagged for kill */
71 /** remove session from linked list */
72 if (sptr == SessionList) {
73 SessionList = SessionList->next;
75 else for (ss=SessionList;ss!=NULL;ss=ss->next) {
76 if (ss->next == sptr) {
77 ss->next = ss->next->next;
81 sptr->next = sessions_to_kill;
82 sessions_to_kill = sptr;
85 pthread_mutex_unlock(&SessionListMutex);
88 * Now free up and destroy the culled sessions.
90 while (sessions_to_kill != NULL) {
91 lprintf(3, "Destroying session %d\n", sessions_to_kill->wc_session);
92 pthread_mutex_lock(&sessions_to_kill->SessionMutex);
93 close(sessions_to_kill->serv_sock);
94 close(sessions_to_kill->chat_sock);
95 // if (sessions_to_kill->preferences != NULL) {
96 // free(sessions_to_kill->preferences);
98 if (sessions_to_kill->cache_fold != NULL) {
99 free(sessions_to_kill->cache_fold);
101 free_attachments(sessions_to_kill);
102 free_march_list(sessions_to_kill);
103 DeleteHash(&(sessions_to_kill->hash_prefs));
104 DeleteHash(&(sessions_to_kill->IconBarSetttings));
105 FreeStrBuf(&(sessions_to_kill->UrlFragment1));
106 FreeStrBuf(&(sessions_to_kill->UrlFragment2));
107 FreeStrBuf(&(sessions_to_kill->WBuf));
108 FreeStrBuf(&(sessions_to_kill->HBuf));
110 pthread_mutex_unlock(&sessions_to_kill->SessionMutex);
111 sptr = sessions_to_kill->next;
112 free(sessions_to_kill);
113 sessions_to_kill = sptr;
118 * If there are more sessions than threads, then we should spawn
119 * more threads ... up to a predefined maximum.
121 while ( (num_sessions > num_threads)
122 && (num_threads <= MAX_WORKER_THREADS) ) {
123 spawn_another_worker_thread();
125 lprintf(3, "There are %d sessions and %d threads active.\n",
126 num_sessions, num_threads);
132 * \brief Wake up occasionally and clean house
134 void housekeeping_loop(void)
137 sleeeeeeeeeep(HOUSEKEEPING);
144 * \brief Create a Session id
145 * Generate a unique WebCit session ID (which is not the same thing as the
146 * Citadel session ID).
148 * \todo FIXME ... ensure that session number is truly unique
151 int GenerateSessionID(void)
153 static int seq = (-1);
156 seq = (int) time(NULL);
164 * Collapse multiple cookies on one line
166 int req_gets(int sock, char *buf, char *hold, size_t hlen)
170 if (IsEmptyStr(hold)) {
172 a = client_getln(sock, buf, SIZ);
175 safestrncpy(buf, hold, SIZ);
179 if (!strncasecmp(buf, "Cookie: ", 8)) {
182 for (a = 0; a < len; ++a)
184 // we don't refresh len, because of we
185 // only exit from here.
186 snprintf(hold, hlen, "Cookie: %s", &buf[a + 1]);
189 while (isspace(hold[b]))
192 memmove(&hold[8], &hold[b], len - b + 1);
201 * lingering_close() a`la Apache. see
202 * http://www.apache.org/docs/misc/fin_wait_2.html for rationale
204 int lingering_close(int fd)
209 struct timeval tv, start;
211 gettimeofday(&start, NULL);
215 gettimeofday(&tv, NULL);
216 tv.tv_sec = SLEEPING - (tv.tv_sec - start.tv_sec);
217 tv.tv_usec = start.tv_usec - tv.tv_usec;
218 if (tv.tv_usec < 0) {
220 tv.tv_usec += 1000000;
224 i = select(fd + 1, &set, NULL, NULL, &tv);
225 } while (i == -1 && errno == EINTR);
230 i = read(fd, buf, sizeof buf);
231 } while (i != 0 && (i != -1 || errno == EINTR));
239 * \brief sanity requests
240 * Check for bogus requests coming from brain-dead Windows boxes.
242 * \param http_cmd The HTTP request to check
244 int is_bogus(char *http_cmd) {
248 url = strstr(http_cmd, " ");
249 if (url == NULL) return(1);
252 char *bogus_prefixes[] = {
253 "/scripts/root.exe", /**< Worms and trojans and viruses, oh my! */
256 "/_vti", /**< Broken Microsoft DAV implementation */
257 "/MSOffice" /**< Stoopid MSOffice thinks everyone is IIS */
260 max = sizeof(bogus_prefixes) / sizeof(char *);
262 for (i=0; i<max; ++i) {
263 if (!strncasecmp(url, bogus_prefixes[i], strlen(bogus_prefixes[i]))) {
268 return(0); /* probably ok */
274 * \brief handle one request
275 * This loop gets called once for every HTTP connection made to WebCit. At
276 * this entry point we have an HTTP socket with a browser allegedly on the
277 * other end, but we have not yet bound to a WebCit session.
279 * The job of this function is to locate the correct session and bind to it,
280 * or create a session if necessary and bind to it, then run the WebCit
281 * transaction loop. Afterwards, we unbind from the session. When this
282 * function returns, the worker thread is then free to handle another
284 * \param sock the socket we will put our answer to
286 void context_loop(int sock)
288 struct httprequest *req = NULL;
289 struct httprequest *last = NULL;
290 struct httprequest *hptr;
291 char buf[SIZ], hold[SIZ];
292 int desired_session = 0;
295 struct wcsession *TheSession, *sptr;
296 char httpauth_string[1024];
297 char httpauth_user[1024];
298 char httpauth_pass[1024];
299 char accept_language[256];
301 int session_is_new = 0;
303 strcpy(httpauth_string, "");
304 strcpy(httpauth_user, DEFAULT_HTTPAUTH_USER);
305 strcpy(httpauth_pass, DEFAULT_HTTPAUTH_PASS);
308 * Find out what it is that the web browser is asking for
310 memset(hold, 0, sizeof(hold));
312 if (req_gets(sock, buf, hold, SIZ) < 0) return;
317 if (!strncasecmp(buf, "Accept-encoding:", 16)) {
318 if (strstr(&buf[16], "gzip")) {
324 * Browser-based sessions use cookies for session authentication
326 if (!strncasecmp(buf, "Cookie: webcit=", 15)) {
327 cookie_to_stuff(&buf[15], &desired_session,
328 NULL, 0, NULL, 0, NULL, 0);
333 * GroupDAV-based sessions use HTTP authentication
335 if (!strncasecmp(buf, "Authorization: Basic ", 21)) {
336 CtdlDecodeBase64(httpauth_string, &buf[21], strlen(&buf[21]));
337 extract_token(httpauth_user, httpauth_string, 0, ':', sizeof httpauth_user);
338 extract_token(httpauth_pass, httpauth_string, 1, ':', sizeof httpauth_pass);
341 if (!strncasecmp(buf, "If-Modified-Since: ", 19)) {
342 if_modified_since = httpdate_to_timestamp(&buf[19]);
345 if (!strncasecmp(buf, "Accept-Language: ", 17)) {
346 safestrncpy(accept_language, &buf[17], sizeof accept_language);
350 * Read in the request
352 hptr = (struct httprequest *)
353 malloc(sizeof(struct httprequest));
361 safestrncpy(hptr->line, buf, sizeof hptr->line);
363 } while (!IsEmptyStr(buf));
366 * If the request is prefixed by "/webcit" then chop that off. This
367 * allows a front end web server to forward all /webcit requests to us
368 * while still using the same web server port for other things.
371 ptr = strstr(req->line, " /webcit "); /*< Handle "/webcit" */
373 strcpy(ptr+2, ptr+8);
376 ptr = strstr(req->line, " /webcit"); /*< Handle "/webcit/" */
378 strcpy(ptr+1, ptr+8);
381 safestrncpy(buf, req->line, sizeof buf);
382 /** Begin parsing the request. */
384 if ((strncmp(req->line+4, "/sslg", 5) != 0) &&
385 (strncmp(req->line+4, "/wholist_section", 16) != 0)) {
387 lprintf(5, "HTTP: %s\n", buf);
392 /** Check for bogus requests */
394 strcpy(req->line, "GET /404 HTTP/1.1");
395 strcpy(buf, "GET /404 HTTP/1.1");
399 * Strip out the method, leaving the URL up front...
401 remove_token(buf, 0, ' ');
402 if (buf[1]==' ') buf[1]=0;
405 * While we're at it, gracefully handle requests for the
406 * robots.txt and favicon.ico files.
408 if (!strncasecmp(buf, "/robots.txt", 11)) {
409 strcpy(req->line, "GET /static/robots.txt"
410 "?force_close_session=yes HTTP/1.1");
412 else if (!strncasecmp(buf, "/favicon.ico", 12)) {
413 strcpy(req->line, "GET /static/favicon.ico");
417 * These are the URL's which may be executed without a
418 * session cookie already set. If it's not one of these,
419 * force the session to close because cookies are
420 * probably disabled on the client browser.
422 else if ( (strcmp(buf, "/"))
423 && (strncasecmp(buf, "/listsub", 8))
424 && (strncasecmp(buf, "/freebusy", 9))
425 && (strncasecmp(buf, "/do_logout", 10))
426 && (strncasecmp(buf, "/groupdav", 9))
427 && (strncasecmp(buf, "/static", 7))
428 && (strncasecmp(buf, "/rss", 4))
429 && (strncasecmp(buf, "/404", 4))
430 && (got_cookie == 0)) {
431 strcpy(req->line, "GET /static/nocookies.html"
432 "?force_close_session=yes HTTP/1.1");
436 * See if there's an existing session open with the desired ID or user/pass
440 if (TheSession == NULL) {
441 pthread_mutex_lock(&SessionListMutex);
442 for (sptr = SessionList; sptr != NULL; sptr = sptr->next) {
444 /** If HTTP-AUTH, look for a session with matching credentials */
445 if ( (!IsEmptyStr(httpauth_user))
446 &&(!strcasecmp(sptr->httpauth_user, httpauth_user))
447 &&(!strcasecmp(sptr->httpauth_pass, httpauth_pass)) ) {
451 /** If cookie-session, look for a session with matching session ID */
452 if ( (desired_session != 0) && (sptr->wc_session == desired_session)) {
457 pthread_mutex_unlock(&SessionListMutex);
461 * Create a new session if we have to
463 if (TheSession == NULL) {
464 lprintf(3, "Creating a new session\n");
465 TheSession = (struct wcsession *)
466 malloc(sizeof(struct wcsession));
467 memset(TheSession, 0, sizeof(struct wcsession));
468 TheSession->serv_sock = (-1);
469 TheSession->chat_sock = (-1);
471 /* If we're recreating a session that expired, it's best to give it the same
472 * session number that it had before. The client browser ought to pick up
473 * the new session number and start using it, but in some rare situations it
474 * doesn't, and that's a Bad Thing because it causes lots of spurious sessions
477 if (desired_session == 0) {
478 TheSession->wc_session = GenerateSessionID();
481 TheSession->wc_session = desired_session;
484 strcpy(TheSession->httpauth_user, httpauth_user);
485 strcpy(TheSession->httpauth_pass, httpauth_pass);
486 TheSession->hash_prefs = NewHash(1,NULL); /* Get a hash table for the user preferences */
487 pthread_mutex_init(&TheSession->SessionMutex, NULL);
488 pthread_mutex_lock(&SessionListMutex);
489 TheSession->urlstrings = NULL;
490 TheSession->vars = NULL;
491 TheSession->nonce = rand();
492 TheSession->WBuf = NULL;
493 TheSession->next = SessionList;
494 SessionList = TheSession;
495 pthread_mutex_unlock(&SessionListMutex);
500 * A future improvement might be to check the session integrity
501 * at this point before continuing.
505 * Bind to the session and perform the transaction
507 pthread_mutex_lock(&TheSession->SessionMutex); /* bind */
508 pthread_setspecific(MyConKey, (void *)TheSession);
510 TheSession->urlstrings = NewHash(1,NULL);
511 TheSession->vars = NewHash(1,NULL);
512 TheSession->http_sock = sock;
513 TheSession->lastreq = time(NULL); /* log */
514 TheSession->gzip_ok = gzip_ok;
516 if (session_is_new) {
517 httplang_to_locale(accept_language);
519 go_selected_language(); /* set locale */
521 session_loop(req); /* do transaction */
523 stop_selected_language(); /* unset locale */
525 DeleteHash(&TheSession->urlstrings);
526 DeleteHash(&TheSession->vars);
527 FreeStrBuf(&TheSession->WBuf);
528 FreeStrBuf(&TheSession->HBuf);
531 pthread_mutex_unlock(&TheSession->SessionMutex); /* unbind */
533 /* Free the request buffer */
534 while (req != NULL) {
541 * Free up any session-local substitution variables which
542 * were set during this transaction