* do non-blocking accept()
[citadel.git] / webcit / context_loop.c
1 /*
2  * $Id$
3  */
4 /**
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 
11  *
12  */
13 /*@{*/
14 #include "webcit.h"
15 #include "webserver.h"
16
17 /** Only one thread may manipulate SessionList at a time... */
18 pthread_mutex_t SessionListMutex;
19
20 struct wcsession *SessionList = NULL; /**< our sessions ????*/
21
22 pthread_key_t MyConKey;         /**< TSD key for MySession() */
23
24
25 /**
26  * \brief free the memory used for viewing atachments
27  * \param sess the session object to destroy
28  */
29 void free_attachments(struct wcsession *sess) {
30         struct wc_attachment *att;
31
32         while (sess->first_attachment != NULL) {
33                 att = sess->first_attachment;
34                 sess->first_attachment = sess->first_attachment->next;
35                 free(att->data);
36                 free(att);
37         }
38 }
39
40
41 void shutdown_sessions(void)
42 {
43         struct wcsession *sptr;
44         
45         for (sptr = SessionList; sptr != NULL; sptr = sptr->next) {
46                         sptr->killthis = 1;
47         }
48 }
49 /**
50  * \brief what??????
51  */
52 void do_housekeeping(void)
53 {
54         struct wcsession *sptr, *ss;
55         struct wcsession *sessions_to_kill = NULL;
56         int num_sessions = 0;
57         static int num_threads = MIN_WORKER_THREADS;
58
59         /**
60          * Lock the session list, moving any candidates for euthanasia into
61          * a separate list.
62          */
63         pthread_mutex_lock(&SessionListMutex);
64         num_sessions = 0;
65         for (sptr = SessionList; sptr != NULL; sptr = sptr->next) {
66                 ++num_sessions;
67
68                 /** Kill idle sessions */
69                 if ((time(NULL) - (sptr->lastreq)) >
70                    (time_t) WEBCIT_TIMEOUT) {
71                         sptr->killthis = 1;
72                 }
73
74                 /** Remove sessions flagged for kill */
75                 if (sptr->killthis) {
76
77                         /** remove session from linked list */
78                         if (sptr == SessionList) {
79                                 SessionList = SessionList->next;
80                         }
81                         else for (ss=SessionList;ss!=NULL;ss=ss->next) {
82                                 if (ss->next == sptr) {
83                                         ss->next = ss->next->next;
84                                 }
85                         }
86
87                         sptr->next = sessions_to_kill;
88                         sessions_to_kill = sptr;
89                 }
90         }
91         pthread_mutex_unlock(&SessionListMutex);
92
93         /**
94          * Now free up and destroy the culled sessions.
95          */
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);
103                 }
104                 if (sessions_to_kill->cache_fold != NULL) {
105                         free(sessions_to_kill->cache_fold);
106                 }
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;
113                 --num_sessions;
114         }
115
116         /**
117          * If there are more sessions than threads, then we should spawn
118          * more threads ... up to a predefined maximum.
119          */
120         while ( (num_sessions > num_threads)
121               && (num_threads <= MAX_WORKER_THREADS) ) {
122                 spawn_another_worker_thread();
123                 ++num_threads;
124                 lprintf(3, "There are %d sessions and %d threads active.\n",
125                         num_sessions, num_threads);
126         }
127 }
128
129
130 /**
131  * \brief Wake up occasionally and clean house
132  */
133 void housekeeping_loop(void)
134 {
135         while (1) {
136                 sleeeeeeeeeep(HOUSEKEEPING);
137                 do_housekeeping();
138         }
139 }
140
141
142 /**
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).
146  *
147  * \todo FIXME ... ensure that session number is truly unique
148  *
149  */
150 int GenerateSessionID(void)
151 {
152         static int seq = (-1);
153
154         if (seq < 0) {
155                 seq = (int) time(NULL);
156         }
157                 
158         return ++seq;
159 }
160
161
162 /**
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
168  */
169 int req_gets(int sock, char *buf, char *hold)
170 {
171         int a, b;
172
173         if (IsEmptyStr(hold)) {
174                 strcpy(buf, "");
175                 a = client_getln(sock, buf, SIZ);
176                 if (a<1) return(-1);
177         } else {
178                 safestrncpy(buf, hold, SIZ);
179         }
180         strcpy(hold, "");
181
182         if (!strncasecmp(buf, "Cookie: ", 8)) {
183                 int len;
184                 len = strlen(buf);
185                 for (a = 0; a < len; ++a)
186                         if (buf[a] == ';') {
187                                 // we don't refresh len, because of we 
188                                 // only exit from here.
189                                 sprintf(hold, "Cookie: %s", &buf[a + 1]);
190                                 buf[a] = 0;
191                                 b = 8;
192                                 while (isspace(hold[b]))
193                                         b++;
194                                 
195                                 memmove(&hold[8], &hold[b], len - b + 1);
196                                 return(0);
197                         }
198         }
199
200         return(0);
201 }
202
203 /**
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.
209  */
210
211 int lingering_close(int fd)
212 {
213         char buf[SIZ];
214         int i;
215         fd_set set;
216         struct timeval tv, start;
217
218         gettimeofday(&start, NULL);
219         shutdown(fd, 1);
220         do {
221                 do {
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) {
226                                 tv.tv_sec--;
227                                 tv.tv_usec += 1000000;
228                         }
229                         FD_ZERO(&set);
230                         FD_SET(fd, &set);
231                         i = select(fd + 1, &set, NULL, NULL, &tv);
232                 } while (i == -1 && errno == EINTR);
233
234                 if (i <= 0)
235                         break;
236
237                 i = read(fd, buf, sizeof buf);
238         } while (i != 0 && (i != -1 || errno == EINTR));
239
240         return close(fd);
241 }
242
243
244
245 /**
246  * \brief       sanity requests
247  *              Check for bogus requests coming from brain-dead Windows boxes.
248  *
249  * \param       http_cmd        The HTTP request to check
250  */
251 int is_bogus(char *http_cmd) {
252         char *url;
253         int i, max;
254
255         url = strstr(http_cmd, " ");
256         if (url == NULL) return(1);
257         ++url;
258
259         char *bogus_prefixes[] = {
260                 "/scripts/root.exe",    /**< Worms and trojans and viruses, oh my! */
261                 "/c/winnt",
262                 "/MSADC/",
263                 "/_vti",                /**< Broken Microsoft DAV implementation */
264                 "/MSOffice"             /**< Stoopid MSOffice thinks everyone is IIS */
265         };
266
267         max = sizeof(bogus_prefixes) / sizeof(char *);
268
269         for (i=0; i<max; ++i) {
270                 if (!strncasecmp(url, bogus_prefixes[i], strlen(bogus_prefixes[i]))) {
271                         return(2);
272                 }
273         }
274
275         return(0);      /* probably ok */
276 }
277
278
279
280 /**
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.
285  *
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
290  * transaction.
291  * \param sock the socket we will put our answer to
292  */
293 void context_loop(int sock)
294 {
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;
300         int got_cookie = 0;
301         int gzip_ok = 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];
307         char *ptr = NULL;
308         int session_is_new = 0;
309
310         strcpy(httpauth_string, "");
311         strcpy(httpauth_user, DEFAULT_HTTPAUTH_USER);
312         strcpy(httpauth_pass, DEFAULT_HTTPAUTH_PASS);
313
314         /**
315          * Find out what it is that the web browser is asking for
316          */
317         memset(hold, 0, sizeof(hold));
318         do {
319                 if (req_gets(sock, buf, hold) < 0) return;
320
321                 /**
322                  * Can we compress?
323                  */
324                 if (!strncasecmp(buf, "Accept-encoding:", 16)) {
325                         if (strstr(&buf[16], "gzip")) {
326                                 gzip_ok = 1;
327                         }
328                 }
329
330                 /**
331                  * Browser-based sessions use cookies for session authentication
332                  */
333                 if (!strncasecmp(buf, "Cookie: webcit=", 15)) {
334                         cookie_to_stuff(&buf[15], &desired_session,
335                                 NULL, 0, NULL, 0, NULL, 0);
336                         got_cookie = 1;
337                 }
338
339                 /**
340                  * GroupDAV-based sessions use HTTP authentication
341                  */
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);
346                 }
347
348                 if (!strncasecmp(buf, "If-Modified-Since: ", 19)) {
349                         if_modified_since = httpdate_to_timestamp(&buf[19]);
350                 }
351
352                 if (!strncasecmp(buf, "Accept-Language: ", 17)) {
353                         safestrncpy(accept_language, &buf[17], sizeof accept_language);
354                 }
355
356                 /**
357                  * Read in the request
358                  */
359                 hptr = (struct httprequest *)
360                         malloc(sizeof(struct httprequest));
361                 if (req == NULL)
362                         req = hptr;
363                 else
364                         last->next = hptr;
365                 hptr->next = NULL;
366                 last = hptr;
367
368                 safestrncpy(hptr->line, buf, sizeof hptr->line);
369
370         } while (!IsEmptyStr(buf));
371
372         /**
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.
376          */
377         
378         ptr = strstr(req->line, " /webcit ");   /*< Handle "/webcit" */
379         if (ptr != NULL) {
380                 strcpy(ptr+2, ptr+8);
381         }
382
383         ptr = strstr(req->line, " /webcit");    /*< Handle "/webcit/" */
384         if (ptr != NULL) {
385                 strcpy(ptr+1, ptr+8);
386         }
387
388         /** Begin parsing the request. */
389
390         safestrncpy(buf, req->line, sizeof buf);
391         lprintf(5, "HTTP: %s\n", buf);
392
393         /** Check for bogus requests */
394         if (is_bogus(buf)) {
395                 strcpy(req->line, "GET /404 HTTP/1.1");
396                 strcpy(buf, "GET /404 HTTP/1.1");
397         }
398
399         /**
400          * Strip out the method, leaving the URL up front...
401          */
402         remove_token(buf, 0, ' ');
403         if (buf[1]==' ') buf[1]=0;
404
405         /**
406          * While we're at it, gracefully handle requests for the
407          * robots.txt and favicon.ico files.
408          */
409         if (!strncasecmp(buf, "/robots.txt", 11)) {
410                 strcpy(req->line, "GET /static/robots.txt"
411                                 "?force_close_session=yes HTTP/1.1");
412         }
413         else if (!strncasecmp(buf, "/favicon.ico", 12)) {
414                 strcpy(req->line, "GET /static/favicon.ico");
415         }
416
417         /**
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.
422          */
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");
434         }
435
436         /**
437          * See if there's an existing session open with the desired ID or user/pass
438          */
439         TheSession = NULL;
440
441         if (TheSession == NULL) {
442                 pthread_mutex_lock(&SessionListMutex);
443                 for (sptr = SessionList; sptr != NULL; sptr = sptr->next) {
444
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)) ) {
449                                 TheSession = sptr;
450                         }
451
452                         /** If cookie-session, look for a session with matching session ID */
453                         if ( (desired_session != 0) && (sptr->wc_session == desired_session)) {
454                                 TheSession = sptr;
455                         }
456
457                 }
458                 pthread_mutex_unlock(&SessionListMutex);
459         }
460
461         /**
462          * Create a new session if we have to
463          */
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);
471         
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
476                  * to get created.
477                  */     
478                 if (desired_session == 0) {
479                         TheSession->wc_session = GenerateSessionID();
480                 }
481                 else {
482                         TheSession->wc_session = desired_session;
483                 }
484
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);
493                 session_is_new = 1;
494         }
495
496         /**
497          * A future improvement might be to check the session integrity
498          * at this point before continuing.
499          */
500
501         /**
502          * Bind to the session and perform the transaction
503          */
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;
509 #ifdef ENABLE_NLS
510         if (session_is_new) {
511                 httplang_to_locale(accept_language);
512         }
513         go_selected_language();                         /*< set locale */
514 #endif
515         session_loop(req);                              /*< do transaction */
516 #ifdef ENABLE_NLS
517         stop_selected_language();                       /*< unset locale */
518 #endif
519         pthread_mutex_unlock(&TheSession->SessionMutex);        /*< unbind */
520
521         /** Free the request buffer */
522         while (req != NULL) {
523                 hptr = req->next;
524                 free(req);
525                 req = hptr;
526         }
527
528         /**
529          * Free up any session-local substitution variables which
530          * were set during this transaction
531          */
532         clear_local_substs();
533 }
534 /*@}*/