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