e979beeb8b17a9fe911df0f8b86b4183c19a06c9
[citadel.git] / webcit / context_loop.c
1 /*
2  * context_loop.c
3  *
4  * This is the other half of the webserver.  It handles the task of hooking
5  * up HTTP requests with the sessions they belong to, using HTTP cookies to
6  * keep track of things.  If the HTTP request doesn't belong to any currently
7  * active session, a new session is started.
8  *
9  * $Id$
10  */
11
12 #include <ctype.h>
13 #include <stdlib.h>
14 #ifdef HAVE_UNISTD_H
15 #include <unistd.h>
16 #endif
17 #include <stdio.h>
18 #ifdef HAVE_FCNTL_H
19 #include <fcntl.h>
20 #endif
21 #include <signal.h>
22 #include <sys/types.h>
23 #include <sys/wait.h>
24 #include <sys/socket.h>
25 #ifdef HAVE_SYS_TIME_H
26 #include <sys/time.h>
27 #endif
28 #ifdef HAVE_LIMITS_H
29 #include <limits.h>
30 #endif
31 #include <netinet/in.h>
32 #include <netdb.h>
33 #include <string.h>
34 #include <errno.h>
35 #include <stdarg.h>
36 #include <pthread.h>
37 #include <signal.h>
38 #include "webcit.h"
39 #include "webserver.h"
40
41 /* Only one thread may manipulate SessionList at a time... */
42 pthread_mutex_t SessionListMutex;
43
44 struct wcsession *SessionList = NULL;
45
46 pthread_key_t MyConKey;                         /* TSD key for MySession() */
47
48 void do_housekeeping(void)
49 {
50         struct wcsession *sptr, *ss, *session_to_kill;
51
52         do {
53                 session_to_kill = NULL;
54                 pthread_mutex_lock(&SessionListMutex);
55                 for (sptr = SessionList; sptr != NULL; sptr = sptr->next) {
56
57                         /* Kill idle sessions */
58                         if ((time(NULL) - (sptr->lastreq)) >
59                            (time_t) WEBCIT_TIMEOUT) {
60                                 sptr->killthis = 1;
61                         }
62
63                         /* Remove sessions flagged for kill */
64                         if (sptr->killthis) {
65
66                                 /* remove session from linked list */
67                                 if (sptr == SessionList) {
68                                         SessionList = SessionList->next;
69                                 }
70                                 else for (ss=SessionList;ss!=NULL;ss=ss->next) {
71                                         if (ss->next == sptr) {
72                                                 ss->next = ss->next->next;
73                                         }
74                                 }
75
76                                 session_to_kill = sptr;
77                                 goto BREAKOUT;
78                         }
79                 }
80 BREAKOUT:       pthread_mutex_unlock(&SessionListMutex);
81
82                 if (session_to_kill != NULL) {
83                         pthread_mutex_lock(&session_to_kill->SessionMutex);
84                         close(session_to_kill->serv_sock);
85                         if (session_to_kill->preferences != NULL) {
86                                 free(session_to_kill->preferences);
87                         }
88                         pthread_mutex_unlock(&session_to_kill->SessionMutex);
89                         free(session_to_kill);
90                 }
91
92         } while (session_to_kill != NULL);
93 }
94
95
96 /* 
97  * Wake up occasionally and clean house
98  */
99 void housekeeping_loop(void)
100 {
101         while (1) {
102                 sleep(HOUSEKEEPING);
103                 do_housekeeping();
104         }
105 }
106
107
108 /*
109  * Generate a unique WebCit session ID (which is not the same thing as the
110  * Citadel session ID).
111  *
112  * FIX ... ensure that session number is truly unique
113  *
114  */
115 int GenerateSessionID(void)
116 {
117         static int seq = (-1);
118
119         if (seq < 0) {
120                 seq = (int) time(NULL);
121         }
122                 
123         return ++seq;
124 }
125
126
127 /*
128  * Collapse multiple cookies on one line
129  */
130 int req_gets(int sock, char *buf, char *hold)
131 {
132         int a;
133
134         if (strlen(hold) == 0) {
135                 strcpy(buf, "");
136                 a = client_gets(sock, buf);
137                 if (a<1) return(-1);
138         } else {
139                 strcpy(buf, hold);
140         }
141         strcpy(hold, "");
142
143         if (!strncasecmp(buf, "Cookie: ", 8)) {
144                 for (a = 0; a < strlen(buf); ++a)
145                         if (buf[a] == ';') {
146                                 sprintf(hold, "Cookie: %s", &buf[a + 1]);
147                                 buf[a] = 0;
148                                 while (isspace(hold[8]))
149                                         strcpy(&hold[8], &hold[9]);
150                                 return(0);
151                         }
152         }
153         return(0);
154 }
155
156 /*
157  * lingering_close() a`la Apache. see
158  * http://www.apache.org/docs/misc/fin_wait_2.html for rationale
159  */
160
161 int lingering_close(int fd)
162 {
163         char buf[SIZ];
164         int i;
165         fd_set set;
166         struct timeval tv, start;
167
168         gettimeofday(&start, NULL);
169         shutdown(fd, 1);
170         do {
171                 do {
172                         gettimeofday(&tv, NULL);
173                         tv.tv_sec = SLEEPING - (tv.tv_sec - start.tv_sec);
174                         tv.tv_usec = start.tv_usec - tv.tv_usec;
175                         if (tv.tv_usec < 0) {
176                                 tv.tv_sec--;
177                                 tv.tv_usec += 1000000;
178                         }
179                         FD_ZERO(&set);
180                         FD_SET(fd, &set);
181                         i = select(fd + 1, &set, NULL, NULL, &tv);
182                 } while (i == -1 && errno == EINTR);
183
184                 if (i <= 0)
185                         break;
186
187                 i = read(fd, buf, sizeof buf);
188         } while (i != 0 && (i != -1 || errno == EINTR));
189
190         return close(fd);
191 }
192
193
194
195 /*
196  * Check for bogus requests coming from (for example) brain-dead
197  * Windoze boxes that are infected with the latest worm-of-the-week.
198  * If we detect one of these, bail out without bothering our Citadel
199  * server.
200  */
201 int is_bogus(char *http_cmd) {
202
203         if (!strncasecmp(http_cmd, "GET /scripts/root.exe", 21)) return(1);
204         if (!strncasecmp(http_cmd, "GET /c/winnt", 12)) return(2);
205         if (!strncasecmp(http_cmd, "GET /MSADC/", 11)) return(3);
206
207         return(0);      /* probably ok */
208 }
209
210
211
212 /*
213  * This loop gets called once for every HTTP connection made to WebCit.  At
214  * this entry point we have an HTTP socket with a browser allegedly on the
215  * other end, but we have not yet bound to a WebCit session.
216  *
217  * The job of this function is to locate the correct session and bind to it,
218  * or create a session if necessary and bind to it, then run the WebCit
219  * transaction loop.  Afterwards, we unbind from the session.  When this
220  * function returns, the worker thread is then free to handle another
221  * transaction.
222  */
223 void context_loop(int sock)
224 {
225         struct httprequest *req = NULL;
226         struct httprequest *last = NULL;
227         struct httprequest *hptr;
228         char buf[SIZ], hold[SIZ];
229         int desired_session = 0;
230         int got_cookie = 0;
231         struct wcsession *TheSession, *sptr;
232
233         /*
234          * Find out what it is that the web browser is asking for
235          */
236         memset(hold, 0, sizeof(hold));
237         do {
238                 if (req_gets(sock, buf, hold) < 0) return;
239                 if (!strncasecmp(buf, "Cookie: webcit=", 15)) {
240                         cookie_to_stuff(&buf[15], &desired_session,
241                                 NULL, NULL, NULL);
242                         got_cookie = 1;
243                 }
244
245                 hptr = (struct httprequest *)
246                         malloc(sizeof(struct httprequest));
247                 if (req == NULL)
248                         req = hptr;
249                 else
250                         last->next = hptr;
251                 hptr->next = NULL;
252                 last = hptr;
253
254                 strcpy(hptr->line, buf);
255
256         } while (strlen(buf) > 0);
257
258         strcpy(buf, req->line);
259         lprintf(5, "HTTP: %s\n", buf);
260
261         /* Check for bogus requests */
262         if (is_bogus(buf)) goto bail;
263
264         /*
265          * If requesting a non-root page, there should already be a cookie
266          * set.  If there isn't, the client browser has cookies turned off
267          * (or doesn't support them) and we have to barf & bail.
268          */
269         if (!strncasecmp(buf, "GET ", 4)) strcpy(buf, &buf[4]);
270         else if (!strncasecmp(buf, "HEAD ", 5)) strcpy(buf, &buf[5]);
271         if (buf[1]==' ') buf[1]=0;
272
273         /*
274          * While we're at it, gracefully handle requests for the
275          * robots.txt file...
276          */
277         if (!strncasecmp(buf, "/robots.txt", 11)) {
278                 strcpy(req->line, "GET /static/robots.txt"
279                                 "?force_close_session=yes HTTP/1.0");
280         }
281
282         /* Do the non-root-cookie check now. */
283         else if ( (strcmp(buf, "/")) && (got_cookie == 0)) {
284                 strcpy(req->line, "GET /static/nocookies.html"
285                                 "?force_close_session=yes HTTP/1.0");
286         }
287
288
289         /*
290          * See if there's an existing session open with the desired ID
291          */
292         TheSession = NULL;
293         if (desired_session != 0) {
294                 pthread_mutex_lock(&SessionListMutex);
295                 for (sptr = SessionList; sptr != NULL; sptr = sptr->next) {
296                         if (sptr->wc_session == desired_session) {
297                                 TheSession = sptr;
298                         }
299                 }
300                 pthread_mutex_unlock(&SessionListMutex);
301         }
302
303         /*
304          * Create a new session if we have to
305          */
306         if (TheSession == NULL) {
307                 lprintf(3, "Creating a new session\n");
308                 TheSession = (struct wcsession *)
309                         malloc(sizeof(struct wcsession));
310                 memset(TheSession, 0, sizeof(struct wcsession));
311                 TheSession->wc_session = GenerateSessionID();
312                 pthread_mutex_init(&TheSession->SessionMutex, NULL);
313
314                 pthread_mutex_lock(&SessionListMutex);
315                 TheSession->next = SessionList;
316                 SessionList = TheSession;
317                 pthread_mutex_unlock(&SessionListMutex);
318         }
319
320
321         /*
322          *
323          * FIX ... check session integrity here before continuing
324          *
325          */
326
327
328         /*
329          * Bind to the session and perform the transaction
330          */
331         pthread_mutex_lock(&TheSession->SessionMutex);          /* bind */
332         pthread_setspecific(MyConKey, (void *)TheSession);
333         TheSession->http_sock = sock;
334         TheSession->lastreq = time(NULL);                       /* log */
335         session_loop(req);              /* perform the requested transaction */
336         pthread_mutex_unlock(&TheSession->SessionMutex);        /* unbind */
337
338         /* Free the request buffer */
339 bail:   while (req != NULL) {
340                 hptr = req->next;
341                 free(req);
342                 req = hptr;
343         }
344 }