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