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