xref: /netbsd/libexec/httpd/cgi-bozo.c (revision daa4ced0)
1 /*	$NetBSD: cgi-bozo.c,v 1.54 2021/04/08 07:02:12 rillig Exp $	*/
2 
3 /*	$eterna: cgi-bozo.c,v 1.40 2011/11/18 09:21:15 mrg Exp $	*/
4 
5 /*
6  * Copyright (c) 1997-2021 Matthew R. Green
7  * All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer and
16  *    dedication in the documentation and/or other materials provided
17  *    with the distribution.
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 <syslog.h>
47 #include <unistd.h>
48 #include <assert.h>
49 
50 #include <netinet/in.h>
51 
52 #include "bozohttpd.h"
53 
54 #define CGIBIN_PREFIX		"cgi-bin/"
55 #define CGIBIN_PREFIX_LEN	(sizeof(CGIBIN_PREFIX)-1)
56 
57 #ifndef USE_ARG
58 #define USE_ARG(x)	/*LINTED*/(void)&(x)
59 #endif
60 
61 /*
62  * given the file name, return a CGI interpreter
63  */
64 static const char *
content_cgihandler(bozohttpd_t * httpd,bozo_httpreq_t * request,const char * file)65 content_cgihandler(bozohttpd_t *httpd, bozo_httpreq_t *request,
66 		   const char *file)
67 {
68 	bozo_content_map_t	*map;
69 
70 	USE_ARG(request);
71 	debug((httpd, DEBUG_FAT, "content_cgihandler: trying file %s", file));
72 	map = bozo_match_content_map(httpd, file, 0);
73 	if (map)
74 		return map->cgihandler;
75 	return NULL;
76 }
77 
78 static int
parse_header(bozo_httpreq_t * request,const char * str,ssize_t len,char ** hdr_str,char ** hdr_val)79 parse_header(bozo_httpreq_t *request, const char *str, ssize_t len,
80 	     char **hdr_str, char **hdr_val)
81 {
82 	struct	bozohttpd_t *httpd = request->hr_httpd;
83 	char	*name, *value;
84 
85 	/* if the string passed is zero-length bail out */
86 	if (*str == '\0')
87 		return -1;
88 
89 	value = bozostrdup(httpd, request, str);
90 
91 	/* locate the ':' separator in the header/value */
92 	name = bozostrnsep(&value, ":", &len);
93 
94 	if (NULL == name || -1 == len) {
95 		free(value);
96 		return -1;
97 	}
98 
99 	/* skip leading space/tab */
100 	while (*value == ' ' || *value == '\t')
101 		len--, value++;
102 
103 	*hdr_str = name;
104 	*hdr_val = value;
105 
106 	return 0;
107 }
108 
109 /*
110  * handle parsing a CGI header output, transposing a Status: header
111  * into the HTTP reply (ie, instead of "200 OK").
112  */
113 static void
finish_cgi_output(bozohttpd_t * httpd,bozo_httpreq_t * request,int in,int nph)114 finish_cgi_output(bozohttpd_t *httpd, bozo_httpreq_t *request, int in, int nph)
115 {
116 	char	buf[BOZO_WRSZ];
117 	char	*str;
118 	ssize_t	len;
119 	ssize_t rbytes;
120 	SIMPLEQ_HEAD(, bozoheaders)	headers;
121 	bozoheaders_t *hdr, *nhdr;
122 	int	write_header, nheaders = 0;
123 
124 	/* much of this code is like bozo_read_request()'s header loop. */
125 	SIMPLEQ_INIT(&headers);
126 	write_header = nph == 0;
127 	while (nph == 0 &&
128 		(str = bozodgetln(httpd, in, &len, bozo_read)) != NULL) {
129 		char	*hdr_name, *hdr_value;
130 
131 		if (parse_header(request, str, len, &hdr_name, &hdr_value))
132 			break;
133 
134 		/*
135 		 * The CGI 1.{1,2} spec both say that if the cgi program
136 		 * returns a `Status:' header field then the server MUST
137 		 * return it in the response.  If the cgi program does
138 		 * not return any `Status:' header then the server should
139 		 * respond with 200 OK.
140 		 * The CGI 1.1 and 1.2 specification differ slightly on
141 		 * this in that v1.2 says that the script MUST NOT return a
142 		 * `Status:' header if it is returning a `Location:' header.
143 		 * For compatibility we are going with the CGI 1.1 behavior.
144 		 */
145 		if (strcasecmp(hdr_name, "status") == 0) {
146 			debug((httpd, DEBUG_OBESE,
147 				"%s: writing HTTP header "
148 				"from status %s ..", __func__, hdr_value));
149 			bozo_printf(httpd, "%s %s\r\n", request->hr_proto,
150 				    hdr_value);
151 			bozo_flush(httpd, stdout);
152 			write_header = 0;
153 			free(hdr_name);
154 			break;
155 		}
156 
157 		hdr = bozomalloc(httpd, sizeof *hdr);
158 		hdr->h_header = hdr_name;
159 		hdr->h_value = hdr_value;
160 		SIMPLEQ_INSERT_TAIL(&headers, hdr, h_next);
161 		nheaders++;
162 	}
163 
164 	if (write_header) {
165 		debug((httpd, DEBUG_OBESE,
166 			"%s: writing HTTP header ..", __func__));
167 		bozo_printf(httpd,
168 			"%s 200 OK\r\n", request->hr_proto);
169 		bozo_flush(httpd, stdout);
170 	}
171 
172 	if (nheaders) {
173 		debug((httpd, DEBUG_OBESE,
174 			"%s:  writing delayed HTTP headers ..", __func__));
175 		SIMPLEQ_FOREACH_SAFE(hdr, &headers, h_next, nhdr) {
176 			bozo_printf(httpd, "%s: %s\r\n", hdr->h_header,
177 				    hdr->h_value);
178 			free(hdr->h_header);
179 			free(hdr);
180 		}
181 		bozo_printf(httpd, "\r\n");
182 		bozo_flush(httpd, stdout);
183 	}
184 
185 	/* CGI programs should perform their own timeouts */
186 	while ((rbytes = read(in, buf, sizeof buf)) > 0) {
187 		ssize_t wbytes;
188 		char *bp = buf;
189 
190 		while (rbytes) {
191 			wbytes = bozo_write(httpd, STDOUT_FILENO, buf,
192 					    (size_t)rbytes);
193 			if (wbytes > 0) {
194 				rbytes -= wbytes;
195 				bp += wbytes;
196 			} else
197 				bozoerr(httpd, 1,
198 					"cgi output write failed: %s",
199 					strerror(errno));
200 		}
201 	}
202 }
203 
204 static void
append_index_html(bozohttpd_t * httpd,char ** url)205 append_index_html(bozohttpd_t *httpd, char **url)
206 {
207 	*url = bozorealloc(httpd, *url,
208 			strlen(*url) + strlen(httpd->index_html) + 1);
209 	strcat(*url, httpd->index_html);
210 	debug((httpd, DEBUG_NORMAL,
211 		"append_index_html: url adjusted to `%s'", *url));
212 }
213 
214 /* This function parse search-string according to section 4.4 of RFC3875 */
215 static char **
parse_search_string(bozo_httpreq_t * request,const char * query,size_t * args_len)216 parse_search_string(bozo_httpreq_t *request, const char *query, size_t *args_len)
217 {
218 	struct	bozohttpd_t *httpd = request->hr_httpd;
219 	size_t i;
220 	char *s, *str, **args;
221 
222 	*args_len = 0;
223 
224 	/* URI MUST not contain any unencoded '=' - RFC3875, section 4.4 */
225 	if (strchr(query, '='))
226 		return NULL;
227 
228 	str = bozostrdup(httpd, request, query);
229 
230 	/*
231 	 * there's no more arguments than '+' chars in the query string as it's
232 	 * the separator
233 	 */
234 	*args_len = 1;
235 	/* count '+' in str */
236 	for (s = str; (s = strchr(s, '+')) != NULL; (*args_len)++)
237 		s++;
238 
239 	args = bozomalloc(httpd, sizeof(*args) * (*args_len + 1));
240 
241 	args[0] = str;
242 	args[*args_len] = NULL;
243 	for (s = str, i = 1; (s = strchr(s, '+')) != NULL; i++) {
244 		*s = '\0';
245 		s++;
246 		args[i] = s;
247 	}
248 
249 	/*
250 	 * check if search-strings are valid:
251 	 *
252 	 * RFC3875, section 4.4:
253 	 *
254 	 * search-string = search-word *( "+" search-word )
255 	 * search-word   = 1*schar
256 	 * schar		 = unreserved | escaped | xreserved
257 	 * xreserved	 = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "," |
258 	 *		   "$"
259 	 *
260 	 * section 2.3:
261 	 *
262 	 * hex	      = digit | "A" | "B" | "C" | "D" | "E" | "F" | "a" |
263 	 *		"b" | "c" | "d" | "e" | "f"
264 	 * escaped    = "%" hex hex
265 	 * unreserved = alpha | digit | mark
266 	 * mark	      = "-" | "_" | "." | "!" | "~" | "*" | "'" | "(" | ")"
267 	 *
268 	 * section 2.2:
269 	 *
270 	 * alpha	= lowalpha | hialpha
271 	 * lowalpha	= "a" | "b" | "c" | "d" | "e" | "f" | "g" | "h" |
272 	 *		  "i" | "j" | "k" | "l" | "m" | "n" | "o" | "p" |
273 	 *		  "q" | "r" | "s" | "t" | "u" | "v" | "w" | "x" |
274 	 *		  "y" | "z"
275 	 * hialpha	= "A" | "B" | "C" | "D" | "E" | "F" | "G" | "H" |
276 	 *		  "I" | "J" | "K" | "L" | "M" | "N" | "O" | "P" |
277 	 *		  "Q" | "R" | "S" | "T" | "U" | "V" | "W" | "X" |
278 	 *	          "Y" | "Z"
279 	 * digit        = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" |
280 	 *		  "8" | "9"
281 	 */
282 #define	UNRESERVED_CHAR	"-_.!~*'()"
283 #define	XRESERVED_CHAR	";/?:@&=,$"
284 
285 	for (i = 0; i < *args_len; i++) {
286 		s = args[i];
287 		/* search-word MUST have at least one schar */
288 		if (*s == '\0')
289 			goto parse_err;
290 		while (*s) {
291 			/* check if it's unreserved */
292 			if (isalpha((unsigned char)*s) ||
293 			    isdigit((unsigned char)*s) ||
294 			    strchr(UNRESERVED_CHAR, *s)) {
295 				s++;
296 				continue;
297 			}
298 
299 			/* check if it's escaped */
300 			if (*s == '%') {
301 				if (s[1] == '\0' || s[2] == '\0')
302 					goto parse_err;
303 				if (!isxdigit((unsigned char)s[1]) ||
304 				    !isxdigit((unsigned char)s[2]))
305 					goto parse_err;
306 				s += 3;
307 				continue;
308 			}
309 
310 			/* check if it's xreserved */
311 
312 			if (strchr(XRESERVED_CHAR, *s)) {
313 				s++;
314 				continue;
315 			}
316 
317 			goto parse_err;
318 		}
319 	}
320 
321 	/* decode percent encoding */
322 	for (i = 0; i < *args_len; i++) {
323 		if (bozo_decode_url_percent(request, args[i]))
324 			goto parse_err;
325 	}
326 
327 	/* allocate each arg separately */
328 	for (i = 0; i < *args_len; i++)
329 		args[i] = bozostrdup(httpd, request, args[i]);
330 	free(str);
331 
332 	return args;
333 
334 parse_err:
335 
336 	free(str);
337 	free(args);
338 	*args_len = 0;
339 
340 	return NULL;
341 
342 }
343 
344 void
bozo_cgi_setbin(bozohttpd_t * httpd,const char * path)345 bozo_cgi_setbin(bozohttpd_t *httpd, const char *path)
346 {
347 	httpd->cgibin = bozostrdup(httpd, NULL, path);
348 	debug((httpd, DEBUG_OBESE, "cgibin (cgi-bin directory) is %s",
349 	       httpd->cgibin));
350 }
351 
352 /* help build up the environ pointer */
353 void
bozo_setenv(bozohttpd_t * httpd,const char * env,const char * val,char ** envp)354 bozo_setenv(bozohttpd_t *httpd, const char *env, const char *val,
355 		char **envp)
356 {
357 	char *s1 = bozomalloc(httpd, strlen(env) + strlen(val) + 2);
358 
359 	strcpy(s1, env);
360 	strcat(s1, "=");
361 	strcat(s1, val);
362 	debug((httpd, DEBUG_OBESE, "bozo_setenv: %s", s1));
363 	*envp = s1;
364 }
365 
366 /*
367  * Checks if the request has asked for a cgi-bin.  Should only be called if
368  * cgibin is set.  If it starts CGIBIN_PREFIX or has a ncontent handler,
369  * process the cgi, otherwise just return.  Returns 0 if it did not handle
370  * the request.
371  */
372 int
bozo_process_cgi(bozo_httpreq_t * request)373 bozo_process_cgi(bozo_httpreq_t *request)
374 {
375 	bozohttpd_t *httpd = request->hr_httpd;
376 	char	buf[BOZO_WRSZ];
377 	char	date[40];
378 	bozoheaders_t *headp;
379 	const char *type, *clen, *info, *cgihandler;
380 	char	*query, *s, *t, *path, *env, *command, *file, *url;
381 	char	**envp, **curenvp, **argv, **search_string_argv = NULL;
382 	char	**lastenvp;
383 	char	*uri;
384 	size_t	i, len, search_string_argc = 0;
385 	ssize_t rbytes;
386 	pid_t	pid;
387 	int	envpsize, ix, nph;
388 	int	sv[2];
389 
390 	if (!httpd->cgibin && !httpd->process_cgi)
391 		return 0;
392 
393 #ifndef NO_USER_SUPPORT
394 	if (request->hr_user && !httpd->enable_cgi_users)
395 		return 0;
396 #endif /* !NO_USER_SUPPORT */
397 
398 	if (request->hr_oldfile && strcmp(request->hr_oldfile, "/") != 0)
399 		uri = request->hr_oldfile;
400 	else
401 		uri = request->hr_file;
402 
403 	if (uri[0] == '/')
404 		file = bozostrdup(httpd, request, uri);
405 	else
406 		bozoasprintf(httpd, &file, "/%s", uri);
407 
408 	if (request->hr_query && strlen(request->hr_query))
409 		query = bozostrdup(httpd, request, request->hr_query);
410 	else
411 		query = NULL;
412 
413 	bozoasprintf(httpd, &url, "%s%s%s",
414 		     file,
415 		     query ? "?" : "",
416 		     query ? query : "");
417 	debug((httpd, DEBUG_NORMAL, "%s: url `%s'", __func__, url));
418 
419 	path = NULL;
420 	envp = NULL;
421 	cgihandler = NULL;
422 	command = NULL;
423 	info = NULL;
424 
425 	len = strlen(url);
426 
427 	if (bozo_auth_check(request, url + 1))
428 		goto out;
429 
430 	if (!httpd->cgibin ||
431 	    strncmp(url + 1, CGIBIN_PREFIX, CGIBIN_PREFIX_LEN) != 0) {
432 		cgihandler = content_cgihandler(httpd, request, file + 1);
433 		if (cgihandler == NULL) {
434 			debug((httpd, DEBUG_FAT,
435 				"%s: no handler, returning", __func__));
436 			goto out;
437 		}
438 		if (len == 0 || file[len - 1] == '/')
439 			append_index_html(httpd, &file);
440 		debug((httpd, DEBUG_NORMAL, "%s: cgihandler `%s'",
441 		    __func__, cgihandler));
442 	} else if (len - 1 == CGIBIN_PREFIX_LEN)	/* url is "/cgi-bin/" */
443 		append_index_html(httpd, &file);
444 
445 	/* RFC3875 sect. 4.4. - search-string support */
446 	if (query != NULL) {
447 		search_string_argv = parse_search_string(request, query,
448 		    &search_string_argc);
449 	}
450 
451 	debug((httpd, DEBUG_NORMAL, "parse_search_string args no: %zu",
452 	    search_string_argc));
453 	for (i = 0; i < search_string_argc; i++) {
454 		debug((httpd, DEBUG_FAT,
455 		    "search_string[%zu]: `%s'", i, search_string_argv[i]));
456 	}
457 
458 	argv = bozomalloc(httpd, sizeof(*argv) * (3 + search_string_argc));
459 
460 	ix = 0;
461 	if (cgihandler) {
462 		command = file + 1;
463 		path = bozostrdup(httpd, request, cgihandler);
464 	} else {
465 		command = file + CGIBIN_PREFIX_LEN + 1;
466 		if ((s = strchr(command, '/')) != NULL) {
467 			info = bozostrdup(httpd, request, s);
468 			*s = '\0';
469 		}
470 		path = bozomalloc(httpd,
471 				strlen(httpd->cgibin) + 1 + strlen(command) + 1);
472 		strcpy(path, httpd->cgibin);
473 		strcat(path, "/");
474 		strcat(path, command);
475 	}
476 
477 	argv[ix++] = path;
478 
479 	/* copy search-string args */
480 	for (i = 0; i < search_string_argc; i++)
481 		argv[ix++] = search_string_argv[i];
482 
483 	argv[ix++] = NULL;
484 	nph = strncmp(command, "nph-", 4) == 0;
485 
486 	type = request->hr_content_type;
487 	clen = request->hr_content_length;
488 
489 	envpsize = 13 + request->hr_nheaders +
490 	    (info && *info ? 1 : 0) +
491 	    (query && *query ? 1 : 0) +
492 	    (type && *type ? 1 : 0) +
493 	    (clen && *clen ? 1 : 0) +
494 	    (request->hr_remotehost && *request->hr_remotehost ? 1 : 0) +
495 	    (request->hr_remoteaddr && *request->hr_remoteaddr ? 1 : 0) +
496 	    (cgihandler ? 1 : 0) +
497 	    bozo_auth_cgi_count(request) +
498 	    (request->hr_serverport && *request->hr_serverport ? 1 : 0);
499 
500 	debug((httpd, DEBUG_FAT,
501 		"%s: path `%s', cmd `%s', info `%s', "
502 		"query `%s', nph `%d', envpsize `%d'", __func__,
503 		path, command, strornull(info),
504 		strornull(query), nph, envpsize));
505 
506 	envp = bozomalloc(httpd, sizeof(*envp) * envpsize);
507 	for (ix = 0; ix < envpsize; ix++)
508 		envp[ix] = NULL;
509 	curenvp = envp;
510 	lastenvp = envp + envpsize;
511 
512 	SIMPLEQ_FOREACH(headp, &request->hr_headers, h_next) {
513 		const char *s2;
514 		env = bozomalloc(httpd, 6 + strlen(headp->h_header) + 1 +
515 		    strlen(headp->h_value));
516 
517 		t = env;
518 		strcpy(t, "HTTP_");
519 		t += strlen(t);
520 		for (s2 = headp->h_header; *s2; t++, s2++)
521 			if (islower((unsigned char)*s2))
522 				*t = toupper((unsigned char)*s2);
523 			else if (*s2 == '-')
524 				*t = '_';
525 			else
526 				*t = *s2;
527 		*t = '\0';
528 		debug((httpd, DEBUG_OBESE, "setting header %s as %s = %s",
529 		    headp->h_header, env, headp->h_value));
530 		bozo_setenv(httpd, env, headp->h_value, curenvp++);
531 		free(env);
532 	}
533 
534 #ifndef _PATH_DEFPATH
535 #define _PATH_DEFPATH "/usr/bin:/bin"
536 #endif
537 
538 	bozo_setenv(httpd, "PATH", _PATH_DEFPATH, curenvp++);
539 	bozo_setenv(httpd, "IFS", " \t\n", curenvp++);
540 	bozo_setenv(httpd, "SERVER_NAME", BOZOHOST(httpd,request), curenvp++);
541 	bozo_setenv(httpd, "GATEWAY_INTERFACE", "CGI/1.1", curenvp++);
542 	bozo_setenv(httpd, "SERVER_PROTOCOL", request->hr_proto, curenvp++);
543 	bozo_setenv(httpd, "REQUEST_METHOD", request->hr_methodstr, curenvp++);
544 	bozo_setenv(httpd, "SCRIPT_NAME", file, curenvp++);
545 	bozo_setenv(httpd, "SCRIPT_FILENAME", file + 1, curenvp++);
546 	bozo_setenv(httpd, "SERVER_SOFTWARE", httpd->server_software,
547 			curenvp++);
548 	bozo_setenv(httpd, "REQUEST_URI", uri, curenvp++);
549 	bozo_setenv(httpd, "DATE_GMT", bozo_http_date(date, sizeof(date)),
550 			curenvp++);
551 	/* RFC3875 section 4.1.7 says that QUERY_STRING MUST be defined. */
552 	if (query && *query)
553 		bozo_setenv(httpd, "QUERY_STRING", query, curenvp++);
554 	else
555 		bozo_setenv(httpd, "QUERY_STRING", "", curenvp++);
556 	if (info && *info)
557 		bozo_setenv(httpd, "PATH_INFO", info, curenvp++);
558 	if (type && *type)
559 		bozo_setenv(httpd, "CONTENT_TYPE", type, curenvp++);
560 	if (clen && *clen)
561 		bozo_setenv(httpd, "CONTENT_LENGTH", clen, curenvp++);
562 	if (request->hr_serverport && *request->hr_serverport)
563 		bozo_setenv(httpd, "SERVER_PORT", request->hr_serverport,
564 				curenvp++);
565 	if (request->hr_remotehost && *request->hr_remotehost)
566 		bozo_setenv(httpd, "REMOTE_HOST", request->hr_remotehost,
567 				curenvp++);
568 	if (request->hr_remoteaddr && *request->hr_remoteaddr)
569 		bozo_setenv(httpd, "REMOTE_ADDR", request->hr_remoteaddr,
570 				curenvp++);
571 	/*
572 	 * Apache does this when invoking content handlers, and PHP
573 	 * 5.3 requires it as a "security" measure.
574 	 */
575 	if (cgihandler)
576 		bozo_setenv(httpd, "REDIRECT_STATUS", "200", curenvp++);
577 	bozo_auth_cgi_setenv(request, &curenvp);
578 
579 	debug((httpd, DEBUG_FAT, "%s: going exec %s with args:", __func__,
580 	    path));
581 
582 	for (i = 0; argv[i] != NULL; i++) {
583 		debug((httpd, DEBUG_FAT, "%s: argv[%zu] = `%s'", __func__,
584 		    i, argv[i]));
585 	}
586 
587 	if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, sv) == -1)
588 		bozoerr(httpd, 1, "child socketpair failed: %s",
589 				strerror(errno));
590 
591 	*curenvp = 0;
592 	assert(lastenvp > curenvp);
593 
594 	/*
595 	 * We create 2 procs: one to become the CGI, one read from
596 	 * the CGI and output to the network, and this parent will
597 	 * continue reading from the network and writing to the
598 	 * CGI procsss.
599 	 */
600 	switch (fork()) {
601 	case -1: /* eep, failure */
602 		bozoerr(httpd, 1, "child fork failed: %s", strerror(errno));
603 		/*NOTREACHED*/
604 	case 0:
605 		close(sv[0]);
606 		dup2(sv[1], STDIN_FILENO);
607 		dup2(sv[1], STDOUT_FILENO);
608 		close(2);
609 		close(sv[1]);
610 		closelog();
611 		bozo_daemon_closefds(httpd);
612 
613 		if (-1 == execve(path, argv, envp)) {
614 			int saveerrno = errno;
615 			bozo_http_error(httpd, 404, request,
616 				"Cannot execute CGI");
617 			/* don't log easy to trigger events */
618 			if (saveerrno != ENOENT &&
619 			    saveerrno != EISDIR &&
620 			    saveerrno != EACCES)
621 				bozoerr(httpd, 1, "child exec failed: %s: %s",
622 				      path, strerror(saveerrno));
623 			_exit(1);
624 		}
625 		/* NOT REACHED */
626 		bozoerr(httpd, 1, "child execve returned?!");
627 	}
628 
629 	free(query);
630 	free(file);
631 	free(url);
632 	for (i = 0; i < search_string_argc; i++)
633 		free(search_string_argv[i]);
634 	free(search_string_argv);
635 
636 	close(sv[1]);
637 
638 	/* parent: read from stdin (bozo_read()) write to sv[0] */
639 	/* child: read from sv[0] (bozo_write()) write to stdout */
640 	pid = fork();
641 	if (pid == -1)
642 		bozoerr(httpd, 1, "io child fork failed: %s", strerror(errno));
643 	else if (pid == 0) {
644 		/* child reader/writer */
645 		close(STDIN_FILENO);
646 		finish_cgi_output(httpd, request, sv[0], nph);
647 		/* if we do SSL, send a SSL_shutdown now */
648 		bozo_ssl_shutdown(request->hr_httpd);
649 		/* if we're done output, our parent is useless... */
650 		kill(getppid(), SIGKILL);
651 		debug((httpd, DEBUG_FAT, "done processing cgi output"));
652 		_exit(0);
653 	}
654 	close(STDOUT_FILENO);
655 
656 	/* CGI programs should perform their own timeouts */
657 	while ((rbytes = bozo_read(httpd, STDIN_FILENO, buf, sizeof buf)) > 0) {
658 		ssize_t wbytes;
659 		char *bp = buf;
660 
661 		while (rbytes) {
662 			wbytes = write(sv[0], buf, (size_t)rbytes);
663 			if (wbytes > 0) {
664 				rbytes -= wbytes;
665 				bp += wbytes;
666 			} else
667 				bozoerr(httpd, 1, "write failed: %s",
668 					strerror(errno));
669 		}
670 	}
671 	debug((httpd, DEBUG_FAT, "done processing cgi input"));
672 	exit(0);
673 
674  out:
675 
676 	for (i = 0; i < search_string_argc; i++)
677 		free(search_string_argv[i]);
678 	free(search_string_argv);
679 	free(query);
680 	free(file);
681 	free(url);
682 	return 0;
683 }
684 
685 #ifndef NO_DYNAMIC_CONTENT
686 /* cgi maps are simple ".postfix /path/to/prog" */
687 void
bozo_add_content_map_cgi(bozohttpd_t * httpd,const char * arg,const char * cgihandler)688 bozo_add_content_map_cgi(bozohttpd_t *httpd, const char *arg,
689                          const char *cgihandler)
690 {
691 	bozo_content_map_t *map;
692 
693 	debug((httpd, DEBUG_NORMAL, "bozo_add_content_map_cgi: name %s cgi %s",
694 		arg, cgihandler));
695 
696 	httpd->process_cgi = 1;
697 
698 	map = bozo_get_content_map(httpd, arg);
699 	map->name = arg;
700 	map->type = map->encoding = map->encoding11 = NULL;
701 	map->cgihandler = cgihandler;
702 }
703 #endif /* NO_DYNAMIC_CONTENT */
704 
705 #endif /* NO_CGIBIN_SUPPORT */
706