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