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));
105 pthread_mutex_unlock(&sessions_to_kill->SessionMutex);
106 sptr = sessions_to_kill->next;
107 free(sessions_to_kill);
108 sessions_to_kill = sptr;
113 * If there are more sessions than threads, then we should spawn
114 * more threads ... up to a predefined maximum.
116 while ( (num_sessions > num_threads)
117 && (num_threads <= MAX_WORKER_THREADS) ) {
118 spawn_another_worker_thread();
120 lprintf(3, "There are %d sessions and %d threads active.\n",
121 num_sessions, num_threads);
127 * \brief Wake up occasionally and clean house
129 void housekeeping_loop(void)
132 sleeeeeeeeeep(HOUSEKEEPING);
139 * \brief Create a Session id
140 * Generate a unique WebCit session ID (which is not the same thing as the
141 * Citadel session ID).
143 * \todo FIXME ... ensure that session number is truly unique
146 int GenerateSessionID(void)
148 static int seq = (-1);
151 seq = (int) time(NULL);
159 * Collapse multiple cookies on one line
161 int req_gets(int sock, char *buf, char *hold, size_t hlen)
165 if (IsEmptyStr(hold)) {
167 a = client_getln(sock, buf, SIZ);
170 safestrncpy(buf, hold, SIZ);
174 if (!strncasecmp(buf, "Cookie: ", 8)) {
177 for (a = 0; a < len; ++a)
179 // we don't refresh len, because of we
180 // only exit from here.
181 snprintf(hold, hlen, "Cookie: %s", &buf[a + 1]);
184 while (isspace(hold[b]))
187 memmove(&hold[8], &hold[b], len - b + 1);
196 * lingering_close() a`la Apache. see
197 * http://www.apache.org/docs/misc/fin_wait_2.html for rationale
199 int lingering_close(int fd)
204 struct timeval tv, start;
206 gettimeofday(&start, NULL);
210 gettimeofday(&tv, NULL);
211 tv.tv_sec = SLEEPING - (tv.tv_sec - start.tv_sec);
212 tv.tv_usec = start.tv_usec - tv.tv_usec;
213 if (tv.tv_usec < 0) {
215 tv.tv_usec += 1000000;
219 i = select(fd + 1, &set, NULL, NULL, &tv);
220 } while (i == -1 && errno == EINTR);
225 i = read(fd, buf, sizeof buf);
226 } while (i != 0 && (i != -1 || errno == EINTR));
234 * \brief sanity requests
235 * Check for bogus requests coming from brain-dead Windows boxes.
237 * \param http_cmd The HTTP request to check
239 int is_bogus(char *http_cmd) {
243 url = strstr(http_cmd, " ");
244 if (url == NULL) return(1);
247 char *bogus_prefixes[] = {
248 "/scripts/root.exe", /**< Worms and trojans and viruses, oh my! */
251 "/_vti", /**< Broken Microsoft DAV implementation */
252 "/MSOffice" /**< Stoopid MSOffice thinks everyone is IIS */
255 max = sizeof(bogus_prefixes) / sizeof(char *);
257 for (i=0; i<max; ++i) {
258 if (!strncasecmp(url, bogus_prefixes[i], strlen(bogus_prefixes[i]))) {
263 return(0); /* probably ok */
269 * \brief handle one request
270 * This loop gets called once for every HTTP connection made to WebCit. At
271 * this entry point we have an HTTP socket with a browser allegedly on the
272 * other end, but we have not yet bound to a WebCit session.
274 * The job of this function is to locate the correct session and bind to it,
275 * or create a session if necessary and bind to it, then run the WebCit
276 * transaction loop. Afterwards, we unbind from the session. When this
277 * function returns, the worker thread is then free to handle another
279 * \param sock the socket we will put our answer to
281 void context_loop(int sock)
283 struct httprequest *req = NULL;
284 struct httprequest *last = NULL;
285 struct httprequest *hptr;
286 char buf[SIZ], hold[SIZ];
287 int desired_session = 0;
290 struct wcsession *TheSession, *sptr;
291 char httpauth_string[1024];
292 char httpauth_user[1024];
293 char httpauth_pass[1024];
294 char accept_language[256];
296 int session_is_new = 0;
298 strcpy(httpauth_string, "");
299 strcpy(httpauth_user, DEFAULT_HTTPAUTH_USER);
300 strcpy(httpauth_pass, DEFAULT_HTTPAUTH_PASS);
303 * Find out what it is that the web browser is asking for
305 memset(hold, 0, sizeof(hold));
307 if (req_gets(sock, buf, hold, SIZ) < 0) return;
312 if (!strncasecmp(buf, "Accept-encoding:", 16)) {
313 if (strstr(&buf[16], "gzip")) {
319 * Browser-based sessions use cookies for session authentication
321 if (!strncasecmp(buf, "Cookie: webcit=", 15)) {
322 cookie_to_stuff(&buf[15], &desired_session,
323 NULL, 0, NULL, 0, NULL, 0);
328 * GroupDAV-based sessions use HTTP authentication
330 if (!strncasecmp(buf, "Authorization: Basic ", 21)) {
331 CtdlDecodeBase64(httpauth_string, &buf[21], strlen(&buf[21]));
332 extract_token(httpauth_user, httpauth_string, 0, ':', sizeof httpauth_user);
333 extract_token(httpauth_pass, httpauth_string, 1, ':', sizeof httpauth_pass);
336 if (!strncasecmp(buf, "If-Modified-Since: ", 19)) {
337 if_modified_since = httpdate_to_timestamp(&buf[19]);
340 if (!strncasecmp(buf, "Accept-Language: ", 17)) {
341 safestrncpy(accept_language, &buf[17], sizeof accept_language);
345 * Read in the request
347 hptr = (struct httprequest *)
348 malloc(sizeof(struct httprequest));
356 safestrncpy(hptr->line, buf, sizeof hptr->line);
358 } while (!IsEmptyStr(buf));
361 * If the request is prefixed by "/webcit" then chop that off. This
362 * allows a front end web server to forward all /webcit requests to us
363 * while still using the same web server port for other things.
366 ptr = strstr(req->line, " /webcit "); /*< Handle "/webcit" */
368 strcpy(ptr+2, ptr+8);
371 ptr = strstr(req->line, " /webcit"); /*< Handle "/webcit/" */
373 strcpy(ptr+1, ptr+8);
376 /** Begin parsing the request. */
378 safestrncpy(buf, req->line, sizeof buf);
379 lprintf(5, "HTTP: %s\n", buf);
381 /** Check for bogus requests */
383 strcpy(req->line, "GET /404 HTTP/1.1");
384 strcpy(buf, "GET /404 HTTP/1.1");
388 * Strip out the method, leaving the URL up front...
390 remove_token(buf, 0, ' ');
391 if (buf[1]==' ') buf[1]=0;
394 * While we're at it, gracefully handle requests for the
395 * robots.txt and favicon.ico files.
397 if (!strncasecmp(buf, "/robots.txt", 11)) {
398 strcpy(req->line, "GET /static/robots.txt"
399 "?force_close_session=yes HTTP/1.1");
401 else if (!strncasecmp(buf, "/favicon.ico", 12)) {
402 strcpy(req->line, "GET /static/favicon.ico");
406 * These are the URL's which may be executed without a
407 * session cookie already set. If it's not one of these,
408 * force the session to close because cookies are
409 * probably disabled on the client browser.
411 else if ( (strcmp(buf, "/"))
412 && (strncasecmp(buf, "/listsub", 8))
413 && (strncasecmp(buf, "/freebusy", 9))
414 && (strncasecmp(buf, "/do_logout", 10))
415 && (strncasecmp(buf, "/groupdav", 9))
416 && (strncasecmp(buf, "/static", 7))
417 && (strncasecmp(buf, "/rss", 4))
418 && (strncasecmp(buf, "/404", 4))
419 && (got_cookie == 0)) {
420 strcpy(req->line, "GET /static/nocookies.html"
421 "?force_close_session=yes HTTP/1.1");
425 * See if there's an existing session open with the desired ID or user/pass
429 if (TheSession == NULL) {
430 pthread_mutex_lock(&SessionListMutex);
431 for (sptr = SessionList; sptr != NULL; sptr = sptr->next) {
433 /** If HTTP-AUTH, look for a session with matching credentials */
434 if ( (!IsEmptyStr(httpauth_user))
435 &&(!strcasecmp(sptr->httpauth_user, httpauth_user))
436 &&(!strcasecmp(sptr->httpauth_pass, httpauth_pass)) ) {
440 /** If cookie-session, look for a session with matching session ID */
441 if ( (desired_session != 0) && (sptr->wc_session == desired_session)) {
446 pthread_mutex_unlock(&SessionListMutex);
450 * Create a new session if we have to
452 if (TheSession == NULL) {
453 lprintf(3, "Creating a new session\n");
454 TheSession = (struct wcsession *)
455 malloc(sizeof(struct wcsession));
456 memset(TheSession, 0, sizeof(struct wcsession));
457 TheSession->serv_sock = (-1);
458 TheSession->chat_sock = (-1);
460 /* If we're recreating a session that expired, it's best to give it the same
461 * session number that it had before. The client browser ought to pick up
462 * the new session number and start using it, but in some rare situations it
463 * doesn't, and that's a Bad Thing because it causes lots of spurious sessions
466 if (desired_session == 0) {
467 TheSession->wc_session = GenerateSessionID();
470 TheSession->wc_session = desired_session;
473 strcpy(TheSession->httpauth_user, httpauth_user);
474 strcpy(TheSession->httpauth_pass, httpauth_pass);
475 TheSession->hash_prefs = NewHash(1,NULL); /* Get a hash table for the user preferences */
476 pthread_mutex_init(&TheSession->SessionMutex, NULL);
477 pthread_mutex_lock(&SessionListMutex);
478 TheSession->urlstrings = NULL;
479 TheSession->vars = NULL;
480 TheSession->nonce = rand();
481 TheSession->next = SessionList;
482 SessionList = TheSession;
483 pthread_mutex_unlock(&SessionListMutex);
488 * A future improvement might be to check the session integrity
489 * at this point before continuing.
493 * Bind to the session and perform the transaction
495 pthread_mutex_lock(&TheSession->SessionMutex); /* bind */
496 pthread_setspecific(MyConKey, (void *)TheSession);
498 TheSession->urlstrings = NewHash(1,NULL);
499 TheSession->vars = NewHash(1,NULL);
500 TheSession->http_sock = sock;
501 TheSession->lastreq = time(NULL); /* log */
502 TheSession->gzip_ok = gzip_ok;
504 if (session_is_new) {
505 httplang_to_locale(accept_language);
507 go_selected_language(); /* set locale */
509 session_loop(req); /* do transaction */
511 stop_selected_language(); /* unset locale */
513 DeleteHash(&TheSession->urlstrings);
514 DeleteHash(&TheSession->vars);
516 pthread_mutex_unlock(&TheSession->SessionMutex); /* unbind */
518 /* Free the request buffer */
519 while (req != NULL) {
526 * Free up any session-local substitution variables which
527 * were set during this transaction