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