* Cleaned up some misc comments
[citadel.git] / webcit / context_loop.c
1 /*
2  * $Id$
3  *
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.
8  *
9  */
10
11 #include "webcit.h"
12 #include "webserver.h"
13
14 /* Only one thread may manipulate SessionList at a time... */
15 pthread_mutex_t SessionListMutex;
16
17 struct wcsession *SessionList = NULL; /**< our sessions ????*/
18
19 pthread_key_t MyConKey;         /**< TSD key for MySession() */
20
21
22 /*
23  * free the memory used for viewing atachments
24  */
25 void free_attachments(struct wcsession *sess) {
26         struct wc_attachment *att;
27
28         while (sess->first_attachment != NULL) {
29                 att = sess->first_attachment;
30                 sess->first_attachment = sess->first_attachment->next;
31                 free(att->data);
32                 free(att);
33         }
34 }
35
36
37 void shutdown_sessions(void)
38 {
39         struct wcsession *sptr;
40         
41         for (sptr = SessionList; sptr != NULL; sptr = sptr->next) {
42                         sptr->killthis = 1;
43         }
44 }
45
46 void do_housekeeping(void)
47 {
48         struct wcsession *sptr, *ss;
49         struct wcsession *sessions_to_kill = NULL;
50         int num_sessions = 0;
51         static int num_threads = MIN_WORKER_THREADS;
52
53         /**
54          * Lock the session list, moving any candidates for euthanasia into
55          * a separate list.
56          */
57         pthread_mutex_lock(&SessionListMutex);
58         num_sessions = 0;
59         for (sptr = SessionList; sptr != NULL; sptr = sptr->next) {
60                 ++num_sessions;
61
62                 /** Kill idle sessions */
63                 if ((time(NULL) - (sptr->lastreq)) >
64                    (time_t) WEBCIT_TIMEOUT) {
65                         sptr->killthis = 1;
66                 }
67
68                 /** Remove sessions flagged for kill */
69                 if (sptr->killthis) {
70
71                         /** remove session from linked list */
72                         if (sptr == SessionList) {
73                                 SessionList = SessionList->next;
74                         }
75                         else for (ss=SessionList;ss!=NULL;ss=ss->next) {
76                                 if (ss->next == sptr) {
77                                         ss->next = ss->next->next;
78                                 }
79                         }
80
81                         sptr->next = sessions_to_kill;
82                         sessions_to_kill = sptr;
83                 }
84         }
85         pthread_mutex_unlock(&SessionListMutex);
86
87         /**
88          * Now free up and destroy the culled sessions.
89          */
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);
97                 }
98                 if (sessions_to_kill->cache_fold != NULL) {
99                         free(sessions_to_kill->cache_fold);
100                 }
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;
108                 --num_sessions;
109         }
110
111         /**
112          * If there are more sessions than threads, then we should spawn
113          * more threads ... up to a predefined maximum.
114          */
115         while ( (num_sessions > num_threads)
116               && (num_threads <= MAX_WORKER_THREADS) ) {
117                 spawn_another_worker_thread();
118                 ++num_threads;
119                 lprintf(3, "There are %d sessions and %d threads active.\n",
120                         num_sessions, num_threads);
121         }
122 }
123
124
125 /**
126  * \brief Wake up occasionally and clean house
127  */
128 void housekeeping_loop(void)
129 {
130         while (1) {
131                 sleeeeeeeeeep(HOUSEKEEPING);
132                 do_housekeeping();
133         }
134 }
135
136
137 /**
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).
141  *
142  * \todo FIXME ... ensure that session number is truly unique
143  *
144  */
145 int GenerateSessionID(void)
146 {
147         static int seq = (-1);
148
149         if (seq < 0) {
150                 seq = (int) time(NULL);
151         }
152                 
153         return ++seq;
154 }
155
156
157 /*
158  * Collapse multiple cookies on one line
159  */
160 int req_gets(int sock, char *buf, char *hold)
161 {
162         int a, b;
163
164         if (IsEmptyStr(hold)) {
165                 strcpy(buf, "");
166                 a = client_getln(sock, buf, SIZ);
167                 if (a<1) return(-1);
168         } else {
169                 safestrncpy(buf, hold, SIZ);
170         }
171         strcpy(hold, "");
172
173         if (!strncasecmp(buf, "Cookie: ", 8)) {
174                 int len;
175                 len = strlen(buf);
176                 for (a = 0; a < len; ++a)
177                         if (buf[a] == ';') {
178                                 // we don't refresh len, because of we 
179                                 // only exit from here.
180                                 sprintf(hold, "Cookie: %s", &buf[a + 1]);
181                                 buf[a] = 0;
182                                 b = 8;
183                                 while (isspace(hold[b]))
184                                         b++;
185                                 
186                                 memmove(&hold[8], &hold[b], len - b + 1);
187                                 return(0);
188                         }
189         }
190
191         return(0);
192 }
193
194 /*
195  * lingering_close() a`la Apache. see
196  * http://www.apache.org/docs/misc/fin_wait_2.html for rationale
197  */
198 int lingering_close(int fd)
199 {
200         char buf[SIZ];
201         int i;
202         fd_set set;
203         struct timeval tv, start;
204
205         gettimeofday(&start, NULL);
206         shutdown(fd, 1);
207         do {
208                 do {
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) {
213                                 tv.tv_sec--;
214                                 tv.tv_usec += 1000000;
215                         }
216                         FD_ZERO(&set);
217                         FD_SET(fd, &set);
218                         i = select(fd + 1, &set, NULL, NULL, &tv);
219                 } while (i == -1 && errno == EINTR);
220
221                 if (i <= 0)
222                         break;
223
224                 i = read(fd, buf, sizeof buf);
225         } while (i != 0 && (i != -1 || errno == EINTR));
226
227         return close(fd);
228 }
229
230
231
232 /**
233  * \brief       sanity requests
234  *              Check for bogus requests coming from brain-dead Windows boxes.
235  *
236  * \param       http_cmd        The HTTP request to check
237  */
238 int is_bogus(char *http_cmd) {
239         char *url;
240         int i, max;
241
242         url = strstr(http_cmd, " ");
243         if (url == NULL) return(1);
244         ++url;
245
246         char *bogus_prefixes[] = {
247                 "/scripts/root.exe",    /**< Worms and trojans and viruses, oh my! */
248                 "/c/winnt",
249                 "/MSADC/",
250                 "/_vti",                /**< Broken Microsoft DAV implementation */
251                 "/MSOffice"             /**< Stoopid MSOffice thinks everyone is IIS */
252         };
253
254         max = sizeof(bogus_prefixes) / sizeof(char *);
255
256         for (i=0; i<max; ++i) {
257                 if (!strncasecmp(url, bogus_prefixes[i], strlen(bogus_prefixes[i]))) {
258                         return(2);
259                 }
260         }
261
262         return(0);      /* probably ok */
263 }
264
265
266
267 /**
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.
272  *
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
277  * transaction.
278  * \param sock the socket we will put our answer to
279  */
280 void context_loop(int sock)
281 {
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;
287         int got_cookie = 0;
288         int gzip_ok = 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];
294         char *ptr = NULL;
295         int session_is_new = 0;
296
297         strcpy(httpauth_string, "");
298         strcpy(httpauth_user, DEFAULT_HTTPAUTH_USER);
299         strcpy(httpauth_pass, DEFAULT_HTTPAUTH_PASS);
300
301         /**
302          * Find out what it is that the web browser is asking for
303          */
304         memset(hold, 0, sizeof(hold));
305         do {
306                 if (req_gets(sock, buf, hold) < 0) return;
307
308                 /**
309                  * Can we compress?
310                  */
311                 if (!strncasecmp(buf, "Accept-encoding:", 16)) {
312                         if (strstr(&buf[16], "gzip")) {
313                                 gzip_ok = 1;
314                         }
315                 }
316
317                 /**
318                  * Browser-based sessions use cookies for session authentication
319                  */
320                 if (!strncasecmp(buf, "Cookie: webcit=", 15)) {
321                         cookie_to_stuff(&buf[15], &desired_session,
322                                 NULL, 0, NULL, 0, NULL, 0);
323                         got_cookie = 1;
324                 }
325
326                 /**
327                  * GroupDAV-based sessions use HTTP authentication
328                  */
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);
333                 }
334
335                 if (!strncasecmp(buf, "If-Modified-Since: ", 19)) {
336                         if_modified_since = httpdate_to_timestamp(&buf[19]);
337                 }
338
339                 if (!strncasecmp(buf, "Accept-Language: ", 17)) {
340                         safestrncpy(accept_language, &buf[17], sizeof accept_language);
341                 }
342
343                 /**
344                  * Read in the request
345                  */
346                 hptr = (struct httprequest *)
347                         malloc(sizeof(struct httprequest));
348                 if (req == NULL)
349                         req = hptr;
350                 else
351                         last->next = hptr;
352                 hptr->next = NULL;
353                 last = hptr;
354
355                 safestrncpy(hptr->line, buf, sizeof hptr->line);
356
357         } while (!IsEmptyStr(buf));
358
359         /**
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.
363          */
364         
365         ptr = strstr(req->line, " /webcit ");   /*< Handle "/webcit" */
366         if (ptr != NULL) {
367                 strcpy(ptr+2, ptr+8);
368         }
369
370         ptr = strstr(req->line, " /webcit");    /*< Handle "/webcit/" */
371         if (ptr != NULL) {
372                 strcpy(ptr+1, ptr+8);
373         }
374
375         /** Begin parsing the request. */
376
377         safestrncpy(buf, req->line, sizeof buf);
378         lprintf(5, "HTTP: %s\n", buf);
379
380         /** Check for bogus requests */
381         if (is_bogus(buf)) {
382                 strcpy(req->line, "GET /404 HTTP/1.1");
383                 strcpy(buf, "GET /404 HTTP/1.1");
384         }
385
386         /**
387          * Strip out the method, leaving the URL up front...
388          */
389         remove_token(buf, 0, ' ');
390         if (buf[1]==' ') buf[1]=0;
391
392         /**
393          * While we're at it, gracefully handle requests for the
394          * robots.txt and favicon.ico files.
395          */
396         if (!strncasecmp(buf, "/robots.txt", 11)) {
397                 strcpy(req->line, "GET /static/robots.txt"
398                                 "?force_close_session=yes HTTP/1.1");
399         }
400         else if (!strncasecmp(buf, "/favicon.ico", 12)) {
401                 strcpy(req->line, "GET /static/favicon.ico");
402         }
403
404         /**
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.
409          */
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");
421         }
422
423         /**
424          * See if there's an existing session open with the desired ID or user/pass
425          */
426         TheSession = NULL;
427
428         if (TheSession == NULL) {
429                 pthread_mutex_lock(&SessionListMutex);
430                 for (sptr = SessionList; sptr != NULL; sptr = sptr->next) {
431
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)) ) {
436                                 TheSession = sptr;
437                         }
438
439                         /** If cookie-session, look for a session with matching session ID */
440                         if ( (desired_session != 0) && (sptr->wc_session == desired_session)) {
441                                 TheSession = sptr;
442                         }
443
444                 }
445                 pthread_mutex_unlock(&SessionListMutex);
446         }
447
448         /**
449          * Create a new session if we have to
450          */
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);
458         
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
463                  * to get created.
464                  */     
465                 if (desired_session == 0) {
466                         TheSession->wc_session = GenerateSessionID();
467                 }
468                 else {
469                         TheSession->wc_session = desired_session;
470                 }
471
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);
480                 session_is_new = 1;
481         }
482
483         /*
484          * A future improvement might be to check the session integrity
485          * at this point before continuing.
486          */
487
488         /*
489          * Bind to the session and perform the transaction
490          */
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;
496 #ifdef ENABLE_NLS
497         if (session_is_new) {
498                 httplang_to_locale(accept_language);
499         }
500         go_selected_language();                                 /* set locale */
501 #endif
502         session_loop(req);                                      /* do transaction */
503 #ifdef ENABLE_NLS
504         stop_selected_language();                               /* unset locale */
505 #endif
506         pthread_mutex_unlock(&TheSession->SessionMutex);        /* unbind */
507
508         /* Free the request buffer */
509         while (req != NULL) {
510                 hptr = req->next;
511                 free(req);
512                 req = hptr;
513         }
514
515         /*
516          * Free up any session-local substitution variables which
517          * were set during this transaction
518          */
519         clear_local_substs();
520 }