Home | History | Annotate | Line # | Download | only in httpd
bozohttpd.c revision 1.75
      1 /*	$NetBSD: bozohttpd.c,v 1.75 2015/12/29 04:21:46 mrg Exp $	*/
      2 
      3 /*	$eterna: bozohttpd.c,v 1.178 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 program is dedicated to the Great God of Processed Cheese */
     34 
     35 /*
     36  * bozohttpd.c:  minimal httpd; provides only these features:
     37  *	- HTTP/0.9 (by virtue of ..)
     38  *	- HTTP/1.0
     39  *	- HTTP/1.1
     40  *	- CGI/1.1 this will only be provided for "system" scripts
     41  *	- automatic "missing trailing slash" redirections
     42  *	- configurable translation of /~user/ to ~user/public_html,
     43  *	  however, this does not include cgi-bin support
     44  *	- access lists via libwrap via inetd/tcpd
     45  *	- virtual hosting
     46  *	- not that we do not even pretend to understand MIME, but
     47  *	  rely only on the HTTP specification
     48  *	- ipv6 support
     49  *	- automatic `index.html' generation
     50  *	- configurable server name
     51  *	- directory index generation
     52  *	- daemon mode (lacks libwrap support)
     53  *	- .htpasswd support
     54  */
     55 
     56 /*
     57  * requirements for minimal http/1.1 (at least, as documented in
     58  * RFC 2616 (HTTP/1.1):
     59  *
     60  *	- 14.11: content-encoding handling. [1]
     61  *
     62  *	- 14.13: content-length handling.  this is only a SHOULD header
     63  *	  thus we could just not send it ever.  [1]
     64  *
     65  *	- 14.17: content-type handling. [1]
     66  *
     67  *	- 14.28: if-unmodified-since handling.  if-modified-since is
     68  *	  done since, shouldn't be too hard for this one.
     69  *
     70  * [1] need to revisit to ensure proper behaviour
     71  *
     72  * and the following is a list of features that we do not need
     73  * to have due to other limits, or are too lazy.  there are more
     74  * of these than are listed, but these are of particular note,
     75  * and could perhaps be implemented.
     76  *
     77  *	- 3.5/3.6: content/transfer codings.  probably can ignore
     78  *	  this?  we "SHOULD"n't.  but 4.4 says we should ignore a
     79  *	  `content-length' header upon reciept of a `transfer-encoding'
     80  *	  header.
     81  *
     82  *	- 5.1.1: request methods.  only MUST support GET and HEAD,
     83  *	  but there are new ones besides POST that are currently
     84  *	  supported: OPTIONS PUT DELETE TRACE and CONNECT, plus
     85  *	  extensions not yet known?
     86  *
     87  * 	- 10.1: we can ignore informational status codes
     88  *
     89  *	- 10.3.3/10.3.4/10.3.8:  just use '302' codes always.
     90  *
     91  *	- 14.1/14.2/14.3/14.27: we do not support Accept: headers.
     92  *	  just ignore them and send the request anyway.  they are
     93  *	  only SHOULD.
     94  *
     95  *	- 14.5/14.16/14.35: only support simple ranges: %d- and %d-%d
     96  *	  would be nice to support more.
     97  *
     98  *	- 14.9: we aren't a cache.
     99  *
    100  *	- 14.15: content-md5 would be nice.
    101  *
    102  *	- 14.24/14.26/14.27: if-match, if-none-match, if-range.  be
    103  *	  nice to support this.
    104  *
    105  *	- 14.44: Vary: seems unneeded.  ignore it for now.
    106  */
    107 
    108 #ifndef INDEX_HTML
    109 #define INDEX_HTML		"index.html"
    110 #endif
    111 #ifndef SERVER_SOFTWARE
    112 #define SERVER_SOFTWARE		"bozohttpd/20150501"
    113 #endif
    114 #ifndef DIRECT_ACCESS_FILE
    115 #define DIRECT_ACCESS_FILE	".bzdirect"
    116 #endif
    117 #ifndef REDIRECT_FILE
    118 #define REDIRECT_FILE		".bzredirect"
    119 #endif
    120 #ifndef ABSREDIRECT_FILE
    121 #define ABSREDIRECT_FILE	".bzabsredirect"
    122 #endif
    123 #ifndef PUBLIC_HTML
    124 #define PUBLIC_HTML		"public_html"
    125 #endif
    126 
    127 #ifndef USE_ARG
    128 #define USE_ARG(x)	/*LINTED*/(void)&(x)
    129 #endif
    130 
    131 /*
    132  * And so it begins ..
    133  */
    134 
    135 #include <sys/param.h>
    136 #include <sys/socket.h>
    137 #include <sys/time.h>
    138 #include <sys/mman.h>
    139 
    140 #include <arpa/inet.h>
    141 
    142 #include <ctype.h>
    143 #include <dirent.h>
    144 #include <errno.h>
    145 #include <fcntl.h>
    146 #include <netdb.h>
    147 #include <pwd.h>
    148 #include <grp.h>
    149 #include <signal.h>
    150 #include <stdarg.h>
    151 #include <stdlib.h>
    152 #include <string.h>
    153 #include <syslog.h>
    154 #include <time.h>
    155 #include <unistd.h>
    156 
    157 #include "bozohttpd.h"
    158 
    159 #ifndef MAX_WAIT_TIME
    160 #define	MAX_WAIT_TIME	60	/* hang around for 60 seconds max */
    161 #endif
    162 
    163 /* variables and functions */
    164 #ifndef LOG_FTP
    165 #define LOG_FTP LOG_DAEMON
    166 #endif
    167 
    168 volatile sig_atomic_t	alarmhit;
    169 
    170 /*
    171  * check there's enough space in the prefs and names arrays.
    172  */
    173 static int
    174 size_arrays(bozoprefs_t *bozoprefs, size_t needed)
    175 {
    176 	char	**temp;
    177 
    178 	if (bozoprefs->size == 0) {
    179 		/* only get here first time around */
    180 		bozoprefs->name = calloc(sizeof(char *), needed);
    181 		if (bozoprefs->name == NULL)
    182 			return 0;
    183 		bozoprefs->value = calloc(sizeof(char *), needed);
    184 		if (bozoprefs->value == NULL) {
    185 			free(bozoprefs->name);
    186 			return 0;
    187 		}
    188 		bozoprefs->size = needed;
    189 	} else if (bozoprefs->count == bozoprefs->size) {
    190 		/* only uses 'needed' when filled array */
    191 		temp = realloc(bozoprefs->name, sizeof(char *) * needed);
    192 		if (temp == NULL)
    193 			return 0;
    194 		bozoprefs->name = temp;
    195 		temp = realloc(bozoprefs->value, sizeof(char *) * needed);
    196 		if (temp == NULL)
    197 			return 0;
    198 		bozoprefs->value = temp;
    199 		bozoprefs->size += needed;
    200 	}
    201 	return 1;
    202 }
    203 
    204 static ssize_t
    205 findvar(bozoprefs_t *bozoprefs, const char *name)
    206 {
    207 	size_t	i;
    208 
    209 	for (i = 0; i < bozoprefs->count; i++)
    210 		if (strcmp(bozoprefs->name[i], name) == 0)
    211 			return (ssize_t)i;
    212 	return -1;
    213 }
    214 
    215 int
    216 bozo_set_pref(bozohttpd_t *httpd, bozoprefs_t *bozoprefs,
    217 	      const char *name, const char *value)
    218 {
    219 	ssize_t	i;
    220 
    221 	if ((i = findvar(bozoprefs, name)) < 0) {
    222 		/* add the element to the array */
    223 		if (!size_arrays(bozoprefs, bozoprefs->size + 15))
    224 			return 0;
    225 		i = bozoprefs->count++;
    226 		bozoprefs->name[i] = bozostrdup(httpd, NULL, name);
    227 	} else {
    228 		/* replace the element in the array */
    229 		if (bozoprefs->value[i]) {
    230 			free(bozoprefs->value[i]);
    231 			bozoprefs->value[i] = NULL;
    232 		}
    233 	}
    234 	bozoprefs->value[i] = bozostrdup(httpd, NULL, value);
    235 	return 1;
    236 }
    237 
    238 /*
    239  * get a variable's value, or NULL
    240  */
    241 char *
    242 bozo_get_pref(bozoprefs_t *bozoprefs, const char *name)
    243 {
    244 	ssize_t	i;
    245 
    246 	i = findvar(bozoprefs, name);
    247 	return i < 0 ? NULL : bozoprefs->value[i];
    248 }
    249 
    250 char *
    251 bozo_http_date(char *date, size_t datelen)
    252 {
    253 	struct	tm *tm;
    254 	time_t	now;
    255 
    256 	/* Sun, 06 Nov 1994 08:49:37 GMT */
    257 	now = time(NULL);
    258 	tm = gmtime(&now);	/* HTTP/1.1 spec rev 06 sez GMT only */
    259 	strftime(date, datelen, "%a, %d %b %Y %H:%M:%S GMT", tm);
    260 	return date;
    261 }
    262 
    263 /*
    264  * convert "in" into the three parts of a request (first line).
    265  * we allocate into file and query, but return pointers into
    266  * "in" for proto and method.
    267  */
    268 static void
    269 parse_request(bozohttpd_t *httpd, char *in, char **method, char **file,
    270 		char **query, char **proto)
    271 {
    272 	ssize_t	len;
    273 	char	*val;
    274 
    275 	USE_ARG(httpd);
    276 	debug((httpd, DEBUG_EXPLODING, "parse in: %s", in));
    277 	*method = *file = *query = *proto = NULL;
    278 
    279 	len = (ssize_t)strlen(in);
    280 	val = bozostrnsep(&in, " \t\n\r", &len);
    281 	if (len < 1 || val == NULL)
    282 		return;
    283 	*method = val;
    284 
    285 	while (*in == ' ' || *in == '\t')
    286 		in++;
    287 	val = bozostrnsep(&in, " \t\n\r", &len);
    288 	if (len < 1) {
    289 		if (len == 0)
    290 			*file = val;
    291 		else
    292 			*file = in;
    293 	} else {
    294 		*file = val;
    295 
    296 		*query = strchr(*file, '?');
    297 		if (*query)
    298 			*(*query)++ = '\0';
    299 
    300 		if (in) {
    301 			while (*in && (*in == ' ' || *in == '\t'))
    302 				in++;
    303 			if (*in)
    304 				*proto = in;
    305 		}
    306 	}
    307 
    308 	/* allocate private copies */
    309 	*file = bozostrdup(httpd, NULL, *file);
    310 	if (*query)
    311 		*query = bozostrdup(httpd, NULL, *query);
    312 
    313 	debug((httpd, DEBUG_FAT,
    314 		"url: method: \"%s\" file: \"%s\" query: \"%s\" proto: \"%s\"",
    315 		*method, *file, *query, *proto));
    316 }
    317 
    318 /*
    319  * cleanup a bozo_httpreq_t after use
    320  */
    321 void
    322 bozo_clean_request(bozo_httpreq_t *request)
    323 {
    324 	struct bozoheaders *hdr, *ohdr = NULL;
    325 
    326 	if (request == NULL)
    327 		return;
    328 
    329 	/* If SSL enabled cleanup SSL structure. */
    330 	bozo_ssl_destroy(request->hr_httpd);
    331 
    332 	/* clean up request */
    333 	free(request->hr_remotehost);
    334 	free(request->hr_remoteaddr);
    335 	free(request->hr_serverport);
    336 	free(request->hr_virthostname);
    337 	free(request->hr_file);
    338 	free(request->hr_oldfile);
    339 	free(request->hr_query);
    340 	free(request->hr_host);
    341 	bozo_user_free(request->hr_user);
    342 	bozo_auth_cleanup(request);
    343 	for (hdr = SIMPLEQ_FIRST(&request->hr_headers); hdr;
    344 	    hdr = SIMPLEQ_NEXT(hdr, h_next)) {
    345 		free(hdr->h_value);
    346 		free(hdr->h_header);
    347 		free(ohdr);
    348 		ohdr = hdr;
    349 	}
    350 	free(ohdr);
    351 
    352 	free(request);
    353 }
    354 
    355 /*
    356  * send a HTTP/1.1 408 response if we timeout.
    357  */
    358 /* ARGSUSED */
    359 static void
    360 alarmer(int sig)
    361 {
    362 	alarmhit = 1;
    363 }
    364 
    365 /*
    366  * add or merge this header (val: str) into the requests list
    367  */
    368 static bozoheaders_t *
    369 addmerge_header(bozo_httpreq_t *request, char *val,
    370 		char *str, ssize_t len)
    371 {
    372 	struct	bozohttpd_t *httpd = request->hr_httpd;
    373 	struct	bozoheaders *hdr;
    374 
    375 	USE_ARG(len);
    376 	/* do we exist already? */
    377 	SIMPLEQ_FOREACH(hdr, &request->hr_headers, h_next) {
    378 		if (strcasecmp(val, hdr->h_header) == 0)
    379 			break;
    380 	}
    381 
    382 	if (hdr) {
    383 		/* yup, merge it in */
    384 		char *nval;
    385 
    386 		bozoasprintf(httpd, &nval, "%s, %s", hdr->h_value, str);
    387 		free(hdr->h_value);
    388 		hdr->h_value = nval;
    389 	} else {
    390 		/* nope, create a new one */
    391 
    392 		hdr = bozomalloc(httpd, sizeof *hdr);
    393 		hdr->h_header = bozostrdup(httpd, request, val);
    394 		if (str && *str)
    395 			hdr->h_value = bozostrdup(httpd, request, str);
    396 		else
    397 			hdr->h_value = bozostrdup(httpd, request, " ");
    398 
    399 		SIMPLEQ_INSERT_TAIL(&request->hr_headers, hdr, h_next);
    400 		request->hr_nheaders++;
    401 	}
    402 
    403 	return hdr;
    404 }
    405 
    406 /*
    407  * as the prototype string is not constant (eg, "HTTP/1.1" is equivalent
    408  * to "HTTP/001.01"), we MUST parse this.
    409  */
    410 static int
    411 process_proto(bozo_httpreq_t *request, const char *proto)
    412 {
    413 	struct	bozohttpd_t *httpd = request->hr_httpd;
    414 	char	majorstr[16], *minorstr;
    415 	int	majorint, minorint;
    416 
    417 	if (proto == NULL) {
    418 got_proto_09:
    419 		request->hr_proto = httpd->consts.http_09;
    420 		debug((httpd, DEBUG_FAT, "request %s is http/0.9",
    421 			request->hr_file));
    422 		return 0;
    423 	}
    424 
    425 	if (strncasecmp(proto, "HTTP/", 5) != 0)
    426 		goto bad;
    427 	strncpy(majorstr, proto + 5, sizeof majorstr);
    428 	majorstr[sizeof(majorstr)-1] = 0;
    429 	minorstr = strchr(majorstr, '.');
    430 	if (minorstr == NULL)
    431 		goto bad;
    432 	*minorstr++ = 0;
    433 
    434 	majorint = atoi(majorstr);
    435 	minorint = atoi(minorstr);
    436 
    437 	switch (majorint) {
    438 	case 0:
    439 		if (minorint != 9)
    440 			break;
    441 		goto got_proto_09;
    442 	case 1:
    443 		if (minorint == 0)
    444 			request->hr_proto = httpd->consts.http_10;
    445 		else if (minorint == 1)
    446 			request->hr_proto = httpd->consts.http_11;
    447 		else
    448 			break;
    449 
    450 		debug((httpd, DEBUG_FAT, "request %s is %s",
    451 		    request->hr_file, request->hr_proto));
    452 		SIMPLEQ_INIT(&request->hr_headers);
    453 		request->hr_nheaders = 0;
    454 		return 0;
    455 	}
    456 bad:
    457 	return bozo_http_error(httpd, 404, NULL, "unknown prototype");
    458 }
    459 
    460 /*
    461  * process each type of HTTP method, setting this HTTP requests
    462  * method type.
    463  */
    464 static struct method_map {
    465 	const char *name;
    466 	int	type;
    467 } method_map[] = {
    468 	{ "GET", 	HTTP_GET, },
    469 	{ "POST",	HTTP_POST, },
    470 	{ "HEAD",	HTTP_HEAD, },
    471 #if 0	/* other non-required http/1.1 methods */
    472 	{ "OPTIONS",	HTTP_OPTIONS, },
    473 	{ "PUT",	HTTP_PUT, },
    474 	{ "DELETE",	HTTP_DELETE, },
    475 	{ "TRACE",	HTTP_TRACE, },
    476 	{ "CONNECT",	HTTP_CONNECT, },
    477 #endif
    478 	{ NULL,		0, },
    479 };
    480 
    481 static int
    482 process_method(bozo_httpreq_t *request, const char *method)
    483 {
    484 	struct	bozohttpd_t *httpd = request->hr_httpd;
    485 	struct	method_map *mmp;
    486 
    487 	if (request->hr_proto == httpd->consts.http_11)
    488 		request->hr_allow = "GET, HEAD, POST";
    489 
    490 	for (mmp = method_map; mmp->name; mmp++)
    491 		if (strcasecmp(method, mmp->name) == 0) {
    492 			request->hr_method = mmp->type;
    493 			request->hr_methodstr = mmp->name;
    494 			return 0;
    495 		}
    496 
    497 	return bozo_http_error(httpd, 404, request, "unknown method");
    498 }
    499 
    500 /*
    501  * This function reads a http request from stdin, returning a pointer to a
    502  * bozo_httpreq_t structure, describing the request.
    503  */
    504 bozo_httpreq_t *
    505 bozo_read_request(bozohttpd_t *httpd)
    506 {
    507 	struct	sigaction	sa;
    508 	char	*str, *val, *method, *file, *proto, *query;
    509 	char	*host, *addr, *port;
    510 	char	bufport[10];
    511 	char	hbuf[NI_MAXHOST], abuf[NI_MAXHOST];
    512 	struct	sockaddr_storage ss;
    513 	ssize_t	len;
    514 	int	line = 0;
    515 	socklen_t slen;
    516 	bozo_httpreq_t *request;
    517 
    518 	/*
    519 	 * if we're in daemon mode, bozo_daemon_fork() will return here twice
    520 	 * for each call.  once in the child, returning 0, and once in the
    521 	 * parent, returning 1.  for each child, then we can setup SSL, and
    522 	 * the parent can signal the caller there was no request to process
    523 	 * and it will wait for another.
    524 	 */
    525 	if (bozo_daemon_fork(httpd))
    526 		return NULL;
    527 	if (bozo_ssl_accept(httpd))
    528 		return NULL;
    529 
    530 	request = bozomalloc(httpd, sizeof(*request));
    531 	memset(request, 0, sizeof(*request));
    532 	request->hr_httpd = httpd;
    533 	request->hr_allow = request->hr_host = NULL;
    534 	request->hr_content_type = request->hr_content_length = NULL;
    535 	request->hr_range = NULL;
    536 	request->hr_last_byte_pos = -1;
    537 	request->hr_if_modified_since = NULL;
    538 	request->hr_virthostname = NULL;
    539 	request->hr_file = NULL;
    540 	request->hr_oldfile = NULL;
    541 	bozo_auth_init(request);
    542 
    543 	slen = sizeof(ss);
    544 	if (getpeername(0, (struct sockaddr *)(void *)&ss, &slen) < 0)
    545 		host = addr = NULL;
    546 	else {
    547 		if (getnameinfo((struct sockaddr *)(void *)&ss, slen,
    548 		    abuf, sizeof abuf, NULL, 0, NI_NUMERICHOST) == 0)
    549 			addr = abuf;
    550 		else
    551 			addr = NULL;
    552 		if (httpd->numeric == 0 &&
    553 		    getnameinfo((struct sockaddr *)(void *)&ss, slen,
    554 				hbuf, sizeof hbuf, NULL, 0, 0) == 0)
    555 			host = hbuf;
    556 		else
    557 			host = NULL;
    558 	}
    559 	if (host != NULL)
    560 		request->hr_remotehost = bozostrdup(httpd, request, host);
    561 	if (addr != NULL)
    562 		request->hr_remoteaddr = bozostrdup(httpd, request, addr);
    563 	slen = sizeof(ss);
    564 
    565 	/*
    566 	 * Override the bound port from the request value, so it works even
    567 	 * if passed through a proxy that doesn't rewrite the port.
    568 	 */
    569 	if (httpd->bindport) {
    570 		if (strcmp(httpd->bindport, "80") != 0)
    571 			port = httpd->bindport;
    572 		else
    573 			port = NULL;
    574 	} else {
    575 		if (getsockname(0, (struct sockaddr *)(void *)&ss, &slen) < 0)
    576 			port = NULL;
    577 		else {
    578 			if (getnameinfo((struct sockaddr *)(void *)&ss, slen,
    579 					NULL, 0, bufport, sizeof bufport,
    580 					NI_NUMERICSERV) == 0)
    581 				port = bufport;
    582 			else
    583 				port = NULL;
    584 		}
    585 	}
    586 	if (port != NULL)
    587 		request->hr_serverport = bozostrdup(httpd, request, port);
    588 
    589 	/*
    590 	 * setup a timer to make sure the request is not hung
    591 	 */
    592 	sa.sa_handler = alarmer;
    593 	sigemptyset(&sa.sa_mask);
    594 	sigaddset(&sa.sa_mask, SIGALRM);
    595 	sa.sa_flags = 0;
    596 	sigaction(SIGALRM, &sa, NULL);
    597 
    598 	alarm(MAX_WAIT_TIME);
    599 	while ((str = bozodgetln(httpd, STDIN_FILENO, &len, bozo_read)) != NULL) {
    600 		alarm(0);
    601 		if (alarmhit) {
    602 			(void)bozo_http_error(httpd, 408, NULL,
    603 					"request timed out");
    604 			goto cleanup;
    605 		}
    606 		line++;
    607 
    608 		if (line == 1) {
    609 
    610 			if (len < 1) {
    611 				(void)bozo_http_error(httpd, 404, NULL,
    612 						"null method");
    613 				goto cleanup;
    614 			}
    615 			bozowarn(httpd,
    616 				  "got request ``%s'' from host %s to port %s",
    617 				  str,
    618 				  host ? host : addr ? addr : "<local>",
    619 				  port ? port : "<stdin>");
    620 
    621 			/* we allocate return space in file and query only */
    622 			parse_request(httpd, str, &method, &file, &query, &proto);
    623 			request->hr_file = file;
    624 			request->hr_query = query;
    625 			if (method == NULL) {
    626 				(void)bozo_http_error(httpd, 404, NULL,
    627 						"null method");
    628 				goto cleanup;
    629 			}
    630 			if (file == NULL) {
    631 				(void)bozo_http_error(httpd, 404, NULL,
    632 						"null file");
    633 				goto cleanup;
    634 			}
    635 
    636 			/*
    637 			 * note that we parse the proto first, so that we
    638 			 * can more properly parse the method and the url.
    639 			 */
    640 
    641 			if (process_proto(request, proto) ||
    642 			    process_method(request, method)) {
    643 				goto cleanup;
    644 			}
    645 
    646 			debug((httpd, DEBUG_FAT, "got file \"%s\" query \"%s\"",
    647 			    request->hr_file,
    648 			    request->hr_query ? request->hr_query : "<none>"));
    649 
    650 			/* http/0.9 has no header processing */
    651 			if (request->hr_proto == httpd->consts.http_09)
    652 				break;
    653 		} else {		/* incoming headers */
    654 			bozoheaders_t *hdr;
    655 
    656 			if (*str == '\0')
    657 				break;
    658 
    659 			val = bozostrnsep(&str, ":", &len);
    660 			debug((httpd, DEBUG_EXPLODING,
    661 			    "read_req2: after bozostrnsep: str ``%s'' val ``%s''",
    662 			    str, val));
    663 			if (val == NULL || len == -1) {
    664 				(void)bozo_http_error(httpd, 404, request,
    665 						"no header");
    666 				goto cleanup;
    667 			}
    668 			while (*str == ' ' || *str == '\t')
    669 				len--, str++;
    670 			while (*val == ' ' || *val == '\t')
    671 				val++;
    672 
    673 			if (bozo_auth_check_headers(request, val, str, len))
    674 				goto next_header;
    675 
    676 			hdr = addmerge_header(request, val, str, len);
    677 
    678 			if (strcasecmp(hdr->h_header, "content-type") == 0)
    679 				request->hr_content_type = hdr->h_value;
    680 			else if (strcasecmp(hdr->h_header, "content-length") == 0)
    681 				request->hr_content_length = hdr->h_value;
    682 			else if (strcasecmp(hdr->h_header, "host") == 0)
    683 				request->hr_host = bozostrdup(httpd, request,
    684 							      hdr->h_value);
    685 			/* RFC 2616 (HTTP/1.1): 14.20 */
    686 			else if (strcasecmp(hdr->h_header, "expect") == 0) {
    687 				(void)bozo_http_error(httpd, 417, request,
    688 						"we don't support Expect:");
    689 				goto cleanup;
    690 			}
    691 			else if (strcasecmp(hdr->h_header, "referrer") == 0 ||
    692 			         strcasecmp(hdr->h_header, "referer") == 0)
    693 				request->hr_referrer = hdr->h_value;
    694 			else if (strcasecmp(hdr->h_header, "range") == 0)
    695 				request->hr_range = hdr->h_value;
    696 			else if (strcasecmp(hdr->h_header,
    697 					"if-modified-since") == 0)
    698 				request->hr_if_modified_since = hdr->h_value;
    699 			else if (strcasecmp(hdr->h_header,
    700 					"accept-encoding") == 0)
    701 				request->hr_accept_encoding = hdr->h_value;
    702 
    703 			debug((httpd, DEBUG_FAT, "adding header %s: %s",
    704 			    hdr->h_header, hdr->h_value));
    705 		}
    706 next_header:
    707 		alarm(MAX_WAIT_TIME);
    708 	}
    709 
    710 	/* now, clear it all out */
    711 	alarm(0);
    712 	signal(SIGALRM, SIG_DFL);
    713 
    714 	/* RFC1945, 8.3 */
    715 	if (request->hr_method == HTTP_POST &&
    716 	    request->hr_content_length == NULL) {
    717 		(void)bozo_http_error(httpd, 400, request,
    718 				"missing content length");
    719 		goto cleanup;
    720 	}
    721 
    722 	/* RFC 2616 (HTTP/1.1), 14.23 & 19.6.1.1 */
    723 	if (request->hr_proto == httpd->consts.http_11 &&
    724 	    /*(strncasecmp(request->hr_file, "http://", 7) != 0) &&*/
    725 	    request->hr_host == NULL) {
    726 		(void)bozo_http_error(httpd, 400, request,
    727 				"missing Host header");
    728 		goto cleanup;
    729 	}
    730 
    731 	if (request->hr_range != NULL) {
    732 		debug((httpd, DEBUG_FAT, "hr_range: %s", request->hr_range));
    733 		/* support only simple ranges %d- and %d-%d */
    734 		if (strchr(request->hr_range, ',') == NULL) {
    735 			const char *rstart, *dash;
    736 
    737 			rstart = strchr(request->hr_range, '=');
    738 			if (rstart != NULL) {
    739 				rstart++;
    740 				dash = strchr(rstart, '-');
    741 				if (dash != NULL && dash != rstart) {
    742 					dash++;
    743 					request->hr_have_range = 1;
    744 					request->hr_first_byte_pos =
    745 					    strtoll(rstart, NULL, 10);
    746 					if (request->hr_first_byte_pos < 0)
    747 						request->hr_first_byte_pos = 0;
    748 					if (*dash != '\0') {
    749 						request->hr_last_byte_pos =
    750 						    strtoll(dash, NULL, 10);
    751 						if (request->hr_last_byte_pos < 0)
    752 							request->hr_last_byte_pos = -1;
    753 					}
    754 				}
    755 			}
    756 		}
    757 	}
    758 
    759 	debug((httpd, DEBUG_FAT, "bozo_read_request returns url %s in request",
    760 	       request->hr_file));
    761 	return request;
    762 
    763 cleanup:
    764 	bozo_clean_request(request);
    765 
    766 	return NULL;
    767 }
    768 
    769 static int
    770 mmap_and_write_part(bozohttpd_t *httpd, int fd, off_t first_byte_pos, size_t sz)
    771 {
    772 	size_t mappedsz, wroffset;
    773 	off_t mappedoffset;
    774 	char *addr;
    775 	void *mappedaddr;
    776 
    777 	/*
    778 	 * we need to ensure that both the size *and* offset arguments to
    779 	 * mmap() are page-aligned.  our formala for this is:
    780 	 *
    781 	 *    input offset: first_byte_pos
    782 	 *    input size: sz
    783 	 *
    784 	 *    mapped offset = page align truncate (input offset)
    785 	 *    mapped size   =
    786 	 *        page align extend (input offset - mapped offset + input size)
    787 	 *    write offset  = input offset - mapped offset
    788 	 *
    789 	 * we use the write offset in all writes
    790 	 */
    791 	mappedoffset = first_byte_pos & ~(httpd->page_size - 1);
    792 	mappedsz = (size_t)
    793 		(first_byte_pos - mappedoffset + sz + httpd->page_size - 1) &
    794 		~(httpd->page_size - 1);
    795 	wroffset = (size_t)(first_byte_pos - mappedoffset);
    796 
    797 	addr = mmap(0, mappedsz, PROT_READ, MAP_SHARED, fd, mappedoffset);
    798 	if (addr == (char *)-1) {
    799 		bozowarn(httpd, "mmap failed: %s", strerror(errno));
    800 		return -1;
    801 	}
    802 	mappedaddr = addr;
    803 
    804 #ifdef MADV_SEQUENTIAL
    805 	(void)madvise(addr, sz, MADV_SEQUENTIAL);
    806 #endif
    807 	while (sz > BOZO_WRSZ) {
    808 		if (bozo_write(httpd, STDOUT_FILENO, addr + wroffset,
    809 				BOZO_WRSZ) != BOZO_WRSZ) {
    810 			bozowarn(httpd, "write failed: %s", strerror(errno));
    811 			goto out;
    812 		}
    813 		debug((httpd, DEBUG_OBESE, "wrote %d bytes", BOZO_WRSZ));
    814 		sz -= BOZO_WRSZ;
    815 		addr += BOZO_WRSZ;
    816 	}
    817 	if (sz && (size_t)bozo_write(httpd, STDOUT_FILENO, addr + wroffset,
    818 				sz) != sz) {
    819 		bozowarn(httpd, "final write failed: %s", strerror(errno));
    820 		goto out;
    821 	}
    822 	debug((httpd, DEBUG_OBESE, "wrote %d bytes", (int)sz));
    823  out:
    824 	if (munmap(mappedaddr, mappedsz) < 0) {
    825 		bozowarn(httpd, "munmap failed");
    826 		return -1;
    827 	}
    828 
    829 	return 0;
    830 }
    831 
    832 static int
    833 parse_http_date(const char *val, time_t *timestamp)
    834 {
    835 	char *remainder;
    836 	struct tm tm;
    837 
    838 	if ((remainder = strptime(val, "%a, %d %b %Y %T GMT", &tm)) == NULL &&
    839 	    (remainder = strptime(val, "%a, %d-%b-%y %T GMT", &tm)) == NULL &&
    840 	    (remainder = strptime(val, "%a %b %d %T %Y", &tm)) == NULL)
    841 		return 0; /* Invalid HTTP date format */
    842 
    843 	if (*remainder)
    844 		return 0; /* No trailing garbage */
    845 
    846 	*timestamp = timegm(&tm);
    847 	return 1;
    848 }
    849 
    850 /*
    851  * given an url, encode it ala rfc 3986.  ie, escape ? and friends.
    852  * note that this function returns a static buffer, and thus needs
    853  * to be updated for any sort of parallel processing. escape only
    854  * chosen characters for absolute redirects
    855  */
    856 char *
    857 bozo_escape_rfc3986(bozohttpd_t *httpd, const char *url, int absolute)
    858 {
    859 	static char *buf;
    860 	static size_t buflen = 0;
    861 	size_t len;
    862 	const char *s;
    863 	char *d;
    864 
    865 	len = strlen(url);
    866 	if (buflen < len * 3 + 1) {
    867 		buflen = len * 3 + 1;
    868 		buf = bozorealloc(httpd, buf, buflen);
    869 	}
    870 
    871 	for (len = 0, s = url, d = buf; *s;) {
    872 		if (*s & 0x80)
    873 			goto encode_it;
    874 		switch (*s) {
    875 		case ':':
    876 		case '?':
    877 		case '#':
    878 		case '[':
    879 		case ']':
    880 		case '@':
    881 		case '!':
    882 		case '$':
    883 		case '&':
    884 		case '\'':
    885 		case '(':
    886 		case ')':
    887 		case '*':
    888 		case '+':
    889 		case ',':
    890 		case ';':
    891 		case '=':
    892 		case '%':
    893 		case '"':
    894 			if (absolute)
    895 				goto leave_it;
    896 		case '\n':
    897 		case '\r':
    898 		case ' ':
    899 		encode_it:
    900 			snprintf(d, 4, "%%%02X", *s++);
    901 			d += 3;
    902 			len += 3;
    903 			break;
    904 		leave_it:
    905 		default:
    906 			*d++ = *s++;
    907 			len++;
    908 			break;
    909 		}
    910 	}
    911 	buf[len] = 0;
    912 
    913 	return buf;
    914 }
    915 
    916 /*
    917  * do automatic redirection -- if there are query parameters or userdir for
    918  * the URL we will tack these on to the new (redirected) URL.
    919  */
    920 static void
    921 handle_redirect(bozo_httpreq_t *request, const char *url, int absolute)
    922 {
    923 	bozohttpd_t *httpd = request->hr_httpd;
    924 	char *finalurl, *urlbuf;
    925 #ifndef NO_USER_SUPPORT
    926 	char *userbuf;
    927 #endif /* !NO_USER_SUPPORT */
    928 	char portbuf[20];
    929 	const char *hostname = BOZOHOST(httpd, request);
    930 	size_t finalurl_len;
    931 	int query = 0;
    932 	int absproto = 0; /* absolute redirect provides own schema
    933 			   * eg. https:// */
    934 
    935 	if (url == NULL) {
    936 		bozoasprintf(httpd, &urlbuf, "/%s/", request->hr_file);
    937 		url = urlbuf;
    938 	} else
    939 		urlbuf = NULL;
    940 
    941 #ifndef NO_USER_SUPPORT
    942 	if (request->hr_user && !absolute) {
    943 		bozoasprintf(httpd, &userbuf, "/~%s%s", request->hr_user, url);
    944 		url = userbuf;
    945 	} else
    946 		userbuf = NULL;
    947 #endif /* !NO_USER_SUPPORT */
    948 
    949 	if (absolute) {
    950 		char *sep = NULL;
    951 		const char *s;
    952 
    953 		/*
    954 		 * absolute redirect may specify own protocol i.e. to redirect
    955 		 * to another schema like https:// or ftp://.
    956 		 * Details: RFC 3986, section 3.
    957 		 */
    958 
    959 		/* 1. check if url contains :// */
    960 		sep = strstr(url, "://");
    961 
    962 		/*
    963 		 * RFC 3986, section 3.1:
    964 		 * scheme      = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )
    965 		 */
    966 		if (sep) {
    967 			for (s = url; s != sep;) {
    968 				if (!isalnum((int)*s) &&
    969 				    *s != '+' && *s != '-' && *s != '.')
    970 					break;
    971 				if (++s == sep) {
    972 					absproto = 1;
    973 				}
    974 			}
    975 		}
    976 	}
    977 
    978 	url = bozo_escape_rfc3986(httpd, url, absolute);
    979 
    980 	if (request->hr_query && strlen(request->hr_query))
    981 		query = 1;
    982 
    983 	if (request->hr_serverport && strcmp(request->hr_serverport, "80") != 0)
    984 		snprintf(portbuf, sizeof(portbuf), ":%s",
    985 		    request->hr_serverport);
    986 	else
    987 		portbuf[0] = '\0';
    988 
    989 	/* construct final redirection url */
    990 	/* XXX asprintf */
    991 	finalurl_len = strlen(url) + 1;
    992 	if (!absproto) {
    993 		/* add default schema */
    994 		if (httpd->sslinfo)
    995 			finalurl_len += sizeof("https://") - 1;
    996 		else
    997 			finalurl_len += sizeof("http://") - 1;
    998 	}
    999 	if (absolute == 0)
   1000 		finalurl_len += strlen(hostname)+strlen(portbuf);
   1001 	if (query)
   1002 		finalurl_len += strlen(request->hr_query) + 1; /* byte more for ? */
   1003 	finalurl = bozomalloc(httpd, finalurl_len);
   1004 	strcpy(finalurl, "");
   1005 	if (!absproto) {
   1006 		/* add default schema */
   1007 		if (httpd->sslinfo)
   1008 			strlcat(finalurl, "https://", finalurl_len);
   1009 		else
   1010 			strlcat(finalurl, "http://", finalurl_len);
   1011 	}
   1012 	if (absolute == 0) {
   1013 		strlcat(finalurl, hostname, finalurl_len);
   1014 		strlcat(finalurl, portbuf, finalurl_len);
   1015 	}
   1016 	strlcat(finalurl, url, finalurl_len);
   1017 	if (query) {
   1018 		strlcat(finalurl, "?", finalurl_len);
   1019 		strlcat(finalurl, request->hr_query, finalurl_len);
   1020 	}
   1021 
   1022 	bozowarn(httpd, "redirecting %s", finalurl);
   1023 	debug((httpd, DEBUG_FAT, "redirecting %s", finalurl));
   1024 
   1025 	bozo_printf(httpd, "%s 301 Document Moved\r\n", request->hr_proto);
   1026 	if (request->hr_proto != httpd->consts.http_09)
   1027 		bozo_print_header(request, NULL, "text/html", NULL);
   1028 	if (request->hr_proto != httpd->consts.http_09)
   1029 		bozo_printf(httpd, "Location: %s\r\n", finalurl);
   1030 	bozo_printf(httpd, "\r\n");
   1031 	if (request->hr_method == HTTP_HEAD)
   1032 		goto head;
   1033 	bozo_printf(httpd, "<html><head><title>Document Moved</title></head>\n");
   1034 	bozo_printf(httpd, "<body><h1>Document Moved</h1>\n");
   1035 	bozo_printf(httpd, "This document had moved <a href=\"%s\">here</a>\n",
   1036 	  finalurl);
   1037 	bozo_printf(httpd, "</body></html>\n");
   1038 head:
   1039 	bozo_flush(httpd, stdout);
   1040 	free(urlbuf);
   1041 	free(finalurl);
   1042 #ifndef NO_USER_SUPPORT
   1043 	free(userbuf);
   1044 #endif /* !NO_USER_SUPPORT */
   1045 }
   1046 
   1047 /*
   1048  * deal with virtual host names; we do this:
   1049  *	if we have a virtual path root (httpd->virtbase), and we are given a
   1050  *	virtual host spec (Host: ho.st or http://ho.st/), see if this
   1051  *	directory exists under httpd->virtbase.  if it does, use this as the
   1052  #	new slashdir.
   1053  */
   1054 static int
   1055 check_virtual(bozo_httpreq_t *request)
   1056 {
   1057 	bozohttpd_t *httpd = request->hr_httpd;
   1058 	char *file = request->hr_file, *s;
   1059 	size_t len;
   1060 
   1061 	/*
   1062 	 * convert http://virtual.host/ to request->hr_host
   1063 	 */
   1064 	debug((httpd, DEBUG_OBESE, "checking for http:// virtual host in ``%s''",
   1065 			file));
   1066 	if (strncasecmp(file, "http://", 7) == 0) {
   1067 		/* we would do virtual hosting here? */
   1068 		file += 7;
   1069 		/* RFC 2616 (HTTP/1.1), 5.2: URI takes precedence over Host: */
   1070 		free(request->hr_host);
   1071 		request->hr_host = bozostrdup(httpd, request, file);
   1072 		if ((s = strchr(request->hr_host, '/')) != NULL)
   1073 			*s = '\0';
   1074 		s = strchr(file, '/');
   1075 		free(request->hr_file);
   1076 		request->hr_file = bozostrdup(httpd, request, s ? s : "/");
   1077 		debug((httpd, DEBUG_OBESE, "got host ``%s'' file is now ``%s''",
   1078 		    request->hr_host, request->hr_file));
   1079 	} else if (!request->hr_host)
   1080 		goto use_slashdir;
   1081 
   1082 	/*
   1083 	 * canonicalise hr_host - that is, remove any :80.
   1084 	 */
   1085 	len = strlen(request->hr_host);
   1086 	if (len > 3 && strcmp(request->hr_host + len - 3, ":80") == 0) {
   1087 		request->hr_host[len - 3] = '\0';
   1088 		len = strlen(request->hr_host);
   1089 	}
   1090 
   1091 	if (!httpd->virtbase) {
   1092 
   1093 		/*
   1094 		 * if we don't use vhost support, then set virthostname if
   1095 		 * user supplied Host header. It will be used for possible
   1096 		 * redirections
   1097 		 */
   1098 
   1099 		if (request->hr_host) {
   1100 			s = strrchr(request->hr_host, ':');
   1101 			if (s != NULL)
   1102 				/* truncate Host: as we want to copy it without port part */
   1103 				*s = '\0';
   1104 			request->hr_virthostname = bozostrdup(httpd, request,
   1105 			  request->hr_host);
   1106 			if (s != NULL)
   1107 				/* fix Host: again, if we truncated it */
   1108 				*s = ':';
   1109 		}
   1110 
   1111 		goto use_slashdir;
   1112 	}
   1113 
   1114 	/*
   1115 	 * ok, we have a virtual host, use opendir(3) to find a case
   1116 	 * insensitive match for the virtual host we are asked for.
   1117 	 * note that if the virtual host is the same as the master,
   1118 	 * we don't need to do anything special.
   1119 	 */
   1120 	debug((httpd, DEBUG_OBESE,
   1121 	    "check_virtual: checking host `%s' under httpd->virtbase `%s' "
   1122 	    "for file `%s'",
   1123 	    request->hr_host, httpd->virtbase, request->hr_file));
   1124 	if (strncasecmp(httpd->virthostname, request->hr_host, len) != 0) {
   1125 		s = 0;
   1126 		DIR *dirp;
   1127 		struct dirent *d;
   1128 
   1129 		if ((dirp = opendir(httpd->virtbase)) != NULL) {
   1130 			while ((d = readdir(dirp)) != NULL) {
   1131 				if (strcmp(d->d_name, ".") == 0 ||
   1132 				    strcmp(d->d_name, "..") == 0) {
   1133 					continue;
   1134 				}
   1135 				debug((httpd, DEBUG_OBESE, "looking at dir``%s''",
   1136 			 	   d->d_name));
   1137 				if (strcmp(d->d_name, request->hr_host) == 0) {
   1138 					/* found it, punch it */
   1139 					debug((httpd, DEBUG_OBESE, "found it punch it"));
   1140 					request->hr_virthostname =
   1141 					    bozostrdup(httpd, request, d->d_name);
   1142 					bozoasprintf(httpd, &s, "%s/%s",
   1143 					    httpd->virtbase,
   1144 					    request->hr_virthostname);
   1145 					break;
   1146 				}
   1147 			}
   1148 			closedir(dirp);
   1149 		}
   1150 		else {
   1151 			debug((httpd, DEBUG_FAT, "opendir %s failed: %s",
   1152 			    httpd->virtbase, strerror(errno)));
   1153 		}
   1154 		if (s == 0) {
   1155 			if (httpd->unknown_slash)
   1156 				goto use_slashdir;
   1157 			return bozo_http_error(httpd, 404, request,
   1158 						"unknown URL");
   1159 		}
   1160 	} else
   1161 use_slashdir:
   1162 		s = httpd->slashdir;
   1163 
   1164 	/*
   1165 	 * ok, nailed the correct slashdir, chdir to it
   1166 	 */
   1167 	if (chdir(s) < 0)
   1168 		return bozo_http_error(httpd, 404, request,
   1169 					"can't chdir to slashdir");
   1170 	return 0;
   1171 }
   1172 
   1173 /*
   1174  * checks to see if this request has a valid .bzredirect file.  returns
   1175  * 0 when no redirection happend, or 1 when handle_redirect() has been
   1176  * called, -1 on error.
   1177  */
   1178 static int
   1179 check_bzredirect(bozo_httpreq_t *request)
   1180 {
   1181 	bozohttpd_t *httpd = request->hr_httpd;
   1182 	struct stat sb;
   1183 	char dir[MAXPATHLEN], redir[MAXPATHLEN], redirpath[MAXPATHLEN + 1],
   1184 	    path[MAXPATHLEN];
   1185 	char *basename, *finalredir;
   1186 	int rv, absolute;
   1187 
   1188 	/*
   1189 	 * if this pathname is really a directory, but doesn't end in /,
   1190 	 * use it as the directory to look for the redir file.
   1191 	 */
   1192 	if((size_t)snprintf(dir, sizeof(dir), "%s", request->hr_file + 1) >=
   1193 	  sizeof(dir)) {
   1194 		bozo_http_error(httpd, 404, request,
   1195 		  "file path too long");
   1196 		return -1;
   1197 	}
   1198 	debug((httpd, DEBUG_FAT, "check_bzredirect: dir %s", dir));
   1199 	basename = strrchr(dir, '/');
   1200 
   1201 	if ((!basename || basename[1] != '\0') &&
   1202 	    lstat(dir, &sb) == 0 && S_ISDIR(sb.st_mode)) {
   1203 		strcpy(path, dir);
   1204 	} else if (basename == NULL) {
   1205 		strcpy(path, ".");
   1206 		strcpy(dir, "");
   1207 	} else {
   1208 		*basename++ = '\0';
   1209 		bozo_check_special_files(request, basename);
   1210 		strcpy(path, dir);
   1211 	}
   1212 
   1213 	debug((httpd, DEBUG_FAT, "check_bzredirect: path %s", path));
   1214 
   1215 	if ((size_t)snprintf(redir, sizeof(redir), "%s/%s", path,
   1216 	  REDIRECT_FILE) >= sizeof(redir)) {
   1217 		bozo_http_error(httpd, 404, request,
   1218 		    "redirectfile path too long");
   1219 		return -1;
   1220 	}
   1221 	if (lstat(redir, &sb) == 0) {
   1222 		if (!S_ISLNK(sb.st_mode))
   1223 			return 0;
   1224 		absolute = 0;
   1225 	} else {
   1226 		if((size_t)snprintf(redir, sizeof(redir), "%s/%s", path,
   1227 		  ABSREDIRECT_FILE) >= sizeof(redir)) {
   1228 			bozo_http_error(httpd, 404, request,
   1229 			  "redirectfile path too long");
   1230 			return -1;
   1231 		}
   1232 		if (lstat(redir, &sb) < 0 || !S_ISLNK(sb.st_mode))
   1233 			return 0;
   1234 		absolute = 1;
   1235 	}
   1236 	debug((httpd, DEBUG_FAT, "check_bzredirect: calling readlink"));
   1237 	rv = readlink(redir, redirpath, sizeof redirpath - 1);
   1238 	if (rv == -1 || rv == 0) {
   1239 		debug((httpd, DEBUG_FAT, "readlink failed"));
   1240 		return 0;
   1241 	}
   1242 	redirpath[rv] = '\0';
   1243 	debug((httpd, DEBUG_FAT, "readlink returned \"%s\"", redirpath));
   1244 
   1245 	/* check if we need authentication */
   1246 	snprintf(path, sizeof(path), "%s/", dir);
   1247 	if (bozo_auth_check(request, path))
   1248 		return 1;
   1249 
   1250 	/* now we have the link pointer, redirect to the real place */
   1251 	if (!absolute && redirpath[0] != '/') {
   1252 		if ((size_t)snprintf(finalredir = redir, sizeof(redir), "%s%s/%s",
   1253 		  (strlen(dir) > 0 ? "/" : ""), dir, redirpath) >= sizeof(redir)) {
   1254 			bozo_http_error(httpd, 404, request,
   1255 			  "redirect path too long");
   1256 			return -1;
   1257 		}
   1258 	} else
   1259 		finalredir = redirpath;
   1260 
   1261 	debug((httpd, DEBUG_FAT, "check_bzredirect: new redir %s", finalredir));
   1262 	handle_redirect(request, finalredir, absolute);
   1263 	return 1;
   1264 }
   1265 
   1266 /* this fixes the %HH hack that RFC2396 requires.  */
   1267 static int
   1268 fix_url_percent(bozo_httpreq_t *request)
   1269 {
   1270 	bozohttpd_t *httpd = request->hr_httpd;
   1271 	char	*s, *t, buf[3], *url;
   1272 	char	*end;	/* if end is not-zero, we don't translate beyond that */
   1273 
   1274 	url = request->hr_file;
   1275 
   1276 	end = url + strlen(url);
   1277 
   1278 	/* fast forward to the first % */
   1279 	if ((s = strchr(url, '%')) == NULL)
   1280 		return 0;
   1281 
   1282 	t = s;
   1283 	do {
   1284 		if (end && s >= end) {
   1285 			debug((httpd, DEBUG_EXPLODING,
   1286 				"fu_%%: past end, filling out.."));
   1287 			while (*s)
   1288 				*t++ = *s++;
   1289 			break;
   1290 		}
   1291 		debug((httpd, DEBUG_EXPLODING,
   1292 			"fu_%%: got s == %%, s[1]s[2] == %c%c",
   1293 			s[1], s[2]));
   1294 		if (s[1] == '\0' || s[2] == '\0') {
   1295 			(void)bozo_http_error(httpd, 400, request,
   1296 			    "percent hack missing two chars afterwards");
   1297 			return 1;
   1298 		}
   1299 		if (s[1] == '0' && s[2] == '0') {
   1300 			(void)bozo_http_error(httpd, 404, request,
   1301 					"percent hack was %00");
   1302 			return 1;
   1303 		}
   1304 		if (s[1] == '2' && s[2] == 'f') {
   1305 			(void)bozo_http_error(httpd, 404, request,
   1306 					"percent hack was %2f (/)");
   1307 			return 1;
   1308 		}
   1309 
   1310 		buf[0] = *++s;
   1311 		buf[1] = *++s;
   1312 		buf[2] = '\0';
   1313 		s++;
   1314 		*t = (char)strtol(buf, NULL, 16);
   1315 		debug((httpd, DEBUG_EXPLODING,
   1316 				"fu_%%: strtol put '%02x' into *t", *t));
   1317 		if (*t++ == '\0') {
   1318 			(void)bozo_http_error(httpd, 400, request,
   1319 					"percent hack got a 0 back");
   1320 			return 1;
   1321 		}
   1322 
   1323 		while (*s && *s != '%') {
   1324 			if (end && s >= end)
   1325 				break;
   1326 			*t++ = *s++;
   1327 		}
   1328 	} while (*s);
   1329 	*t = '\0';
   1330 
   1331 	debug((httpd, DEBUG_FAT, "fix_url_percent returns %s in url",
   1332 			request->hr_file));
   1333 
   1334 	return 0;
   1335 }
   1336 
   1337 /*
   1338  * transform_request does this:
   1339  *	- ``expand'' %20 crapola
   1340  *	- punt if it doesn't start with /
   1341  *	- look for "http://myname/" and deal with it.
   1342  *	- maybe call bozo_process_cgi()
   1343  *	- check for ~user and call bozo_user_transform() if so
   1344  *	- if the length > 1, check for trailing slash.  if so,
   1345  *	  add the index.html file
   1346  *	- if the length is 1, return the index.html file
   1347  *	- disallow anything ending up with a file starting
   1348  *	  at "/" or having ".." in it.
   1349  *	- anything else is a really weird internal error
   1350  *	- returns malloced file to serve, if unhandled
   1351  */
   1352 static int
   1353 transform_request(bozo_httpreq_t *request, int *isindex)
   1354 {
   1355 	bozohttpd_t *httpd = request->hr_httpd;
   1356 	char	*file, *newfile = NULL;
   1357 	size_t	len;
   1358 
   1359 	file = NULL;
   1360 	*isindex = 0;
   1361 	debug((httpd, DEBUG_FAT, "tf_req: file %s", request->hr_file));
   1362 	if (fix_url_percent(request)) {
   1363 		goto bad_done;
   1364 	}
   1365 	if (check_virtual(request)) {
   1366 		goto bad_done;
   1367 	}
   1368 	file = request->hr_file;
   1369 
   1370 	if (file[0] != '/') {
   1371 		(void)bozo_http_error(httpd, 404, request, "unknown URL");
   1372 		goto bad_done;
   1373 	}
   1374 
   1375 	/* omit additional slashes at the beginning */
   1376 	while (file[1] == '/')
   1377 		file++;
   1378 
   1379 	/* fix file provided by user as it's used in other handlers */
   1380 	request->hr_file = file;
   1381 
   1382 	len = strlen(file);
   1383 
   1384 #ifndef NO_USER_SUPPORT
   1385 	/* first of all expand user path */
   1386 	if (len > 1 && httpd->enable_users && file[1] == '~') {
   1387 		if (file[2] == '\0') {
   1388 			(void)bozo_http_error(httpd, 404, request,
   1389 						"missing username");
   1390 			goto bad_done;
   1391 		}
   1392 		if (strchr(file + 2, '/') == NULL) {
   1393 			char *userredirecturl;
   1394 			bozoasprintf(httpd, &userredirecturl, "%s/", file);
   1395 			handle_redirect(request, userredirecturl, 0);
   1396 			free(userredirecturl);
   1397 			return 0;
   1398 		}
   1399 		debug((httpd, DEBUG_FAT, "calling bozo_user_transform"));
   1400 
   1401 		if (!bozo_user_transform(request))
   1402 			return 0;
   1403 
   1404 		file = request->hr_file;
   1405 		len = strlen(file);
   1406 	}
   1407 #endif /* NO_USER_SUPPORT */
   1408 
   1409 
   1410 	switch (check_bzredirect(request)) {
   1411 	case -1:
   1412 		goto bad_done;
   1413 	case 1:
   1414 		return 0;
   1415 	}
   1416 
   1417 	if (len > 1) {
   1418 		debug((httpd, DEBUG_FAT, "file[len-1] == %c", file[len-1]));
   1419 		if (file[len-1] == '/') {	/* append index.html */
   1420 			*isindex = 1;
   1421 			debug((httpd, DEBUG_FAT, "appending index.html"));
   1422 			newfile = bozomalloc(httpd,
   1423 					len + strlen(httpd->index_html) + 1);
   1424 			strcpy(newfile, file + 1);
   1425 			strcat(newfile, httpd->index_html);
   1426 		} else
   1427 			newfile = bozostrdup(httpd, request, file + 1);
   1428 	} else if (len == 1) {
   1429 		debug((httpd, DEBUG_EXPLODING, "tf_req: len == 1"));
   1430 		newfile = bozostrdup(httpd, request, httpd->index_html);
   1431 		*isindex = 1;
   1432 	} else {	/* len == 0 ? */
   1433 		(void)bozo_http_error(httpd, 500, request,
   1434 					"request->hr_file is nul?");
   1435 		goto bad_done;
   1436 	}
   1437 
   1438 	if (newfile == NULL) {
   1439 		(void)bozo_http_error(httpd, 500, request, "internal failure");
   1440 		goto bad_done;
   1441 	}
   1442 
   1443 	/*
   1444 	 * stop traversing outside our domain
   1445 	 *
   1446 	 * XXX true security only comes from our parent using chroot(2)
   1447 	 * before execve(2)'ing us.  or our own built in chroot(2) support.
   1448 	 */
   1449 
   1450 	debug((httpd, DEBUG_FAT, "newfile: %s", newfile));
   1451 
   1452 	if (*newfile == '/' || strcmp(newfile, "..") == 0 ||
   1453 	    strstr(newfile, "/..") || strstr(newfile, "../")) {
   1454 		(void)bozo_http_error(httpd, 403, request, "illegal request");
   1455 		goto bad_done;
   1456 	}
   1457 
   1458 	if (bozo_auth_check(request, newfile))
   1459 		goto bad_done;
   1460 
   1461 	if (strlen(newfile)) {
   1462 		request->hr_oldfile = request->hr_file;
   1463 		request->hr_file = newfile;
   1464 	}
   1465 
   1466 	if (bozo_process_cgi(request))
   1467 		return 0;
   1468 
   1469 	if (bozo_process_lua(request))
   1470 		return 0;
   1471 
   1472 	debug((httpd, DEBUG_FAT, "transform_request set: %s", newfile));
   1473 	return 1;
   1474 bad_done:
   1475 	debug((httpd, DEBUG_FAT, "transform_request returning: 0"));
   1476 	free(newfile);
   1477 	return 0;
   1478 }
   1479 
   1480 /*
   1481  * can_gzip checks if the request supports and prefers gzip encoding.
   1482  *
   1483  * XXX: we do not consider the associated q with gzip in making our
   1484  *      decision which is broken.
   1485  */
   1486 
   1487 static int
   1488 can_gzip(bozo_httpreq_t *request)
   1489 {
   1490 	const char	*pos;
   1491 	const char	*tmp;
   1492 	size_t		 len;
   1493 
   1494 	/* First we decide if the request can be gzipped at all. */
   1495 
   1496 	/* not if we already are encoded... */
   1497 	tmp = bozo_content_encoding(request, request->hr_file);
   1498 	if (tmp && *tmp)
   1499 		return 0;
   1500 
   1501 	/* not if we are not asking for the whole file... */
   1502 	if (request->hr_last_byte_pos != -1 || request->hr_have_range)
   1503 		return 0;
   1504 
   1505 	/* Then we determine if gzip is on the cards. */
   1506 
   1507 	for (pos = request->hr_accept_encoding; pos && *pos; pos += len) {
   1508 		while (*pos == ' ')
   1509 			pos++;
   1510 
   1511 		len = strcspn(pos, ";,");
   1512 
   1513 		if ((len == 4 && strncasecmp("gzip", pos, 4) == 0) ||
   1514 		    (len == 6 && strncasecmp("x-gzip", pos, 6) == 0))
   1515 			return 1;
   1516 
   1517 		if (pos[len] == ';')
   1518 			len += strcspn(&pos[len], ",");
   1519 
   1520 		if (pos[len])
   1521 			len++;
   1522 	}
   1523 
   1524 	return 0;
   1525 }
   1526 
   1527 /*
   1528  * bozo_process_request does the following:
   1529  *	- check the request is valid
   1530  *	- process cgi-bin if necessary
   1531  *	- transform a filename if necesarry
   1532  *	- return the HTTP request
   1533  */
   1534 void
   1535 bozo_process_request(bozo_httpreq_t *request)
   1536 {
   1537 	bozohttpd_t *httpd = request->hr_httpd;
   1538 	struct	stat sb;
   1539 	time_t timestamp;
   1540 	char	*file;
   1541 	const char *type, *encoding;
   1542 	int	fd, isindex;
   1543 
   1544 	/*
   1545 	 * note that transform_request chdir()'s if required.  also note
   1546 	 * that cgi is handed here.  if transform_request() returns 0
   1547 	 * then the request has been handled already.
   1548 	 */
   1549 	if (transform_request(request, &isindex) == 0)
   1550 		return;
   1551 
   1552 	fd = -1;
   1553 	encoding = NULL;
   1554 	if (can_gzip(request)) {
   1555 		bozoasprintf(httpd, &file, "%s.gz", request->hr_file);
   1556 		fd = open(file, O_RDONLY);
   1557 		if (fd >= 0)
   1558 			encoding = "gzip";
   1559 		free(file);
   1560 	}
   1561 
   1562 	file = request->hr_file;
   1563 
   1564 	if (fd < 0)
   1565 		fd = open(file, O_RDONLY);
   1566 
   1567 	if (fd < 0) {
   1568 		debug((httpd, DEBUG_FAT, "open failed: %s", strerror(errno)));
   1569 		switch (errno) {
   1570 		case EPERM:
   1571 		case EACCES:
   1572 			(void)bozo_http_error(httpd, 403, request,
   1573 						"no permission to open file");
   1574 			break;
   1575 		case ENAMETOOLONG:
   1576 			/*FALLTHROUGH*/
   1577 		case ENOENT:
   1578 			if (!bozo_dir_index(request, file, isindex))
   1579 				(void)bozo_http_error(httpd, 404, request,
   1580 							"no file");
   1581 			break;
   1582 		default:
   1583 			(void)bozo_http_error(httpd, 500, request, "open file");
   1584 		}
   1585 		goto cleanup_nofd;
   1586 	}
   1587 	if (fstat(fd, &sb) < 0) {
   1588 		(void)bozo_http_error(httpd, 500, request, "can't fstat");
   1589 		goto cleanup;
   1590 	}
   1591 	if (S_ISDIR(sb.st_mode)) {
   1592 		handle_redirect(request, NULL, 0);
   1593 		goto cleanup;
   1594 	}
   1595 
   1596 	if (request->hr_if_modified_since &&
   1597 	    parse_http_date(request->hr_if_modified_since, &timestamp) &&
   1598 	    timestamp >= sb.st_mtime) {
   1599 		/* XXX ignore subsecond of timestamp */
   1600 		bozo_printf(httpd, "%s 304 Not Modified\r\n",
   1601 				request->hr_proto);
   1602 		bozo_printf(httpd, "\r\n");
   1603 		bozo_flush(httpd, stdout);
   1604 		goto cleanup;
   1605 	}
   1606 
   1607 	/* validate requested range */
   1608 	if (request->hr_last_byte_pos == -1 ||
   1609 	    request->hr_last_byte_pos >= sb.st_size)
   1610 		request->hr_last_byte_pos = sb.st_size - 1;
   1611 	if (request->hr_have_range &&
   1612 	    request->hr_first_byte_pos > request->hr_last_byte_pos) {
   1613 		request->hr_have_range = 0;	/* punt */
   1614 		request->hr_first_byte_pos = 0;
   1615 		request->hr_last_byte_pos = sb.st_size - 1;
   1616 	}
   1617 	debug((httpd, DEBUG_FAT, "have_range %d first_pos %lld last_pos %lld",
   1618 	    request->hr_have_range,
   1619 	    (long long)request->hr_first_byte_pos,
   1620 	    (long long)request->hr_last_byte_pos));
   1621 	if (request->hr_have_range)
   1622 		bozo_printf(httpd, "%s 206 Partial Content\r\n",
   1623 				request->hr_proto);
   1624 	else
   1625 		bozo_printf(httpd, "%s 200 OK\r\n", request->hr_proto);
   1626 
   1627 	if (request->hr_proto != httpd->consts.http_09) {
   1628 		type = bozo_content_type(request, file);
   1629 		if (!encoding)
   1630 			encoding = bozo_content_encoding(request, file);
   1631 
   1632 		bozo_print_header(request, &sb, type, encoding);
   1633 		bozo_printf(httpd, "\r\n");
   1634 	}
   1635 	bozo_flush(httpd, stdout);
   1636 
   1637 	if (request->hr_method != HTTP_HEAD) {
   1638 		off_t szleft, cur_byte_pos;
   1639 
   1640 		szleft =
   1641 		     request->hr_last_byte_pos - request->hr_first_byte_pos + 1;
   1642 		cur_byte_pos = request->hr_first_byte_pos;
   1643 
   1644  retry:
   1645 		while (szleft) {
   1646 			size_t sz;
   1647 
   1648 			if ((off_t)httpd->mmapsz < szleft)
   1649 				sz = httpd->mmapsz;
   1650 			else
   1651 				sz = (size_t)szleft;
   1652 			if (mmap_and_write_part(httpd, fd, cur_byte_pos, sz)) {
   1653 				if (errno == ENOMEM) {
   1654 					httpd->mmapsz /= 2;
   1655 					if (httpd->mmapsz >= httpd->page_size)
   1656 						goto retry;
   1657 				}
   1658 				goto cleanup;
   1659 			}
   1660 			cur_byte_pos += sz;
   1661 			szleft -= sz;
   1662 		}
   1663 	}
   1664  cleanup:
   1665 	close(fd);
   1666  cleanup_nofd:
   1667 	close(STDIN_FILENO);
   1668 	close(STDOUT_FILENO);
   1669 	/*close(STDERR_FILENO);*/
   1670 }
   1671 
   1672 /* make sure we're not trying to access special files */
   1673 int
   1674 bozo_check_special_files(bozo_httpreq_t *request, const char *name)
   1675 {
   1676 	bozohttpd_t *httpd = request->hr_httpd;
   1677 
   1678 	/* ensure basename(name) != special files */
   1679 	if (strcmp(name, DIRECT_ACCESS_FILE) == 0)
   1680 		return bozo_http_error(httpd, 403, request,
   1681 		    "no permission to open direct access file");
   1682 	if (strcmp(name, REDIRECT_FILE) == 0)
   1683 		return bozo_http_error(httpd, 403, request,
   1684 		    "no permission to open redirect file");
   1685 	if (strcmp(name, ABSREDIRECT_FILE) == 0)
   1686 		return bozo_http_error(httpd, 403, request,
   1687 		    "no permission to open redirect file");
   1688 	return bozo_auth_check_special_files(request, name);
   1689 }
   1690 
   1691 /* generic header printing routine */
   1692 void
   1693 bozo_print_header(bozo_httpreq_t *request,
   1694 		struct stat *sbp, const char *type, const char *encoding)
   1695 {
   1696 	bozohttpd_t *httpd = request->hr_httpd;
   1697 	off_t len;
   1698 	char	date[40];
   1699 
   1700 	bozo_printf(httpd, "Date: %s\r\n", bozo_http_date(date, sizeof(date)));
   1701 	bozo_printf(httpd, "Server: %s\r\n", httpd->server_software);
   1702 	bozo_printf(httpd, "Accept-Ranges: bytes\r\n");
   1703 	if (sbp) {
   1704 		char filedate[40];
   1705 		struct	tm *tm;
   1706 
   1707 		tm = gmtime(&sbp->st_mtime);
   1708 		strftime(filedate, sizeof filedate,
   1709 		    "%a, %d %b %Y %H:%M:%S GMT", tm);
   1710 		bozo_printf(httpd, "Last-Modified: %s\r\n", filedate);
   1711 	}
   1712 	if (type && *type)
   1713 		bozo_printf(httpd, "Content-Type: %s\r\n", type);
   1714 	if (encoding && *encoding)
   1715 		bozo_printf(httpd, "Content-Encoding: %s\r\n", encoding);
   1716 	if (sbp) {
   1717 		if (request->hr_have_range) {
   1718 			len = request->hr_last_byte_pos -
   1719 					request->hr_first_byte_pos +1;
   1720 			bozo_printf(httpd,
   1721 				"Content-Range: bytes %qd-%qd/%qd\r\n",
   1722 				(long long) request->hr_first_byte_pos,
   1723 				(long long) request->hr_last_byte_pos,
   1724 				(long long) sbp->st_size);
   1725 		} else
   1726 			len = sbp->st_size;
   1727 		bozo_printf(httpd, "Content-Length: %qd\r\n", (long long)len);
   1728 	}
   1729 	if (request->hr_proto == httpd->consts.http_11)
   1730 		bozo_printf(httpd, "Connection: close\r\n");
   1731 	bozo_flush(httpd, stdout);
   1732 }
   1733 
   1734 #ifndef NO_DEBUG
   1735 void
   1736 debug__(bozohttpd_t *httpd, int level, const char *fmt, ...)
   1737 {
   1738 	va_list	ap;
   1739 	int savederrno;
   1740 
   1741 	/* only log if the level is low enough */
   1742 	if (httpd->debug < level)
   1743 		return;
   1744 
   1745 	savederrno = errno;
   1746 	va_start(ap, fmt);
   1747 	if (httpd->logstderr) {
   1748 		vfprintf(stderr, fmt, ap);
   1749 		fputs("\n", stderr);
   1750 	} else
   1751 		vsyslog(LOG_DEBUG, fmt, ap);
   1752 	va_end(ap);
   1753 	errno = savederrno;
   1754 }
   1755 #endif /* NO_DEBUG */
   1756 
   1757 /* these are like warn() and err(), except for syslog not stderr */
   1758 void
   1759 bozowarn(bozohttpd_t *httpd, const char *fmt, ...)
   1760 {
   1761 	va_list ap;
   1762 
   1763 	va_start(ap, fmt);
   1764 	if (httpd->logstderr || isatty(STDERR_FILENO)) {
   1765 		//fputs("warning: ", stderr);
   1766 		vfprintf(stderr, fmt, ap);
   1767 		fputs("\n", stderr);
   1768 	} else
   1769 		vsyslog(LOG_INFO, fmt, ap);
   1770 	va_end(ap);
   1771 }
   1772 
   1773 void
   1774 bozoerr(bozohttpd_t *httpd, int code, const char *fmt, ...)
   1775 {
   1776 	va_list ap;
   1777 
   1778 	va_start(ap, fmt);
   1779 	if (httpd->logstderr || isatty(STDERR_FILENO)) {
   1780 		//fputs("error: ", stderr);
   1781 		vfprintf(stderr, fmt, ap);
   1782 		fputs("\n", stderr);
   1783 	} else
   1784 		vsyslog(LOG_ERR, fmt, ap);
   1785 	va_end(ap);
   1786 	exit(code);
   1787 }
   1788 
   1789 void
   1790 bozoasprintf(bozohttpd_t *httpd, char **str, const char *fmt, ...)
   1791 {
   1792 	va_list ap;
   1793 	int e;
   1794 
   1795 	va_start(ap, fmt);
   1796 	e = vasprintf(str, fmt, ap);
   1797 	va_end(ap);
   1798 
   1799 	if (e < 0)
   1800 		bozoerr(httpd, EXIT_FAILURE, "asprintf");
   1801 }
   1802 
   1803 /*
   1804  * this escapes HTML tags.  returns allocated escaped
   1805  * string if needed, or NULL on allocation failure or
   1806  * lack of escape need.
   1807  * call with NULL httpd in error paths, to avoid recursive
   1808  * malloc failure.  call with valid httpd in normal paths
   1809  * to get automatic allocation failure handling.
   1810  */
   1811 char *
   1812 bozo_escape_html(bozohttpd_t *httpd, const char *url)
   1813 {
   1814 	int	i, j;
   1815 	char	*tmp;
   1816 	size_t	len;
   1817 
   1818 	for (i = 0, j = 0; url[i]; i++) {
   1819 		switch (url[i]) {
   1820 		case '<':
   1821 		case '>':
   1822 			j += 4;
   1823 			break;
   1824 		case '&':
   1825 			j += 5;
   1826 			break;
   1827 		}
   1828 	}
   1829 
   1830 	if (j == 0)
   1831 		return NULL;
   1832 
   1833 	/*
   1834 	 * we need to handle being called from different
   1835 	 * pathnames.
   1836 	 */
   1837 	len = strlen(url) + j;
   1838 	if (httpd)
   1839 		tmp = bozomalloc(httpd, len);
   1840 	else if ((tmp = malloc(len)) == 0)
   1841 			return NULL;
   1842 
   1843 	for (i = 0, j = 0; url[i]; i++) {
   1844 		switch (url[i]) {
   1845 		case '<':
   1846 			memcpy(tmp + j, "&lt;", 4);
   1847 			j += 4;
   1848 			break;
   1849 		case '>':
   1850 			memcpy(tmp + j, "&gt;", 4);
   1851 			j += 4;
   1852 			break;
   1853 		case '&':
   1854 			memcpy(tmp + j, "&amp;", 5);
   1855 			j += 5;
   1856 			break;
   1857 		default:
   1858 			tmp[j++] = url[i];
   1859 		}
   1860 	}
   1861 	tmp[j] = 0;
   1862 
   1863 	return tmp;
   1864 }
   1865 
   1866 /* short map between error code, and short/long messages */
   1867 static struct errors_map {
   1868 	int	code;			/* HTTP return code */
   1869 	const char *shortmsg;		/* short version of message */
   1870 	const char *longmsg;		/* long version of message */
   1871 } errors_map[] = {
   1872 	{ 400,	"400 Bad Request",	"The request was not valid", },
   1873 	{ 401,	"401 Unauthorized",	"No authorization", },
   1874 	{ 403,	"403 Forbidden",	"Access to this item has been denied",},
   1875 	{ 404, 	"404 Not Found",	"This item has not been found", },
   1876 	{ 408, 	"408 Request Timeout",	"This request took too long", },
   1877 	{ 417,	"417 Expectation Failed","Expectations not available", },
   1878 	{ 420,	"420 Enhance Your Calm","Chill, Winston", },
   1879 	{ 500,	"500 Internal Error",	"An error occured on the server", },
   1880 	{ 501,	"501 Not Implemented",	"This request is not available", },
   1881 	{ 0,	NULL,			NULL, },
   1882 };
   1883 
   1884 static const char *help = "DANGER! WILL ROBINSON! DANGER!";
   1885 
   1886 static const char *
   1887 http_errors_short(int code)
   1888 {
   1889 	struct errors_map *ep;
   1890 
   1891 	for (ep = errors_map; ep->code; ep++)
   1892 		if (ep->code == code)
   1893 			return (ep->shortmsg);
   1894 	return (help);
   1895 }
   1896 
   1897 static const char *
   1898 http_errors_long(int code)
   1899 {
   1900 	struct errors_map *ep;
   1901 
   1902 	for (ep = errors_map; ep->code; ep++)
   1903 		if (ep->code == code)
   1904 			return (ep->longmsg);
   1905 	return (help);
   1906 }
   1907 
   1908 /* the follow functions and variables are used in handling HTTP errors */
   1909 /* ARGSUSED */
   1910 int
   1911 bozo_http_error(bozohttpd_t *httpd, int code, bozo_httpreq_t *request,
   1912 		const char *msg)
   1913 {
   1914 	char portbuf[20];
   1915 	const char *header = http_errors_short(code);
   1916 	const char *reason = http_errors_long(code);
   1917 	const char *proto = (request && request->hr_proto) ?
   1918 				request->hr_proto : httpd->consts.http_11;
   1919 	int	size;
   1920 
   1921 	debug((httpd, DEBUG_FAT, "bozo_http_error %d: %s", code, msg));
   1922 	if (header == NULL || reason == NULL) {
   1923 		bozoerr(httpd, 1,
   1924 			"bozo_http_error() failed (short = %p, long = %p)",
   1925 			header, reason);
   1926 		return code;
   1927 	}
   1928 
   1929 	if (request && request->hr_serverport &&
   1930 	    strcmp(request->hr_serverport, "80") != 0)
   1931 		snprintf(portbuf, sizeof(portbuf), ":%s",
   1932 				request->hr_serverport);
   1933 	else
   1934 		portbuf[0] = '\0';
   1935 
   1936 	if (request && request->hr_file) {
   1937 		char *file = NULL, *user = NULL, *user_escaped = NULL;
   1938 		int file_alloc = 0;
   1939 		const char *hostname = BOZOHOST(httpd, request);
   1940 
   1941 		/* bozo_escape_html() failure here is just too bad. */
   1942 		file = bozo_escape_html(NULL, request->hr_file);
   1943 		if (file == NULL)
   1944 			file = request->hr_file;
   1945 		else
   1946 			file_alloc = 1;
   1947 
   1948 #ifndef NO_USER_SUPPORT
   1949 		if (request->hr_user != NULL) {
   1950 			user_escaped = bozo_escape_html(NULL, request->hr_user);
   1951 			if (user_escaped == NULL)
   1952 				user_escaped = request->hr_user;
   1953 			/* expand username to ~user/ */
   1954 			bozoasprintf(httpd, &user, "~%s/", user_escaped);
   1955 			if (user_escaped != request->hr_user)
   1956 				free(user_escaped);
   1957 		}
   1958 #endif /* !NO_USER_SUPPORT */
   1959 
   1960 		size = snprintf(httpd->errorbuf, BUFSIZ,
   1961 		    "<html><head><title>%s</title></head>\n"
   1962 		    "<body><h1>%s</h1>\n"
   1963 		    "%s%s: <pre>%s</pre>\n"
   1964  		    "<hr><address><a href=\"http://%s%s/\">%s%s</a></address>\n"
   1965 		    "</body></html>\n",
   1966 		    header, header,
   1967 		    user ? user : "", file,
   1968 		    reason, hostname, portbuf, hostname, portbuf);
   1969 		free(user);
   1970 		if (size >= (int)BUFSIZ) {
   1971 			bozowarn(httpd,
   1972 				"bozo_http_error buffer too small, truncated");
   1973 			size = (int)BUFSIZ;
   1974 		}
   1975 
   1976 		if (file_alloc)
   1977 			free(file);
   1978 	} else
   1979 		size = 0;
   1980 
   1981 	bozo_printf(httpd, "%s %s\r\n", proto, header);
   1982 	if (request)
   1983 		bozo_auth_check_401(request, code);
   1984 
   1985 	bozo_printf(httpd, "Content-Type: text/html\r\n");
   1986 	bozo_printf(httpd, "Content-Length: %d\r\n", size);
   1987 	bozo_printf(httpd, "Server: %s\r\n", httpd->server_software);
   1988 	if (request && request->hr_allow)
   1989 		bozo_printf(httpd, "Allow: %s\r\n", request->hr_allow);
   1990 	bozo_printf(httpd, "\r\n");
   1991 	/* According to the RFC 2616 sec. 9.4 HEAD method MUST NOT return a
   1992 	 * message-body in the response */
   1993 	if (size && request && request->hr_method != HTTP_HEAD)
   1994 		bozo_printf(httpd, "%s", httpd->errorbuf);
   1995 	bozo_flush(httpd, stdout);
   1996 
   1997 	return code;
   1998 }
   1999 
   2000 /* Below are various modified libc functions */
   2001 
   2002 /*
   2003  * returns -1 in lenp if the string ran out before finding a delimiter,
   2004  * but is otherwise the same as strsep.  Note that the length must be
   2005  * correctly passed in.
   2006  */
   2007 char *
   2008 bozostrnsep(char **strp, const char *delim, ssize_t	*lenp)
   2009 {
   2010 	char	*s;
   2011 	const	char *spanp;
   2012 	int	c, sc;
   2013 	char	*tok;
   2014 
   2015 	if ((s = *strp) == NULL)
   2016 		return (NULL);
   2017 	for (tok = s;;) {
   2018 		if (lenp && --(*lenp) == -1)
   2019 			return (NULL);
   2020 		c = *s++;
   2021 		spanp = delim;
   2022 		do {
   2023 			if ((sc = *spanp++) == c) {
   2024 				if (c == 0)
   2025 					s = NULL;
   2026 				else
   2027 					s[-1] = '\0';
   2028 				*strp = s;
   2029 				return (tok);
   2030 			}
   2031 		} while (sc != 0);
   2032 	}
   2033 	/* NOTREACHED */
   2034 }
   2035 
   2036 /*
   2037  * inspired by fgetln(3), but works for fd's.  should work identically
   2038  * except it, however, does *not* return the newline, and it does nul
   2039  * terminate the string.
   2040  */
   2041 char *
   2042 bozodgetln(bozohttpd_t *httpd, int fd, ssize_t *lenp,
   2043 	ssize_t (*readfn)(bozohttpd_t *, int, void *, size_t))
   2044 {
   2045 	ssize_t	len;
   2046 	int	got_cr = 0;
   2047 	char	c, *nbuffer;
   2048 
   2049 	/* initialise */
   2050 	if (httpd->getln_buflen == 0) {
   2051 		/* should be plenty for most requests */
   2052 		httpd->getln_buflen = 128;
   2053 		httpd->getln_buffer = malloc((size_t)httpd->getln_buflen);
   2054 		if (httpd->getln_buffer == NULL) {
   2055 			httpd->getln_buflen = 0;
   2056 			return NULL;
   2057 		}
   2058 	}
   2059 	len = 0;
   2060 
   2061 	/*
   2062 	 * we *have* to read one byte at a time, to not break cgi
   2063 	 * programs (for we pass stdin off to them).  could fix this
   2064 	 * by becoming a fd-passing program instead of just exec'ing
   2065 	 * the program
   2066 	 *
   2067 	 * the above is no longer true, we are the fd-passing
   2068 	 * program already.
   2069 	 */
   2070 	for (; readfn(httpd, fd, &c, 1) == 1; ) {
   2071 		debug((httpd, DEBUG_EXPLODING, "bozodgetln read %c", c));
   2072 
   2073 		if (len >= httpd->getln_buflen - 1) {
   2074 			httpd->getln_buflen *= 2;
   2075 			debug((httpd, DEBUG_EXPLODING, "bozodgetln: "
   2076 				"reallocating buffer to buflen %zu",
   2077 				httpd->getln_buflen));
   2078 			nbuffer = bozorealloc(httpd, httpd->getln_buffer,
   2079 				(size_t)httpd->getln_buflen);
   2080 			httpd->getln_buffer = nbuffer;
   2081 		}
   2082 
   2083 		httpd->getln_buffer[len++] = c;
   2084 		if (c == '\r') {
   2085 			got_cr = 1;
   2086 			continue;
   2087 		} else if (c == '\n') {
   2088 			/*
   2089 			 * HTTP/1.1 spec says to ignore CR and treat
   2090 			 * LF as the real line terminator.  even though
   2091 			 * the same spec defines CRLF as the line
   2092 			 * terminator, it is recommended in section 19.3
   2093 			 * to do the LF trick for tolerance.
   2094 			 */
   2095 			if (got_cr)
   2096 				len -= 2;
   2097 			else
   2098 				len -= 1;
   2099 			break;
   2100 		}
   2101 
   2102 	}
   2103 	httpd->getln_buffer[len] = '\0';
   2104 	debug((httpd, DEBUG_OBESE, "bozodgetln returns: ``%s'' with len %zd",
   2105 	       httpd->getln_buffer, len));
   2106 	*lenp = len;
   2107 	return httpd->getln_buffer;
   2108 }
   2109 
   2110 void *
   2111 bozorealloc(bozohttpd_t *httpd, void *ptr, size_t size)
   2112 {
   2113 	void	*p;
   2114 
   2115 	p = realloc(ptr, size);
   2116 	if (p)
   2117 		return p;
   2118 
   2119 	(void)bozo_http_error(httpd, 500, NULL, "memory allocation failure");
   2120 	exit(EXIT_FAILURE);
   2121 }
   2122 
   2123 void *
   2124 bozomalloc(bozohttpd_t *httpd, size_t size)
   2125 {
   2126 	void	*p;
   2127 
   2128 	p = malloc(size);
   2129 	if (p)
   2130 		return p;
   2131 
   2132 	(void)bozo_http_error(httpd, 500, NULL, "memory allocation failure");
   2133 	exit(EXIT_FAILURE);
   2134 }
   2135 
   2136 char *
   2137 bozostrdup(bozohttpd_t *httpd, bozo_httpreq_t *request, const char *str)
   2138 {
   2139 	char	*p;
   2140 
   2141 	p = strdup(str);
   2142 	if (p)
   2143 		return p;
   2144 
   2145 	if (!request)
   2146 		bozoerr(httpd, EXIT_FAILURE, "strdup");
   2147 
   2148 	(void)bozo_http_error(httpd, 500, request, "memory allocation failure");
   2149 	exit(EXIT_FAILURE);
   2150 }
   2151 
   2152 /* set default values in bozohttpd_t struct */
   2153 int
   2154 bozo_init_httpd(bozohttpd_t *httpd)
   2155 {
   2156 	/* make sure everything is clean */
   2157 	(void) memset(httpd, 0x0, sizeof(*httpd));
   2158 
   2159 	/* constants */
   2160 	httpd->consts.http_09 = "HTTP/0.9";
   2161 	httpd->consts.http_10 = "HTTP/1.0";
   2162 	httpd->consts.http_11 = "HTTP/1.1";
   2163 	httpd->consts.text_plain = "text/plain";
   2164 
   2165 	/* mmap region size */
   2166 	httpd->mmapsz = BOZO_MMAPSZ;
   2167 
   2168 	/* error buffer for bozo_http_error() */
   2169 	if ((httpd->errorbuf = malloc(BUFSIZ)) == NULL) {
   2170 		(void) fprintf(stderr,
   2171 			"bozohttpd: memory_allocation failure\n");
   2172 		return 0;
   2173 	}
   2174 #ifndef NO_LUA_SUPPORT
   2175 	SIMPLEQ_INIT(&httpd->lua_states);
   2176 #endif
   2177 	return 1;
   2178 }
   2179 
   2180 /* set default values in bozoprefs_t struct */
   2181 int
   2182 bozo_init_prefs(bozohttpd_t *httpd, bozoprefs_t *prefs)
   2183 {
   2184 	/* make sure everything is clean */
   2185 	(void) memset(prefs, 0x0, sizeof(*prefs));
   2186 
   2187 	/* set up default values */
   2188 	if (!bozo_set_pref(httpd, prefs, "server software", SERVER_SOFTWARE) ||
   2189 	    !bozo_set_pref(httpd, prefs, "index.html", INDEX_HTML) ||
   2190 	    !bozo_set_pref(httpd, prefs, "public_html", PUBLIC_HTML))
   2191 		return 0;
   2192 
   2193 	return 1;
   2194 }
   2195 
   2196 /* set default values */
   2197 int
   2198 bozo_set_defaults(bozohttpd_t *httpd, bozoprefs_t *prefs)
   2199 {
   2200 	return bozo_init_httpd(httpd) && bozo_init_prefs(httpd, prefs);
   2201 }
   2202 
   2203 /* set the virtual host name, port and root */
   2204 int
   2205 bozo_setup(bozohttpd_t *httpd, bozoprefs_t *prefs, const char *vhost,
   2206 		const char *root)
   2207 {
   2208 	struct passwd	 *pw;
   2209 	extern char	**environ;
   2210 	static char	 *cleanenv[1] = { NULL };
   2211 	uid_t		  uid;
   2212 	char		 *chrootdir;
   2213 	char		 *username;
   2214 	char		 *portnum;
   2215 	char		 *cp;
   2216 	int		  dirtyenv;
   2217 
   2218 	dirtyenv = 0;
   2219 
   2220 	if (vhost == NULL) {
   2221 		httpd->virthostname = bozomalloc(httpd, MAXHOSTNAMELEN+1);
   2222 		if (gethostname(httpd->virthostname, MAXHOSTNAMELEN+1) < 0)
   2223 			bozoerr(httpd, 1, "gethostname");
   2224 		httpd->virthostname[MAXHOSTNAMELEN] = '\0';
   2225 	} else {
   2226 		httpd->virthostname = bozostrdup(httpd, NULL, vhost);
   2227 	}
   2228 	httpd->slashdir = bozostrdup(httpd, NULL, root);
   2229 	if ((portnum = bozo_get_pref(prefs, "port number")) != NULL) {
   2230 		httpd->bindport = bozostrdup(httpd, NULL, portnum);
   2231 	}
   2232 
   2233 	/* go over preferences now */
   2234 	if ((cp = bozo_get_pref(prefs, "numeric")) != NULL &&
   2235 	    strcmp(cp, "true") == 0) {
   2236 		httpd->numeric = 1;
   2237 	}
   2238 	if ((cp = bozo_get_pref(prefs, "log to stderr")) != NULL &&
   2239 	    strcmp(cp, "true") == 0) {
   2240 		httpd->logstderr = 1;
   2241 	}
   2242 	if ((cp = bozo_get_pref(prefs, "bind address")) != NULL) {
   2243 		httpd->bindaddress = bozostrdup(httpd, NULL, cp);
   2244 	}
   2245 	if ((cp = bozo_get_pref(prefs, "background")) != NULL) {
   2246 		httpd->background = atoi(cp);
   2247 	}
   2248 	if ((cp = bozo_get_pref(prefs, "foreground")) != NULL &&
   2249 	    strcmp(cp, "true") == 0) {
   2250 		httpd->foreground = 1;
   2251 	}
   2252 	if ((cp = bozo_get_pref(prefs, "pid file")) != NULL) {
   2253 		httpd->pidfile = bozostrdup(httpd, NULL, cp);
   2254 	}
   2255 	if ((cp = bozo_get_pref(prefs, "unknown slash")) != NULL &&
   2256 	    strcmp(cp, "true") == 0) {
   2257 		httpd->unknown_slash = 1;
   2258 	}
   2259 	if ((cp = bozo_get_pref(prefs, "virtual base")) != NULL) {
   2260 		httpd->virtbase = bozostrdup(httpd, NULL, cp);
   2261 	}
   2262 	if ((cp = bozo_get_pref(prefs, "enable users")) != NULL &&
   2263 	    strcmp(cp, "true") == 0) {
   2264 		httpd->enable_users = 1;
   2265 	}
   2266 	if ((cp = bozo_get_pref(prefs, "enable user cgibin")) != NULL &&
   2267 	    strcmp(cp, "true") == 0) {
   2268 		httpd->enable_cgi_users = 1;
   2269 	}
   2270 	if ((cp = bozo_get_pref(prefs, "dirty environment")) != NULL &&
   2271 	    strcmp(cp, "true") == 0) {
   2272 		dirtyenv = 1;
   2273 	}
   2274 	if ((cp = bozo_get_pref(prefs, "hide dots")) != NULL &&
   2275 	    strcmp(cp, "true") == 0) {
   2276 		httpd->hide_dots = 1;
   2277 	}
   2278 	if ((cp = bozo_get_pref(prefs, "directory indexing")) != NULL &&
   2279 	    strcmp(cp, "true") == 0) {
   2280 		httpd->dir_indexing = 1;
   2281 	}
   2282 	if ((cp = bozo_get_pref(prefs, "public_html")) != NULL) {
   2283 		httpd->public_html = bozostrdup(httpd, NULL, cp);
   2284 	}
   2285 	httpd->server_software =
   2286 	    bozostrdup(httpd, NULL, bozo_get_pref(prefs, "server software"));
   2287 	httpd->index_html =
   2288 	    bozostrdup(httpd, NULL, bozo_get_pref(prefs, "index.html"));
   2289 
   2290 	/*
   2291 	 * initialise ssl and daemon mode if necessary.
   2292 	 */
   2293 	bozo_ssl_init(httpd);
   2294 	bozo_daemon_init(httpd);
   2295 
   2296 	username = bozo_get_pref(prefs, "username");
   2297 	if (username != NULL) {
   2298 		if ((pw = getpwnam(username)) == NULL)
   2299 			bozoerr(httpd, 1, "getpwnam(%s): %s", username,
   2300 				strerror(errno));
   2301 		if (initgroups(pw->pw_name, pw->pw_gid) == -1)
   2302 			bozoerr(httpd, 1, "initgroups: %s", strerror(errno));
   2303 		if (setgid(pw->pw_gid) == -1)
   2304 			bozoerr(httpd, 1, "setgid(%u): %s", pw->pw_gid,
   2305 				strerror(errno));
   2306 		uid = pw->pw_uid;
   2307 	}
   2308 	/*
   2309 	 * handle chroot.
   2310 	 */
   2311 	if ((chrootdir = bozo_get_pref(prefs, "chroot dir")) != NULL) {
   2312 		httpd->rootdir = bozostrdup(httpd, NULL, chrootdir);
   2313 		if (chdir(httpd->rootdir) == -1)
   2314 			bozoerr(httpd, 1, "chdir(%s): %s", httpd->rootdir,
   2315 				strerror(errno));
   2316 		if (chroot(httpd->rootdir) == -1)
   2317 			bozoerr(httpd, 1, "chroot(%s): %s", httpd->rootdir,
   2318 				strerror(errno));
   2319 	}
   2320 
   2321 	if (username != NULL && setuid(uid) == -1)
   2322 		bozoerr(httpd, 1, "setuid(%d): %s", uid, strerror(errno));
   2323 
   2324 	/*
   2325 	 * prevent info leakage between different compartments.
   2326 	 * some PATH values in the environment would be invalided
   2327 	 * by chroot. cross-user settings might result in undesirable
   2328 	 * effects.
   2329 	 */
   2330 	if ((chrootdir != NULL || username != NULL) && !dirtyenv)
   2331 		environ = cleanenv;
   2332 
   2333 #ifdef _SC_PAGESIZE
   2334 	httpd->page_size = (long)sysconf(_SC_PAGESIZE);
   2335 #else
   2336 	httpd->page_size = 4096;
   2337 #endif
   2338 	debug((httpd, DEBUG_OBESE, "myname is %s, slashdir is %s",
   2339 			httpd->virthostname, httpd->slashdir));
   2340 
   2341 	return 1;
   2342 }
   2343