* migrated to new hash create signature
[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                 DeleteHash(&(sessions_to_kill->hash_prefs));
105                 
106                 pthread_mutex_unlock(&sessions_to_kill->SessionMutex);
107                 sptr = sessions_to_kill->next;
108                 free(sessions_to_kill);
109                 sessions_to_kill = sptr;
110                 --num_sessions;
111         }
112
113         /**
114          * If there are more sessions than threads, then we should spawn
115          * more threads ... up to a predefined maximum.
116          */
117         while ( (num_sessions > num_threads)
118               && (num_threads <= MAX_WORKER_THREADS) ) {
119                 spawn_another_worker_thread();
120                 ++num_threads;
121                 lprintf(3, "There are %d sessions and %d threads active.\n",
122                         num_sessions, num_threads);
123         }
124 }
125
126
127 /**
128  * \brief Wake up occasionally and clean house
129  */
130 void housekeeping_loop(void)
131 {
132         while (1) {
133                 sleeeeeeeeeep(HOUSEKEEPING);
134                 do_housekeeping();
135         }
136 }
137
138
139 /**
140  * \brief Create a Session id
141  * Generate a unique WebCit session ID (which is not the same thing as the
142  * Citadel session ID).
143  *
144  * \todo FIXME ... ensure that session number is truly unique
145  *
146  */
147 int GenerateSessionID(void)
148 {
149         static int seq = (-1);
150
151         if (seq < 0) {
152                 seq = (int) time(NULL);
153         }
154                 
155         return ++seq;
156 }
157
158
159 /*
160  * Collapse multiple cookies on one line
161  */
162 int req_gets(int sock, char *buf, char *hold, size_t hlen)
163 {
164         int a, b;
165
166         if (IsEmptyStr(hold)) {
167                 strcpy(buf, "");
168                 a = client_getln(sock, buf, SIZ);
169                 if (a<1) return(-1);
170         } else {
171                 safestrncpy(buf, hold, SIZ);
172         }
173         strcpy(hold, "");
174
175         if (!strncasecmp(buf, "Cookie: ", 8)) {
176                 int len;
177                 len = strlen(buf);
178                 for (a = 0; a < len; ++a)
179                         if (buf[a] == ';') {
180                                 // we don't refresh len, because of we 
181                                 // only exit from here.
182                                 snprintf(hold, hlen, "Cookie: %s", &buf[a + 1]);
183                                 buf[a] = 0;
184                                 b = 8;
185                                 while (isspace(hold[b]))
186                                         b++;
187                                 
188                                 memmove(&hold[8], &hold[b], len - b + 1);
189                                 return(0);
190                         }
191         }
192
193         return(0);
194 }
195
196 /*
197  * lingering_close() a`la Apache. see
198  * http://www.apache.org/docs/misc/fin_wait_2.html for rationale
199  */
200 int lingering_close(int fd)
201 {
202         char buf[SIZ];
203         int i;
204         fd_set set;
205         struct timeval tv, start;
206
207         gettimeofday(&start, NULL);
208         shutdown(fd, 1);
209         do {
210                 do {
211                         gettimeofday(&tv, NULL);
212                         tv.tv_sec = SLEEPING - (tv.tv_sec - start.tv_sec);
213                         tv.tv_usec = start.tv_usec - tv.tv_usec;
214                         if (tv.tv_usec < 0) {
215                                 tv.tv_sec--;
216                                 tv.tv_usec += 1000000;
217                         }
218                         FD_ZERO(&set);
219                         FD_SET(fd, &set);
220                         i = select(fd + 1, &set, NULL, NULL, &tv);
221                 } while (i == -1 && errno == EINTR);
222
223                 if (i <= 0)
224                         break;
225
226                 i = read(fd, buf, sizeof buf);
227         } while (i != 0 && (i != -1 || errno == EINTR));
228
229         return close(fd);
230 }
231
232
233
234 /**
235  * \brief       sanity requests
236  *              Check for bogus requests coming from brain-dead Windows boxes.
237  *
238  * \param       http_cmd        The HTTP request to check
239  */
240 int is_bogus(char *http_cmd) {
241         char *url;
242         int i, max;
243
244         url = strstr(http_cmd, " ");
245         if (url == NULL) return(1);
246         ++url;
247
248         char *bogus_prefixes[] = {
249                 "/scripts/root.exe",    /**< Worms and trojans and viruses, oh my! */
250                 "/c/winnt",
251                 "/MSADC/",
252                 "/_vti",                /**< Broken Microsoft DAV implementation */
253                 "/MSOffice"             /**< Stoopid MSOffice thinks everyone is IIS */
254         };
255
256         max = sizeof(bogus_prefixes) / sizeof(char *);
257
258         for (i=0; i<max; ++i) {
259                 if (!strncasecmp(url, bogus_prefixes[i], strlen(bogus_prefixes[i]))) {
260                         return(2);
261                 }
262         }
263
264         return(0);      /* probably ok */
265 }
266
267
268
269 /**
270  * \brief handle one request
271  * This loop gets called once for every HTTP connection made to WebCit.  At
272  * this entry point we have an HTTP socket with a browser allegedly on the
273  * other end, but we have not yet bound to a WebCit session.
274  *
275  * The job of this function is to locate the correct session and bind to it,
276  * or create a session if necessary and bind to it, then run the WebCit
277  * transaction loop.  Afterwards, we unbind from the session.  When this
278  * function returns, the worker thread is then free to handle another
279  * transaction.
280  * \param sock the socket we will put our answer to
281  */
282 void context_loop(int sock)
283 {
284         struct httprequest *req = NULL;
285         struct httprequest *last = NULL;
286         struct httprequest *hptr;
287         char buf[SIZ], hold[SIZ];
288         int desired_session = 0;
289         int got_cookie = 0;
290         int gzip_ok = 0;
291         struct wcsession *TheSession, *sptr;
292         char httpauth_string[1024];
293         char httpauth_user[1024];
294         char httpauth_pass[1024];
295         char accept_language[256];
296         char *ptr = NULL;
297         int session_is_new = 0;
298
299         strcpy(httpauth_string, "");
300         strcpy(httpauth_user, DEFAULT_HTTPAUTH_USER);
301         strcpy(httpauth_pass, DEFAULT_HTTPAUTH_PASS);
302
303         /**
304          * Find out what it is that the web browser is asking for
305          */
306         memset(hold, 0, sizeof(hold));
307         do {
308                 if (req_gets(sock, buf, hold, SIZ) < 0) return;
309
310                 /**
311                  * Can we compress?
312                  */
313                 if (!strncasecmp(buf, "Accept-encoding:", 16)) {
314                         if (strstr(&buf[16], "gzip")) {
315                                 gzip_ok = 1;
316                         }
317                 }
318
319                 /**
320                  * Browser-based sessions use cookies for session authentication
321                  */
322                 if (!strncasecmp(buf, "Cookie: webcit=", 15)) {
323                         cookie_to_stuff(&buf[15], &desired_session,
324                                 NULL, 0, NULL, 0, NULL, 0);
325                         got_cookie = 1;
326                 }
327
328                 /**
329                  * GroupDAV-based sessions use HTTP authentication
330                  */
331                 if (!strncasecmp(buf, "Authorization: Basic ", 21)) {
332                         CtdlDecodeBase64(httpauth_string, &buf[21], strlen(&buf[21]));
333                         extract_token(httpauth_user, httpauth_string, 0, ':', sizeof httpauth_user);
334                         extract_token(httpauth_pass, httpauth_string, 1, ':', sizeof httpauth_pass);
335                 }
336
337                 if (!strncasecmp(buf, "If-Modified-Since: ", 19)) {
338                         if_modified_since = httpdate_to_timestamp(&buf[19]);
339                 }
340
341                 if (!strncasecmp(buf, "Accept-Language: ", 17)) {
342                         safestrncpy(accept_language, &buf[17], sizeof accept_language);
343                 }
344
345                 /**
346                  * Read in the request
347                  */
348                 hptr = (struct httprequest *)
349                         malloc(sizeof(struct httprequest));
350                 if (req == NULL)
351                         req = hptr;
352                 else
353                         last->next = hptr;
354                 hptr->next = NULL;
355                 last = hptr;
356
357                 safestrncpy(hptr->line, buf, sizeof hptr->line);
358
359         } while (!IsEmptyStr(buf));
360
361         /**
362          * If the request is prefixed by "/webcit" then chop that off.  This
363          * allows a front end web server to forward all /webcit requests to us
364          * while still using the same web server port for other things.
365          */
366         
367         ptr = strstr(req->line, " /webcit ");   /*< Handle "/webcit" */
368         if (ptr != NULL) {
369                 strcpy(ptr+2, ptr+8);
370         }
371
372         ptr = strstr(req->line, " /webcit");    /*< Handle "/webcit/" */
373         if (ptr != NULL) {
374                 strcpy(ptr+1, ptr+8);
375         }
376
377         /** Begin parsing the request. */
378
379         safestrncpy(buf, req->line, sizeof buf);
380         lprintf(5, "HTTP: %s\n", buf);
381
382         /** Check for bogus requests */
383         if (is_bogus(buf)) {
384                 strcpy(req->line, "GET /404 HTTP/1.1");
385                 strcpy(buf, "GET /404 HTTP/1.1");
386         }
387
388         /**
389          * Strip out the method, leaving the URL up front...
390          */
391         remove_token(buf, 0, ' ');
392         if (buf[1]==' ') buf[1]=0;
393
394         /**
395          * While we're at it, gracefully handle requests for the
396          * robots.txt and favicon.ico files.
397          */
398         if (!strncasecmp(buf, "/robots.txt", 11)) {
399                 strcpy(req->line, "GET /static/robots.txt"
400                                 "?force_close_session=yes HTTP/1.1");
401         }
402         else if (!strncasecmp(buf, "/favicon.ico", 12)) {
403                 strcpy(req->line, "GET /static/favicon.ico");
404         }
405
406         /**
407          * These are the URL's which may be executed without a
408          * session cookie already set.  If it's not one of these,
409          * force the session to close because cookies are
410          * probably disabled on the client browser.
411          */
412         else if ( (strcmp(buf, "/"))
413                 && (strncasecmp(buf, "/listsub", 8))
414                 && (strncasecmp(buf, "/freebusy", 9))
415                 && (strncasecmp(buf, "/do_logout", 10))
416                 && (strncasecmp(buf, "/groupdav", 9))
417                 && (strncasecmp(buf, "/static", 7))
418                 && (strncasecmp(buf, "/rss", 4))
419                 && (strncasecmp(buf, "/404", 4))
420                 && (got_cookie == 0)) {
421                 strcpy(req->line, "GET /static/nocookies.html"
422                                 "?force_close_session=yes HTTP/1.1");
423         }
424
425         /**
426          * See if there's an existing session open with the desired ID or user/pass
427          */
428         TheSession = NULL;
429
430         if (TheSession == NULL) {
431                 pthread_mutex_lock(&SessionListMutex);
432                 for (sptr = SessionList; sptr != NULL; sptr = sptr->next) {
433
434                         /** If HTTP-AUTH, look for a session with matching credentials */
435                         if ( (!IsEmptyStr(httpauth_user))
436                            &&(!strcasecmp(sptr->httpauth_user, httpauth_user))
437                            &&(!strcasecmp(sptr->httpauth_pass, httpauth_pass)) ) {
438                                 TheSession = sptr;
439                         }
440
441                         /** If cookie-session, look for a session with matching session ID */
442                         if ( (desired_session != 0) && (sptr->wc_session == desired_session)) {
443                                 TheSession = sptr;
444                         }
445
446                 }
447                 pthread_mutex_unlock(&SessionListMutex);
448         }
449
450         /**
451          * Create a new session if we have to
452          */
453         if (TheSession == NULL) {
454                 lprintf(3, "Creating a new session\n");
455                 TheSession = (struct wcsession *)
456                         malloc(sizeof(struct wcsession));
457                 memset(TheSession, 0, sizeof(struct wcsession));
458                 TheSession->serv_sock = (-1);
459                 TheSession->chat_sock = (-1);
460         
461                 /* If we're recreating a session that expired, it's best to give it the same
462                  * session number that it had before.  The client browser ought to pick up
463                  * the new session number and start using it, but in some rare situations it
464                  * doesn't, and that's a Bad Thing because it causes lots of spurious sessions
465                  * to get created.
466                  */     
467                 if (desired_session == 0) {
468                         TheSession->wc_session = GenerateSessionID();
469                 }
470                 else {
471                         TheSession->wc_session = desired_session;
472                 }
473
474                 strcpy(TheSession->httpauth_user, httpauth_user);
475                 strcpy(TheSession->httpauth_pass, httpauth_pass);
476                 TheSession->hash_prefs = NewHash(1,NULL);       /* Get a hash table for the user preferences */
477                 pthread_mutex_init(&TheSession->SessionMutex, NULL);
478                 pthread_mutex_lock(&SessionListMutex);
479                 TheSession->nonce = rand();
480                 TheSession->next = SessionList;
481                 SessionList = TheSession;
482                 pthread_mutex_unlock(&SessionListMutex);
483                 session_is_new = 1;
484         }
485
486         /*
487          * A future improvement might be to check the session integrity
488          * at this point before continuing.
489          */
490
491         /*
492          * Bind to the session and perform the transaction
493          */
494         pthread_mutex_lock(&TheSession->SessionMutex);          /* bind */
495         pthread_setspecific(MyConKey, (void *)TheSession);
496         TheSession->http_sock = sock;
497         TheSession->lastreq = time(NULL);                       /* log */
498         TheSession->gzip_ok = gzip_ok;
499 #ifdef ENABLE_NLS
500         if (session_is_new) {
501                 httplang_to_locale(accept_language);
502         }
503         go_selected_language();                                 /* set locale */
504 #endif
505         session_loop(req);                                      /* do transaction */
506 #ifdef ENABLE_NLS
507         stop_selected_language();                               /* unset locale */
508 #endif
509         pthread_mutex_unlock(&TheSession->SessionMutex);        /* unbind */
510
511         /* Free the request buffer */
512         while (req != NULL) {
513                 hptr = req->next;
514                 free(req);
515                 req = hptr;
516         }
517
518         /*
519          * Free up any session-local substitution variables which
520          * were set during this transaction
521          */
522         clear_local_substs();
523 }