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