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