5 * \defgroup WebServerII some of the webserver stuff.
6 * This is the other half of the webserver. It handles the task of hooking
7 * up HTTP requests with the sessions they belong to, using HTTP cookies to
8 * keep track of things. If the HTTP request doesn't belong to any currently
9 * active session, a new session is started.
10 * \ingroup WebcitHttpServer
15 #include "webserver.h"
17 /** Only one thread may manipulate SessionList at a time... */
18 pthread_mutex_t SessionListMutex;
20 struct wcsession *SessionList = NULL; /**< our sessions ????*/
22 pthread_key_t MyConKey; /**< TSD key for MySession() */
26 * \brief free the memory used for viewing atachments
27 * \param sess the session object to destroy
29 void free_attachments(struct wcsession *sess) {
30 struct wc_attachment *att;
32 while (sess->first_attachment != NULL) {
33 att = sess->first_attachment;
34 sess->first_attachment = sess->first_attachment->next;
41 void shutdown_sessions(void)
43 struct wcsession *sptr;
45 for (sptr = SessionList; sptr != NULL; sptr = sptr->next) {
52 void do_housekeeping(void)
54 struct wcsession *sptr, *ss;
55 struct wcsession *sessions_to_kill = NULL;
57 static int num_threads = MIN_WORKER_THREADS;
60 * Lock the session list, moving any candidates for euthanasia into
63 pthread_mutex_lock(&SessionListMutex);
65 for (sptr = SessionList; sptr != NULL; sptr = sptr->next) {
68 /** Kill idle sessions */
69 if ((time(NULL) - (sptr->lastreq)) >
70 (time_t) WEBCIT_TIMEOUT) {
74 /** Remove sessions flagged for kill */
77 /** remove session from linked list */
78 if (sptr == SessionList) {
79 SessionList = SessionList->next;
81 else for (ss=SessionList;ss!=NULL;ss=ss->next) {
82 if (ss->next == sptr) {
83 ss->next = ss->next->next;
87 sptr->next = sessions_to_kill;
88 sessions_to_kill = sptr;
91 pthread_mutex_unlock(&SessionListMutex);
94 * Now free up and destroy the culled sessions.
96 while (sessions_to_kill != NULL) {
97 lprintf(3, "Destroying session %d\n", sessions_to_kill->wc_session);
98 pthread_mutex_lock(&sessions_to_kill->SessionMutex);
99 close(sessions_to_kill->serv_sock);
100 close(sessions_to_kill->chat_sock);
101 if (sessions_to_kill->preferences != NULL) {
102 free(sessions_to_kill->preferences);
104 if (sessions_to_kill->cache_fold != NULL) {
105 free(sessions_to_kill->cache_fold);
107 free_attachments(sessions_to_kill);
108 free_march_list(sessions_to_kill);
109 pthread_mutex_unlock(&sessions_to_kill->SessionMutex);
110 sptr = sessions_to_kill->next;
111 free(sessions_to_kill);
112 sessions_to_kill = sptr;
117 * If there are more sessions than threads, then we should spawn
118 * more threads ... up to a predefined maximum.
120 while ( (num_sessions > num_threads)
121 && (num_threads <= MAX_WORKER_THREADS) ) {
122 spawn_another_worker_thread();
124 lprintf(3, "There are %d sessions and %d threads active.\n",
125 num_sessions, num_threads);
131 * \brief Wake up occasionally and clean house
133 void housekeeping_loop(void)
136 sleeeeeeeeeep(HOUSEKEEPING);
143 * \brief Create a Session id
144 * Generate a unique WebCit session ID (which is not the same thing as the
145 * Citadel session ID).
147 * \todo FIXME ... ensure that session number is truly unique
150 int GenerateSessionID(void)
152 static int seq = (-1);
155 seq = (int) time(NULL);
163 * \brief Collapse multiple cookies on one line
164 * \param sock a socket?
165 * \param buf some bunch of chars?
166 * \param hold hold what?
167 * TODO: get this comment right
169 int req_gets(int sock, char *buf, char *hold)
173 if (IsEmptyStr(hold)) {
175 a = client_getln(sock, buf, SIZ);
178 safestrncpy(buf, hold, SIZ);
182 if (!strncasecmp(buf, "Cookie: ", 8)) {
185 for (a = 0; a < len; ++a)
187 // we don't refresh len, because of we
188 // only exit from here.
189 sprintf(hold, "Cookie: %s", &buf[a + 1]);
192 while (isspace(hold[b]))
195 memmove(&hold[8], &hold[b], len - b + 1);
204 * \brief close some fd for some reason???
205 * \param fd the fd to close??????
206 * lingering_close() a`la Apache. see
207 * http://www.apache.org/docs/misc/fin_wait_2.html for rationale
208 * TODO: get this comment precise.
211 int lingering_close(int fd)
216 struct timeval tv, start;
218 gettimeofday(&start, NULL);
222 gettimeofday(&tv, NULL);
223 tv.tv_sec = SLEEPING - (tv.tv_sec - start.tv_sec);
224 tv.tv_usec = start.tv_usec - tv.tv_usec;
225 if (tv.tv_usec < 0) {
227 tv.tv_usec += 1000000;
231 i = select(fd + 1, &set, NULL, NULL, &tv);
232 } while (i == -1 && errno == EINTR);
237 i = read(fd, buf, sizeof buf);
238 } while (i != 0 && (i != -1 || errno == EINTR));
246 * \brief sanity requests
247 * Check for bogus requests coming from brain-dead Windows boxes.
249 * \param http_cmd The HTTP request to check
251 int is_bogus(char *http_cmd) {
255 url = strstr(http_cmd, " ");
256 if (url == NULL) return(1);
259 char *bogus_prefixes[] = {
260 "/scripts/root.exe", /**< Worms and trojans and viruses, oh my! */
263 "/_vti", /**< Broken Microsoft DAV implementation */
264 "/MSOffice" /**< Stoopid MSOffice thinks everyone is IIS */
267 max = sizeof(bogus_prefixes) / sizeof(char *);
269 for (i=0; i<max; ++i) {
270 if (!strncasecmp(url, bogus_prefixes[i], strlen(bogus_prefixes[i]))) {
275 return(0); /* probably ok */
281 * \brief handle one request
282 * This loop gets called once for every HTTP connection made to WebCit. At
283 * this entry point we have an HTTP socket with a browser allegedly on the
284 * other end, but we have not yet bound to a WebCit session.
286 * The job of this function is to locate the correct session and bind to it,
287 * or create a session if necessary and bind to it, then run the WebCit
288 * transaction loop. Afterwards, we unbind from the session. When this
289 * function returns, the worker thread is then free to handle another
291 * \param sock the socket we will put our answer to
293 void context_loop(int sock)
295 struct httprequest *req = NULL;
296 struct httprequest *last = NULL;
297 struct httprequest *hptr;
298 char buf[SIZ], hold[SIZ];
299 int desired_session = 0;
302 struct wcsession *TheSession, *sptr;
303 char httpauth_string[1024];
304 char httpauth_user[1024];
305 char httpauth_pass[1024];
306 char accept_language[256];
308 int session_is_new = 0;
310 strcpy(httpauth_string, "");
311 strcpy(httpauth_user, DEFAULT_HTTPAUTH_USER);
312 strcpy(httpauth_pass, DEFAULT_HTTPAUTH_PASS);
315 * Find out what it is that the web browser is asking for
317 memset(hold, 0, sizeof(hold));
319 if (req_gets(sock, buf, hold) < 0) return;
324 if (!strncasecmp(buf, "Accept-encoding:", 16)) {
325 if (strstr(&buf[16], "gzip")) {
331 * Browser-based sessions use cookies for session authentication
333 if (!strncasecmp(buf, "Cookie: webcit=", 15)) {
334 cookie_to_stuff(&buf[15], &desired_session,
335 NULL, 0, NULL, 0, NULL, 0);
340 * GroupDAV-based sessions use HTTP authentication
342 if (!strncasecmp(buf, "Authorization: Basic ", 21)) {
343 CtdlDecodeBase64(httpauth_string, &buf[21], strlen(&buf[21]));
344 extract_token(httpauth_user, httpauth_string, 0, ':', sizeof httpauth_user);
345 extract_token(httpauth_pass, httpauth_string, 1, ':', sizeof httpauth_pass);
348 if (!strncasecmp(buf, "If-Modified-Since: ", 19)) {
349 if_modified_since = httpdate_to_timestamp(&buf[19]);
352 if (!strncasecmp(buf, "Accept-Language: ", 17)) {
353 safestrncpy(accept_language, &buf[17], sizeof accept_language);
357 * Read in the request
359 hptr = (struct httprequest *)
360 malloc(sizeof(struct httprequest));
368 safestrncpy(hptr->line, buf, sizeof hptr->line);
370 } while (!IsEmptyStr(buf));
373 * If the request is prefixed by "/webcit" then chop that off. This
374 * allows a front end web server to forward all /webcit requests to us
375 * while still using the same web server port for other things.
378 ptr = strstr(req->line, " /webcit "); /*< Handle "/webcit" */
380 strcpy(ptr+2, ptr+8);
383 ptr = strstr(req->line, " /webcit"); /*< Handle "/webcit/" */
385 strcpy(ptr+1, ptr+8);
388 /** Begin parsing the request. */
390 safestrncpy(buf, req->line, sizeof buf);
391 lprintf(5, "HTTP: %s\n", buf);
393 /** Check for bogus requests */
395 strcpy(req->line, "GET /404 HTTP/1.1");
396 strcpy(buf, "GET /404 HTTP/1.1");
400 * Strip out the method, leaving the URL up front...
402 remove_token(buf, 0, ' ');
403 if (buf[1]==' ') buf[1]=0;
406 * While we're at it, gracefully handle requests for the
407 * robots.txt and favicon.ico files.
409 if (!strncasecmp(buf, "/robots.txt", 11)) {
410 strcpy(req->line, "GET /static/robots.txt"
411 "?force_close_session=yes HTTP/1.1");
413 else if (!strncasecmp(buf, "/favicon.ico", 12)) {
414 strcpy(req->line, "GET /static/favicon.ico");
418 * These are the URL's which may be executed without a
419 * session cookie already set. If it's not one of these,
420 * force the session to close because cookies are
421 * probably disabled on the client browser.
423 else if ( (strcmp(buf, "/"))
424 && (strncasecmp(buf, "/listsub", 8))
425 && (strncasecmp(buf, "/freebusy", 9))
426 && (strncasecmp(buf, "/do_logout", 10))
427 && (strncasecmp(buf, "/groupdav", 9))
428 && (strncasecmp(buf, "/static", 7))
429 && (strncasecmp(buf, "/rss", 4))
430 && (strncasecmp(buf, "/404", 4))
431 && (got_cookie == 0)) {
432 strcpy(req->line, "GET /static/nocookies.html"
433 "?force_close_session=yes HTTP/1.1");
437 * See if there's an existing session open with the desired ID or user/pass
441 if (TheSession == NULL) {
442 pthread_mutex_lock(&SessionListMutex);
443 for (sptr = SessionList; sptr != NULL; sptr = sptr->next) {
445 /** If HTTP-AUTH, look for a session with matching credentials */
446 if ( (!IsEmptyStr(httpauth_user))
447 &&(!strcasecmp(sptr->httpauth_user, httpauth_user))
448 &&(!strcasecmp(sptr->httpauth_pass, httpauth_pass)) ) {
452 /** If cookie-session, look for a session with matching session ID */
453 if ( (desired_session != 0) && (sptr->wc_session == desired_session)) {
458 pthread_mutex_unlock(&SessionListMutex);
462 * Create a new session if we have to
464 if (TheSession == NULL) {
465 lprintf(3, "Creating a new session\n");
466 TheSession = (struct wcsession *)
467 malloc(sizeof(struct wcsession));
468 memset(TheSession, 0, sizeof(struct wcsession));
469 TheSession->serv_sock = (-1);
470 TheSession->chat_sock = (-1);
472 /* If we're recreating a session that expired, it's best to give it the same
473 * session number that it had before. The client browser ought to pick up
474 * the new session number and start using it, but in some rare situations it
475 * doesn't, and that's a Bad Thing because it causes lots of spurious sessions
478 if (desired_session == 0) {
479 TheSession->wc_session = GenerateSessionID();
482 TheSession->wc_session = desired_session;
485 strcpy(TheSession->httpauth_user, httpauth_user);
486 strcpy(TheSession->httpauth_pass, httpauth_pass);
487 pthread_mutex_init(&TheSession->SessionMutex, NULL);
488 pthread_mutex_lock(&SessionListMutex);
489 TheSession->nonce = rand();
490 TheSession->next = SessionList;
491 SessionList = TheSession;
492 pthread_mutex_unlock(&SessionListMutex);
497 * A future improvement might be to check the session integrity
498 * at this point before continuing.
502 * Bind to the session and perform the transaction
504 pthread_mutex_lock(&TheSession->SessionMutex); /*< bind */
505 pthread_setspecific(MyConKey, (void *)TheSession);
506 TheSession->http_sock = sock;
507 TheSession->lastreq = time(NULL); /*< log */
508 TheSession->gzip_ok = gzip_ok;
510 if (session_is_new) {
511 httplang_to_locale(accept_language);
513 go_selected_language(); /*< set locale */
515 session_loop(req); /*< do transaction */
517 stop_selected_language(); /*< unset locale */
519 pthread_mutex_unlock(&TheSession->SessionMutex); /*< unbind */
521 /** Free the request buffer */
522 while (req != NULL) {
529 * Free up any session-local substitution variables which
530 * were set during this transaction
532 clear_local_substs();