webcit_before_automake is now the trunk
[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
236         url = strstr(http_cmd, " ");
237         if (url == NULL) return(1);
238         ++url;
239
240         /** Worms and trojans and viruses, oh my! */
241         if (!strncasecmp(url, "/scripts/root.exe", 17)) return(2);
242         if (!strncasecmp(url, "/c/winnt", 8)) return(2);
243         if (!strncasecmp(url, "/MSADC/", 7)) return(2);
244
245         /** Broken Microsoft DAV implementation */
246         if (!strncasecmp(url, "/_vti", 5)) return(3);
247
248         return(0);      /* probably ok */
249 }
250
251
252
253 /**
254  * \brief handle one request
255  * This loop gets called once for every HTTP connection made to WebCit.  At
256  * this entry point we have an HTTP socket with a browser allegedly on the
257  * other end, but we have not yet bound to a WebCit session.
258  *
259  * The job of this function is to locate the correct session and bind to it,
260  * or create a session if necessary and bind to it, then run the WebCit
261  * transaction loop.  Afterwards, we unbind from the session.  When this
262  * function returns, the worker thread is then free to handle another
263  * transaction.
264  * \param sock the socket we will put our answer to
265  */
266 void context_loop(int sock)
267 {
268         struct httprequest *req = NULL;
269         struct httprequest *last = NULL;
270         struct httprequest *hptr;
271         char buf[SIZ], hold[SIZ];
272         int desired_session = 0;
273         int got_cookie = 0;
274         int gzip_ok = 0;
275         struct wcsession *TheSession, *sptr;
276         char httpauth_string[1024];
277         char httpauth_user[1024];
278         char httpauth_pass[1024];
279         char accept_language[256];
280         char *ptr = NULL;
281         int session_is_new = 0;
282
283         strcpy(httpauth_string, "");
284         strcpy(httpauth_user, DEFAULT_HTTPAUTH_USER);
285         strcpy(httpauth_pass, DEFAULT_HTTPAUTH_PASS);
286
287         /**
288          * Find out what it is that the web browser is asking for
289          */
290         memset(hold, 0, sizeof(hold));
291         do {
292                 if (req_gets(sock, buf, hold) < 0) return;
293
294                 /**
295                  * Can we compress?
296                  */
297                 if (!strncasecmp(buf, "Accept-encoding:", 16)) {
298                         if (strstr(&buf[16], "gzip")) {
299                                 gzip_ok = 1;
300                         }
301                 }
302
303                 /**
304                  * Browser-based sessions use cookies for session authentication
305                  */
306                 if (!strncasecmp(buf, "Cookie: webcit=", 15)) {
307                         cookie_to_stuff(&buf[15], &desired_session,
308                                 NULL, 0, NULL, 0, NULL, 0);
309                         got_cookie = 1;
310                 }
311
312                 /**
313                  * GroupDAV-based sessions use HTTP authentication
314                  */
315                 if (!strncasecmp(buf, "Authorization: Basic ", 21)) {
316                         CtdlDecodeBase64(httpauth_string, &buf[21], strlen(&buf[21]));
317                         extract_token(httpauth_user, httpauth_string, 0, ':', sizeof httpauth_user);
318                         extract_token(httpauth_pass, httpauth_string, 1, ':', sizeof httpauth_pass);
319                 }
320
321                 if (!strncasecmp(buf, "If-Modified-Since: ", 19)) {
322                         if_modified_since = httpdate_to_timestamp(&buf[19]);
323                 }
324
325                 if (!strncasecmp(buf, "Accept-Language: ", 17)) {
326                         safestrncpy(accept_language, &buf[17], sizeof accept_language);
327                 }
328
329                 /**
330                  * Read in the request
331                  */
332                 hptr = (struct httprequest *)
333                         malloc(sizeof(struct httprequest));
334                 if (req == NULL)
335                         req = hptr;
336                 else
337                         last->next = hptr;
338                 hptr->next = NULL;
339                 last = hptr;
340
341                 safestrncpy(hptr->line, buf, sizeof hptr->line);
342
343         } while (strlen(buf) > 0);
344
345         /**
346          * If the request is prefixed by "/webcit" then chop that off.  This
347          * allows a front end web server to forward all /webcit requests to us
348          * while still using the same web server port for other things.
349          */
350         
351         ptr = strstr(req->line, " /webcit ");   /*< Handle "/webcit" */
352         if (ptr != NULL) {
353                 strcpy(ptr+2, ptr+8);
354         }
355
356         ptr = strstr(req->line, " /webcit");    /*< Handle "/webcit/" */
357         if (ptr != NULL) {
358                 strcpy(ptr+1, ptr+8);
359         }
360
361         /** Begin parsing the request. */
362
363         safestrncpy(buf, req->line, sizeof buf);
364         lprintf(5, "HTTP: %s\n", buf);
365
366         /** Check for bogus requests */
367         if (is_bogus(buf)) {
368                 strcpy(req->line, "GET /404 HTTP/1.1");
369                 strcpy(buf, "GET /404 HTTP/1.1");
370         }
371
372         /**
373          * Strip out the method, leaving the URL up front...
374          */
375         remove_token(buf, 0, ' ');
376         if (buf[1]==' ') buf[1]=0;
377
378         /**
379          * While we're at it, gracefully handle requests for the
380          * robots.txt and favicon.ico files.
381          */
382         if (!strncasecmp(buf, "/robots.txt", 11)) {
383                 strcpy(req->line, "GET /static/robots.txt"
384                                 "?force_close_session=yes HTTP/1.1");
385         }
386         else if (!strncasecmp(buf, "/favicon.ico", 12)) {
387                 strcpy(req->line, "GET /static/favicon.ico");
388         }
389
390         /**
391          * These are the URL's which may be executed without a
392          * session cookie already set.  If it's not one of these,
393          * force the session to close because cookies are
394          * probably disabled on the client browser.
395          */
396         else if ( (strcmp(buf, "/"))
397                 && (strncasecmp(buf, "/listsub", 8))
398                 && (strncasecmp(buf, "/freebusy", 9))
399                 && (strncasecmp(buf, "/do_logout", 10))
400                 && (strncasecmp(buf, "/groupdav", 9))
401                 && (strncasecmp(buf, "/static", 7))
402                 && (strncasecmp(buf, "/rss", 4))
403                 && (strncasecmp(buf, "/404", 4))
404                 && (got_cookie == 0)) {
405                 strcpy(req->line, "GET /static/nocookies.html"
406                                 "?force_close_session=yes HTTP/1.1");
407         }
408
409         /**
410          * See if there's an existing session open with the desired ID or user/pass
411          */
412         TheSession = NULL;
413
414         if (TheSession == NULL) {
415                 pthread_mutex_lock(&SessionListMutex);
416                 for (sptr = SessionList; sptr != NULL; sptr = sptr->next) {
417
418                         /** If HTTP-AUTH, look for a session with matching credentials */
419                         if ( (strlen(httpauth_user) > 0)
420                            &&(!strcasecmp(sptr->httpauth_user, httpauth_user))
421                            &&(!strcasecmp(sptr->httpauth_pass, httpauth_pass)) ) {
422                                 TheSession = sptr;
423                         }
424
425                         /** If cookie-session, look for a session with matching session ID */
426                         if ( (desired_session != 0) && (sptr->wc_session == desired_session)) {
427                                 TheSession = sptr;
428                         }
429
430                 }
431                 pthread_mutex_unlock(&SessionListMutex);
432         }
433
434         /**
435          * Create a new session if we have to
436          */
437         if (TheSession == NULL) {
438                 lprintf(3, "Creating a new session\n");
439                 TheSession = (struct wcsession *)
440                         malloc(sizeof(struct wcsession));
441                 memset(TheSession, 0, sizeof(struct wcsession));
442                 TheSession->serv_sock = (-1);
443                 TheSession->chat_sock = (-1);
444                 TheSession->wc_session = GenerateSessionID();
445                 strcpy(TheSession->httpauth_user, httpauth_user);
446                 strcpy(TheSession->httpauth_pass, httpauth_pass);
447                 pthread_mutex_init(&TheSession->SessionMutex, NULL);
448                 pthread_mutex_lock(&SessionListMutex);
449                 TheSession->next = SessionList;
450                 SessionList = TheSession;
451                 pthread_mutex_unlock(&SessionListMutex);
452                 session_is_new = 1;
453         }
454
455         /**
456          * A future improvement might be to check the session integrity
457          * at this point before continuing.
458          */
459
460         /**
461          * Bind to the session and perform the transaction
462          */
463         pthread_mutex_lock(&TheSession->SessionMutex);          /*< bind */
464         pthread_setspecific(MyConKey, (void *)TheSession);
465         TheSession->http_sock = sock;
466         TheSession->lastreq = time(NULL);                       /*< log */
467         TheSession->gzip_ok = gzip_ok;
468 #ifdef ENABLE_NLS
469         if (session_is_new) {
470                 httplang_to_locale(accept_language);
471         }
472         go_selected_language();                         /*< set locale */
473 #endif
474         session_loop(req);                              /*< do transaction */
475 #ifdef ENABLE_NLS
476         stop_selected_language();                       /*< unset locale */
477 #endif
478         pthread_mutex_unlock(&TheSession->SessionMutex);        /*< unbind */
479
480         /** Free the request buffer */
481         while (req != NULL) {
482                 hptr = req->next;
483                 free(req);
484                 req = hptr;
485         }
486
487         /**
488          * Free up any session-local substitution variables which
489          * were set during this transaction
490          */
491         clear_local_substs();
492 }
493 /*@}*/