Home | History | Annotate | Line # | Download | only in httpd
cgi-bozo.c revision 1.32
      1 /*	$NetBSD: cgi-bozo.c,v 1.32 2015/12/31 04:39:16 mrg Exp $	*/
      2 
      3 /*	$eterna: cgi-bozo.c,v 1.40 2011/11/18 09:21:15 mrg Exp $	*/
      4 
      5 /*
      6  * Copyright (c) 1997-2015 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 
     49 #include <netinet/in.h>
     50 
     51 #include "bozohttpd.h"
     52 
     53 #define CGIBIN_PREFIX		"cgi-bin/"
     54 #define CGIBIN_PREFIX_LEN	(sizeof(CGIBIN_PREFIX)-1)
     55 
     56 #ifndef USE_ARG
     57 #define USE_ARG(x)	/*LINTED*/(void)&(x)
     58 #endif
     59 
     60 /*
     61  * given the file name, return a CGI interpreter
     62  */
     63 static const char *
     64 content_cgihandler(bozohttpd_t *httpd, bozo_httpreq_t *request,
     65 		const char *file)
     66 {
     67 	bozo_content_map_t	*map;
     68 
     69 	USE_ARG(request);
     70 	debug((httpd, DEBUG_FAT, "content_cgihandler: trying file %s", file));
     71 	map = bozo_match_content_map(httpd, file, 0);
     72 	if (map)
     73 		return map->cgihandler;
     74 	return NULL;
     75 }
     76 
     77 static int
     78 parse_header(bozo_httpreq_t *request, const char *str, ssize_t len,
     79 	     char **hdr_str, char **hdr_val)
     80 {
     81 	struct	bozohttpd_t *httpd = request->hr_httpd;
     82 	char	*name, *value;
     83 
     84 	/* if the string passed is zero-length bail out */
     85 	if (*str == '\0')
     86 		return -1;
     87 
     88 	value = bozostrdup(httpd, request, str);
     89 
     90 	/* locate the ':' separator in the header/value */
     91 	name = bozostrnsep(&value, ":", &len);
     92 
     93 	if (NULL == name || -1 == len) {
     94 		free(value);
     95 		return -1;
     96 	}
     97 
     98 	/* skip leading space/tab */
     99 	while (*value == ' ' || *value == '\t')
    100 		len--, value++;
    101 
    102 	*hdr_str = name;
    103 	*hdr_val = value;
    104 
    105 	return 0;
    106 }
    107 
    108 /*
    109  * handle parsing a CGI header output, transposing a Status: header
    110  * into the HTTP reply (ie, instead of "200 OK").
    111  */
    112 static void
    113 finish_cgi_output(bozohttpd_t *httpd, bozo_httpreq_t *request, int in, int nph)
    114 {
    115 	char	buf[BOZO_WRSZ];
    116 	char	*str;
    117 	ssize_t	len;
    118 	ssize_t rbytes;
    119 	SIMPLEQ_HEAD(, bozoheaders)	headers;
    120 	bozoheaders_t *hdr, *nhdr;
    121 	int	write_header, nheaders = 0;
    122 
    123 	/* much of this code is like bozo_read_request()'s header loop. */
    124 	SIMPLEQ_INIT(&headers);
    125 	write_header = nph == 0;
    126 	/* was read(2) here - XXX - agc */
    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 		 * XXX 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 				"bozo_process_cgi:  writing HTTP header "
    148 				"from status %s ..", 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 			"bozo_process_cgi:  writing HTTP header .."));
    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 			"bozo_process_cgi:  writing delayed HTTP headers .."));
    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 	/* XXX we should have some goo that times us out
    186 	 */
    187 	while ((rbytes = read(in, buf, sizeof buf)) > 0) {
    188 		ssize_t wbytes;
    189 		char *bp = buf;
    190 
    191 		while (rbytes) {
    192 			wbytes = bozo_write(httpd, STDOUT_FILENO, buf,
    193 						(size_t)rbytes);
    194 			if (wbytes > 0) {
    195 				rbytes -= wbytes;
    196 				bp += wbytes;
    197 			} else
    198 				bozoerr(httpd, 1,
    199 					"cgi output write failed: %s",
    200 					strerror(errno));
    201 		}
    202 	}
    203 }
    204 
    205 static void
    206 append_index_html(bozohttpd_t *httpd, char **url)
    207 {
    208 	*url = bozorealloc(httpd, *url,
    209 			strlen(*url) + strlen(httpd->index_html) + 1);
    210 	strcat(*url, httpd->index_html);
    211 	debug((httpd, DEBUG_NORMAL,
    212 		"append_index_html: url adjusted to `%s'", *url));
    213 }
    214 
    215 void
    216 bozo_cgi_setbin(bozohttpd_t *httpd, const char *path)
    217 {
    218 	httpd->cgibin = bozostrdup(httpd, NULL, path);
    219 	debug((httpd, DEBUG_OBESE, "cgibin (cgi-bin directory) is %s",
    220 		httpd->cgibin));
    221 }
    222 
    223 /* help build up the environ pointer */
    224 void
    225 bozo_setenv(bozohttpd_t *httpd, const char *env, const char *val,
    226 		char **envp)
    227 {
    228 	char *s1 = bozomalloc(httpd, strlen(env) + strlen(val) + 2);
    229 
    230 	strcpy(s1, env);
    231 	strcat(s1, "=");
    232 	strcat(s1, val);
    233 	debug((httpd, DEBUG_OBESE, "bozo_setenv: %s", s1));
    234 	*envp = s1;
    235 }
    236 
    237 /*
    238  * Checks if the request has asked for a cgi-bin.  Should only be called if
    239  * cgibin is set.  If it starts CGIBIN_PREFIX or has a ncontent handler,
    240  * process the cgi, otherwise just return.  Returns 0 if it did not handle
    241  * the request.
    242  */
    243 int
    244 bozo_process_cgi(bozo_httpreq_t *request)
    245 {
    246 	bozohttpd_t *httpd = request->hr_httpd;
    247 	char	buf[BOZO_WRSZ];
    248 	char	date[40];
    249 	bozoheaders_t *headp;
    250 	const char *type, *clen, *info, *cgihandler;
    251 	char	*query, *s, *t, *path, *env, *command, *file, *url;
    252 	char	**envp, **curenvp, *argv[4];
    253 	char	*uri;
    254 	size_t	len;
    255 	ssize_t rbytes;
    256 	pid_t	pid;
    257 	int	envpsize, ix, nph;
    258 	int	sv[2];
    259 
    260 	if (!httpd->cgibin && !httpd->process_cgi)
    261 		return 0;
    262 
    263 #ifndef NO_USER_SUPPORT
    264 	if (request->hr_user && !httpd->enable_cgi_users)
    265 		return 0;
    266 #endif /* !NO_USER_SUPPORT */
    267 
    268 	if (request->hr_oldfile && strcmp(request->hr_oldfile, "/") != 0)
    269 		uri = request->hr_oldfile;
    270 	else
    271 		uri = request->hr_file;
    272 
    273 	if (uri[0] == '/')
    274 		file = bozostrdup(httpd, request, uri);
    275 	else
    276 		bozoasprintf(httpd, &file, "/%s", uri);
    277 
    278 	if (request->hr_query && strlen(request->hr_query))
    279 		query = bozostrdup(httpd, request, request->hr_query);
    280 	else
    281 		query = NULL;
    282 
    283 	bozoasprintf(httpd, &url, "%s%s%s",
    284 		     file,
    285 		     query ? "?" : "",
    286 		     query ? query : "");
    287 	debug((httpd, DEBUG_NORMAL, "bozo_process_cgi: url `%s'", url));
    288 
    289 	path = NULL;
    290 	envp = NULL;
    291 	cgihandler = NULL;
    292 	command = NULL;
    293 	info = NULL;
    294 
    295 	len = strlen(url);
    296 
    297 	if (bozo_auth_check(request, url + 1))
    298 		goto out;
    299 
    300 	if (!httpd->cgibin ||
    301 	    strncmp(url + 1, CGIBIN_PREFIX, CGIBIN_PREFIX_LEN) != 0) {
    302 		cgihandler = content_cgihandler(httpd, request, file + 1);
    303 		if (cgihandler == NULL) {
    304 			debug((httpd, DEBUG_FAT,
    305 				"bozo_process_cgi: no handler, returning"));
    306 			goto out;
    307 		}
    308 		if (len == 0 || file[len - 1] == '/')
    309 			append_index_html(httpd, &file);
    310 		debug((httpd, DEBUG_NORMAL, "bozo_process_cgi: cgihandler `%s'",
    311 		    cgihandler));
    312 	} else if (len - 1 == CGIBIN_PREFIX_LEN)	/* url is "/cgi-bin/" */
    313 		append_index_html(httpd, &file);
    314 
    315 	ix = 0;
    316 	if (cgihandler) {
    317 		command = file + 1;
    318 		path = bozostrdup(httpd, request, cgihandler);
    319 		argv[ix++] = path;
    320 			/* argv[] = [ path, command, query, NULL ] */
    321 	} else {
    322 		command = file + CGIBIN_PREFIX_LEN + 1;
    323 		if ((s = strchr(command, '/')) != NULL) {
    324 			info = bozostrdup(httpd, request, s);
    325 			*s = '\0';
    326 		}
    327 		path = bozomalloc(httpd,
    328 				strlen(httpd->cgibin) + 1 + strlen(command) + 1);
    329 		strcpy(path, httpd->cgibin);
    330 		strcat(path, "/");
    331 		strcat(path, command);
    332 			/* argv[] = [ command, query, NULL ] */
    333 	}
    334 	argv[ix++] = command;
    335 	argv[ix++] = query;
    336 	argv[ix++] = NULL;
    337 
    338 	nph = strncmp(command, "nph-", 4) == 0;
    339 
    340 	type = request->hr_content_type;
    341 	clen = request->hr_content_length;
    342 
    343 	envpsize = 13 + request->hr_nheaders +
    344 	    (info && *info ? 1 : 0) +
    345 	    (query && *query ? 1 : 0) +
    346 	    (type && *type ? 1 : 0) +
    347 	    (clen && *clen ? 1 : 0) +
    348 	    (request->hr_remotehost && *request->hr_remotehost ? 1 : 0) +
    349 	    (request->hr_remoteaddr && *request->hr_remoteaddr ? 1 : 0) +
    350 	    bozo_auth_cgi_count(request) +
    351 	    (request->hr_serverport && *request->hr_serverport ? 1 : 0);
    352 
    353 	debug((httpd, DEBUG_FAT,
    354 		"bozo_process_cgi: path `%s', cmd `%s', info `%s', "
    355 		"query `%s', nph `%d', envpsize `%d'",
    356 		path, command, strornull(info),
    357 		strornull(query), nph, envpsize));
    358 
    359 	envp = bozomalloc(httpd, sizeof(*envp) * envpsize);
    360 	for (ix = 0; ix < envpsize; ix++)
    361 		envp[ix] = NULL;
    362 	curenvp = envp;
    363 
    364 	SIMPLEQ_FOREACH(headp, &request->hr_headers, h_next) {
    365 		const char *s2;
    366 		env = bozomalloc(httpd, 6 + strlen(headp->h_header) + 1 +
    367 		    strlen(headp->h_value));
    368 
    369 		t = env;
    370 		strcpy(t, "HTTP_");
    371 		t += strlen(t);
    372 		for (s2 = headp->h_header; *s2; t++, s2++)
    373 			if (islower((u_int)*s2))
    374 				*t = toupper((u_int)*s2);
    375 			else if (*s2 == '-')
    376 				*t = '_';
    377 			else
    378 				*t = *s2;
    379 		*t = '\0';
    380 		debug((httpd, DEBUG_OBESE, "setting header %s as %s = %s",
    381 		    headp->h_header, env, headp->h_value));
    382 		bozo_setenv(httpd, env, headp->h_value, curenvp++);
    383 		free(env);
    384 	}
    385 
    386 #ifndef _PATH_DEFPATH
    387 #define _PATH_DEFPATH "/usr/bin:/bin"
    388 #endif
    389 
    390 	bozo_setenv(httpd, "PATH", _PATH_DEFPATH, curenvp++);
    391 	bozo_setenv(httpd, "IFS", " \t\n", curenvp++);
    392 	bozo_setenv(httpd, "SERVER_NAME", BOZOHOST(httpd,request), curenvp++);
    393 	bozo_setenv(httpd, "GATEWAY_INTERFACE", "CGI/1.1", curenvp++);
    394 	bozo_setenv(httpd, "SERVER_PROTOCOL", request->hr_proto, curenvp++);
    395 	bozo_setenv(httpd, "REQUEST_METHOD", request->hr_methodstr, curenvp++);
    396 	bozo_setenv(httpd, "SCRIPT_NAME", file, curenvp++);
    397 	bozo_setenv(httpd, "SCRIPT_FILENAME", file + 1, curenvp++);
    398 	bozo_setenv(httpd, "SERVER_SOFTWARE", httpd->server_software,
    399 			curenvp++);
    400 	bozo_setenv(httpd, "REQUEST_URI", uri, curenvp++);
    401 	bozo_setenv(httpd, "DATE_GMT", bozo_http_date(date, sizeof(date)),
    402 			curenvp++);
    403 	if (query && *query)
    404 		bozo_setenv(httpd, "QUERY_STRING", query, curenvp++);
    405 	if (info && *info)
    406 		bozo_setenv(httpd, "PATH_INFO", info, curenvp++);
    407 	if (type && *type)
    408 		bozo_setenv(httpd, "CONTENT_TYPE", type, curenvp++);
    409 	if (clen && *clen)
    410 		bozo_setenv(httpd, "CONTENT_LENGTH", clen, curenvp++);
    411 	if (request->hr_serverport && *request->hr_serverport)
    412 		bozo_setenv(httpd, "SERVER_PORT", request->hr_serverport,
    413 				curenvp++);
    414 	if (request->hr_remotehost && *request->hr_remotehost)
    415 		bozo_setenv(httpd, "REMOTE_HOST", request->hr_remotehost,
    416 				curenvp++);
    417 	if (request->hr_remoteaddr && *request->hr_remoteaddr)
    418 		bozo_setenv(httpd, "REMOTE_ADDR", request->hr_remoteaddr,
    419 				curenvp++);
    420 	/*
    421 	 * Apache does this when invoking content handlers, and PHP
    422 	 * 5.3 requires it as a "security" measure.
    423 	 */
    424 	if (cgihandler)
    425 		bozo_setenv(httpd, "REDIRECT_STATUS", "200", curenvp++);
    426 	bozo_auth_cgi_setenv(request, &curenvp);
    427 
    428 	debug((httpd, DEBUG_FAT, "bozo_process_cgi: going exec %s, %s %s %s",
    429 	    path, argv[0], strornull(argv[1]), strornull(argv[2])));
    430 
    431 	if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, sv) == -1)
    432 		bozoerr(httpd, 1, "child socketpair failed: %s",
    433 				strerror(errno));
    434 
    435 	/*
    436 	 * We create 2 procs: one to become the CGI, one read from
    437 	 * the CGI and output to the network, and this parent will
    438 	 * continue reading from the network and writing to the
    439 	 * CGI procsss.
    440 	 */
    441 	switch (fork()) {
    442 	case -1: /* eep, failure */
    443 		bozoerr(httpd, 1, "child fork failed: %s", strerror(errno));
    444 		/*NOTREACHED*/
    445 	case 0:
    446 		close(sv[0]);
    447 		dup2(sv[1], STDIN_FILENO);
    448 		dup2(sv[1], STDOUT_FILENO);
    449 		close(2);
    450 		close(sv[1]);
    451 		closelog();
    452 		bozo_daemon_closefds(httpd);
    453 
    454 		if (-1 == execve(path, argv, envp))
    455 			bozoerr(httpd, 1, "child exec failed: %s: %s",
    456 			      path, strerror(errno));
    457 		/* NOT REACHED */
    458 		bozoerr(httpd, 1, "child execve returned?!");
    459 	}
    460 
    461 	free(query);
    462 	free(file);
    463 	free(url);
    464 
    465 	close(sv[1]);
    466 
    467 	/* parent: read from stdin (bozo_read()) write to sv[0] */
    468 	/* child: read from sv[0] (bozo_write()) write to stdout */
    469 	pid = fork();
    470 	if (pid == -1)
    471 		bozoerr(httpd, 1, "io child fork failed: %s", strerror(errno));
    472 	else if (pid == 0) {
    473 		/* child reader/writer */
    474 		close(STDIN_FILENO);
    475 		finish_cgi_output(httpd, request, sv[0], nph);
    476 		/* if we're done output, our parent is useless... */
    477 		kill(getppid(), SIGKILL);
    478 		debug((httpd, DEBUG_FAT, "done processing cgi output"));
    479 		_exit(0);
    480 	}
    481 	close(STDOUT_FILENO);
    482 
    483 	/* XXX we should have some goo that times us out
    484 	 */
    485 	while ((rbytes = bozo_read(httpd, STDIN_FILENO, buf, sizeof buf)) > 0) {
    486 		ssize_t wbytes;
    487 		char *bp = buf;
    488 
    489 		while (rbytes) {
    490 			wbytes = write(sv[0], buf, (size_t)rbytes);
    491 			if (wbytes > 0) {
    492 				rbytes -= wbytes;
    493 				bp += wbytes;
    494 			} else
    495 				bozoerr(httpd, 1, "write failed: %s",
    496 					strerror(errno));
    497 		}
    498 	}
    499 	debug((httpd, DEBUG_FAT, "done processing cgi input"));
    500 	exit(0);
    501 
    502  out:
    503 	free(query);
    504 	free(file);
    505 	free(url);
    506 	return 0;
    507 }
    508 
    509 #ifndef NO_DYNAMIC_CONTENT
    510 /* cgi maps are simple ".postfix /path/to/prog" */
    511 void
    512 bozo_add_content_map_cgi(bozohttpd_t *httpd, const char *arg,
    513                          const char *cgihandler)
    514 {
    515 	bozo_content_map_t *map;
    516 
    517 	debug((httpd, DEBUG_NORMAL, "bozo_add_content_map_cgi: name %s cgi %s",
    518 		arg, cgihandler));
    519 
    520 	httpd->process_cgi = 1;
    521 
    522 	map = bozo_get_content_map(httpd, arg);
    523 	map->name = arg;
    524 	map->type = map->encoding = map->encoding11 = NULL;
    525 	map->cgihandler = cgihandler;
    526 }
    527 #endif /* NO_DYNAMIC_CONTENT */
    528 
    529 #endif /* NO_CGIBIN_SUPPORT */
    530