10bb87c9af47e6223dc35fd237a40fad51d2d98b
[ashd.git] / src / callcgi.c
1 /*
2     ashd - A Sane HTTP Daemon
3     Copyright (C) 2008  Fredrik Tolf <fredrik@dolda2000.com>
4
5     This program is free software: you can redistribute it and/or modify
6     it under the terms of the GNU General Public License as published by
7     the Free Software Foundation, either version 3 of the License, or
8     (at your option) any later version.
9
10     This program is distributed in the hope that it will be useful,
11     but WITHOUT ANY WARRANTY; without even the implied warranty of
12     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13     GNU General Public License for more details.
14
15     You should have received a copy of the GNU General Public License
16     along with this program.  If not, see <http://www.gnu.org/licenses/>.
17 */
18
19 #include <stdlib.h>
20 #include <string.h>
21 #include <stdio.h>
22 #include <unistd.h>
23 #include <errno.h>
24 #include <ctype.h>
25 #include <signal.h>
26
27 #ifdef HAVE_CONFIG_H
28 #include <config.h>
29 #endif
30 #include <utils.h>
31 #include <log.h>
32
33 static char **environ;
34
35 static void passdata(FILE *in, FILE *out)
36 {
37     int ret;
38     char *buf;
39     
40     buf = smalloc(65536);
41     while(!feof(in)) {
42         ret = fread(buf, 1, 65536, in);
43         if(ferror(in)) {
44             flog(LOG_ERR, "sendfile: could not read input: %s", strerror(errno));
45             break;
46         }
47         if(fwrite(buf, 1, ret, out) != ret) {
48             flog(LOG_ERR, "sendfile: could not write output: %s", strerror(errno));
49             break;
50         }
51     }
52     free(buf);
53 }
54
55 static char *absolutify(char *file)
56 {
57     char cwd[1024];
58     
59     if(*file != '/') {
60         getcwd(cwd, sizeof(cwd));
61         return(sprintf2("%s/%s", cwd, file));
62     }
63     return(sstrdup(file));
64 }
65
66 static void forkchild(int inpath, char *prog, char *file, char *method, char *url, char *rest, int *infd, int *outfd)
67 {
68     int i;
69     char *qp, **env, *name;
70     int inp[2], outp[2];
71     pid_t pid;
72
73     pipe(inp);
74     pipe(outp);
75     if((pid = fork()) < 0) {
76         flog(LOG_ERR, "callcgi: could not fork");
77         exit(1);
78     }
79     if(pid == 0) {
80         close(inp[1]);
81         close(outp[0]);
82         dup2(inp[0], 0);
83         dup2(outp[1], 1);
84         for(i = 3; i < FD_SETSIZE; i++)
85             close(i);
86         if((qp = strchr(url, '?')) != NULL)
87             *(qp++) = 0;
88         putenv(sprintf2("SERVER_SOFTWARE=ashd/%s", VERSION));
89         putenv("GATEWAY_INTERFACE=CGI/1.1");
90         if(getenv("HTTP_VERSION"))
91             putenv(sprintf2("SERVER_PROTOCOL=%s", getenv("HTTP_VERSION")));
92         putenv(sprintf2("REQUEST_METHOD=%s", method));
93         putenv(sprintf2("PATH_INFO=/%s", rest));
94         name = url;
95         /* XXX: This is an ugly hack (I think), but though I can think
96          * of several alternatives, none seem to be better. */
97         if(*rest && (strlen(url) > strlen(rest)) &&
98            !strcmp(rest, url + strlen(url) - strlen(rest)) &&
99            (url[strlen(url) - strlen(rest) - 1] == '/')) {
100             name = sprintf2("%.*s", (int)(strlen(url) - strlen(rest) - 1), url);
101         }
102         putenv(sprintf2("SCRIPT_NAME=%s", name));
103         putenv(sprintf2("QUERY_STRING=%s", qp?qp:""));
104         if(getenv("REQ_HOST"))
105             putenv(sprintf2("SERVER_NAME=%s", getenv("REQ_HOST")));
106         if(getenv("REQ_X_ASH_SERVER_PORT"))
107             putenv(sprintf2("SERVER_PORT=%s", getenv("REQ_X_ASH_SERVER_PORT")));
108         if(getenv("REQ_X_ASH_PROTOCOL") && !strcmp(getenv("REQ_X_ASH_PROTOCOL"), "https"))
109             putenv("HTTPS=on");
110         if(getenv("REQ_X_ASH_ADDRESS"))
111             putenv(sprintf2("REMOTE_ADDR=%s", getenv("REQ_X_ASH_ADDRESS")));
112         if(getenv("REQ_CONTENT_TYPE"))
113             putenv(sprintf2("CONTENT_TYPE=%s", getenv("REQ_CONTENT_TYPE")));
114         if(getenv("REQ_CONTENT_LENGTH"))
115             putenv(sprintf2("CONTENT_LENGTH=%s", getenv("REQ_CONTENT_LENGTH")));
116         for(env = environ; *env; env++) {
117             if(!strncmp(*env, "REQ_", 4))
118                 putenv(sprintf2("HTTP_%s", (*env) + 4));
119         }
120         /*
121          * This is (understandably) missing from the CGI
122          * specification, but PHP seems to require it.
123          */
124         putenv(sprintf2("SCRIPT_FILENAME=%s", absolutify(file)));
125         if(inpath)
126             execlp(prog, prog, file, NULL);
127         else
128             execl(prog, prog, file, NULL);
129         exit(127);
130     }
131     close(inp[0]);
132     close(outp[1]);
133     *infd = inp[1];
134     *outfd = outp[0];
135 }
136
137 static void trim(struct charbuf *buf)
138 {
139     char *p;
140     
141     for(p = buf->b; (p - buf->b < buf->d) && isspace(*p); p++);
142     memmove(buf->b, p, buf->d -= (p - buf->b));
143     for(p = buf->b + buf->d - 1; (p > buf->b) && isspace(*p); p--, buf->d--);
144 }
145
146 static char **parseheaders(FILE *s)
147 {
148     int c, state;
149     struct charvbuf hbuf;
150     struct charbuf buf;
151     
152     bufinit(hbuf);
153     bufinit(buf);
154     state = 0;
155     while(1) {
156         c = fgetc(s);
157     again:
158         if(state == 0) {
159             if(c == '\r') {
160             } else if(c == '\n') {
161                 break;
162             } else if(c == EOF) {
163                 goto fail;
164             } else {
165                 state = 1;
166                 goto again;
167             }
168         } else if(state == 1) {
169             if(c == ':') {
170                 trim(&buf);
171                 bufadd(buf, 0);
172                 bufadd(hbuf, buf.b);
173                 bufinit(buf);
174                 state = 2;
175             } else if(c == '\r') {
176             } else if(c == '\n') {
177                 goto fail;
178             } else if(c == EOF) {
179                 goto fail;
180             } else {
181                 bufadd(buf, c);
182             }
183         } else if(state == 2) {
184             if(c == '\r') {
185             } else if(c == '\n') {
186                 trim(&buf);
187                 bufadd(buf, 0);
188                 bufadd(hbuf, buf.b);
189                 bufinit(buf);
190                 state = 0;
191             } else if(c == EOF) {
192                 goto fail;
193             } else {
194                 bufadd(buf, c);
195             }
196         }
197     }
198     bufadd(hbuf, NULL);
199     return(hbuf.b);
200     
201 fail:
202     buffree(hbuf);
203     buffree(buf);
204     return(NULL);
205 }
206
207 static char *defstatus(int code)
208 {
209     if(code == 200)
210         return("OK");
211     else if(code == 201)
212         return("Created");
213     else if(code == 202)
214         return("Accepted");
215     else if(code == 204)
216         return("No Content");
217     else if(code == 300)
218         return("Multiple Choices");
219     else if(code == 301)
220         return("Moved Permanently");
221     else if(code == 302)
222         return("Found");
223     else if(code == 303)
224         return("See Other");
225     else if(code == 304)
226         return("Not Modified");
227     else if(code == 307)
228         return("Moved Temporarily");
229     else if(code == 400)
230         return("Bad Request");
231     else if(code == 401)
232         return("Unauthorized");
233     else if(code == 403)
234         return("Forbidden");
235     else if(code == 404)
236         return("Not Found");
237     else if(code == 500)
238         return("Internal Server Error");
239     else if(code == 501)
240         return("Not Implemented");
241     else if(code == 503)
242         return("Service Unavailable");
243     else
244         return("Unknown status");
245 }
246
247 static void sendstatus(char **headers, FILE *out)
248 {
249     char **hp;
250     char *status, *location;
251     
252     hp = headers;
253     status = location = NULL;
254     while(*hp) {
255         if(!strcasecmp(hp[0], "status")) {
256             status = hp[1];
257             /* Clear this header, so that it is not transmitted by sendheaders. */
258             **hp = 0;
259         } else if(!strcasecmp(hp[0], "location")) {
260             location = hp[1];
261             hp += 2;
262         } else {
263             hp += 2;
264         }
265     }
266     if(status) {
267         if(strchr(status, ' '))
268             fprintf(out, "HTTP/1.1 %s\n", status);
269         else
270             fprintf(out, "HTTP/1.1 %i %s\n", atoi(status), defstatus(atoi(status)));
271     } else if(location) {
272         fprintf(out, "HTTP/1.1 303 See Other\n");
273     } else {
274         fprintf(out, "HTTP/1.1 200 OK\n");
275     }
276 }
277
278 static void sendheaders(char **headers, FILE *out)
279 {
280     while(*headers) {
281         if(**headers)
282             fprintf(out, "%s: %s\n", headers[0], headers[1]);
283         headers += 2;
284     }
285 }
286
287 static void usage(void)
288 {
289     flog(LOG_ERR, "usage: callcgi [-p PROGRAM] METHOD URL REST");
290 }
291
292 int main(int argc, char **argv, char **envp)
293 {
294     int c;
295     char *file, *prog;
296     int inpath;
297     int infd, outfd;
298     FILE *in, *out;
299     char **headers;
300     
301     environ = envp;
302     signal(SIGPIPE, SIG_IGN);
303     
304     prog = NULL;
305     inpath = 0;
306     while((c = getopt(argc, argv, "p:")) >= 0) {
307         switch(c) {
308         case 'p':
309             prog = optarg;
310             inpath = 1;
311             break;
312         default:
313             usage();
314             exit(1);
315         }
316     }
317     
318     if(argc - optind < 3) {
319         usage();
320         exit(1);
321     }
322     if((file = getenv("REQ_X_ASH_FILE")) == NULL) {
323         flog(LOG_ERR, "callcgi: needs to be called with the X-Ash-File header");
324         exit(1);
325     }
326     if(prog == NULL)
327         prog = file;
328     forkchild(inpath, prog, file, argv[optind], argv[optind + 1], argv[optind + 2], &infd, &outfd);
329     in = fdopen(infd, "w");
330     passdata(stdin, in);
331     fclose(in);
332     out = fdopen(outfd, "r");
333     if((headers = parseheaders(out)) == NULL) {
334         flog(LOG_WARNING, "CGI handler returned invalid headers");
335         exit(1);
336     }
337     sendstatus(headers, stdout);
338     sendheaders(headers, stdout);
339     printf("\n");
340     passdata(out, stdout);
341     return(0);
342 }