* context_loop.c: really fix the SO_LINGER stuff
[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 "webcit.h"
38 #include "webserver.h"
39
40 /*
41  * We keep one of these around for each active session
42  */
43 struct wc_session {
44         struct wc_session *next;        /* Next session in list */
45         int session_id;                 /* Session ID */
46         int inpipe[2];                  /* Data from webserver to session */
47         int outpipe[2];                 /* Data from session to webserver */
48         pthread_mutex_t critter;        /* Critical section uses pipes */
49         };
50
51 struct wc_session *SessionList = NULL;
52
53 /* Only one thread may manipulate SessionList at a time... */
54 pthread_mutex_t MasterCritter;
55
56 int GenerateSessionID(void) {
57         return getpid();
58         }
59
60
61 void gets0(int fd, char buf[]) {
62
63         buf[0] = 0;
64         do {
65                 buf[strlen(buf)+1] = 0;
66                 read(fd, &buf[strlen(buf)], 1);
67                 } while (buf[strlen(buf)-1] >= 32);
68         buf[strlen(buf)-1] = 0;
69         }
70
71 /*
72  * Collapse multiple cookies on one line
73  */
74 void req_gets(int sock, char *buf, char *hold) {
75         int a;
76
77         if (strlen(hold)==0) {
78                 client_gets(sock, buf);
79                 }
80         else {
81                 strcpy(buf, hold);
82                 }
83         strcpy(hold, "");
84
85         if (!strncasecmp(buf, "Cookie: ", 8)) {
86                 for (a=0; a<strlen(buf); ++a) if (buf[a]==';') {
87                         sprintf(hold, "Cookie: %s", &buf[a+1]);
88                         buf[a]=0;
89                         while (isspace(hold[8])) strcpy(&hold[8], &hold[9]);
90                         return;
91                         }
92                 }
93         }
94
95 /*
96  * Grab a lock on the session, so other threads don't try to access
97  * the pipes at the same time.
98  */
99 static void lock_session(struct wc_session *session) {
100         printf("Locking session %d...\n", session->session_id);
101         pthread_mutex_lock(&session->critter);
102         printf("   ...got lock\n");
103         }
104
105 /*
106  * Let go of the lock.
107  */
108 static void unlock_session(struct wc_session *session) {
109         printf("Unlocking.\n");
110         pthread_mutex_unlock(&session->critter);
111         }
112
113 /*
114  * lingering_close() a`la Apache. see
115  * http://www.apache.org/docs/misc/fin_wait_2.html for rationale
116  */
117
118 static int lingering_close(int fd) {
119         char buf[256];
120         int i;
121         fd_set set;
122         struct timeval tv, start;
123
124         gettimeofday(&start, NULL);
125         shutdown(fd, 1);
126         do {
127                 do {
128                         gettimeofday(&tv, NULL);
129                         tv.tv_sec = SLEEPING - (tv.tv_sec - start.tv_sec);
130                         tv.tv_usec = start.tv_usec - tv.tv_usec;
131                         if (tv.tv_usec < 0) {
132                                 tv.tv_sec--;
133                                 tv.tv_usec += 1000000;
134                                 }
135                                 
136                         FD_ZERO(&set);
137                         FD_SET(fd, &set);
138                         i = select(fd + 1, &set, NULL, NULL, &tv);
139                         } while (i == -1 && errno == EINTR);
140
141                 if (i <= 0)
142                         break;
143
144                 i = read(fd, buf, sizeof buf);
145                 } while (i != 0 && (i != -1 || errno == EINTR));
146
147         return close(fd);
148         }
149
150 extern const char *defaulthost;
151 extern const char *defaultport;
152
153 /*
154  * This loop gets called once for every HTTP connection made to WebCit.
155  */
156 void *context_loop(int sock) {
157         char (*req)[256];
158         char buf[256], hold[256];
159         int num_lines = 0;
160         int a;
161         int f;
162         int desired_session = 0;
163         char str_session[256];
164         struct wc_session *sptr;
165         struct wc_session *TheSession;
166         int ContentLength;
167         int CloseSession = 0;
168
169         if ((req = malloc((long)sizeof(char[256][256]))) == NULL) {
170                 sprintf(buf, "Can't malloc buffers; dropping connection.\n");
171                 fprintf(stderr, "%s", buf);
172                 write(sock, buf, strlen(buf));
173                 close (sock);
174                 pthread_exit(NULL);
175                 }
176
177         printf("Reading request from socket %d\n", sock);
178
179         /*
180          * Find out what it is that the web browser is asking for
181          */
182         ContentLength = 0;
183         do {
184                 req_gets(sock, buf, hold);
185                 if (!strncasecmp(buf, "Cookie: wc_session=", 19)) {
186                         desired_session = atoi(&buf[19]);
187                         }
188                 if (!strncasecmp(buf, "Content-length: ", 16)) {
189                         ContentLength = atoi(&buf[16]);
190                         }
191                 strcpy(&req[num_lines++][0], buf);
192                 } while(strlen(buf)>0);
193
194         /*
195          * See if there's an existing session open with the desired ID
196          */
197         TheSession = NULL;
198         if (desired_session != 0) {
199                 pthread_mutex_lock(&MasterCritter);
200                 for (sptr=SessionList; sptr!=NULL; sptr=sptr->next) {
201                         if (sptr->session_id == desired_session) {
202                                 TheSession = sptr;
203                                 lock_session(TheSession);
204                                 }
205                         }
206                 pthread_mutex_unlock(&MasterCritter);
207                 }
208
209         /*
210          * Create a new session if we have to
211          */
212         if (TheSession == NULL) {
213                 printf("Creating a new session\n");
214                 pthread_mutex_lock(&MasterCritter);
215                 TheSession = (struct wc_session *)
216                         malloc(sizeof(struct wc_session));
217                 TheSession->session_id = GenerateSessionID();
218                 pipe(TheSession->inpipe);
219                 pipe(TheSession->outpipe);
220                 pthread_mutex_init(&TheSession->critter, NULL);
221                 lock_session(TheSession);
222                 TheSession->next = SessionList;
223                 SessionList = TheSession;
224                 pthread_mutex_unlock(&MasterCritter);
225                 sprintf(str_session, "%d", TheSession->session_id);
226                 f = fork();
227                 fflush(stdout); fflush(stdin);
228                 if (f==0) {
229                         dup2(TheSession->inpipe[0], 0);
230                         dup2(TheSession->outpipe[1], 1);
231                         /* Close the ends of the pipes that we're not using */
232                         close(TheSession->inpipe[1]);
233                         close(TheSession->outpipe[0]);
234                         close(sock);
235                         execlp("./webcit", "webcit", str_session, defaulthost,
236                                defaultport, NULL);
237                         printf("HTTP/1.0 404 WebCit Failure\n\n");
238                         printf("Server: %s\n", SERVER);
239                         printf("Content-type: text/html\n");
240                         printf("Content-length: 76\n");
241                         printf("\n");
242                         printf("<HTML><HEAD><TITLE>Error</TITLE></HEAD>\n");
243                         printf("<BODY BACKGROUND=\"/image&name=background\" TEXT=\"#000000\" LINK=\"#004400\">execlp() failed</BODY></HTML>\n");
244                         exit(0);
245                         }
246                 /* Close the ends of the pipes that we're not using */
247                 close(TheSession->inpipe[0]);
248                 close(TheSession->outpipe[1]);
249                 }
250
251         /* 
252          * Send the request to the appropriate session...
253          */
254         printf("   Writing %d lines of command\n", num_lines);
255         printf("%s\n", &req[0][0]);
256         for (a=0; a<num_lines; ++a) {
257                 write(TheSession->inpipe[1], &req[a][0], strlen(&req[a][0]));
258                 write(TheSession->inpipe[1], "\n", 1);
259                 }
260         printf("   Writing %d bytes of content\n", ContentLength);
261         while (ContentLength > 0) {
262                 a = ContentLength;
263                 if (a > sizeof buf) a = sizeof buf;
264                 if (!client_read(sock, buf, a)) goto end;
265                 if (write(TheSession->inpipe[1], buf, a) != a) goto end;
266                 ContentLength -= a;
267                 }
268
269         /*
270          * ...and get the response.
271          */
272         printf("   Reading response\n");
273         ContentLength = 0;
274         do {
275                 gets0(TheSession->outpipe[0], buf);
276                 write(sock, buf, strlen(buf));
277                 write(sock, "\n", 1);
278                 if (!strncasecmp(buf, "Content-length: ", 16))
279                         ContentLength = atoi(&buf[16]);
280                 if (!strcasecmp(buf, "X-WebCit-Session: close")) {
281                         CloseSession = 1;
282                         }
283                 } while (strlen(buf) > 0);
284
285         printf("   Reading %d bytes of content\n", ContentLength);
286         while(ContentLength--) {
287                 read(TheSession->outpipe[0], buf, 1);
288                 write(sock, buf, 1);
289                 }
290
291         /*
292          * If the last response included a "close session" directive,
293          * remove the context now.
294          */
295         if (CloseSession) {
296                 printf("Removing session.\n");
297                 pthread_mutex_lock(&MasterCritter);
298
299                 if (SessionList==TheSession) {
300                         SessionList = SessionList->next;
301                         }
302                 else {
303                         for (sptr=SessionList; sptr!=NULL; sptr=sptr->next) {
304                                 if (sptr->next == TheSession) {
305                                         sptr->next = TheSession->next;
306                                         }
307                                 }
308                         }
309
310                 close(TheSession->inpipe[1]);
311                 close(TheSession->outpipe[0]);
312                 unlock_session(TheSession);
313                 free(TheSession);
314         
315                 pthread_mutex_unlock(&MasterCritter);
316                 }
317         else {
318         end:
319                 unlock_session(TheSession);
320                 }
321         free(req);
322
323
324         /*
325          * Now our HTTP connection is done.  It would be relatively easy
326          * to support HTTP/1.1 "persistent" connections by looping back to
327          * the top of this function.  For now, we'll just close.
328          */
329         printf("   Closing socket %d ... ret=%d\n", sock,
330                lingering_close(sock));
331
332         /*
333          * The thread handling this HTTP connection is now finished.
334          */
335         pthread_exit(NULL);
336         }