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;
43 void do_housekeeping(void)
45 struct wcsession *sptr, *ss;
46 struct wcsession *sessions_to_kill = NULL;
48 static int num_threads = MIN_WORKER_THREADS;
51 * Lock the session list, moving any candidates for euthanasia into
54 pthread_mutex_lock(&SessionListMutex);
56 for (sptr = SessionList; sptr != NULL; sptr = sptr->next) {
59 /** Kill idle sessions */
60 if ((time(NULL) - (sptr->lastreq)) >
61 (time_t) WEBCIT_TIMEOUT) {
65 /** Remove sessions flagged for kill */
68 /** remove session from linked list */
69 if (sptr == SessionList) {
70 SessionList = SessionList->next;
72 else for (ss=SessionList;ss!=NULL;ss=ss->next) {
73 if (ss->next == sptr) {
74 ss->next = ss->next->next;
78 sptr->next = sessions_to_kill;
79 sessions_to_kill = sptr;
82 pthread_mutex_unlock(&SessionListMutex);
85 * Now free up and destroy the culled sessions.
87 while (sessions_to_kill != NULL) {
88 lprintf(3, "Destroying session %d\n", sessions_to_kill->wc_session);
89 pthread_mutex_lock(&sessions_to_kill->SessionMutex);
90 close(sessions_to_kill->serv_sock);
91 close(sessions_to_kill->chat_sock);
92 if (sessions_to_kill->preferences != NULL) {
93 free(sessions_to_kill->preferences);
95 if (sessions_to_kill->cache_fold != NULL) {
96 free(sessions_to_kill->cache_fold);
98 free_attachments(sessions_to_kill);
99 free_march_list(sessions_to_kill);
100 pthread_mutex_unlock(&sessions_to_kill->SessionMutex);
101 sptr = sessions_to_kill->next;
102 free(sessions_to_kill);
103 sessions_to_kill = sptr;
108 * If there are more sessions than threads, then we should spawn
109 * more threads ... up to a predefined maximum.
111 while ( (num_sessions > num_threads)
112 && (num_threads <= MAX_WORKER_THREADS) ) {
113 spawn_another_worker_thread();
115 lprintf(3, "There are %d sessions and %d threads active.\n",
116 num_sessions, num_threads);
122 * \brief Wake up occasionally and clean house
124 void housekeeping_loop(void)
127 sleeeeeeeeeep(HOUSEKEEPING);
134 * \brief Create a Session id
135 * Generate a unique WebCit session ID (which is not the same thing as the
136 * Citadel session ID).
138 * \todo FIXME ... ensure that session number is truly unique
141 int GenerateSessionID(void)
143 static int seq = (-1);
146 seq = (int) time(NULL);
154 * \brief Collapse multiple cookies on one line
155 * \param sock a socket?
156 * \param buf some bunch of chars?
157 * \param hold hold what?
158 * TODO: get this comment right
160 int req_gets(int sock, char *buf, char *hold)
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 sprintf(hold, "Cookie: %s", &buf[a + 1]);
183 while (isspace(hold[b]))
186 memmove(&hold[8], &hold[b], len - b + 1);
195 * \brief close some fd for some reason???
196 * \param fd the fd to close??????
197 * lingering_close() a`la Apache. see
198 * http://www.apache.org/docs/misc/fin_wait_2.html for rationale
199 * TODO: get this comment precise.
202 int lingering_close(int fd)
207 struct timeval tv, start;
209 gettimeofday(&start, NULL);
213 gettimeofday(&tv, NULL);
214 tv.tv_sec = SLEEPING - (tv.tv_sec - start.tv_sec);
215 tv.tv_usec = start.tv_usec - tv.tv_usec;
216 if (tv.tv_usec < 0) {
218 tv.tv_usec += 1000000;
222 i = select(fd + 1, &set, NULL, NULL, &tv);
223 } while (i == -1 && errno == EINTR);
228 i = read(fd, buf, sizeof buf);
229 } while (i != 0 && (i != -1 || errno == EINTR));
237 * \brief sanity requests
238 * Check for bogus requests coming from brain-dead Windows boxes.
240 * \param http_cmd The HTTP request to check
242 int is_bogus(char *http_cmd) {
246 url = strstr(http_cmd, " ");
247 if (url == NULL) return(1);
250 char *bogus_prefixes[] = {
251 "/scripts/root.exe", /**< Worms and trojans and viruses, oh my! */
254 "/_vti", /**< Broken Microsoft DAV implementation */
255 "/MSOffice" /**< Stoopid MSOffice thinks everyone is IIS */
258 max = sizeof(bogus_prefixes) / sizeof(char *);
260 for (i=0; i<max; ++i) {
261 if (!strncasecmp(url, bogus_prefixes[i], strlen(bogus_prefixes[i]))) {
266 return(0); /* probably ok */
272 * \brief handle one request
273 * This loop gets called once for every HTTP connection made to WebCit. At
274 * this entry point we have an HTTP socket with a browser allegedly on the
275 * other end, but we have not yet bound to a WebCit session.
277 * The job of this function is to locate the correct session and bind to it,
278 * or create a session if necessary and bind to it, then run the WebCit
279 * transaction loop. Afterwards, we unbind from the session. When this
280 * function returns, the worker thread is then free to handle another
282 * \param sock the socket we will put our answer to
284 void context_loop(int sock)
286 struct httprequest *req = NULL;
287 struct httprequest *last = NULL;
288 struct httprequest *hptr;
289 char buf[SIZ], hold[SIZ];
290 int desired_session = 0;
293 struct wcsession *TheSession, *sptr;
294 char httpauth_string[1024];
295 char httpauth_user[1024];
296 char httpauth_pass[1024];
297 char accept_language[256];
299 int session_is_new = 0;
301 strcpy(httpauth_string, "");
302 strcpy(httpauth_user, DEFAULT_HTTPAUTH_USER);
303 strcpy(httpauth_pass, DEFAULT_HTTPAUTH_PASS);
306 * Find out what it is that the web browser is asking for
308 memset(hold, 0, sizeof(hold));
310 if (req_gets(sock, buf, hold) < 0) return;
315 if (!strncasecmp(buf, "Accept-encoding:", 16)) {
316 if (strstr(&buf[16], "gzip")) {
322 * Browser-based sessions use cookies for session authentication
324 if (!strncasecmp(buf, "Cookie: webcit=", 15)) {
325 cookie_to_stuff(&buf[15], &desired_session,
326 NULL, 0, NULL, 0, NULL, 0);
331 * GroupDAV-based sessions use HTTP authentication
333 if (!strncasecmp(buf, "Authorization: Basic ", 21)) {
334 CtdlDecodeBase64(httpauth_string, &buf[21], strlen(&buf[21]));
335 extract_token(httpauth_user, httpauth_string, 0, ':', sizeof httpauth_user);
336 extract_token(httpauth_pass, httpauth_string, 1, ':', sizeof httpauth_pass);
339 if (!strncasecmp(buf, "If-Modified-Since: ", 19)) {
340 if_modified_since = httpdate_to_timestamp(&buf[19]);
343 if (!strncasecmp(buf, "Accept-Language: ", 17)) {
344 safestrncpy(accept_language, &buf[17], sizeof accept_language);
348 * Read in the request
350 hptr = (struct httprequest *)
351 malloc(sizeof(struct httprequest));
359 safestrncpy(hptr->line, buf, sizeof hptr->line);
361 } while (!IsEmptyStr(buf));
364 * If the request is prefixed by "/webcit" then chop that off. This
365 * allows a front end web server to forward all /webcit requests to us
366 * while still using the same web server port for other things.
369 ptr = strstr(req->line, " /webcit "); /*< Handle "/webcit" */
371 strcpy(ptr+2, ptr+8);
374 ptr = strstr(req->line, " /webcit"); /*< Handle "/webcit/" */
376 strcpy(ptr+1, ptr+8);
379 /** Begin parsing the request. */
381 safestrncpy(buf, req->line, sizeof buf);
382 lprintf(5, "HTTP: %s\n", buf);
384 /** Check for bogus requests */
386 strcpy(req->line, "GET /404 HTTP/1.1");
387 strcpy(buf, "GET /404 HTTP/1.1");
391 * Strip out the method, leaving the URL up front...
393 remove_token(buf, 0, ' ');
394 if (buf[1]==' ') buf[1]=0;
397 * While we're at it, gracefully handle requests for the
398 * robots.txt and favicon.ico files.
400 if (!strncasecmp(buf, "/robots.txt", 11)) {
401 strcpy(req->line, "GET /static/robots.txt"
402 "?force_close_session=yes HTTP/1.1");
404 else if (!strncasecmp(buf, "/favicon.ico", 12)) {
405 strcpy(req->line, "GET /static/favicon.ico");
409 * These are the URL's which may be executed without a
410 * session cookie already set. If it's not one of these,
411 * force the session to close because cookies are
412 * probably disabled on the client browser.
414 else if ( (strcmp(buf, "/"))
415 && (strncasecmp(buf, "/listsub", 8))
416 && (strncasecmp(buf, "/freebusy", 9))
417 && (strncasecmp(buf, "/do_logout", 10))
418 && (strncasecmp(buf, "/groupdav", 9))
419 && (strncasecmp(buf, "/static", 7))
420 && (strncasecmp(buf, "/rss", 4))
421 && (strncasecmp(buf, "/404", 4))
422 && (got_cookie == 0)) {
423 strcpy(req->line, "GET /static/nocookies.html"
424 "?force_close_session=yes HTTP/1.1");
428 * See if there's an existing session open with the desired ID or user/pass
432 if (TheSession == NULL) {
433 pthread_mutex_lock(&SessionListMutex);
434 for (sptr = SessionList; sptr != NULL; sptr = sptr->next) {
436 /** If HTTP-AUTH, look for a session with matching credentials */
437 if ( (!IsEmptyStr(httpauth_user))
438 &&(!strcasecmp(sptr->httpauth_user, httpauth_user))
439 &&(!strcasecmp(sptr->httpauth_pass, httpauth_pass)) ) {
443 /** If cookie-session, look for a session with matching session ID */
444 if ( (desired_session != 0) && (sptr->wc_session == desired_session)) {
449 pthread_mutex_unlock(&SessionListMutex);
453 * Create a new session if we have to
455 if (TheSession == NULL) {
456 lprintf(3, "Creating a new session\n");
457 TheSession = (struct wcsession *)
458 malloc(sizeof(struct wcsession));
459 memset(TheSession, 0, sizeof(struct wcsession));
460 TheSession->serv_sock = (-1);
461 TheSession->chat_sock = (-1);
463 /* If we're recreating a session that expired, it's best to give it the same
464 * session number that it had before. The client browser ought to pick up
465 * the new session number and start using it, but in some rare situations it
466 * doesn't, and that's a Bad Thing because it causes lots of spurious sessions
469 if (desired_session == 0) {
470 TheSession->wc_session = GenerateSessionID();
473 TheSession->wc_session = desired_session;
476 strcpy(TheSession->httpauth_user, httpauth_user);
477 strcpy(TheSession->httpauth_pass, httpauth_pass);
478 pthread_mutex_init(&TheSession->SessionMutex, NULL);
479 pthread_mutex_lock(&SessionListMutex);
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);
497 TheSession->http_sock = sock;
498 TheSession->lastreq = time(NULL); /*< log */
499 TheSession->gzip_ok = gzip_ok;
501 if (session_is_new) {
502 httplang_to_locale(accept_language);
504 go_selected_language(); /*< set locale */
506 session_loop(req); /*< do transaction */
508 stop_selected_language(); /*< unset locale */
510 pthread_mutex_unlock(&TheSession->SessionMutex); /*< unbind */
512 /** Free the request buffer */
513 while (req != NULL) {
520 * Free up any session-local substitution variables which
521 * were set during this transaction
523 clear_local_substs();