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