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 pthread_mutex_unlock(&sessions_to_kill->SessionMutex);
105 sptr = sessions_to_kill->next;
106 free(sessions_to_kill);
107 sessions_to_kill = sptr;
112 * If there are more sessions than threads, then we should spawn
113 * more threads ... up to a predefined maximum.
115 while ( (num_sessions > num_threads)
116 && (num_threads <= MAX_WORKER_THREADS) ) {
117 spawn_another_worker_thread();
119 lprintf(3, "There are %d sessions and %d threads active.\n",
120 num_sessions, num_threads);
126 * \brief Wake up occasionally and clean house
128 void housekeeping_loop(void)
131 sleeeeeeeeeep(HOUSEKEEPING);
138 * \brief Create a Session id
139 * Generate a unique WebCit session ID (which is not the same thing as the
140 * Citadel session ID).
142 * \todo FIXME ... ensure that session number is truly unique
145 int GenerateSessionID(void)
147 static int seq = (-1);
150 seq = (int) time(NULL);
158 * Collapse multiple cookies on one line
160 int req_gets(int sock, char *buf, char *hold, size_t hlen)
164 if (IsEmptyStr(hold)) {
166 a = client_getln(sock, buf, SIZ);
169 safestrncpy(buf, hold, SIZ);
173 if (!strncasecmp(buf, "Cookie: ", 8)) {
176 for (a = 0; a < len; ++a)
178 // we don't refresh len, because of we
179 // only exit from here.
180 snprintf(hold, hlen, "Cookie: %s", &buf[a + 1]);
183 while (isspace(hold[b]))
186 memmove(&hold[8], &hold[b], len - b + 1);
195 * lingering_close() a`la Apache. see
196 * http://www.apache.org/docs/misc/fin_wait_2.html for rationale
198 int lingering_close(int fd)
203 struct timeval tv, start;
205 gettimeofday(&start, NULL);
209 gettimeofday(&tv, NULL);
210 tv.tv_sec = SLEEPING - (tv.tv_sec - start.tv_sec);
211 tv.tv_usec = start.tv_usec - tv.tv_usec;
212 if (tv.tv_usec < 0) {
214 tv.tv_usec += 1000000;
218 i = select(fd + 1, &set, NULL, NULL, &tv);
219 } while (i == -1 && errno == EINTR);
224 i = read(fd, buf, sizeof buf);
225 } while (i != 0 && (i != -1 || errno == EINTR));
233 * \brief sanity requests
234 * Check for bogus requests coming from brain-dead Windows boxes.
236 * \param http_cmd The HTTP request to check
238 int is_bogus(char *http_cmd) {
242 url = strstr(http_cmd, " ");
243 if (url == NULL) return(1);
246 char *bogus_prefixes[] = {
247 "/scripts/root.exe", /**< Worms and trojans and viruses, oh my! */
250 "/_vti", /**< Broken Microsoft DAV implementation */
251 "/MSOffice" /**< Stoopid MSOffice thinks everyone is IIS */
254 max = sizeof(bogus_prefixes) / sizeof(char *);
256 for (i=0; i<max; ++i) {
257 if (!strncasecmp(url, bogus_prefixes[i], strlen(bogus_prefixes[i]))) {
262 return(0); /* probably ok */
268 * \brief handle one request
269 * This loop gets called once for every HTTP connection made to WebCit. At
270 * this entry point we have an HTTP socket with a browser allegedly on the
271 * other end, but we have not yet bound to a WebCit session.
273 * The job of this function is to locate the correct session and bind to it,
274 * or create a session if necessary and bind to it, then run the WebCit
275 * transaction loop. Afterwards, we unbind from the session. When this
276 * function returns, the worker thread is then free to handle another
278 * \param sock the socket we will put our answer to
280 void context_loop(int sock)
282 struct httprequest *req = NULL;
283 struct httprequest *last = NULL;
284 struct httprequest *hptr;
285 char buf[SIZ], hold[SIZ];
286 int desired_session = 0;
289 struct wcsession *TheSession, *sptr;
290 char httpauth_string[1024];
291 char httpauth_user[1024];
292 char httpauth_pass[1024];
293 char accept_language[256];
295 int session_is_new = 0;
297 strcpy(httpauth_string, "");
298 strcpy(httpauth_user, DEFAULT_HTTPAUTH_USER);
299 strcpy(httpauth_pass, DEFAULT_HTTPAUTH_PASS);
302 * Find out what it is that the web browser is asking for
304 memset(hold, 0, sizeof(hold));
306 if (req_gets(sock, buf, hold, SIZ) < 0) return;
311 if (!strncasecmp(buf, "Accept-encoding:", 16)) {
312 if (strstr(&buf[16], "gzip")) {
318 * Browser-based sessions use cookies for session authentication
320 if (!strncasecmp(buf, "Cookie: webcit=", 15)) {
321 cookie_to_stuff(&buf[15], &desired_session,
322 NULL, 0, NULL, 0, NULL, 0);
327 * GroupDAV-based sessions use HTTP authentication
329 if (!strncasecmp(buf, "Authorization: Basic ", 21)) {
330 CtdlDecodeBase64(httpauth_string, &buf[21], strlen(&buf[21]));
331 extract_token(httpauth_user, httpauth_string, 0, ':', sizeof httpauth_user);
332 extract_token(httpauth_pass, httpauth_string, 1, ':', sizeof httpauth_pass);
335 if (!strncasecmp(buf, "If-Modified-Since: ", 19)) {
336 if_modified_since = httpdate_to_timestamp(&buf[19]);
339 if (!strncasecmp(buf, "Accept-Language: ", 17)) {
340 safestrncpy(accept_language, &buf[17], sizeof accept_language);
344 * Read in the request
346 hptr = (struct httprequest *)
347 malloc(sizeof(struct httprequest));
355 safestrncpy(hptr->line, buf, sizeof hptr->line);
357 } while (!IsEmptyStr(buf));
360 * If the request is prefixed by "/webcit" then chop that off. This
361 * allows a front end web server to forward all /webcit requests to us
362 * while still using the same web server port for other things.
365 ptr = strstr(req->line, " /webcit "); /*< Handle "/webcit" */
367 strcpy(ptr+2, ptr+8);
370 ptr = strstr(req->line, " /webcit"); /*< Handle "/webcit/" */
372 strcpy(ptr+1, ptr+8);
375 /** Begin parsing the request. */
377 safestrncpy(buf, req->line, sizeof buf);
378 lprintf(5, "HTTP: %s\n", buf);
380 /** Check for bogus requests */
382 strcpy(req->line, "GET /404 HTTP/1.1");
383 strcpy(buf, "GET /404 HTTP/1.1");
387 * Strip out the method, leaving the URL up front...
389 remove_token(buf, 0, ' ');
390 if (buf[1]==' ') buf[1]=0;
393 * While we're at it, gracefully handle requests for the
394 * robots.txt and favicon.ico files.
396 if (!strncasecmp(buf, "/robots.txt", 11)) {
397 strcpy(req->line, "GET /static/robots.txt"
398 "?force_close_session=yes HTTP/1.1");
400 else if (!strncasecmp(buf, "/favicon.ico", 12)) {
401 strcpy(req->line, "GET /static/favicon.ico");
405 * These are the URL's which may be executed without a
406 * session cookie already set. If it's not one of these,
407 * force the session to close because cookies are
408 * probably disabled on the client browser.
410 else if ( (strcmp(buf, "/"))
411 && (strncasecmp(buf, "/listsub", 8))
412 && (strncasecmp(buf, "/freebusy", 9))
413 && (strncasecmp(buf, "/do_logout", 10))
414 && (strncasecmp(buf, "/groupdav", 9))
415 && (strncasecmp(buf, "/static", 7))
416 && (strncasecmp(buf, "/rss", 4))
417 && (strncasecmp(buf, "/404", 4))
418 && (got_cookie == 0)) {
419 strcpy(req->line, "GET /static/nocookies.html"
420 "?force_close_session=yes HTTP/1.1");
424 * See if there's an existing session open with the desired ID or user/pass
428 if (TheSession == NULL) {
429 pthread_mutex_lock(&SessionListMutex);
430 for (sptr = SessionList; sptr != NULL; sptr = sptr->next) {
432 /** If HTTP-AUTH, look for a session with matching credentials */
433 if ( (!IsEmptyStr(httpauth_user))
434 &&(!strcasecmp(sptr->httpauth_user, httpauth_user))
435 &&(!strcasecmp(sptr->httpauth_pass, httpauth_pass)) ) {
439 /** If cookie-session, look for a session with matching session ID */
440 if ( (desired_session != 0) && (sptr->wc_session == desired_session)) {
445 pthread_mutex_unlock(&SessionListMutex);
449 * Create a new session if we have to
451 if (TheSession == NULL) {
452 lprintf(3, "Creating a new session\n");
453 TheSession = (struct wcsession *)
454 malloc(sizeof(struct wcsession));
455 memset(TheSession, 0, sizeof(struct wcsession));
456 TheSession->serv_sock = (-1);
457 TheSession->chat_sock = (-1);
459 /* If we're recreating a session that expired, it's best to give it the same
460 * session number that it had before. The client browser ought to pick up
461 * the new session number and start using it, but in some rare situations it
462 * doesn't, and that's a Bad Thing because it causes lots of spurious sessions
465 if (desired_session == 0) {
466 TheSession->wc_session = GenerateSessionID();
469 TheSession->wc_session = desired_session;
472 strcpy(TheSession->httpauth_user, httpauth_user);
473 strcpy(TheSession->httpauth_pass, httpauth_pass);
474 pthread_mutex_init(&TheSession->SessionMutex, NULL);
475 pthread_mutex_lock(&SessionListMutex);
476 TheSession->nonce = rand();
477 TheSession->next = SessionList;
478 SessionList = TheSession;
479 pthread_mutex_unlock(&SessionListMutex);
484 * A future improvement might be to check the session integrity
485 * at this point before continuing.
489 * Bind to the session and perform the transaction
491 pthread_mutex_lock(&TheSession->SessionMutex); /* bind */
492 pthread_setspecific(MyConKey, (void *)TheSession);
493 TheSession->http_sock = sock;
494 TheSession->lastreq = time(NULL); /* log */
495 TheSession->gzip_ok = gzip_ok;
497 if (session_is_new) {
498 httplang_to_locale(accept_language);
500 go_selected_language(); /* set locale */
502 session_loop(req); /* do transaction */
504 stop_selected_language(); /* unset locale */
506 pthread_mutex_unlock(&TheSession->SessionMutex); /* unbind */
508 /* Free the request buffer */
509 while (req != NULL) {
516 * Free up any session-local substitution variables which
517 * were set during this transaction
519 clear_local_substs();