* Brought over the newer string tokenizer from Citadel
[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                         pthread_mutex_unlock(&session_to_kill->SessionMutex);
86                         free(session_to_kill);
87                 }
88
89         } while (session_to_kill != NULL);
90 }
91
92
93 /* 
94  * Wake up occasionally and clean house
95  */
96 void housekeeping_loop(void)
97 {
98         while (1) {
99                 sleep(HOUSEKEEPING);
100                 do_housekeeping();
101         }
102 }
103
104
105 /*
106  * Generate a unique WebCit session ID (which is not the same thing as the
107  * Citadel session ID).
108  *
109  * FIX ... ensure that session number is truly unique
110  *
111  */
112 int GenerateSessionID(void)
113 {
114         static int seq = (-1);
115
116         if (seq < 0) {
117                 seq = (int) time(NULL);
118         }
119                 
120         return ++seq;
121 }
122
123
124 /*
125  * Collapse multiple cookies on one line
126  */
127 int req_gets(int sock, char *buf, char *hold)
128 {
129         int a;
130
131         if (strlen(hold) == 0) {
132                 strcpy(buf, "");
133                 a = client_gets(sock, buf);
134                 if (a<1) return(-1);
135         } else {
136                 strcpy(buf, hold);
137         }
138         strcpy(hold, "");
139
140         if (!strncasecmp(buf, "Cookie: ", 8)) {
141                 for (a = 0; a < strlen(buf); ++a)
142                         if (buf[a] == ';') {
143                                 sprintf(hold, "Cookie: %s", &buf[a + 1]);
144                                 buf[a] = 0;
145                                 while (isspace(hold[8]))
146                                         strcpy(&hold[8], &hold[9]);
147                                 return(0);
148                         }
149         }
150         return(0);
151 }
152
153 /*
154  * lingering_close() a`la Apache. see
155  * http://www.apache.org/docs/misc/fin_wait_2.html for rationale
156  */
157
158 int lingering_close(int fd)
159 {
160         char buf[SIZ];
161         int i;
162         fd_set set;
163         struct timeval tv, start;
164
165         gettimeofday(&start, NULL);
166         shutdown(fd, 1);
167         do {
168                 do {
169                         gettimeofday(&tv, NULL);
170                         tv.tv_sec = SLEEPING - (tv.tv_sec - start.tv_sec);
171                         tv.tv_usec = start.tv_usec - tv.tv_usec;
172                         if (tv.tv_usec < 0) {
173                                 tv.tv_sec--;
174                                 tv.tv_usec += 1000000;
175                         }
176                         FD_ZERO(&set);
177                         FD_SET(fd, &set);
178                         i = select(fd + 1, &set, NULL, NULL, &tv);
179                 } while (i == -1 && errno == EINTR);
180
181                 if (i <= 0)
182                         break;
183
184                 i = read(fd, buf, sizeof buf);
185         } while (i != 0 && (i != -1 || errno == EINTR));
186
187         return close(fd);
188 }
189
190
191
192 /*
193  * Check for bogus requests coming from (for example) brain-dead
194  * Windoze boxes that are infected with the latest worm-of-the-week.
195  * If we detect one of these, bail out without bothering our Citadel
196  * server.
197  */
198 int is_bogus(char *http_cmd) {
199
200         if (!strncasecmp(http_cmd, "GET /scripts/root.exe", 21)) return(1);
201         if (!strncasecmp(http_cmd, "GET /c/winnt", 12)) return(2);
202         if (!strncasecmp(http_cmd, "GET /MSADC/", 11)) return(3);
203
204         return(0);      /* probably ok */
205 }
206
207
208
209 /*
210  * This loop gets called once for every HTTP connection made to WebCit.  At
211  * this entry point we have an HTTP socket with a browser allegedly on the
212  * other end, but we have not yet bound to a WebCit session.
213  *
214  * The job of this function is to locate the correct session and bind to it,
215  * or create a session if necessary and bind to it, then run the WebCit
216  * transaction loop.  Afterwards, we unbind from the session.  When this
217  * function returns, the worker thread is then free to handle another
218  * transaction.
219  */
220 void context_loop(int sock)
221 {
222         struct httprequest *req = NULL;
223         struct httprequest *last = NULL;
224         struct httprequest *hptr;
225         char buf[SIZ], hold[SIZ];
226         int desired_session = 0;
227         int got_cookie = 0;
228         struct wcsession *TheSession, *sptr;
229
230         /*
231          * Find out what it is that the web browser is asking for
232          */
233         memset(hold, 0, sizeof(hold));
234         do {
235                 if (req_gets(sock, buf, hold) < 0) return;
236                 if (!strncasecmp(buf, "Cookie: webcit=", 15)) {
237                         cookie_to_stuff(&buf[15], &desired_session,
238                                 NULL, NULL, NULL);
239                         got_cookie = 1;
240                 }
241
242                 hptr = (struct httprequest *)
243                         malloc(sizeof(struct httprequest));
244                 if (req == NULL)
245                         req = hptr;
246                 else
247                         last->next = hptr;
248                 hptr->next = NULL;
249                 last = hptr;
250
251                 strcpy(hptr->line, buf);
252
253         } while (strlen(buf) > 0);
254
255         strcpy(buf, req->line);
256         fprintf(stderr, "%s\n", buf);
257
258         /* Check for bogus requests */
259         if (is_bogus(buf)) goto bail;
260
261         /*
262          * If requesting a non-root page, there should already be a cookie
263          * set.  If there isn't, the client browser has cookies turned off
264          * (or doesn't support them) and we have to barf & bail.
265          */
266         if (!strncasecmp(buf, "GET ", 4)) strcpy(buf, &buf[4]);
267         else if (!strncasecmp(buf, "HEAD ", 5)) strcpy(buf, &buf[5]);
268         if (buf[1]==' ') buf[1]=0;
269
270         /*
271          * While we're at it, gracefully handle requests for the
272          * robots.txt file...
273          */
274         if (!strncasecmp(buf, "/robots.txt", 11)) {
275                 strcpy(req->line, "GET /static/robots.txt"
276                                 "?force_close_session=yes HTTP/1.0");
277         }
278
279         /* Do the non-root-cookie check now. */
280         else if ( (strcmp(buf, "/")) && (got_cookie == 0)) {
281                 strcpy(req->line, "GET /static/nocookies.html"
282                                 "?force_close_session=yes HTTP/1.0");
283         }
284
285
286
287         /*
288          * See if there's an existing session open with the desired ID
289          */
290         TheSession = NULL;
291         if (desired_session != 0) {
292                 pthread_mutex_lock(&SessionListMutex);
293                 for (sptr = SessionList; sptr != NULL; sptr = sptr->next) {
294                         if (sptr->wc_session == desired_session) {
295                                 TheSession = sptr;
296                         }
297                 }
298                 pthread_mutex_unlock(&SessionListMutex);
299         }
300
301         /*
302          * Create a new session if we have to
303          */
304         if (TheSession == NULL) {
305                 fprintf(stderr, "Creating a new session\n");
306                 TheSession = (struct wcsession *)
307                         malloc(sizeof(struct wcsession));
308                 memset(TheSession, 0, sizeof(struct wcsession));
309                 TheSession->wc_session = GenerateSessionID();
310                 pthread_mutex_init(&TheSession->SessionMutex, NULL);
311
312                 pthread_mutex_lock(&SessionListMutex);
313                 TheSession->next = SessionList;
314                 SessionList = TheSession;
315                 pthread_mutex_unlock(&SessionListMutex);
316         }
317
318
319         /*
320          *
321          * FIX ... check session integrity here before continuing
322          *
323          */
324
325
326         /*
327          * Bind to the session and perform the transaction
328          */
329         pthread_mutex_lock(&TheSession->SessionMutex);          /* bind */
330         pthread_setspecific(MyConKey, (void *)TheSession);
331         TheSession->http_sock = sock;
332         TheSession->lastreq = time(NULL);                       /* log */
333         session_loop(req);              /* perform the requested transaction */
334         pthread_mutex_unlock(&TheSession->SessionMutex);        /* unbind */
335
336         /* Free the request buffer */
337 bail:   while (req != NULL) {
338                 hptr = req->next;
339                 free(req);
340                 req = hptr;
341         }
342 }