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