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 clear_substs(sessions_to_kill);
104 DeleteHash(&(sessions_to_kill->hash_prefs));
106 pthread_mutex_unlock(&sessions_to_kill->SessionMutex);
107 sptr = sessions_to_kill->next;
108 free(sessions_to_kill);
109 sessions_to_kill = sptr;
114 * If there are more sessions than threads, then we should spawn
115 * more threads ... up to a predefined maximum.
117 while ( (num_sessions > num_threads)
118 && (num_threads <= MAX_WORKER_THREADS) ) {
119 spawn_another_worker_thread();
121 lprintf(3, "There are %d sessions and %d threads active.\n",
122 num_sessions, num_threads);
128 * \brief Wake up occasionally and clean house
130 void housekeeping_loop(void)
133 sleeeeeeeeeep(HOUSEKEEPING);
140 * \brief Create a Session id
141 * Generate a unique WebCit session ID (which is not the same thing as the
142 * Citadel session ID).
144 * \todo FIXME ... ensure that session number is truly unique
147 int GenerateSessionID(void)
149 static int seq = (-1);
152 seq = (int) time(NULL);
160 * Collapse multiple cookies on one line
162 int req_gets(int sock, char *buf, char *hold, size_t hlen)
166 if (IsEmptyStr(hold)) {
168 a = client_getln(sock, buf, SIZ);
171 safestrncpy(buf, hold, SIZ);
175 if (!strncasecmp(buf, "Cookie: ", 8)) {
178 for (a = 0; a < len; ++a)
180 // we don't refresh len, because of we
181 // only exit from here.
182 snprintf(hold, hlen, "Cookie: %s", &buf[a + 1]);
185 while (isspace(hold[b]))
188 memmove(&hold[8], &hold[b], len - b + 1);
197 * lingering_close() a`la Apache. see
198 * http://www.apache.org/docs/misc/fin_wait_2.html for rationale
200 int lingering_close(int fd)
205 struct timeval tv, start;
207 gettimeofday(&start, NULL);
211 gettimeofday(&tv, NULL);
212 tv.tv_sec = SLEEPING - (tv.tv_sec - start.tv_sec);
213 tv.tv_usec = start.tv_usec - tv.tv_usec;
214 if (tv.tv_usec < 0) {
216 tv.tv_usec += 1000000;
220 i = select(fd + 1, &set, NULL, NULL, &tv);
221 } while (i == -1 && errno == EINTR);
226 i = read(fd, buf, sizeof buf);
227 } while (i != 0 && (i != -1 || errno == EINTR));
235 * \brief sanity requests
236 * Check for bogus requests coming from brain-dead Windows boxes.
238 * \param http_cmd The HTTP request to check
240 int is_bogus(char *http_cmd) {
244 url = strstr(http_cmd, " ");
245 if (url == NULL) return(1);
248 char *bogus_prefixes[] = {
249 "/scripts/root.exe", /**< Worms and trojans and viruses, oh my! */
252 "/_vti", /**< Broken Microsoft DAV implementation */
253 "/MSOffice" /**< Stoopid MSOffice thinks everyone is IIS */
256 max = sizeof(bogus_prefixes) / sizeof(char *);
258 for (i=0; i<max; ++i) {
259 if (!strncasecmp(url, bogus_prefixes[i], strlen(bogus_prefixes[i]))) {
264 return(0); /* probably ok */
270 * \brief handle one request
271 * This loop gets called once for every HTTP connection made to WebCit. At
272 * this entry point we have an HTTP socket with a browser allegedly on the
273 * other end, but we have not yet bound to a WebCit session.
275 * The job of this function is to locate the correct session and bind to it,
276 * or create a session if necessary and bind to it, then run the WebCit
277 * transaction loop. Afterwards, we unbind from the session. When this
278 * function returns, the worker thread is then free to handle another
280 * \param sock the socket we will put our answer to
282 void context_loop(int sock)
284 struct httprequest *req = NULL;
285 struct httprequest *last = NULL;
286 struct httprequest *hptr;
287 char buf[SIZ], hold[SIZ];
288 int desired_session = 0;
291 struct wcsession *TheSession, *sptr;
292 char httpauth_string[1024];
293 char httpauth_user[1024];
294 char httpauth_pass[1024];
295 char accept_language[256];
297 int session_is_new = 0;
299 strcpy(httpauth_string, "");
300 strcpy(httpauth_user, DEFAULT_HTTPAUTH_USER);
301 strcpy(httpauth_pass, DEFAULT_HTTPAUTH_PASS);
304 * Find out what it is that the web browser is asking for
306 memset(hold, 0, sizeof(hold));
308 if (req_gets(sock, buf, hold, SIZ) < 0) return;
313 if (!strncasecmp(buf, "Accept-encoding:", 16)) {
314 if (strstr(&buf[16], "gzip")) {
320 * Browser-based sessions use cookies for session authentication
322 if (!strncasecmp(buf, "Cookie: webcit=", 15)) {
323 cookie_to_stuff(&buf[15], &desired_session,
324 NULL, 0, NULL, 0, NULL, 0);
329 * GroupDAV-based sessions use HTTP authentication
331 if (!strncasecmp(buf, "Authorization: Basic ", 21)) {
332 CtdlDecodeBase64(httpauth_string, &buf[21], strlen(&buf[21]));
333 extract_token(httpauth_user, httpauth_string, 0, ':', sizeof httpauth_user);
334 extract_token(httpauth_pass, httpauth_string, 1, ':', sizeof httpauth_pass);
337 if (!strncasecmp(buf, "If-Modified-Since: ", 19)) {
338 if_modified_since = httpdate_to_timestamp(&buf[19]);
341 if (!strncasecmp(buf, "Accept-Language: ", 17)) {
342 safestrncpy(accept_language, &buf[17], sizeof accept_language);
346 * Read in the request
348 hptr = (struct httprequest *)
349 malloc(sizeof(struct httprequest));
357 safestrncpy(hptr->line, buf, sizeof hptr->line);
359 } while (!IsEmptyStr(buf));
362 * If the request is prefixed by "/webcit" then chop that off. This
363 * allows a front end web server to forward all /webcit requests to us
364 * while still using the same web server port for other things.
367 ptr = strstr(req->line, " /webcit "); /*< Handle "/webcit" */
369 strcpy(ptr+2, ptr+8);
372 ptr = strstr(req->line, " /webcit"); /*< Handle "/webcit/" */
374 strcpy(ptr+1, ptr+8);
377 /** Begin parsing the request. */
379 safestrncpy(buf, req->line, sizeof buf);
380 lprintf(5, "HTTP: %s\n", buf);
382 /** Check for bogus requests */
384 strcpy(req->line, "GET /404 HTTP/1.1");
385 strcpy(buf, "GET /404 HTTP/1.1");
389 * Strip out the method, leaving the URL up front...
391 remove_token(buf, 0, ' ');
392 if (buf[1]==' ') buf[1]=0;
395 * While we're at it, gracefully handle requests for the
396 * robots.txt and favicon.ico files.
398 if (!strncasecmp(buf, "/robots.txt", 11)) {
399 strcpy(req->line, "GET /static/robots.txt"
400 "?force_close_session=yes HTTP/1.1");
402 else if (!strncasecmp(buf, "/favicon.ico", 12)) {
403 strcpy(req->line, "GET /static/favicon.ico");
407 * These are the URL's which may be executed without a
408 * session cookie already set. If it's not one of these,
409 * force the session to close because cookies are
410 * probably disabled on the client browser.
412 else if ( (strcmp(buf, "/"))
413 && (strncasecmp(buf, "/listsub", 8))
414 && (strncasecmp(buf, "/freebusy", 9))
415 && (strncasecmp(buf, "/do_logout", 10))
416 && (strncasecmp(buf, "/groupdav", 9))
417 && (strncasecmp(buf, "/static", 7))
418 && (strncasecmp(buf, "/rss", 4))
419 && (strncasecmp(buf, "/404", 4))
420 && (got_cookie == 0)) {
421 strcpy(req->line, "GET /static/nocookies.html"
422 "?force_close_session=yes HTTP/1.1");
426 * See if there's an existing session open with the desired ID or user/pass
430 if (TheSession == NULL) {
431 pthread_mutex_lock(&SessionListMutex);
432 for (sptr = SessionList; sptr != NULL; sptr = sptr->next) {
434 /** If HTTP-AUTH, look for a session with matching credentials */
435 if ( (!IsEmptyStr(httpauth_user))
436 &&(!strcasecmp(sptr->httpauth_user, httpauth_user))
437 &&(!strcasecmp(sptr->httpauth_pass, httpauth_pass)) ) {
441 /** If cookie-session, look for a session with matching session ID */
442 if ( (desired_session != 0) && (sptr->wc_session == desired_session)) {
447 pthread_mutex_unlock(&SessionListMutex);
451 * Create a new session if we have to
453 if (TheSession == NULL) {
454 lprintf(3, "Creating a new session\n");
455 TheSession = (struct wcsession *)
456 malloc(sizeof(struct wcsession));
457 memset(TheSession, 0, sizeof(struct wcsession));
458 TheSession->serv_sock = (-1);
459 TheSession->chat_sock = (-1);
461 /* If we're recreating a session that expired, it's best to give it the same
462 * session number that it had before. The client browser ought to pick up
463 * the new session number and start using it, but in some rare situations it
464 * doesn't, and that's a Bad Thing because it causes lots of spurious sessions
467 if (desired_session == 0) {
468 TheSession->wc_session = GenerateSessionID();
471 TheSession->wc_session = desired_session;
474 strcpy(TheSession->httpauth_user, httpauth_user);
475 strcpy(TheSession->httpauth_pass, httpauth_pass);
476 TheSession->hash_prefs = NewHash(); /* Get a hash table for the user preferences */
477 pthread_mutex_init(&TheSession->SessionMutex, NULL);
478 pthread_mutex_lock(&SessionListMutex);
479 TheSession->nonce = rand();
480 TheSession->next = SessionList;
481 SessionList = TheSession;
482 pthread_mutex_unlock(&SessionListMutex);
487 * A future improvement might be to check the session integrity
488 * at this point before continuing.
492 * Bind to the session and perform the transaction
494 pthread_mutex_lock(&TheSession->SessionMutex); /* bind */
495 pthread_setspecific(MyConKey, (void *)TheSession);
496 TheSession->http_sock = sock;
497 TheSession->lastreq = time(NULL); /* log */
498 TheSession->gzip_ok = gzip_ok;
500 if (session_is_new) {
501 httplang_to_locale(accept_language);
503 go_selected_language(); /* set locale */
505 session_loop(req); /* do transaction */
507 stop_selected_language(); /* unset locale */
509 pthread_mutex_unlock(&TheSession->SessionMutex); /* unbind */
511 /* Free the request buffer */
512 while (req != NULL) {
519 * Free up any session-local substitution variables which
520 * were set during this transaction
522 clear_local_substs();