528219a5dbccb99003ed6bf0461c03753a0eedba
[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 #include <sys/poll.h>
27
28 #ifdef HAVE_CONFIG_H
29 #include <config.h>
30 #endif
31 #include <utils.h>
32 #include <log.h>
33
34 static char **environ;
35
36 static int passdata(FILE *in, FILE *out)
37 {
38     int ret;
39     char buf[65536];
40     struct pollfd pfds[2];
41     
42     while(!feof(in)) {
43         memset(pfds, 0, sizeof(struct pollfd) * 2);
44         pfds[0].fd = fileno(in);
45         pfds[0].events = POLLIN;
46         pfds[1].fd = fileno(out);
47         pfds[1].events = POLLHUP;
48         ret = poll(pfds, 2, -1);
49         if(ret < 0) {
50             if(errno != EINTR) {
51                 flog(LOG_ERR, "callcgi: error in poll: %s", strerror(errno));
52                 return(1);
53             }
54         }
55         if(ret > 0) {
56             if(pfds[0].revents & (POLLIN | POLLERR | POLLHUP)) {
57                 ret = fread(buf, 1, 65536, in);
58                 if(ferror(in)) {
59                     flog(LOG_ERR, "callcgi: could not read input: %s", strerror(errno));
60                     return(1);
61                 }
62                 if(fwrite(buf, 1, ret, out) != ret) {
63                     flog(LOG_ERR, "callcgi: could not write output: %s", strerror(errno));
64                     return(1);
65                 }
66             }
67             if(pfds[1].revents & POLLHUP)
68                 return(1);
69         }
70     }
71     return(0);
72 }
73
74 static char *absolutify(char *file)
75 {
76     char cwd[1024];
77     
78     if(*file != '/') {
79         getcwd(cwd, sizeof(cwd));
80         return(sprintf2("%s/%s", cwd, file));
81     }
82     return(sstrdup(file));
83 }
84
85 static pid_t forkchild(int inpath, char *prog, char *file, char *method, char *url, char *rest, int *infd, int *outfd)
86 {
87     int i;
88     char *qp, **env, *name;
89     int inp[2], outp[2];
90     pid_t pid;
91
92     pipe(inp);
93     pipe(outp);
94     if((pid = fork()) < 0) {
95         flog(LOG_ERR, "callcgi: could not fork");
96         exit(1);
97     }
98     if(pid == 0) {
99         close(inp[1]);
100         close(outp[0]);
101         dup2(inp[0], 0);
102         dup2(outp[1], 1);
103         for(i = 3; i < FD_SETSIZE; i++)
104             close(i);
105         if((qp = strchr(url, '?')) != NULL)
106             *(qp++) = 0;
107         putenv(sprintf2("SERVER_SOFTWARE=ashd/%s", VERSION));
108         putenv("GATEWAY_INTERFACE=CGI/1.1");
109         if(getenv("HTTP_VERSION"))
110             putenv(sprintf2("SERVER_PROTOCOL=%s", getenv("HTTP_VERSION")));
111         putenv(sprintf2("REQUEST_METHOD=%s", method));
112         putenv(sprintf2("PATH_INFO=%s", rest));
113         name = url;
114         /* XXX: This is an ugly hack (I think), but though I can think
115          * of several alternatives, none seem to be better. */
116         if(*rest && (strlen(url) >= strlen(rest)) &&
117            !strcmp(rest, url + strlen(url) - strlen(rest))) {
118             name = sprintf2("%.*s", (int)(strlen(url) - strlen(rest)), url);
119         }
120         putenv(sprintf2("SCRIPT_NAME=%s", name));
121         putenv(sprintf2("QUERY_STRING=%s", qp?qp:""));
122         if(getenv("REQ_HOST"))
123             putenv(sprintf2("SERVER_NAME=%s", getenv("REQ_HOST")));
124         if(getenv("REQ_X_ASH_SERVER_PORT"))
125             putenv(sprintf2("SERVER_PORT=%s", getenv("REQ_X_ASH_SERVER_PORT")));
126         if(getenv("REQ_X_ASH_PROTOCOL") && !strcmp(getenv("REQ_X_ASH_PROTOCOL"), "https"))
127             putenv("HTTPS=on");
128         if(getenv("REQ_X_ASH_ADDRESS"))
129             putenv(sprintf2("REMOTE_ADDR=%s", getenv("REQ_X_ASH_ADDRESS")));
130         if(getenv("REQ_X_ASH_REMOTE_USER"))
131             putenv(sprintf2("REMOTE_USER=%s", getenv("REQ_X_ASH_REMOTE_USER")));
132         if(getenv("REQ_CONTENT_TYPE"))
133             putenv(sprintf2("CONTENT_TYPE=%s", getenv("REQ_CONTENT_TYPE")));
134         if(getenv("REQ_CONTENT_LENGTH"))
135             putenv(sprintf2("CONTENT_LENGTH=%s", getenv("REQ_CONTENT_LENGTH")));
136         for(env = environ; *env; env++) {
137             if(!strncmp(*env, "REQ_", 4))
138                 putenv(sprintf2("HTTP_%s", (*env) + 4));
139         }
140         /*
141          * This is (understandably) missing from the CGI
142          * specification, but PHP seems to require it.
143          */
144         putenv(sprintf2("SCRIPT_FILENAME=%s", absolutify(file)));
145         if(inpath)
146             execlp(prog, prog, file, NULL);
147         else
148             execl(prog, prog, file, NULL);
149         exit(127);
150     }
151     close(inp[0]);
152     close(outp[1]);
153     *infd = inp[1];
154     *outfd = outp[0];
155     return(pid);
156 }
157
158 static void trim(struct charbuf *buf)
159 {
160     char *p;
161     
162     for(p = buf->b; (p - buf->b < buf->d) && isspace(*p); p++);
163     memmove(buf->b, p, buf->d -= (p - buf->b));
164     for(p = buf->b + buf->d - 1; (p > buf->b) && isspace(*p); p--, buf->d--);
165 }
166
167 static char **parseheaders(FILE *s)
168 {
169     int c, state;
170     struct charvbuf hbuf;
171     struct charbuf buf;
172     
173     bufinit(hbuf);
174     bufinit(buf);
175     state = 0;
176     while(1) {
177         c = fgetc(s);
178     again:
179         if(state == 0) {
180             if(c == '\r') {
181             } else if(c == '\n') {
182                 break;
183             } else if(c == EOF) {
184                 goto fail;
185             } else {
186                 state = 1;
187                 goto again;
188             }
189         } else if(state == 1) {
190             if(c == ':') {
191                 trim(&buf);
192                 bufadd(buf, 0);
193                 bufadd(hbuf, buf.b);
194                 bufinit(buf);
195                 state = 2;
196             } else if(c == '\r') {
197             } else if(c == '\n') {
198                 goto fail;
199             } else if(c == EOF) {
200                 goto fail;
201             } else {
202                 bufadd(buf, c);
203             }
204         } else if(state == 2) {
205             if(c == '\r') {
206             } else if(c == '\n') {
207                 trim(&buf);
208                 bufadd(buf, 0);
209                 bufadd(hbuf, buf.b);
210                 bufinit(buf);
211                 state = 0;
212             } else if(c == EOF) {
213                 goto fail;
214             } else {
215                 bufadd(buf, c);
216             }
217         }
218     }
219     bufadd(hbuf, NULL);
220     return(hbuf.b);
221     
222 fail:
223     buffree(hbuf);
224     buffree(buf);
225     return(NULL);
226 }
227
228 static char *defstatus(int code)
229 {
230     if(code == 200)
231         return("OK");
232     else if(code == 201)
233         return("Created");
234     else if(code == 202)
235         return("Accepted");
236     else if(code == 204)
237         return("No Content");
238     else if(code == 300)
239         return("Multiple Choices");
240     else if(code == 301)
241         return("Moved Permanently");
242     else if(code == 302)
243         return("Found");
244     else if(code == 303)
245         return("See Other");
246     else if(code == 304)
247         return("Not Modified");
248     else if(code == 307)
249         return("Moved Temporarily");
250     else if(code == 400)
251         return("Bad Request");
252     else if(code == 401)
253         return("Unauthorized");
254     else if(code == 403)
255         return("Forbidden");
256     else if(code == 404)
257         return("Not Found");
258     else if(code == 500)
259         return("Internal Server Error");
260     else if(code == 501)
261         return("Not Implemented");
262     else if(code == 503)
263         return("Service Unavailable");
264     else
265         return("Unknown status");
266 }
267
268 static void sendstatus(char **headers, FILE *out)
269 {
270     char **hp;
271     char *status, *location;
272     
273     hp = headers;
274     status = location = NULL;
275     while(*hp) {
276         if(!strcasecmp(hp[0], "status")) {
277             status = hp[1];
278             /* Clear this header, so that it is not transmitted by sendheaders. */
279             **hp = 0;
280         } else if(!strcasecmp(hp[0], "location")) {
281             location = hp[1];
282             hp += 2;
283         } else {
284             hp += 2;
285         }
286     }
287     if(status) {
288         if(strchr(status, ' '))
289             fprintf(out, "HTTP/1.1 %s\n", status);
290         else
291             fprintf(out, "HTTP/1.1 %i %s\n", atoi(status), defstatus(atoi(status)));
292     } else if(location) {
293         fprintf(out, "HTTP/1.1 303 See Other\n");
294     } else {
295         fprintf(out, "HTTP/1.1 200 OK\n");
296     }
297 }
298
299 static void sendheaders(char **headers, FILE *out)
300 {
301     while(*headers) {
302         if(**headers)
303             fprintf(out, "%s: %s\n", headers[0], headers[1]);
304         headers += 2;
305     }
306 }
307
308 static void usage(void)
309 {
310     flog(LOG_ERR, "usage: callcgi [-c] [-p PROGRAM] METHOD URL REST");
311 }
312
313 int main(int argc, char **argv, char **envp)
314 {
315     int c;
316     char *file, *prog, *sp;
317     int inpath, cd;
318     int infd, outfd;
319     FILE *in, *out;
320     char **headers;
321     pid_t child;
322     
323     environ = envp;
324     signal(SIGPIPE, SIG_IGN);
325     
326     prog = NULL;
327     inpath = 0;
328     cd = 0;
329     while((c = getopt(argc, argv, "cp:")) >= 0) {
330         switch(c) {
331         case 'c':
332             cd = 1;
333             break;
334         case 'p':
335             prog = optarg;
336             inpath = 1;
337             break;
338         default:
339             usage();
340             exit(1);
341         }
342     }
343     
344     if(argc - optind < 3) {
345         usage();
346         exit(1);
347     }
348     if((file = getenv("REQ_X_ASH_FILE")) == NULL) {
349         flog(LOG_ERR, "callcgi: needs to be called with the X-Ash-File header");
350         exit(1);
351     }
352     
353     if(cd) {
354         /* This behavior is encouraged by the CGI specification (RFC 3875, 7.2),
355          * but not strictly required, and I get the feeling it might break some
356          * relative paths here or there, so it's not the default for now. */
357         if((sp = strrchr(file, '/')) != NULL) {
358             *sp = 0;
359             if(chdir(file)) {
360                 *sp = '/';
361             } else {
362                 file = sp + 1;
363             }
364         }
365     }
366     
367     if(prog == NULL)
368         prog = file;
369     child = forkchild(inpath, prog, file, argv[optind], argv[optind + 1], argv[optind + 2], &infd, &outfd);
370     in = fdopen(infd, "w");
371     passdata(stdin, in);        /* Ignore errors, perhaps? */
372     fclose(in);
373     out = fdopen(outfd, "r");
374     if((headers = parseheaders(out)) == NULL) {
375         flog(LOG_WARNING, "CGI handler returned invalid headers");
376         exit(1);
377     }
378     sendstatus(headers, stdout);
379     sendheaders(headers, stdout);
380     printf("\n");
381     if(passdata(out, stdout))
382         kill(child, SIGINT);
383     return(0);
384 }