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 clear_substs(sessions_to_kill);
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 * \brief Collapse multiple cookies on one line
165 * \param sock a socket?
166 * \param buf some bunch of chars?
167 * \param hold hold what?
168 * TODO: get this comment right
170 int req_gets(int sock, char *buf, char *hold)
174 if (IsEmptyStr(hold)) {
176 a = client_getln(sock, buf, SIZ);
179 safestrncpy(buf, hold, SIZ);
183 if (!strncasecmp(buf, "Cookie: ", 8)) {
186 for (a = 0; a < len; ++a)
188 // we don't refresh len, because of we
189 // only exit from here.
190 sprintf(hold, "Cookie: %s", &buf[a + 1]);
193 while (isspace(hold[b]))
196 memmove(&hold[8], &hold[b], len - b + 1);
205 * \brief close some fd for some reason???
206 * \param fd the fd to close??????
207 * lingering_close() a`la Apache. see
208 * http://www.apache.org/docs/misc/fin_wait_2.html for rationale
209 * TODO: get this comment precise.
212 int lingering_close(int fd)
217 struct timeval tv, start;
219 gettimeofday(&start, NULL);
223 gettimeofday(&tv, NULL);
224 tv.tv_sec = SLEEPING - (tv.tv_sec - start.tv_sec);
225 tv.tv_usec = start.tv_usec - tv.tv_usec;
226 if (tv.tv_usec < 0) {
228 tv.tv_usec += 1000000;
232 i = select(fd + 1, &set, NULL, NULL, &tv);
233 } while (i == -1 && errno == EINTR);
238 i = read(fd, buf, sizeof buf);
239 } while (i != 0 && (i != -1 || errno == EINTR));
247 * \brief sanity requests
248 * Check for bogus requests coming from brain-dead Windows boxes.
250 * \param http_cmd The HTTP request to check
252 int is_bogus(char *http_cmd) {
256 url = strstr(http_cmd, " ");
257 if (url == NULL) return(1);
260 char *bogus_prefixes[] = {
261 "/scripts/root.exe", /**< Worms and trojans and viruses, oh my! */
264 "/_vti", /**< Broken Microsoft DAV implementation */
265 "/MSOffice" /**< Stoopid MSOffice thinks everyone is IIS */
268 max = sizeof(bogus_prefixes) / sizeof(char *);
270 for (i=0; i<max; ++i) {
271 if (!strncasecmp(url, bogus_prefixes[i], strlen(bogus_prefixes[i]))) {
276 return(0); /* probably ok */
282 * \brief handle one request
283 * This loop gets called once for every HTTP connection made to WebCit. At
284 * this entry point we have an HTTP socket with a browser allegedly on the
285 * other end, but we have not yet bound to a WebCit session.
287 * The job of this function is to locate the correct session and bind to it,
288 * or create a session if necessary and bind to it, then run the WebCit
289 * transaction loop. Afterwards, we unbind from the session. When this
290 * function returns, the worker thread is then free to handle another
292 * \param sock the socket we will put our answer to
294 void context_loop(int sock)
296 struct httprequest *req = NULL;
297 struct httprequest *last = NULL;
298 struct httprequest *hptr;
299 char buf[SIZ], hold[SIZ];
300 int desired_session = 0;
303 struct wcsession *TheSession, *sptr;
304 char httpauth_string[1024];
305 char httpauth_user[1024];
306 char httpauth_pass[1024];
307 char accept_language[256];
309 int session_is_new = 0;
311 strcpy(httpauth_string, "");
312 strcpy(httpauth_user, DEFAULT_HTTPAUTH_USER);
313 strcpy(httpauth_pass, DEFAULT_HTTPAUTH_PASS);
316 * Find out what it is that the web browser is asking for
318 memset(hold, 0, sizeof(hold));
320 if (req_gets(sock, buf, hold) < 0) return;
325 if (!strncasecmp(buf, "Accept-encoding:", 16)) {
326 if (strstr(&buf[16], "gzip")) {
332 * Browser-based sessions use cookies for session authentication
334 if (!strncasecmp(buf, "Cookie: webcit=", 15)) {
335 cookie_to_stuff(&buf[15], &desired_session,
336 NULL, 0, NULL, 0, NULL, 0);
341 * GroupDAV-based sessions use HTTP authentication
343 if (!strncasecmp(buf, "Authorization: Basic ", 21)) {
344 CtdlDecodeBase64(httpauth_string, &buf[21], strlen(&buf[21]));
345 extract_token(httpauth_user, httpauth_string, 0, ':', sizeof httpauth_user);
346 extract_token(httpauth_pass, httpauth_string, 1, ':', sizeof httpauth_pass);
349 if (!strncasecmp(buf, "If-Modified-Since: ", 19)) {
350 if_modified_since = httpdate_to_timestamp(&buf[19]);
353 if (!strncasecmp(buf, "Accept-Language: ", 17)) {
354 safestrncpy(accept_language, &buf[17], sizeof accept_language);
358 * Read in the request
360 hptr = (struct httprequest *)
361 malloc(sizeof(struct httprequest));
369 safestrncpy(hptr->line, buf, sizeof hptr->line);
371 } while (!IsEmptyStr(buf));
374 * If the request is prefixed by "/webcit" then chop that off. This
375 * allows a front end web server to forward all /webcit requests to us
376 * while still using the same web server port for other things.
379 ptr = strstr(req->line, " /webcit "); /*< Handle "/webcit" */
381 strcpy(ptr+2, ptr+8);
384 ptr = strstr(req->line, " /webcit"); /*< Handle "/webcit/" */
386 strcpy(ptr+1, ptr+8);
389 /** Begin parsing the request. */
391 safestrncpy(buf, req->line, sizeof buf);
392 lprintf(5, "HTTP: %s\n", buf);
394 /** Check for bogus requests */
396 strcpy(req->line, "GET /404 HTTP/1.1");
397 strcpy(buf, "GET /404 HTTP/1.1");
401 * Strip out the method, leaving the URL up front...
403 remove_token(buf, 0, ' ');
404 if (buf[1]==' ') buf[1]=0;
407 * While we're at it, gracefully handle requests for the
408 * robots.txt and favicon.ico files.
410 if (!strncasecmp(buf, "/robots.txt", 11)) {
411 strcpy(req->line, "GET /static/robots.txt"
412 "?force_close_session=yes HTTP/1.1");
414 else if (!strncasecmp(buf, "/favicon.ico", 12)) {
415 strcpy(req->line, "GET /static/favicon.ico");
419 * These are the URL's which may be executed without a
420 * session cookie already set. If it's not one of these,
421 * force the session to close because cookies are
422 * probably disabled on the client browser.
424 else if ( (strcmp(buf, "/"))
425 && (strncasecmp(buf, "/listsub", 8))
426 && (strncasecmp(buf, "/freebusy", 9))
427 && (strncasecmp(buf, "/do_logout", 10))
428 && (strncasecmp(buf, "/groupdav", 9))
429 && (strncasecmp(buf, "/static", 7))
430 && (strncasecmp(buf, "/rss", 4))
431 && (strncasecmp(buf, "/404", 4))
432 && (got_cookie == 0)) {
433 strcpy(req->line, "GET /static/nocookies.html"
434 "?force_close_session=yes HTTP/1.1");
438 * See if there's an existing session open with the desired ID or user/pass
442 if (TheSession == NULL) {
443 pthread_mutex_lock(&SessionListMutex);
444 for (sptr = SessionList; sptr != NULL; sptr = sptr->next) {
446 /** If HTTP-AUTH, look for a session with matching credentials */
447 if ( (!IsEmptyStr(httpauth_user))
448 &&(!strcasecmp(sptr->httpauth_user, httpauth_user))
449 &&(!strcasecmp(sptr->httpauth_pass, httpauth_pass)) ) {
453 /** If cookie-session, look for a session with matching session ID */
454 if ( (desired_session != 0) && (sptr->wc_session == desired_session)) {
459 pthread_mutex_unlock(&SessionListMutex);
463 * Create a new session if we have to
465 if (TheSession == NULL) {
466 lprintf(3, "Creating a new session\n");
467 TheSession = (struct wcsession *)
468 malloc(sizeof(struct wcsession));
469 memset(TheSession, 0, sizeof(struct wcsession));
470 TheSession->serv_sock = (-1);
471 TheSession->chat_sock = (-1);
473 /* If we're recreating a session that expired, it's best to give it the same
474 * session number that it had before. The client browser ought to pick up
475 * the new session number and start using it, but in some rare situations it
476 * doesn't, and that's a Bad Thing because it causes lots of spurious sessions
479 if (desired_session == 0) {
480 TheSession->wc_session = GenerateSessionID();
483 TheSession->wc_session = desired_session;
486 strcpy(TheSession->httpauth_user, httpauth_user);
487 strcpy(TheSession->httpauth_pass, httpauth_pass);
488 pthread_mutex_init(&TheSession->SessionMutex, NULL);
489 pthread_mutex_lock(&SessionListMutex);
490 TheSession->nonce = rand();
491 TheSession->next = SessionList;
492 SessionList = TheSession;
493 pthread_mutex_unlock(&SessionListMutex);
498 * A future improvement might be to check the session integrity
499 * at this point before continuing.
503 * Bind to the session and perform the transaction
505 pthread_mutex_lock(&TheSession->SessionMutex); /*< bind */
506 pthread_setspecific(MyConKey, (void *)TheSession);
507 TheSession->http_sock = sock;
508 TheSession->lastreq = time(NULL); /*< log */
509 TheSession->gzip_ok = gzip_ok;
511 if (session_is_new) {
512 httplang_to_locale(accept_language);
514 go_selected_language(); /*< set locale */
516 session_loop(req); /*< do transaction */
518 stop_selected_language(); /*< unset locale */
520 pthread_mutex_unlock(&TheSession->SessionMutex); /*< unbind */
522 /** Free the request buffer */
523 while (req != NULL) {
530 * Free up any session-local substitution variables which
531 * were set during this transaction
533 clear_local_substs();