cgi-bozo.c revision 1.3 1 /* $eterna: cgi-bozo.c,v 1.13 2006/05/17 08:19:10 mrg Exp $ */
2
3 /*
4 * Copyright (c) 1997-2006 Matthew R. Green
5 * All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer and
14 * dedication in the documentation and/or other materials provided
15 * with the distribution.
16 * 3. The name of the author may not be used to endorse or promote products
17 * derived from this software without specific prior written permission.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
20 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
21 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
22 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
23 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
24 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
25 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
26 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
27 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29 * SUCH DAMAGE.
30 *
31 */
32
33 /* this code implements CGI/1.2 for bozohttpd */
34
35 #ifndef NO_CGIBIN_SUPPORT
36
37 #include <sys/param.h>
38 #include <sys/socket.h>
39
40 #include <ctype.h>
41 #include <errno.h>
42 #include <paths.h>
43 #include <signal.h>
44 #include <stdlib.h>
45 #include <string.h>
46 #include <unistd.h>
47
48 #include <netinet/in.h>
49
50 #include "bozohttpd.h"
51
52 #define CGIBIN_PREFIX "cgi-bin/"
53 #define CGIBIN_PREFIX_LEN (sizeof(CGIBIN_PREFIX)-1)
54
55 static char *cgibin; /* cgi-bin directory */
56 static int Cflag; /* added a cgi handler, always process_cgi() */
57
58 static const char *content_cgihandler(http_req *, const char *);
59 static void finish_cgi_output(http_req *request, int, int);
60
61 void
62 set_cgibin(char *path)
63 {
64 cgibin = path;
65 debug((DEBUG_OBESE, "cgibin (cgi-bin directory) is %s", cgibin));
66 }
67
68 /* help build up the environ pointer */
69 void
70 spsetenv(const char *env, const char *val, char **envp)
71 {
72 char *s1 = bozomalloc(strlen(env) + strlen(val) + 2);
73
74 strcpy(s1, env);
75 strcat(s1, "=");
76 strcat(s1, val);
77 debug((DEBUG_OBESE, "spsetenv: %s", s1));
78 *envp = s1;
79 }
80
81 /*
82 * Checks if the request has asked for a cgi-bin. Should only be called if
83 * cgibin is set. If it starts CGIBIN_PREFIX or has a ncontent handler,
84 * process the cgi, otherwise just return.
85 */
86 void
87 process_cgi(http_req *request)
88 {
89 char buf[WRSZ];
90 struct headers *headp;
91 const char *type, *clen, *info, *cgihandler;
92 char *query, *s, *t, *path, *env, *command, *url;
93 char **envp, **curenvp, *argv[4];
94 size_t len;
95 ssize_t rbytes;
96 pid_t pid;
97 int envpsize, ix, nph;
98 int sv[2];
99
100 if (!cgibin && !Cflag)
101 return;
102
103 debug((DEBUG_NORMAL, "process_cgi: url `%s'", request->hr_url));
104
105 url = bozostrdup(request->hr_url);
106 if ((s = strchr(url, '?')) != NULL) {
107 *s++ = '\0';
108 query = s;
109 } else
110 query = NULL;
111 path = NULL;
112 envp = NULL;
113 cgihandler = NULL;
114 command = NULL;
115 info = NULL;
116
117 len = strlen(url);
118 if (len == 0 || url[len - 1] == '/') { /* append index.html */
119 debug((DEBUG_FAT, "appending index.html"));
120 url = bozorealloc(url, len + strlen(index_html) + 1);
121 strcat(url, index_html);
122 debug((DEBUG_NORMAL, "process_cgi: url adjusted to `%s'", url));
123 }
124
125 auth_check(request, url + 1);
126
127 if (!cgibin || strncmp(url + 1, CGIBIN_PREFIX, CGIBIN_PREFIX_LEN) != 0) {
128 cgihandler = content_cgihandler(request, url + 1);
129 if (cgihandler == NULL) {
130 free(url);
131 return;
132 }
133 debug((DEBUG_NORMAL, "process_cgi: cgihandler `%s'",
134 cgihandler));
135 }
136
137 ix = 0;
138 if (cgihandler) {
139 command = url + 1;
140 path = bozostrdup(cgihandler);
141 argv[ix++] = path;
142 /* argv[] = [ path, command, query, NULL ] */
143 } else {
144 command = url + CGIBIN_PREFIX_LEN + 1;
145 if ((s = strchr(command, '/')) != NULL) {
146 info = bozostrdup(s);
147 *s = '\0';
148 }
149 path = bozomalloc(strlen(cgibin) + 1 + strlen(command) + 1);
150 strcpy(path, cgibin);
151 strcat(path, "/");
152 strcat(path, command);
153 /* argv[] = [ command, query, NULL ] */
154 }
155 argv[ix++] = command;
156 argv[ix++] = query;
157 argv[ix++] = NULL;
158
159 nph = strncmp(command, "nph-", 4) == 0;
160
161 debug((DEBUG_FAT,
162 "process_cgi: path `%s' cmd `%s' info `%s' query `%s' nph `%d'",
163 path, command, strornull(info), strornull(query), nph));
164
165 type = request->hr_content_type;
166 clen = request->hr_content_length;
167
168 envpsize = 13 + request->hr_nheaders +
169 (info && *info ? 1 : 0) +
170 (query && *query ? 1 : 0) +
171 (type && *type ? 1 : 0) +
172 (clen && *clen ? 1 : 0) +
173 (request->hr_remotehost && *request->hr_remotehost ? 1 : 0) +
174 (request->hr_remoteaddr && *request->hr_remoteaddr ? 1 : 0) +
175 auth_cgi_count(request) +
176 (request->hr_serverport && *request->hr_serverport ? 1 : 0);
177
178 envp = bozomalloc(sizeof(*envp) * envpsize);
179 for (ix = 0; ix < envpsize; ix++)
180 envp[ix] = NULL;
181 curenvp = envp;
182
183 SIMPLEQ_FOREACH(headp, &request->hr_headers, h_next) {
184 const char *s2;
185 env = bozomalloc(6 + strlen(headp->h_header) + 1 +
186 strlen(headp->h_value));
187
188 t = env;
189 strcpy(t, "HTTP_");
190 t += strlen(t);
191 for (s2 = headp->h_header; *s2; t++, s2++)
192 if (islower((u_int)*s2))
193 *t = toupper((u_int)*s2);
194 else if (*s2 == '-')
195 *t = '_';
196 else
197 *t = *s2;
198 *t = '\0';
199 debug((DEBUG_OBESE, "setting header %s as %s = %s",
200 headp->h_header, env, headp->h_value));
201 spsetenv(env, headp->h_value, curenvp++);
202 free(env);
203 }
204
205 #ifndef _PATH_DEFPATH
206 #define _PATH_DEFPATH "/usr/bin:/bin"
207 #endif
208
209 spsetenv("PATH", _PATH_DEFPATH, curenvp++);
210 spsetenv("IFS", " \t\n", curenvp++);
211 spsetenv("SERVER_NAME", myname, curenvp++);
212 spsetenv("GATEWAY_INTERFACE", "CGI/1.1", curenvp++);
213 spsetenv("SERVER_PROTOCOL", request->hr_proto, curenvp++);
214 spsetenv("REQUEST_METHOD", request->hr_methodstr, curenvp++);
215 spsetenv("SCRIPT_NAME", url, curenvp++);
216 spsetenv("SCRIPT_FILENAME", url + 1, curenvp++);
217 spsetenv("SERVER_SOFTWARE", server_software, curenvp++);
218 spsetenv("REQUEST_URI", request->hr_url, curenvp++);
219 spsetenv("DATE_GMT", http_date(), curenvp++);
220 if (query && *query)
221 spsetenv("QUERY_STRING", query, curenvp++);
222 if (info && *info)
223 spsetenv("PATH_INFO", info, curenvp++);
224 if (type && *type)
225 spsetenv("CONTENT_TYPE", type, curenvp++);
226 if (clen && *clen)
227 spsetenv("CONTENT_LENGTH", clen, curenvp++);
228 if (request->hr_serverport && *request->hr_serverport)
229 spsetenv("SERVER_PORT", request->hr_serverport, curenvp++);
230 if (request->hr_remotehost && *request->hr_remotehost)
231 spsetenv("REMOTE_HOST", request->hr_remotehost, curenvp++);
232 if (request->hr_remoteaddr && *request->hr_remoteaddr)
233 spsetenv("REMOTE_ADDR", request->hr_remoteaddr, curenvp++);
234 auth_cgi_setenv(request, &curenvp);
235
236 debug((DEBUG_FAT, "process_cgi: going exec %s, %s %s %s",
237 path, argv[0], strornull(argv[1]), strornull(argv[2])));
238
239 if (-1 == socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, sv))
240 error(1, "child socketpair failed: %s", strerror(errno));
241
242 /*
243 * We create 2 procs: one to become the CGI, one read from
244 * the CGI and output to the network, and this parent will
245 * continue reading from the network and writing to the
246 * CGI procsss.
247 */
248 switch (fork()) {
249 case -1: /* eep, failure */
250 error(1, "child fork failed: %s", strerror(errno));
251 case 0:
252 close(sv[0]);
253 dup2(sv[1], STDIN_FILENO);
254 dup2(sv[1], STDOUT_FILENO);
255
256 if (-1 == execve(path, argv, envp))
257 error(1, "child exec failed: %s", path);
258 /* NOT REACHED */
259 error(1, "child execve returned?!");
260 }
261
262 close(sv[1]);
263
264 /* parent: read from stdin (bozoread()) write to sv[0] */
265 /* child: read from sv[0] (bozowrite()) write to stdout */
266 pid = fork();
267 if (pid == -1)
268 error(1, "io child fork failed: %s", strerror(errno));
269 else if (pid == 0) {
270 /* child reader/writer */
271 close(STDIN_FILENO);
272 finish_cgi_output(request, sv[0], nph);
273 /* if we're done output, our parent is useless... */
274 kill(getppid(), SIGKILL);
275 debug((DEBUG_FAT, "done processing cgi output"));
276 _exit(0);
277 }
278 close(STDOUT_FILENO);
279
280 /* XXX we should have some goo that times us out
281 */
282 while ((rbytes = bozoread(STDIN_FILENO, buf, sizeof buf)) > 0) {
283 ssize_t wbytes;
284 char *bp = buf;
285
286 while (rbytes) {
287 wbytes = write(sv[0], buf , rbytes);
288 if (wbytes > 0) {
289 rbytes -= wbytes;
290 bp += wbytes;
291 } else
292 error(1, "write failed: %s", strerror(errno));
293 }
294 }
295 debug((DEBUG_FAT, "done processing cgi input"));
296 exit(0);
297 }
298
299 /*
300 * handle parsing a CGI header output, transposing a Status: header
301 * into the HTTP reply (ie, instead of "200 OK").
302 */
303 static void
304 finish_cgi_output(http_req *request, int in, int nph)
305 {
306 char buf[WRSZ];
307 char *str, *val;
308 size_t len;
309 ssize_t rbytes;
310 SIMPLEQ_HEAD(, headers) headers;
311 struct headers *hdr;
312 int write_header, nheaders = 0, write_str = 0;
313
314 /* much of this code is like read_request()'s header loop. hmmm... */
315 SIMPLEQ_INIT(&headers);
316 write_header = nph == 0;
317 while (nph == 0 && (str = dgetln(in, (ssize_t *)&len, read)) != NULL) {
318 str = bozostrdup(str); /* we use this copy */
319
320 if (*str == '\0') {
321 write_str = 1;
322 break;
323 }
324
325 val = strnsep(&str, ":", (ssize_t *)&len);
326 debug((DEBUG_EXPLODING,
327 "read_req2: after strnsep: str ``%s'' val ``%s''",
328 str, val));
329 if (val == NULL || len == -1) {
330 write_str = 1;
331 break;
332 }
333 while (*str == ' ' || *str == '\t')
334 len--, str++;
335
336 /*
337 * The CGI 1.{1,2} spec both say that if the cgi program
338 * returns a `Status:' header field then the server MUST
339 * return it in the response. If the cgi program does
340 * not return any `Status:' header then the server should
341 * respond with 200 OK.
342 * XXX The CGI 1.1 and 1.2 specification differ slightly on
343 * this in that v1.2 says that the script MUST NOT return a
344 * `Status:' header if it is returning a `Location:' header.
345 * For compatibility we are going with the CGI 1.1 behavior.
346 */
347 if (strcasecmp(val, "status") == 0) {
348 debug((DEBUG_OBESE, "process_cgi: writing HTTP header "
349 "from status %s ..", str));
350 bozoprintf("%s %s\r\n", request->hr_proto, str);
351 bozoflush(stdout);
352 write_header = 0;
353 break;
354 }
355
356 hdr = bozomalloc(sizeof *hdr);
357 hdr->h_header = val;
358 hdr->h_value = str;
359 SIMPLEQ_INSERT_TAIL(&headers, hdr, h_next);
360 nheaders++;
361 }
362
363 if (write_header) {
364 debug((DEBUG_OBESE, "process_cgi: writing HTTP header .."));
365 bozoprintf("%s 200 OK\r\n", request->hr_proto);
366 bozoflush(stdout);
367 }
368
369 if (nheaders) {
370 debug((DEBUG_OBESE, "process_cgi: writing delayed HTTP "
371 "headers .."));
372 SIMPLEQ_FOREACH(hdr, &headers, h_next) {
373 bozoprintf("%s: %s\r\n", hdr->h_header, hdr->h_value);
374 free(hdr->h_value);
375 }
376 bozoflush(stdout);
377 }
378
379 /* XXX we should have some goo that times us out
380 */
381 while ((rbytes = read(in, buf, sizeof buf)) > 0) {
382 ssize_t wbytes;
383 char *bp = buf;
384
385 while (rbytes) {
386 wbytes = bozowrite(STDOUT_FILENO, buf, rbytes);
387 if (wbytes > 0) {
388 rbytes -= wbytes;
389 bp += wbytes;
390 } else
391 error(1, "cgi output write failed: %s",
392 strerror(errno));
393 }
394 }
395 }
396
397 /*
398 * given the file name, return a CGI interpreter
399 */
400 static const char *
401 content_cgihandler(http_req *request, const char *file)
402 {
403 struct content_map *map;
404
405 map = match_content_map(file, 0);
406 if (map)
407 return (map->cgihandler);
408 return (NULL);
409 }
410
411 #ifndef NO_DYNAMIC_CONTENT
412 /* cgi maps are simple ".postfix /path/to/prog" */
413 void
414 add_content_map_cgi(char *arg, char *cgihandler)
415 {
416 struct content_map *map;
417
418 debug((DEBUG_NORMAL, "add_content_map_cgi: name %s cgi %s", arg, cgihandler));
419
420 Cflag = 1;
421
422 map = get_content_map(arg);
423 map->name = arg;
424 map->type = map->encoding = map->encoding11 = NULL;
425 map->cgihandler = cgihandler;
426 }
427 #endif /* NO_DYNAMIC_CONTENT */
428
429 #endif /* NO_CGIBIN_SUPPORT */
430