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