Home | History | Annotate | Line # | Download | only in httpd
cgi-bozo.c revision 1.13
      1 /*	$NetBSD: cgi-bozo.c,v 1.13 2009/04/18 21:22:03 mrg Exp $	*/
      2 
      3 /*	$eterna: cgi-bozo.c,v 1.30 2009/04/18 12:39:28 mrg Exp $	*/
      4 
      5 /*
      6  * Copyright (c) 1997-2009 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 static	char	*cgibin;	/* cgi-bin directory */
     57 static	int	Cflag;		/* added a cgi handler, always process_cgi() */
     58 
     59 static	const char *	content_cgihandler(http_req *, const char *);
     60 static	void		finish_cgi_output(http_req *request, int, int);
     61 static	int		parse_header(const char *, ssize_t, char **, char **);
     62 static	void		append_index_html(char **);
     63 
     64 void
     65 set_cgibin(char *path)
     66 {
     67 	cgibin = path;
     68 	debug((DEBUG_OBESE, "cgibin (cgi-bin directory) is %s", cgibin));
     69 }
     70 
     71 /* help build up the environ pointer */
     72 void
     73 spsetenv(const char *env, const char *val, char **envp)
     74 {
     75 	char *s1 = bozomalloc(strlen(env) + strlen(val) + 2);
     76 
     77 	strcpy(s1, env);
     78 	strcat(s1, "=");
     79 	strcat(s1, val);
     80 	debug((DEBUG_OBESE, "spsetenv: %s", s1));
     81 	*envp = s1;
     82 }
     83 
     84 /*
     85  * Checks if the request has asked for a cgi-bin.  Should only be called if
     86  * cgibin is set.  If it starts CGIBIN_PREFIX or has a ncontent handler,
     87  * process the cgi, otherwise just return.  Returns 0 if it did not handle
     88  * the request.
     89  */
     90 int
     91 process_cgi(http_req *request)
     92 {
     93 	char	buf[WRSZ];
     94 	struct	headers *headp;
     95 	const char *type, *clen, *info, *cgihandler;
     96 	char	*query, *s, *t, *path, *env, *command, *file, *url;
     97 	char	**envp, **curenvp, *argv[4];
     98 	size_t	len;
     99 	ssize_t rbytes;
    100 	pid_t	pid;
    101 	int	envpsize, ix, nph;
    102 	int	sv[2];
    103 
    104 	if (!cgibin && !Cflag)
    105 		return 0;
    106 
    107 	asprintf(&file, "/%s", request->hr_file);
    108 	if (file == NULL)
    109 		return 0;
    110 	if (request->hr_query && strlen(request->hr_query))
    111 		query = bozostrdup(request->hr_query);
    112 	else
    113 		query = NULL;
    114 
    115 	asprintf(&url, "%s%s%s", file, query ? "?" : "", query ? query : "");
    116 	if (url == NULL)
    117 		goto out;
    118 	debug((DEBUG_NORMAL, "process_cgi: url `%s'", url));
    119 
    120 	path = NULL;
    121 	envp = NULL;
    122 	cgihandler = NULL;
    123 	command = NULL;
    124 	info = NULL;
    125 
    126 	len = strlen(url);
    127 
    128 	if (auth_check(request, url + 1))
    129 		goto out;
    130 
    131 	if (!cgibin || strncmp(url + 1, CGIBIN_PREFIX, CGIBIN_PREFIX_LEN) != 0) {
    132 		cgihandler = content_cgihandler(request, file + 1);
    133 		if (cgihandler == NULL) {
    134 			debug((DEBUG_FAT, "process_cgi: no handler, returning"));
    135 			goto out;
    136 		}
    137 		if (len == 0 || file[len - 1] == '/')
    138 			append_index_html(&file);
    139 		debug((DEBUG_NORMAL, "process_cgi: cgihandler `%s'",
    140 		    cgihandler));
    141 	} else if (len - 1 == CGIBIN_PREFIX_LEN)	/* url is "/cgi-bin/" */
    142 		append_index_html(&file);
    143 
    144 	ix = 0;
    145 	if (cgihandler) {
    146 		command = file + 1;
    147 		path = bozostrdup(cgihandler);
    148 		argv[ix++] = path;
    149 			/* argv[] = [ path, command, query, NULL ] */
    150 	} else {
    151 		command = file + CGIBIN_PREFIX_LEN + 1;
    152 		if ((s = strchr(command, '/')) != NULL) {
    153 			info = bozostrdup(s);
    154 			*s = '\0';
    155 		}
    156 		path = bozomalloc(strlen(cgibin) + 1 + strlen(command) + 1);
    157 		strcpy(path, cgibin);
    158 		strcat(path, "/");
    159 		strcat(path, command);
    160 			/* argv[] = [ command, query, NULL ] */
    161 	}
    162 	argv[ix++] = command;
    163 	argv[ix++] = query;
    164 	argv[ix++] = NULL;
    165 
    166 	nph = strncmp(command, "nph-", 4) == 0;
    167 
    168 	debug((DEBUG_FAT,
    169 	    "process_cgi: path `%s' cmd `%s' info `%s' query `%s' nph `%d'",
    170 	    path, command, strornull(info), strornull(query), nph));
    171 
    172 	type = request->hr_content_type;
    173 	clen = request->hr_content_length;
    174 
    175 	envpsize = 13 + request->hr_nheaders +
    176 	    (info && *info ? 1 : 0) +
    177 	    (query && *query ? 1 : 0) +
    178 	    (type && *type ? 1 : 0) +
    179 	    (clen && *clen ? 1 : 0) +
    180 	    (request->hr_remotehost && *request->hr_remotehost ? 1 : 0) +
    181 	    (request->hr_remoteaddr && *request->hr_remoteaddr ? 1 : 0) +
    182 	    auth_cgi_count(request) +
    183 	    (request->hr_serverport && *request->hr_serverport ? 1 : 0);
    184 
    185 	envp = bozomalloc(sizeof(*envp) * envpsize);
    186 	for (ix = 0; ix < envpsize; ix++)
    187 		envp[ix] = NULL;
    188 	curenvp = envp;
    189 
    190 	SIMPLEQ_FOREACH(headp, &request->hr_headers, h_next) {
    191 		const char *s2;
    192 		env = bozomalloc(6 + strlen(headp->h_header) + 1 +
    193 		    strlen(headp->h_value));
    194 
    195 		t = env;
    196 		strcpy(t, "HTTP_");
    197 		t += strlen(t);
    198 		for (s2 = headp->h_header; *s2; t++, s2++)
    199 			if (islower((u_int)*s2))
    200 				*t = toupper((u_int)*s2);
    201 			else if (*s2 == '-')
    202 				*t = '_';
    203 			else
    204 				*t = *s2;
    205 		*t = '\0';
    206 		debug((DEBUG_OBESE, "setting header %s as %s = %s",
    207 		    headp->h_header, env, headp->h_value));
    208 		spsetenv(env, headp->h_value, curenvp++);
    209 		free(env);
    210 	}
    211 
    212 #ifndef _PATH_DEFPATH
    213 #define _PATH_DEFPATH "/usr/bin:/bin"
    214 #endif
    215 
    216 	spsetenv("PATH", _PATH_DEFPATH, curenvp++);
    217 	spsetenv("IFS", " \t\n", curenvp++);
    218 	spsetenv("SERVER_NAME", myname, curenvp++);
    219 	spsetenv("GATEWAY_INTERFACE", "CGI/1.1", curenvp++);
    220 	spsetenv("SERVER_PROTOCOL", request->hr_proto, curenvp++);
    221 	spsetenv("REQUEST_METHOD", request->hr_methodstr, curenvp++);
    222 	spsetenv("SCRIPT_NAME", file, curenvp++);
    223 	spsetenv("SCRIPT_FILENAME", file + 1, curenvp++);
    224 	spsetenv("SERVER_SOFTWARE", server_software, curenvp++);
    225 	spsetenv("REQUEST_URI", request->hr_file, curenvp++);
    226 	spsetenv("DATE_GMT", http_date(), curenvp++);
    227 	if (query && *query)
    228 		spsetenv("QUERY_STRING", query, curenvp++);
    229 	if (info && *info)
    230 		spsetenv("PATH_INFO", info, curenvp++);
    231 	if (type && *type)
    232 		spsetenv("CONTENT_TYPE", type, curenvp++);
    233 	if (clen && *clen)
    234 		spsetenv("CONTENT_LENGTH", clen, curenvp++);
    235 	if (request->hr_serverport && *request->hr_serverport)
    236 		spsetenv("SERVER_PORT", request->hr_serverport, curenvp++);
    237 	if (request->hr_remotehost && *request->hr_remotehost)
    238 		spsetenv("REMOTE_HOST", request->hr_remotehost, curenvp++);
    239 	if (request->hr_remoteaddr && *request->hr_remoteaddr)
    240 		spsetenv("REMOTE_ADDR", request->hr_remoteaddr, curenvp++);
    241 	auth_cgi_setenv(request, &curenvp);
    242 
    243 	free(file);
    244 	free(url);
    245 
    246 	debug((DEBUG_FAT, "process_cgi: going exec %s, %s %s %s",
    247 	    path, argv[0], strornull(argv[1]), strornull(argv[2])));
    248 
    249 	if (-1 == socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, sv))
    250 		error(1, "child socketpair failed: %s", strerror(errno));
    251 
    252 	/*
    253 	 * We create 2 procs: one to become the CGI, one read from
    254 	 * the CGI and output to the network, and this parent will
    255 	 * continue reading from the network and writing to the
    256 	 * CGI procsss.
    257 	 */
    258 	switch (fork()) {
    259 	case -1: /* eep, failure */
    260 		error(1, "child fork failed: %s", strerror(errno));
    261 	case 0:
    262 		close(sv[0]);
    263 		dup2(sv[1], STDIN_FILENO);
    264 		dup2(sv[1], STDOUT_FILENO);
    265 		close(2);
    266 		close(sv[1]);
    267 		closelog();
    268 
    269 		if (-1 == execve(path, argv, envp))
    270 			error(1, "child exec failed: %s: %s",
    271 			      path, strerror(errno));
    272 		/* NOT REACHED */
    273 		error(1, "child execve returned?!");
    274 	}
    275 
    276 	close(sv[1]);
    277 
    278 	/* parent: read from stdin (bozoread()) write to sv[0] */
    279 	/* child: read from sv[0] (bozowrite()) write to stdout */
    280 	pid = fork();
    281 	if (pid == -1)
    282 		error(1, "io child fork failed: %s", strerror(errno));
    283 	else if (pid == 0) {
    284 		/* child reader/writer */
    285 		close(STDIN_FILENO);
    286 		finish_cgi_output(request, sv[0], nph);
    287 		/* if we're done output, our parent is useless... */
    288 		kill(getppid(), SIGKILL);
    289 		debug((DEBUG_FAT, "done processing cgi output"));
    290 		_exit(0);
    291 	}
    292 	close(STDOUT_FILENO);
    293 
    294 	/* XXX we should have some goo that times us out
    295 	 */
    296 	while ((rbytes = bozoread(STDIN_FILENO, buf, sizeof buf)) > 0) {
    297 		ssize_t wbytes;
    298 		char *bp = buf;
    299 
    300 		while (rbytes) {
    301 			wbytes = write(sv[0], buf , rbytes);
    302 			if (wbytes > 0) {
    303 				rbytes -= wbytes;
    304 				bp += wbytes;
    305 			} else
    306 				error(1, "write failed: %s", strerror(errno));
    307 		}
    308 	}
    309 	debug((DEBUG_FAT, "done processing cgi input"));
    310 	exit(0);
    311 
    312  out:
    313 	if (query)
    314 		free(query);
    315 	if (file)
    316 		free(file);
    317 	if (url)
    318 		free(url);
    319 	return 0;
    320 }
    321 
    322 /*
    323  * handle parsing a CGI header output, transposing a Status: header
    324  * into the HTTP reply (ie, instead of "200 OK").
    325  */
    326 static void
    327 finish_cgi_output(http_req *request, int in, int nph)
    328 {
    329 	char	buf[WRSZ];
    330 	char	*str;
    331 	ssize_t	len;
    332 	ssize_t rbytes;
    333 	SIMPLEQ_HEAD(, headers)	headers;
    334 	struct	headers *hdr, *nhdr;
    335 	int	write_header, nheaders = 0;
    336 
    337 	/* much of this code is like read_request()'s header loop. hmmm... */
    338 	SIMPLEQ_INIT(&headers);
    339 	write_header = nph == 0;
    340 	while (nph == 0 && (str = bozodgetln(in, &len, read)) != NULL) {
    341 		char	*hdr_name, *hdr_value;
    342 
    343 		if (parse_header(str, len, &hdr_name, &hdr_value))
    344 			break;
    345 
    346 		/*
    347 		 * The CGI 1.{1,2} spec both say that if the cgi program
    348 		 * returns a `Status:' header field then the server MUST
    349 		 * return it in the response.  If the cgi program does
    350 		 * not return any `Status:' header then the server should
    351 		 * respond with 200 OK.
    352 		 * XXX The CGI 1.1 and 1.2 specification differ slightly on
    353 		 * this in that v1.2 says that the script MUST NOT return a
    354 		 * `Status:' header if it is returning a `Location:' header.
    355 		 * For compatibility we are going with the CGI 1.1 behavior.
    356 		 */
    357 		if (strcasecmp(hdr_name, "status") == 0) {
    358 			debug((DEBUG_OBESE, "process_cgi:  writing HTTP header "
    359 					    "from status %s ..", hdr_value));
    360 			bozoprintf("%s %s\r\n", request->hr_proto, hdr_value);
    361 			bozoflush(stdout);
    362 			write_header = 0;
    363 			free(hdr_name);
    364 			break;
    365 		}
    366 
    367 		hdr = bozomalloc(sizeof *hdr);
    368 		hdr->h_header = hdr_name;
    369 		hdr->h_value = hdr_value;
    370 		SIMPLEQ_INSERT_TAIL(&headers, hdr, h_next);
    371 		nheaders++;
    372 	}
    373 
    374 	if (write_header) {
    375 		debug((DEBUG_OBESE, "process_cgi:  writing HTTP header .."));
    376 		bozoprintf("%s 200 OK\r\n", request->hr_proto);
    377 		bozoflush(stdout);
    378 	}
    379 
    380 	if (nheaders) {
    381 		debug((DEBUG_OBESE, "process_cgi:  writing delayed HTTP "
    382 				    "headers .."));
    383 		SIMPLEQ_FOREACH_SAFE(hdr, &headers, h_next, nhdr) {
    384 			bozoprintf("%s: %s\r\n", hdr->h_header, hdr->h_value);
    385 			free(hdr->h_header);
    386 			free(hdr);
    387 		}
    388 		bozoprintf("\r\n");
    389 		bozoflush(stdout);
    390 	}
    391 
    392 	/* XXX we should have some goo that times us out
    393 	 */
    394 	while ((rbytes = read(in, buf, sizeof buf)) > 0) {
    395 		ssize_t wbytes;
    396 		char *bp = buf;
    397 
    398 		while (rbytes) {
    399 			wbytes = bozowrite(STDOUT_FILENO, buf, rbytes);
    400 			if (wbytes > 0) {
    401 				rbytes -= wbytes;
    402 				bp += wbytes;
    403 			} else
    404 				error(1, "cgi output write failed: %s",
    405 				    strerror(errno));
    406 		}
    407 	}
    408 }
    409 
    410 static int
    411 parse_header(const char *str, ssize_t len, char **hdr_str, char **hdr_val)
    412 {
    413 	char	*name, *value;
    414 
    415 	/* if the string passed is zero-length bail out */
    416 	if (*str == '\0')
    417 		return -1;
    418 
    419 	value = bozostrdup(str);
    420 
    421 	/* locate the ':' separator in the header/value */
    422 	name = bozostrnsep(&value, ":", &len);
    423 
    424 	if (NULL == name || -1 == len) {
    425 		free(name);
    426 		return -1;
    427 	}
    428 
    429 	/* skip leading space/tab */
    430 	while (*value == ' ' || *value == '\t')
    431 		len--, value++;
    432 
    433 	*hdr_str = name;
    434 	*hdr_val = value;
    435 
    436 	return 0;
    437 }
    438 
    439 /*
    440  * given the file name, return a CGI interpreter
    441  */
    442 static const char *
    443 content_cgihandler(http_req *request, const char *file)
    444 {
    445 	struct	content_map	*map;
    446 
    447 	debug((DEBUG_FAT, "content_cgihandler: trying file %s", file));
    448 	map = match_content_map(file, 0);
    449 	if (map)
    450 		return (map->cgihandler);
    451 	return (NULL);
    452 }
    453 
    454 static void
    455 append_index_html(char **url)
    456 {
    457 	*url = bozorealloc(*url, strlen(*url) + strlen(index_html) + 1);
    458 	strcat(*url, index_html);
    459 	debug((DEBUG_NORMAL, "append_index_html: url adjusted to `%s'", *url));
    460 }
    461 
    462 #ifndef NO_DYNAMIC_CONTENT
    463 /* cgi maps are simple ".postfix /path/to/prog" */
    464 void
    465 add_content_map_cgi(char *arg, char *cgihandler)
    466 {
    467 	struct content_map *map;
    468 
    469 	debug((DEBUG_NORMAL, "add_content_map_cgi: name %s cgi %s", arg, cgihandler));
    470 
    471 	Cflag = 1;
    472 
    473 	map = get_content_map(arg);
    474 	map->name = arg;
    475 	map->type = map->encoding = map->encoding11 = NULL;
    476 	map->cgihandler = cgihandler;
    477 }
    478 #endif /* NO_DYNAMIC_CONTENT */
    479 
    480 #endif /* NO_CGIBIN_SUPPORT */
    481