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