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