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