cda7e9a37ed485a7cdfb3028b9e372cc1afdbd89
[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 <stdlib.h>
13 #include <unistd.h>
14 #include <stdio.h>
15 #include <fcntl.h>
16 #include <signal.h>
17 #include <sys/types.h>
18 #include <sys/wait.h>
19 #include <sys/socket.h>
20 #include <sys/time.h>
21 #include <limits.h>
22 #include <netinet/in.h>
23 #include <netdb.h>
24 #include <string.h>
25 #include <errno.h>
26 #include <stdarg.h>
27 #include <pthread.h>
28 #include "webcit.h"
29
30 /*
31  * We keep one of these around for each active session
32  */
33 struct wc_session {
34         struct wc_session *next;        /* Next session in list */
35         int session_id;                 /* Session ID */
36         int inpipe[2];                  /* Data from webserver to session */
37         int outpipe[2];                 /* Data from session to webserver */
38         pthread_mutex_t critter;        /* Critical section uses pipes */
39         };
40
41 struct wc_session *SessionList = NULL;
42
43 /* Only one thread may manipulate SessionList at a time... */
44 pthread_mutex_t MasterCritter;
45
46 int GenerateSessionID() {
47         return getpid();
48         }
49
50
51 void gets0(int fd, char buf[]) {
52
53         buf[0] = 0;
54         do {
55                 buf[strlen(buf)+1] = 0;
56                 read(fd, &buf[strlen(buf)], 1);
57                 } while (buf[strlen(buf)-1] >= 32);
58         buf[strlen(buf)-1] = 0;
59         }
60
61 /*
62  * Collapse multiple cookies on one line
63  */
64 void req_gets(int sock, char *buf, char *hold) {
65         int a;
66
67         if (strlen(hold)==0) {
68                 client_gets(sock, buf);
69                 }
70         else {
71                 strcpy(buf, hold);
72                 }
73         strcpy(hold, "");
74
75         if (!strncasecmp(buf, "Cookie: ", 8)) {
76                 for (a=0; a<strlen(buf); ++a) if (buf[a]==';') {
77                         sprintf(hold, "Cookie: %s", &buf[a+1]);
78                         buf[a]=0;
79                         while (isspace(hold[8])) strcpy(&hold[8], &hold[9]);
80                         return;
81                         }
82                 }
83         }
84
85 extern const char *defaulthost;
86 extern const char *defaultport;
87
88 /*
89  * This loop gets called once for every HTTP connection made to WebCit.
90  */
91 void *context_loop(int sock) {
92         char req[256][256];
93         char buf[256], hold[256];
94         int num_lines = 0;
95         int a;
96         int f;
97         int desired_session = 0;
98         char str_session[256];
99         struct wc_session *sptr;
100         struct wc_session *TheSession;
101         int ContentLength;
102         int CloseSession = 0;
103
104         printf("Reading request from socket %d\n", sock);
105
106         /*
107          * Find out what it is that the web browser is asking for
108          */
109         ContentLength = 0;
110         do {
111                 req_gets(sock, buf, hold);
112                 if (!strncasecmp(buf, "Cookie: wc_session=", 19)) {
113                         desired_session = atoi(&buf[19]);
114                         }
115                 if (!strncasecmp(buf, "Content-length: ", 16)) {
116                         ContentLength = atoi(&buf[16]);
117                         }
118                 strcpy(&req[num_lines++][0], buf);
119                 } while(strlen(buf)>0);
120
121         /*
122          * See if there's an existing session open with the desired ID
123          */
124         TheSession = NULL;
125         if (desired_session != 0) {
126                 pthread_mutex_lock(&MasterCritter);
127                 for (sptr=SessionList; sptr!=NULL; sptr=sptr->next) {
128                         if (sptr->session_id == desired_session) {
129                                 TheSession = sptr;
130                                 }
131                         }
132                 pthread_mutex_unlock(&MasterCritter);
133                 }
134
135         /*
136          * Create a new session if we have to
137          */
138         if (TheSession == NULL) {
139                 printf("Creating a new session\n");
140                 pthread_mutex_lock(&MasterCritter);
141                 TheSession = (struct wc_session *)
142                         malloc(sizeof(struct wc_session));
143                 TheSession->session_id = GenerateSessionID();
144                 pipe(TheSession->inpipe);
145                 pipe(TheSession->outpipe);
146                 pthread_mutex_init(&TheSession->critter, NULL);
147                 TheSession->next = SessionList;
148                 SessionList = TheSession;
149                 sprintf(str_session, "%d", TheSession->session_id);
150                 f = fork();
151                 fflush(stdout); fflush(stdin);
152                 if (f==0) {
153                         dup2(TheSession->inpipe[0], 0);
154                         dup2(TheSession->outpipe[1], 1);
155                         execlp("./webcit", "webcit", str_session, defaulthost,
156                                defaultport, NULL);
157                         printf("HTTP/1.0 404 WebCit Failure\n\n");
158                         printf("Server: %s\n", SERVER);
159                         printf("Content-type: text/html\n");
160                         printf("Content-length: 76\n");
161                         printf("\n");
162                         printf("<HTML><HEAD><TITLE>Error</TITLE></HEAD>\n");
163                         printf("<BODY>execlp() failed</BODY></HTML>\n");
164                         exit(0);
165                         }
166                 pthread_mutex_unlock(&MasterCritter);
167                 }
168
169         /*
170          * Grab a lock on the session, so other threads don't try to access
171          * the pipes at the same time.
172          */
173         printf("Locking session %d...\n", TheSession->session_id);
174         pthread_mutex_lock(&TheSession->critter);
175         printf("   ...got lock\n");
176
177         /* 
178          * Send the request to the appropriate session...
179          */
180         printf("   Writing %d lines of command\n", num_lines);
181         printf("%s\n", &req[0][0]);
182         for (a=0; a<num_lines; ++a) {
183                 write(TheSession->inpipe[1], &req[a][0], strlen(&req[a][0]));
184                 write(TheSession->inpipe[1], "\n", 1);
185                 }
186         printf("   Writing %d bytes of content\n", ContentLength);
187         while (ContentLength--) {
188                 read(sock, buf, 1);
189                 write(TheSession->inpipe[1], buf, 1);
190                 }
191
192         /*
193          * ...and get the response.
194          */
195         printf("   Reading response\n");
196         ContentLength = 0;
197         do {
198                 gets0(TheSession->outpipe[0], buf);
199                 write(sock, buf, strlen(buf));
200                 write(sock, "\n", 1);
201                 if (!strncasecmp(buf, "Content-length: ", 16))
202                         ContentLength = atoi(&buf[16]);
203                 if (!strcasecmp(buf, "X-WebCit-Session: close")) {
204                         CloseSession = 1;
205                         }
206                 } while (strlen(buf) > 0);
207
208         printf("   Reading %d bytes of content\n");
209         while(ContentLength--) {
210                 read(TheSession->outpipe[0], buf, 1);
211                 write(sock, buf, 1);
212                 }
213
214         /*
215          * Now our HTTP connection is done.  It would be relatively easy
216          * to support HTTP/1.1 "persistent" connections by looping back to
217          * the top of this function.  For now, we'll just close.
218          */
219         printf("   Closing socket\n");
220         close(sock);
221
222         /*
223          * Let go of the lock
224          */
225         printf("Unlocking.\n");
226         pthread_mutex_unlock(&TheSession->critter);
227
228
229
230         /*
231          * If the last response included a "close session" directive,
232          * remove the context now.
233          */
234         if (CloseSession) {
235                 printf("Removing session.\n");
236                 pthread_mutex_lock(&MasterCritter);
237
238                 if (SessionList==TheSession) {
239                         SessionList = SessionList->next;
240                         }
241                 else {
242                         for (sptr=SessionList; sptr!=NULL; sptr=sptr->next) {
243                                 if (sptr->next == TheSession) {
244                                         sptr->next = TheSession->next;
245                                         }
246                                 }
247                         }
248         
249                 free(TheSession);
250         
251                 pthread_mutex_unlock(&MasterCritter);
252                 }
253
254
255
256         /*
257          * The thread handling this HTTP connection is now finished.
258          */
259         pthread_exit(NULL);
260         }