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