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