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