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