Home | History | Annotate | Line # | Download | only in httpd
bozohttpd.c revision 1.31
      1 /*	$NetBSD: bozohttpd.c,v 1.31 2012/02/20 09:26:56 elric 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  * checks to see if this request has a valid .bzdirect file.  returns
    851  * 0 on failure and 1 on success.
    852  */
    853 static int
    854 check_direct_access(bozo_httpreq_t *request)
    855 {
    856 	FILE *fp;
    857 	struct stat sb;
    858 	char dir[MAXPATHLEN], dirfile[MAXPATHLEN], *basename;
    859 
    860 	snprintf(dir, sizeof(dir), "%s", request->hr_file + 1);
    861 	debug((request->hr_httpd, DEBUG_FAT, "check_bzredirect: dir %s", dir));
    862 	basename = strrchr(dir, '/');
    863 
    864 	if ((!basename || basename[1] != '\0') &&
    865 	    lstat(dir, &sb) == 0 && S_ISDIR(sb.st_mode))
    866 		/* nothing */;
    867 	else if (basename == NULL)
    868 		strcpy(dir, ".");
    869 	else {
    870 		*basename++ = '\0';
    871 		bozo_check_special_files(request, basename);
    872 	}
    873 
    874 	snprintf(dirfile, sizeof(dirfile), "%s/%s", dir, DIRECT_ACCESS_FILE);
    875 	if (stat(dirfile, &sb) < 0 ||
    876 	    (fp = fopen(dirfile, "r")) == NULL)
    877 		return 0;
    878 	fclose(fp);
    879 	return 1;
    880 }
    881 
    882 /*
    883  * do automatic redirection -- if there are query parameters for the URL
    884  * we will tack these on to the new (redirected) URL.
    885  */
    886 static void
    887 handle_redirect(bozo_httpreq_t *request,
    888 		const char *url, int absolute)
    889 {
    890 	bozohttpd_t *httpd = request->hr_httpd;
    891 	char *urlbuf;
    892 	char portbuf[20];
    893 	int query = 0;
    894 
    895 	if (url == NULL) {
    896 		if (asprintf(&urlbuf, "/%s/", request->hr_file) < 0)
    897 			bozo_err(httpd, 1, "asprintf");
    898 		url = urlbuf;
    899 	} else
    900 		urlbuf = NULL;
    901 
    902 	if (request->hr_query && strlen(request->hr_query)) {
    903 		query = 1;
    904 	}
    905 
    906 	if (request->hr_serverport && strcmp(request->hr_serverport, "80") != 0)
    907 		snprintf(portbuf, sizeof(portbuf), ":%s",
    908 		    request->hr_serverport);
    909 	else
    910 		portbuf[0] = '\0';
    911 	bozo_warn(httpd, "redirecting %s%s%s", httpd->virthostname, portbuf, url);
    912 	debug((httpd, DEBUG_FAT, "redirecting %s", url));
    913 	bozo_printf(httpd, "%s 301 Document Moved\r\n", request->hr_proto);
    914 	if (request->hr_proto != httpd->consts.http_09)
    915 		bozo_print_header(request, NULL, "text/html", NULL);
    916 	if (request->hr_proto != httpd->consts.http_09) {
    917 		bozo_printf(httpd, "Location: http://");
    918 		if (absolute == 0)
    919 			bozo_printf(httpd, "%s%s", httpd->virthostname, portbuf);
    920 		if (query) {
    921 		  bozo_printf(httpd, "%s?%s\r\n", url, request->hr_query);
    922 		} else {
    923 		  bozo_printf(httpd, "%s\r\n", url);
    924 		}
    925 	}
    926 	bozo_printf(httpd, "\r\n");
    927 	if (request->hr_method == HTTP_HEAD)
    928 		goto head;
    929 	bozo_printf(httpd, "<html><head><title>Document Moved</title></head>\n");
    930 	bozo_printf(httpd, "<body><h1>Document Moved</h1>\n");
    931 	bozo_printf(httpd, "This document had moved <a href=\"http://");
    932 	if (query) {
    933 	  if (absolute)
    934 	    bozo_printf(httpd, "%s?%s", url, request->hr_query);
    935 	  else
    936 	    bozo_printf(httpd, "%s%s%s?%s", httpd->virthostname, portbuf, url,
    937 	    		request->hr_query);
    938         } else {
    939 	  if (absolute)
    940 	    bozo_printf(httpd, "%s", url);
    941 	  else
    942 	    bozo_printf(httpd, "%s%s%s", httpd->virthostname, portbuf, url);
    943 	}
    944 	bozo_printf(httpd, "\">here</a>\n");
    945 	bozo_printf(httpd, "</body></html>\n");
    946 head:
    947 	bozo_flush(httpd, stdout);
    948 	if (urlbuf)
    949 		free(urlbuf);
    950 }
    951 
    952 /*
    953  * deal with virtual host names; we do this:
    954  *	if we have a virtual path root (httpd->virtbase), and we are given a
    955  *	virtual host spec (Host: ho.st or http://ho.st/), see if this
    956  *	directory exists under httpd->virtbase.  if it does, use this as the
    957  #	new slashdir.
    958  */
    959 static int
    960 check_virtual(bozo_httpreq_t *request)
    961 {
    962 	bozohttpd_t *httpd = request->hr_httpd;
    963 	char *file = request->hr_file, *s;
    964 	size_t len;
    965 
    966 	if (!httpd->virtbase)
    967 		goto use_slashdir;
    968 
    969 	/*
    970 	 * convert http://virtual.host/ to request->hr_host
    971 	 */
    972 	debug((httpd, DEBUG_OBESE, "checking for http:// virtual host in ``%s''",
    973 			file));
    974 	if (strncasecmp(file, "http://", 7) == 0) {
    975 		/* we would do virtual hosting here? */
    976 		file += 7;
    977 		s = strchr(file, '/');
    978 		/* HTTP/1.1 draft rev-06, 5.2: URI takes precedence over Host: */
    979 		request->hr_host = file;
    980 		request->hr_file = bozostrdup(request->hr_httpd, s ? s : "/");
    981 		debug((httpd, DEBUG_OBESE, "got host ``%s'' file is now ``%s''",
    982 		    request->hr_host, request->hr_file));
    983 	} else if (!request->hr_host)
    984 		goto use_slashdir;
    985 
    986 	/*
    987 	 * ok, we have a virtual host, use scandir(3) to find a case
    988 	 * insensitive match for the virtual host we are asked for.
    989 	 * note that if the virtual host is the same as the master,
    990 	 * we don't need to do anything special.
    991 	 */
    992 	len = strlen(request->hr_host);
    993 	debug((httpd, DEBUG_OBESE,
    994 	    "check_virtual: checking host `%s' under httpd->virtbase `%s' "
    995 	    "for file `%s'",
    996 	    request->hr_host, httpd->virtbase, request->hr_file));
    997 	if (strncasecmp(httpd->virthostname, request->hr_host, len) != 0) {
    998 		s = 0;
    999 		DIR *dirp;
   1000 		struct dirent *d;
   1001 
   1002 		if ((dirp = opendir(httpd->virtbase)) != NULL) {
   1003 			while ((d = readdir(dirp)) != NULL) {
   1004 				if (strcmp(d->d_name, ".") == 0 ||
   1005 				    strcmp(d->d_name, "..") == 0) {
   1006 					continue;
   1007 				}
   1008 				debug((httpd, DEBUG_OBESE, "looking at dir``%s''",
   1009 			 	   d->d_name));
   1010 				if (strncasecmp(d->d_name, request->hr_host,
   1011 				    len) == 0) {
   1012 					/* found it, punch it */
   1013 					debug((httpd, DEBUG_OBESE, "found it punch it"));
   1014 					httpd->virthostname = d->d_name;
   1015 					if (asprintf(&s, "%s/%s", httpd->virtbase,
   1016 					    httpd->virthostname) < 0)
   1017 						bozo_err(httpd, 1, "asprintf");
   1018 					break;
   1019 				}
   1020 			}
   1021 			closedir(dirp);
   1022 		}
   1023 		else {
   1024 			debug((httpd, DEBUG_FAT, "opendir %s failed: %s",
   1025 			    httpd->virtbase, strerror(errno)));
   1026 		}
   1027 		if (s == 0) {
   1028 			if (httpd->unknown_slash)
   1029 				goto use_slashdir;
   1030 			return bozo_http_error(httpd, 404, request,
   1031 						"unknown URL");
   1032 		}
   1033 	} else
   1034 use_slashdir:
   1035 		s = httpd->slashdir;
   1036 
   1037 	/*
   1038 	 * ok, nailed the correct slashdir, chdir to it
   1039 	 */
   1040 	if (chdir(s) < 0)
   1041 		return bozo_http_error(httpd, 404, request,
   1042 					"can't chdir to slashdir");
   1043 	return 0;
   1044 }
   1045 
   1046 /*
   1047  * checks to see if this request has a valid .bzredirect file.  returns
   1048  * 0 on failure and 1 on success.
   1049  */
   1050 static void
   1051 check_bzredirect(bozo_httpreq_t *request)
   1052 {
   1053 	struct stat sb;
   1054 	char dir[MAXPATHLEN], redir[MAXPATHLEN], redirpath[MAXPATHLEN + 1];
   1055 	char *basename, *finalredir;
   1056 	int rv, absolute;
   1057 
   1058 	/*
   1059 	 * if this pathname is really a directory, but doesn't end in /,
   1060 	 * use it as the directory to look for the redir file.
   1061 	 */
   1062 	snprintf(dir, sizeof(dir), "%s", request->hr_file + 1);
   1063 	debug((request->hr_httpd, DEBUG_FAT, "check_bzredirect: dir %s", dir));
   1064 	basename = strrchr(dir, '/');
   1065 
   1066 	if ((!basename || basename[1] != '\0') &&
   1067 	    lstat(dir, &sb) == 0 && S_ISDIR(sb.st_mode))
   1068 		/* nothing */;
   1069 	else if (basename == NULL)
   1070 		strcpy(dir, ".");
   1071 	else {
   1072 		*basename++ = '\0';
   1073 		bozo_check_special_files(request, basename);
   1074 	}
   1075 
   1076 	snprintf(redir, sizeof(redir), "%s/%s", dir, REDIRECT_FILE);
   1077 	if (lstat(redir, &sb) == 0) {
   1078 		if (!S_ISLNK(sb.st_mode))
   1079 			return;
   1080 		absolute = 0;
   1081 	} else {
   1082 		snprintf(redir, sizeof(redir), "%s/%s", dir, ABSREDIRECT_FILE);
   1083 		if (lstat(redir, &sb) < 0 || !S_ISLNK(sb.st_mode))
   1084 			return;
   1085 		absolute = 1;
   1086 	}
   1087 	debug((request->hr_httpd, DEBUG_FAT,
   1088 	       "check_bzredirect: calling readlink"));
   1089 	rv = readlink(redir, redirpath, sizeof redirpath - 1);
   1090 	if (rv == -1 || rv == 0) {
   1091 		debug((request->hr_httpd, DEBUG_FAT, "readlink failed"));
   1092 		return;
   1093 	}
   1094 	redirpath[rv] = '\0';
   1095 	debug((request->hr_httpd, DEBUG_FAT,
   1096 	       "readlink returned \"%s\"", redirpath));
   1097 
   1098 	/* now we have the link pointer, redirect to the real place */
   1099 	if (absolute)
   1100 		finalredir = redirpath;
   1101 	else
   1102 		snprintf(finalredir = redir, sizeof(redir), "/%s/%s", dir,
   1103 			 redirpath);
   1104 
   1105 	debug((request->hr_httpd, DEBUG_FAT,
   1106 	       "check_bzredirect: new redir %s", finalredir));
   1107 	handle_redirect(request, finalredir, absolute);
   1108 }
   1109 
   1110 /* this fixes the %HH hack that RFC2396 requires.  */
   1111 static void
   1112 fix_url_percent(bozo_httpreq_t *request)
   1113 {
   1114 	bozohttpd_t *httpd = request->hr_httpd;
   1115 	char	*s, *t, buf[3], *url;
   1116 	char	*end;	/* if end is not-zero, we don't translate beyond that */
   1117 
   1118 	url = request->hr_file;
   1119 
   1120 	end = url + strlen(url);
   1121 
   1122 	/* fast forward to the first % */
   1123 	if ((s = strchr(url, '%')) == NULL)
   1124 		return;
   1125 
   1126 	t = s;
   1127 	do {
   1128 		if (end && s >= end) {
   1129 			debug((httpd, DEBUG_EXPLODING,
   1130 				"fu_%%: past end, filling out.."));
   1131 			while (*s)
   1132 				*t++ = *s++;
   1133 			break;
   1134 		}
   1135 		debug((httpd, DEBUG_EXPLODING,
   1136 			"fu_%%: got s == %%, s[1]s[2] == %c%c",
   1137 			s[1], s[2]));
   1138 		if (s[1] == '\0' || s[2] == '\0') {
   1139 			(void)bozo_http_error(httpd, 400, request,
   1140 			    "percent hack missing two chars afterwards");
   1141 			goto copy_rest;
   1142 		}
   1143 		if (s[1] == '0' && s[2] == '0') {
   1144 			(void)bozo_http_error(httpd, 404, request,
   1145 					"percent hack was %00");
   1146 			goto copy_rest;
   1147 		}
   1148 		if (s[1] == '2' && s[2] == 'f') {
   1149 			(void)bozo_http_error(httpd, 404, request,
   1150 					"percent hack was %2f (/)");
   1151 			goto copy_rest;
   1152 		}
   1153 
   1154 		buf[0] = *++s;
   1155 		buf[1] = *++s;
   1156 		buf[2] = '\0';
   1157 		s++;
   1158 		*t = (char)strtol(buf, NULL, 16);
   1159 		debug((httpd, DEBUG_EXPLODING,
   1160 				"fu_%%: strtol put '%02x' into *t", *t));
   1161 		if (*t++ == '\0') {
   1162 			(void)bozo_http_error(httpd, 400, request,
   1163 					"percent hack got a 0 back");
   1164 			goto copy_rest;
   1165 		}
   1166 
   1167 		while (*s && *s != '%') {
   1168 			if (end && s >= end)
   1169 				break;
   1170 			*t++ = *s++;
   1171 		}
   1172 	} while (*s);
   1173 copy_rest:
   1174 	while (*s) {
   1175 		if (s >= end)
   1176 			break;
   1177 		*t++ = *s++;
   1178 	}
   1179 	*t = '\0';
   1180 	debug((httpd, DEBUG_FAT, "fix_url_percent returns %s in url",
   1181 			request->hr_file));
   1182 }
   1183 
   1184 /*
   1185  * transform_request does this:
   1186  *	- ``expand'' %20 crapola
   1187  *	- punt if it doesn't start with /
   1188  *	- check httpd->untrustedref / referrer
   1189  *	- look for "http://myname/" and deal with it.
   1190  *	- maybe call bozo_process_cgi()
   1191  *	- check for ~user and call bozo_user_transform() if so
   1192  *	- if the length > 1, check for trailing slash.  if so,
   1193  *	  add the index.html file
   1194  *	- if the length is 1, return the index.html file
   1195  *	- disallow anything ending up with a file starting
   1196  *	  at "/" or having ".." in it.
   1197  *	- anything else is a really weird internal error
   1198  *	- returns malloced file to serve, if unhandled
   1199  */
   1200 static int
   1201 transform_request(bozo_httpreq_t *request, int *isindex)
   1202 {
   1203 	bozohttpd_t *httpd = request->hr_httpd;
   1204 	char	*file, *newfile = NULL;
   1205 	size_t	len;
   1206 
   1207 	file = NULL;
   1208 	*isindex = 0;
   1209 	debug((httpd, DEBUG_FAT, "tf_req: file %s", request->hr_file));
   1210 	fix_url_percent(request);
   1211 	if (check_virtual(request)) {
   1212 		goto bad_done;
   1213 	}
   1214 	file = request->hr_file;
   1215 
   1216 	if (file[0] != '/') {
   1217 		(void)bozo_http_error(httpd, 404, request, "unknown URL");
   1218 		goto bad_done;
   1219 	}
   1220 
   1221 	check_bzredirect(request);
   1222 
   1223 	if (httpd->untrustedref) {
   1224 		int to_indexhtml = 0;
   1225 
   1226 #define TOP_PAGE(x)	(strcmp((x), "/") == 0 || \
   1227 			 strcmp((x) + 1, httpd->index_html) == 0 || \
   1228 			 strcmp((x) + 1, "favicon.ico") == 0)
   1229 
   1230 		debug((httpd, DEBUG_EXPLODING, "checking httpd->untrustedref"));
   1231 		/*
   1232 		 * first check that this path isn't allowed via .bzdirect file,
   1233 		 * and then check referrer; make sure that people come via the
   1234 		 * real name... otherwise if we aren't looking at / or
   1235 		 * /index.html, redirect...  we also special case favicon.ico.
   1236 		 */
   1237 		if (check_direct_access(request))
   1238 			/* nothing */;
   1239 		else if (request->hr_referrer) {
   1240 			const char *r = request->hr_referrer;
   1241 
   1242 			debug((httpd, DEBUG_FAT,
   1243 				"checking referrer \"%s\" vs virthostname %s",
   1244 				r, httpd->virthostname));
   1245 			if (strncmp(r, "http://", 7) != 0 ||
   1246 			    (strncasecmp(r + 7, httpd->virthostname,
   1247 			    		 strlen(httpd->virthostname)) != 0 &&
   1248 			     !TOP_PAGE(file)))
   1249 				to_indexhtml = 1;
   1250 		} else {
   1251 			const char *h = request->hr_host;
   1252 
   1253 			debug((httpd, DEBUG_FAT, "url has no referrer at all"));
   1254 			/* if there's no referrer, let / or /index.html past */
   1255 			if (!TOP_PAGE(file) ||
   1256 			    (h && strncasecmp(h, httpd->virthostname,
   1257 			    		strlen(httpd->virthostname)) != 0))
   1258 				to_indexhtml = 1;
   1259 		}
   1260 
   1261 		if (to_indexhtml) {
   1262 			char *slashindexhtml;
   1263 
   1264 			if (asprintf(&slashindexhtml, "/%s",
   1265 					httpd->index_html) < 0)
   1266 				bozo_err(httpd, 1, "asprintf");
   1267 			debug((httpd, DEBUG_FAT,
   1268 				"httpd->untrustedref: redirecting %s to %s",
   1269 				file, slashindexhtml));
   1270 			handle_redirect(request, slashindexhtml, 0);
   1271 			free(slashindexhtml);
   1272 			return 0;
   1273 		}
   1274 	}
   1275 
   1276 	len = strlen(file);
   1277 	if (/*CONSTCOND*/0) {
   1278 #ifndef NO_USER_SUPPORT
   1279 	} else if (len > 1 && httpd->enable_users && file[1] == '~') {
   1280 		if (file[2] == '\0') {
   1281 			(void)bozo_http_error(httpd, 404, request,
   1282 						"missing username");
   1283 			goto bad_done;
   1284 		}
   1285 		if (strchr(file + 2, '/') == NULL) {
   1286 			handle_redirect(request, NULL, 0);
   1287 			return 0;
   1288 		}
   1289 		debug((httpd, DEBUG_FAT, "calling bozo_user_transform"));
   1290 
   1291 		return bozo_user_transform(request, isindex);
   1292 #endif /* NO_USER_SUPPORT */
   1293 	} else if (len > 1) {
   1294 		debug((httpd, DEBUG_FAT, "file[len-1] == %c", file[len-1]));
   1295 		if (file[len-1] == '/') {	/* append index.html */
   1296 			*isindex = 1;
   1297 			debug((httpd, DEBUG_FAT, "appending index.html"));
   1298 			newfile = bozomalloc(httpd,
   1299 					len + strlen(httpd->index_html) + 1);
   1300 			strcpy(newfile, file + 1);
   1301 			strcat(newfile, httpd->index_html);
   1302 		} else
   1303 			newfile = bozostrdup(request->hr_httpd, file + 1);
   1304 	} else if (len == 1) {
   1305 		debug((httpd, DEBUG_EXPLODING, "tf_req: len == 1"));
   1306 		newfile = bozostrdup(request->hr_httpd, httpd->index_html);
   1307 		*isindex = 1;
   1308 	} else {	/* len == 0 ? */
   1309 		(void)bozo_http_error(httpd, 500, request,
   1310 					"request->hr_file is nul?");
   1311 		goto bad_done;
   1312 	}
   1313 
   1314 	if (newfile == NULL) {
   1315 		(void)bozo_http_error(httpd, 500, request, "internal failure");
   1316 		goto bad_done;
   1317 	}
   1318 
   1319 	/*
   1320 	 * look for "http://myname/" and deal with it as necessary.
   1321 	 */
   1322 
   1323 	/*
   1324 	 * stop traversing outside our domain
   1325 	 *
   1326 	 * XXX true security only comes from our parent using chroot(2)
   1327 	 * before execve(2)'ing us.  or our own built in chroot(2) support.
   1328 	 */
   1329 	if (*newfile == '/' || strcmp(newfile, "..") == 0 ||
   1330 	    strstr(newfile, "/..") || strstr(newfile, "../")) {
   1331 		(void)bozo_http_error(httpd, 403, request, "illegal request");
   1332 		goto bad_done;
   1333 	}
   1334 
   1335 	if (bozo_auth_check(request, newfile))
   1336 		goto bad_done;
   1337 
   1338 	if (strlen(newfile)) {
   1339 		request->hr_oldfile = request->hr_file;
   1340 		request->hr_file = newfile;
   1341 	}
   1342 
   1343 	if (bozo_process_cgi(request))
   1344 		return 0;
   1345 
   1346 	debug((httpd, DEBUG_FAT, "transform_request set: %s", newfile));
   1347 	return 1;
   1348 bad_done:
   1349 	debug((httpd, DEBUG_FAT, "transform_request returning: 0"));
   1350 	if (newfile)
   1351 		free(newfile);
   1352 	return 0;
   1353 }
   1354 
   1355 /*
   1356  * can_gzip checks if the request supports and prefers gzip encoding.
   1357  *
   1358  * XXX: we do not consider the associated q with gzip in making our
   1359  *      decision which is broken.
   1360  */
   1361 
   1362 static int
   1363 can_gzip(bozo_httpreq_t *request)
   1364 {
   1365 	const char	*pos;
   1366 	const char	*tmp;
   1367 	size_t		 len;
   1368 
   1369 	/* First we decide if the request can be gzipped at all. */
   1370 
   1371 	/* not if we already are encoded... */
   1372 	tmp = bozo_content_encoding(request, request->hr_file);
   1373 	if (tmp && *tmp)
   1374 		return 0;
   1375 
   1376 	/* not if we are not asking for the whole file... */
   1377 	if (request->hr_last_byte_pos != -1 || request->hr_have_range)
   1378 		return 0;
   1379 
   1380 	/* Then we determine if gzip is on the cards. */
   1381 
   1382 	for (pos = request->hr_accept_encoding; pos && *pos; pos += len) {
   1383 		while (*pos == ' ')
   1384 			pos++;
   1385 
   1386 		len = strcspn(pos, ";,");
   1387 
   1388 		if ((len == 4 && strncasecmp("gzip", pos, 4) == 0) ||
   1389 		    (len == 6 && strncasecmp("x-gzip", pos, 6) == 0))
   1390 			return 1;
   1391 
   1392 		if (pos[len] == ';')
   1393 			len += strcspn(&pos[len], ",");
   1394 
   1395 		if (pos[len])
   1396 			len++;
   1397 	}
   1398 
   1399 	return 0;
   1400 }
   1401 
   1402 /*
   1403  * bozo_process_request does the following:
   1404  *	- check the request is valid
   1405  *	- process cgi-bin if necessary
   1406  *	- transform a filename if necesarry
   1407  *	- return the HTTP request
   1408  */
   1409 void
   1410 bozo_process_request(bozo_httpreq_t *request)
   1411 {
   1412 	bozohttpd_t *httpd = request->hr_httpd;
   1413 	struct	stat sb;
   1414 	time_t timestamp;
   1415 	char	*file;
   1416 	const char *type, *encoding;
   1417 	int	fd, isindex;
   1418 
   1419 	/*
   1420 	 * note that transform_request chdir()'s if required.  also note
   1421 	 * that cgi is handed here.  if transform_request() returns 0
   1422 	 * then the request has been handled already.
   1423 	 */
   1424 	if (transform_request(request, &isindex) == 0)
   1425 		return;
   1426 
   1427 	fd = -1;
   1428 	encoding = NULL;
   1429 	if (can_gzip(request)) {
   1430 		asprintf(&file, "%s.gz", request->hr_file);
   1431 		fd = open(file, O_RDONLY);
   1432 		if (fd >= 0)
   1433 			encoding = "gzip";
   1434 		free(file);
   1435 	}
   1436 
   1437 	file = request->hr_file;
   1438 
   1439 	if (fd < 0)
   1440 		fd = open(file, O_RDONLY);
   1441 
   1442 	if (fd < 0) {
   1443 		debug((httpd, DEBUG_FAT, "open failed: %s", strerror(errno)));
   1444 		if (errno == EPERM)
   1445 			(void)bozo_http_error(httpd, 403, request,
   1446 						"no permission to open file");
   1447 		else if (errno == ENOENT) {
   1448 			if (!bozo_dir_index(request, file, isindex))
   1449 				(void)bozo_http_error(httpd, 404, request,
   1450 							"no file");
   1451 		} else
   1452 			(void)bozo_http_error(httpd, 500, request, "open file");
   1453 		goto cleanup_nofd;
   1454 	}
   1455 	if (fstat(fd, &sb) < 0) {
   1456 		(void)bozo_http_error(httpd, 500, request, "can't fstat");
   1457 		goto cleanup;
   1458 	}
   1459 	if (S_ISDIR(sb.st_mode)) {
   1460 		handle_redirect(request, NULL, 0);
   1461 		goto cleanup;
   1462 	}
   1463 
   1464 	if (request->hr_if_modified_since &&
   1465 	    parse_http_date(request->hr_if_modified_since, &timestamp) &&
   1466 	    timestamp >= sb.st_mtime) {
   1467 		/* XXX ignore subsecond of timestamp */
   1468 		bozo_printf(httpd, "%s 304 Not Modified\r\n",
   1469 				request->hr_proto);
   1470 		bozo_printf(httpd, "\r\n");
   1471 		bozo_flush(httpd, stdout);
   1472 		goto cleanup;
   1473 	}
   1474 
   1475 	/* validate requested range */
   1476 	if (request->hr_last_byte_pos == -1 ||
   1477 	    request->hr_last_byte_pos >= sb.st_size)
   1478 		request->hr_last_byte_pos = sb.st_size - 1;
   1479 	if (request->hr_have_range &&
   1480 	    request->hr_first_byte_pos > request->hr_last_byte_pos) {
   1481 		request->hr_have_range = 0;	/* punt */
   1482 		request->hr_first_byte_pos = 0;
   1483 		request->hr_last_byte_pos = sb.st_size - 1;
   1484 	}
   1485 	debug((httpd, DEBUG_FAT, "have_range %d first_pos %lld last_pos %lld",
   1486 	    request->hr_have_range,
   1487 	    (long long)request->hr_first_byte_pos,
   1488 	    (long long)request->hr_last_byte_pos));
   1489 	if (request->hr_have_range)
   1490 		bozo_printf(httpd, "%s 206 Partial Content\r\n",
   1491 				request->hr_proto);
   1492 	else
   1493 		bozo_printf(httpd, "%s 200 OK\r\n", request->hr_proto);
   1494 
   1495 	if (request->hr_proto != httpd->consts.http_09) {
   1496 		type = bozo_content_type(request, file);
   1497 		if (!encoding)
   1498 			encoding = bozo_content_encoding(request, file);
   1499 
   1500 		bozo_print_header(request, &sb, type, encoding);
   1501 		bozo_printf(httpd, "\r\n");
   1502 	}
   1503 	bozo_flush(httpd, stdout);
   1504 
   1505 	if (request->hr_method != HTTP_HEAD) {
   1506 		off_t szleft, cur_byte_pos;
   1507 
   1508 		szleft =
   1509 		     request->hr_last_byte_pos - request->hr_first_byte_pos + 1;
   1510 		cur_byte_pos = request->hr_first_byte_pos;
   1511 
   1512  retry:
   1513 		while (szleft) {
   1514 			size_t sz;
   1515 
   1516 			/* This should take care of the first unaligned chunk */
   1517 			if ((cur_byte_pos & (httpd->page_size - 1)) != 0)
   1518 				sz = (size_t)(cur_byte_pos & ~httpd->page_size);
   1519 			if ((off_t)httpd->mmapsz < szleft)
   1520 				sz = httpd->mmapsz;
   1521 			else
   1522 				sz = (size_t)szleft;
   1523 			if (mmap_and_write_part(httpd, fd, cur_byte_pos, sz)) {
   1524 				if (errno == ENOMEM) {
   1525 					httpd->mmapsz /= 2;
   1526 					if (httpd->mmapsz >= httpd->page_size)
   1527 						goto retry;
   1528 				}
   1529 				goto cleanup;
   1530 			}
   1531 			cur_byte_pos += sz;
   1532 			szleft -= sz;
   1533 		}
   1534 	}
   1535  cleanup:
   1536 	close(fd);
   1537  cleanup_nofd:
   1538 	close(STDIN_FILENO);
   1539 	close(STDOUT_FILENO);
   1540 	/*close(STDERR_FILENO);*/
   1541 }
   1542 
   1543 /* make sure we're not trying to access special files */
   1544 int
   1545 bozo_check_special_files(bozo_httpreq_t *request, const char *name)
   1546 {
   1547 	bozohttpd_t *httpd = request->hr_httpd;
   1548 
   1549 	/* ensure basename(name) != special files */
   1550 	if (strcmp(name, DIRECT_ACCESS_FILE) == 0)
   1551 		return bozo_http_error(httpd, 403, request,
   1552 		    "no permission to open direct access file");
   1553 	if (strcmp(name, REDIRECT_FILE) == 0)
   1554 		return bozo_http_error(httpd, 403, request,
   1555 		    "no permission to open redirect file");
   1556 	if (strcmp(name, ABSREDIRECT_FILE) == 0)
   1557 		return bozo_http_error(httpd, 403, request,
   1558 		    "no permission to open redirect file");
   1559 	return bozo_auth_check_special_files(request, name);
   1560 }
   1561 
   1562 /* generic header printing routine */
   1563 void
   1564 bozo_print_header(bozo_httpreq_t *request,
   1565 		struct stat *sbp, const char *type, const char *encoding)
   1566 {
   1567 	bozohttpd_t *httpd = request->hr_httpd;
   1568 	off_t len;
   1569 	char	date[40];
   1570 
   1571 	bozo_printf(httpd, "Date: %s\r\n", bozo_http_date(date, sizeof(date)));
   1572 	bozo_printf(httpd, "Server: %s\r\n", httpd->server_software);
   1573 	bozo_printf(httpd, "Accept-Ranges: bytes\r\n");
   1574 	if (sbp) {
   1575 		char filedate[40];
   1576 		struct	tm *tm;
   1577 
   1578 		tm = gmtime(&sbp->st_mtime);
   1579 		strftime(filedate, sizeof filedate,
   1580 		    "%a, %d %b %Y %H:%M:%S GMT", tm);
   1581 		bozo_printf(httpd, "Last-Modified: %s\r\n", filedate);
   1582 	}
   1583 	if (type && *type)
   1584 		bozo_printf(httpd, "Content-Type: %s\r\n", type);
   1585 	if (encoding && *encoding)
   1586 		bozo_printf(httpd, "Content-Encoding: %s\r\n", encoding);
   1587 	if (sbp) {
   1588 		if (request->hr_have_range) {
   1589 			len = request->hr_last_byte_pos -
   1590 					request->hr_first_byte_pos +1;
   1591 			bozo_printf(httpd,
   1592 				"Content-Range: bytes %qd-%qd/%qd\r\n",
   1593 				(long long) request->hr_first_byte_pos,
   1594 				(long long) request->hr_last_byte_pos,
   1595 				(long long) sbp->st_size);
   1596 		} else
   1597 			len = sbp->st_size;
   1598 		bozo_printf(httpd, "Content-Length: %qd\r\n", (long long)len);
   1599 	}
   1600 	if (request && request->hr_proto == httpd->consts.http_11)
   1601 		bozo_printf(httpd, "Connection: close\r\n");
   1602 	bozo_flush(httpd, stdout);
   1603 }
   1604 
   1605 #ifndef NO_DEBUG
   1606 void
   1607 debug__(bozohttpd_t *httpd, int level, const char *fmt, ...)
   1608 {
   1609 	va_list	ap;
   1610 	int savederrno;
   1611 
   1612 	/* only log if the level is low enough */
   1613 	if (httpd->debug < level)
   1614 		return;
   1615 
   1616 	savederrno = errno;
   1617 	va_start(ap, fmt);
   1618 	if (httpd->logstderr) {
   1619 		vfprintf(stderr, fmt, ap);
   1620 		fputs("\n", stderr);
   1621 	} else
   1622 		vsyslog(LOG_DEBUG, fmt, ap);
   1623 	va_end(ap);
   1624 	errno = savederrno;
   1625 }
   1626 #endif /* NO_DEBUG */
   1627 
   1628 /* these are like warn() and err(), except for syslog not stderr */
   1629 void
   1630 bozo_warn(bozohttpd_t *httpd, const char *fmt, ...)
   1631 {
   1632 	va_list ap;
   1633 
   1634 	va_start(ap, fmt);
   1635 	if (httpd->logstderr || isatty(STDERR_FILENO)) {
   1636 		//fputs("warning: ", stderr);
   1637 		vfprintf(stderr, fmt, ap);
   1638 		fputs("\n", stderr);
   1639 	} else
   1640 		vsyslog(LOG_INFO, fmt, ap);
   1641 	va_end(ap);
   1642 }
   1643 
   1644 void
   1645 bozo_err(bozohttpd_t *httpd, int code, const char *fmt, ...)
   1646 {
   1647 	va_list ap;
   1648 
   1649 	va_start(ap, fmt);
   1650 	if (httpd->logstderr || isatty(STDERR_FILENO)) {
   1651 		//fputs("error: ", stderr);
   1652 		vfprintf(stderr, fmt, ap);
   1653 		fputs("\n", stderr);
   1654 	} else
   1655 		vsyslog(LOG_ERR, fmt, ap);
   1656 	va_end(ap);
   1657 	exit(code);
   1658 }
   1659 
   1660 /* this escape HTML tags */
   1661 static void
   1662 escape_html(bozo_httpreq_t *request)
   1663 {
   1664 	int	i, j;
   1665 	char	*url = request->hr_file, *tmp;
   1666 
   1667 	for (i = 0, j = 0; url[i]; i++) {
   1668 		switch (url[i]) {
   1669 		case '<':
   1670 		case '>':
   1671 			j += 4;
   1672 			break;
   1673 		case '&':
   1674 			j += 5;
   1675 			break;
   1676 		}
   1677 	}
   1678 
   1679 	if (j == 0)
   1680 		return;
   1681 
   1682 	if ((tmp = (char *) malloc(strlen(url) + j)) == 0)
   1683 		/*
   1684 		 * ouch, but we are only called from an error context, and
   1685 		 * most paths here come from malloc(3) failures anyway...
   1686 		 * we could completely punt and just exit, but isn't returning
   1687 		 * an not-quite-correct error better than nothing at all?
   1688 		 */
   1689 		return;
   1690 
   1691 	for (i = 0, j = 0; url[i]; i++) {
   1692 		switch (url[i]) {
   1693 		case '<':
   1694 			memcpy(tmp + j, "&lt;", 4);
   1695 			j += 4;
   1696 			break;
   1697 		case '>':
   1698 			memcpy(tmp + j, "&gt;", 4);
   1699 			j += 4;
   1700 			break;
   1701 		case '&':
   1702 			memcpy(tmp + j, "&amp;", 5);
   1703 			j += 5;
   1704 			break;
   1705 		default:
   1706 			tmp[j++] = url[i];
   1707 		}
   1708 	}
   1709 	tmp[j] = 0;
   1710 
   1711 	free(request->hr_file);
   1712 	request->hr_file = tmp;
   1713 }
   1714 
   1715 /* short map between error code, and short/long messages */
   1716 static struct errors_map {
   1717 	int	code;			/* HTTP return code */
   1718 	const char *shortmsg;		/* short version of message */
   1719 	const char *longmsg;		/* long version of message */
   1720 } errors_map[] = {
   1721 	{ 400,	"400 Bad Request",	"The request was not valid", },
   1722 	{ 401,	"401 Unauthorized",	"No authorization", },
   1723 	{ 403,	"403 Forbidden",	"Access to this item has been denied",},
   1724 	{ 404, 	"404 Not Found",	"This item has not been found", },
   1725 	{ 408, 	"408 Request Timeout",	"This request took too long", },
   1726 	{ 417,	"417 Expectation Failed","Expectations not available", },
   1727 	{ 500,	"500 Internal Error",	"An error occured on the server", },
   1728 	{ 501,	"501 Not Implemented",	"This request is not available", },
   1729 	{ 0,	NULL,			NULL, },
   1730 };
   1731 
   1732 static const char *help = "DANGER! WILL ROBINSON! DANGER!";
   1733 
   1734 static const char *
   1735 http_errors_short(int code)
   1736 {
   1737 	struct errors_map *ep;
   1738 
   1739 	for (ep = errors_map; ep->code; ep++)
   1740 		if (ep->code == code)
   1741 			return (ep->shortmsg);
   1742 	return (help);
   1743 }
   1744 
   1745 static const char *
   1746 http_errors_long(int code)
   1747 {
   1748 	struct errors_map *ep;
   1749 
   1750 	for (ep = errors_map; ep->code; ep++)
   1751 		if (ep->code == code)
   1752 			return (ep->longmsg);
   1753 	return (help);
   1754 }
   1755 
   1756 /* the follow functions and variables are used in handling HTTP errors */
   1757 /* ARGSUSED */
   1758 int
   1759 bozo_http_error(bozohttpd_t *httpd, int code, bozo_httpreq_t *request,
   1760 		const char *msg)
   1761 {
   1762 	char portbuf[20];
   1763 	const char *header = http_errors_short(code);
   1764 	const char *reason = http_errors_long(code);
   1765 	const char *proto = (request && request->hr_proto) ?
   1766 				request->hr_proto : httpd->consts.http_11;
   1767 	int	size;
   1768 
   1769 	debug((httpd, DEBUG_FAT, "bozo_http_error %d: %s", code, msg));
   1770 	if (header == NULL || reason == NULL) {
   1771 		bozo_err(httpd, 1,
   1772 			"bozo_http_error() failed (short = %p, long = %p)",
   1773 			header, reason);
   1774 		return code;
   1775 	}
   1776 
   1777 	if (request && request->hr_serverport &&
   1778 	    strcmp(request->hr_serverport, "80") != 0)
   1779 		snprintf(portbuf, sizeof(portbuf), ":%s",
   1780 				request->hr_serverport);
   1781 	else
   1782 		portbuf[0] = '\0';
   1783 
   1784 	if (request && request->hr_file) {
   1785 		escape_html(request);
   1786 		size = snprintf(httpd->errorbuf, BUFSIZ,
   1787 		    "<html><head><title>%s</title></head>\n"
   1788 		    "<body><h1>%s</h1>\n"
   1789 		    "%s: <pre>%s</pre>\n"
   1790  		    "<hr><address><a href=\"http://%s%s/\">%s%s</a></address>\n"
   1791 		    "</body></html>\n",
   1792 		    header, header, request->hr_file, reason,
   1793 		    httpd->virthostname, portbuf, httpd->virthostname, portbuf);
   1794 		if (size >= (int)BUFSIZ) {
   1795 			bozo_warn(httpd,
   1796 				"bozo_http_error buffer too small, truncated");
   1797 			size = (int)BUFSIZ;
   1798 		}
   1799 	} else
   1800 		size = 0;
   1801 
   1802 	bozo_printf(httpd, "%s %s\r\n", proto, header);
   1803 	if (request)
   1804 		bozo_auth_check_401(request, code);
   1805 
   1806 	bozo_printf(httpd, "Content-Type: text/html\r\n");
   1807 	bozo_printf(httpd, "Content-Length: %d\r\n", size);
   1808 	bozo_printf(httpd, "Server: %s\r\n", httpd->server_software);
   1809 	if (request && request->hr_allow)
   1810 		bozo_printf(httpd, "Allow: %s\r\n", request->hr_allow);
   1811 	bozo_printf(httpd, "\r\n");
   1812 	if (size)
   1813 		bozo_printf(httpd, "%s", httpd->errorbuf);
   1814 	bozo_flush(httpd, stdout);
   1815 
   1816 	return code;
   1817 }
   1818 
   1819 /* Below are various modified libc functions */
   1820 
   1821 /*
   1822  * returns -1 in lenp if the string ran out before finding a delimiter,
   1823  * but is otherwise the same as strsep.  Note that the length must be
   1824  * correctly passed in.
   1825  */
   1826 char *
   1827 bozostrnsep(char **strp, const char *delim, ssize_t	*lenp)
   1828 {
   1829 	char	*s;
   1830 	const	char *spanp;
   1831 	int	c, sc;
   1832 	char	*tok;
   1833 
   1834 	if ((s = *strp) == NULL)
   1835 		return (NULL);
   1836 	for (tok = s;;) {
   1837 		if (lenp && --(*lenp) == -1)
   1838 			return (NULL);
   1839 		c = *s++;
   1840 		spanp = delim;
   1841 		do {
   1842 			if ((sc = *spanp++) == c) {
   1843 				if (c == 0)
   1844 					s = NULL;
   1845 				else
   1846 					s[-1] = '\0';
   1847 				*strp = s;
   1848 				return (tok);
   1849 			}
   1850 		} while (sc != 0);
   1851 	}
   1852 	/* NOTREACHED */
   1853 }
   1854 
   1855 /*
   1856  * inspired by fgetln(3), but works for fd's.  should work identically
   1857  * except it, however, does *not* return the newline, and it does nul
   1858  * terminate the string.
   1859  */
   1860 char *
   1861 bozodgetln(bozohttpd_t *httpd, int fd, ssize_t *lenp,
   1862 	ssize_t (*readfn)(bozohttpd_t *, int, void *, size_t))
   1863 {
   1864 	ssize_t	len;
   1865 	int	got_cr = 0;
   1866 	char	c, *nbuffer;
   1867 
   1868 	/* initialise */
   1869 	if (httpd->getln_buflen == 0) {
   1870 		/* should be plenty for most requests */
   1871 		httpd->getln_buflen = 128;
   1872 		httpd->getln_buffer = malloc((size_t)httpd->getln_buflen);
   1873 		if (httpd->getln_buffer == NULL) {
   1874 			httpd->getln_buflen = 0;
   1875 			return NULL;
   1876 		}
   1877 	}
   1878 	len = 0;
   1879 
   1880 	/*
   1881 	 * we *have* to read one byte at a time, to not break cgi
   1882 	 * programs (for we pass stdin off to them).  could fix this
   1883 	 * by becoming a fd-passing program instead of just exec'ing
   1884 	 * the program
   1885 	 *
   1886 	 * the above is no longer true, we are the fd-passing
   1887 	 * program already.
   1888 	 */
   1889 	for (; readfn(httpd, fd, &c, 1) == 1; ) {
   1890 		debug((httpd, DEBUG_EXPLODING, "bozodgetln read %c", c));
   1891 
   1892 		if (len >= httpd->getln_buflen - 1) {
   1893 			httpd->getln_buflen *= 2;
   1894 			debug((httpd, DEBUG_EXPLODING, "bozodgetln: "
   1895 				"reallocating buffer to buflen %zu",
   1896 				httpd->getln_buflen));
   1897 			nbuffer = bozorealloc(httpd, httpd->getln_buffer,
   1898 				(size_t)httpd->getln_buflen);
   1899 			httpd->getln_buffer = nbuffer;
   1900 		}
   1901 
   1902 		httpd->getln_buffer[len++] = c;
   1903 		if (c == '\r') {
   1904 			got_cr = 1;
   1905 			continue;
   1906 		} else if (c == '\n') {
   1907 			/*
   1908 			 * HTTP/1.1 spec says to ignore CR and treat
   1909 			 * LF as the real line terminator.  even though
   1910 			 * the same spec defines CRLF as the line
   1911 			 * terminator, it is recommended in section 19.3
   1912 			 * to do the LF trick for tolerance.
   1913 			 */
   1914 			if (got_cr)
   1915 				len -= 2;
   1916 			else
   1917 				len -= 1;
   1918 			break;
   1919 		}
   1920 
   1921 	}
   1922 	httpd->getln_buffer[len] = '\0';
   1923 	debug((httpd, DEBUG_OBESE, "bozodgetln returns: ``%s'' with len %zd",
   1924 	       httpd->getln_buffer, len));
   1925 	*lenp = len;
   1926 	return httpd->getln_buffer;
   1927 }
   1928 
   1929 void *
   1930 bozorealloc(bozohttpd_t *httpd, void *ptr, size_t size)
   1931 {
   1932 	void	*p;
   1933 
   1934 	p = realloc(ptr, size);
   1935 	if (p == NULL) {
   1936 		(void)bozo_http_error(httpd, 500, NULL,
   1937 				"memory allocation failure");
   1938 		exit(1);
   1939 	}
   1940 	return (p);
   1941 }
   1942 
   1943 void *
   1944 bozomalloc(bozohttpd_t *httpd, size_t size)
   1945 {
   1946 	void	*p;
   1947 
   1948 	p = malloc(size);
   1949 	if (p == NULL) {
   1950 		(void)bozo_http_error(httpd, 500, NULL,
   1951 				"memory allocation failure");
   1952 		exit(1);
   1953 	}
   1954 	return (p);
   1955 }
   1956 
   1957 char *
   1958 bozostrdup(bozohttpd_t *httpd, const char *str)
   1959 {
   1960 	char	*p;
   1961 
   1962 	p = strdup(str);
   1963 	if (p == NULL) {
   1964 		(void)bozo_http_error(httpd, 500, NULL,
   1965 					"memory allocation failure");
   1966 		exit(1);
   1967 	}
   1968 	return (p);
   1969 }
   1970 
   1971 /* set default values in bozohttpd_t struct */
   1972 int
   1973 bozo_init_httpd(bozohttpd_t *httpd)
   1974 {
   1975 	/* make sure everything is clean */
   1976 	(void) memset(httpd, 0x0, sizeof(*httpd));
   1977 
   1978 	/* constants */
   1979 	httpd->consts.http_09 = "HTTP/0.9";
   1980 	httpd->consts.http_10 = "HTTP/1.0";
   1981 	httpd->consts.http_11 = "HTTP/1.1";
   1982 	httpd->consts.text_plain = "text/plain";
   1983 
   1984 	/* mmap region size */
   1985 	httpd->mmapsz = BOZO_MMAPSZ;
   1986 
   1987 	/* error buffer for bozo_http_error() */
   1988 	if ((httpd->errorbuf = malloc(BUFSIZ)) == NULL) {
   1989 		(void) fprintf(stderr,
   1990 			"bozohttpd: memory_allocation failure\n");
   1991 		return 0;
   1992 	}
   1993 	return 1;
   1994 }
   1995 
   1996 /* set default values in bozoprefs_t struct */
   1997 int
   1998 bozo_init_prefs(bozoprefs_t *prefs)
   1999 {
   2000 	/* make sure everything is clean */
   2001 	(void) memset(prefs, 0x0, sizeof(*prefs));
   2002 
   2003 	/* set up default values */
   2004 	bozo_set_pref(prefs, "server software", SERVER_SOFTWARE);
   2005 	bozo_set_pref(prefs, "index.html", INDEX_HTML);
   2006 	bozo_set_pref(prefs, "public_html", PUBLIC_HTML);
   2007 
   2008 	return 1;
   2009 }
   2010 
   2011 /* set default values */
   2012 int
   2013 bozo_set_defaults(bozohttpd_t *httpd, bozoprefs_t *prefs)
   2014 {
   2015 	return bozo_init_httpd(httpd) && bozo_init_prefs(prefs);
   2016 }
   2017 
   2018 /* set the virtual host name, port and root */
   2019 int
   2020 bozo_setup(bozohttpd_t *httpd, bozoprefs_t *prefs, const char *vhost,
   2021 		const char *root)
   2022 {
   2023 	struct passwd	 *pw;
   2024 	extern char	**environ;
   2025 	static char	 *cleanenv[1] = { NULL };
   2026 	uid_t		  uid;
   2027 	char		 *chrootdir;
   2028 	char		 *username;
   2029 	char		 *portnum;
   2030 	char		 *cp;
   2031 	int		  dirtyenv;
   2032 
   2033 	dirtyenv = 0;
   2034 
   2035 	if (vhost == NULL) {
   2036 		httpd->virthostname = bozomalloc(httpd, MAXHOSTNAMELEN+1);
   2037 		/* XXX we do not check for FQDN here */
   2038 		if (gethostname(httpd->virthostname, MAXHOSTNAMELEN+1) < 0)
   2039 			bozo_err(httpd, 1, "gethostname");
   2040 		httpd->virthostname[MAXHOSTNAMELEN] = '\0';
   2041 	} else {
   2042 		httpd->virthostname = strdup(vhost);
   2043 	}
   2044 	httpd->slashdir = strdup(root);
   2045 	if ((portnum = bozo_get_pref(prefs, "port number")) != NULL) {
   2046 		httpd->bindport = strdup(portnum);
   2047 	}
   2048 
   2049 	/* go over preferences now */
   2050 	if ((cp = bozo_get_pref(prefs, "numeric")) != NULL &&
   2051 	    strcmp(cp, "true") == 0) {
   2052 		httpd->numeric = 1;
   2053 	}
   2054 	if ((cp = bozo_get_pref(prefs, "trusted referal")) != NULL &&
   2055 	    strcmp(cp, "true") == 0) {
   2056 		httpd->untrustedref = 1;
   2057 	}
   2058 	if ((cp = bozo_get_pref(prefs, "log to stderr")) != NULL &&
   2059 	    strcmp(cp, "true") == 0) {
   2060 		httpd->logstderr = 1;
   2061 	}
   2062 	if ((cp = bozo_get_pref(prefs, "bind address")) != NULL) {
   2063 		httpd->bindaddress = strdup(cp);
   2064 	}
   2065 	if ((cp = bozo_get_pref(prefs, "background")) != NULL) {
   2066 		httpd->background = atoi(cp);
   2067 	}
   2068 	if ((cp = bozo_get_pref(prefs, "foreground")) != NULL &&
   2069 	    strcmp(cp, "true") == 0) {
   2070 		httpd->foreground = 1;
   2071 	}
   2072 	if ((cp = bozo_get_pref(prefs, "pid file")) != NULL) {
   2073 		httpd->pidfile = strdup(cp);
   2074 	}
   2075 	if ((cp = bozo_get_pref(prefs, "unknown slash")) != NULL &&
   2076 	    strcmp(cp, "true") == 0) {
   2077 		httpd->unknown_slash = 1;
   2078 	}
   2079 	if ((cp = bozo_get_pref(prefs, "virtual base")) != NULL) {
   2080 		httpd->virtbase = strdup(cp);
   2081 	}
   2082 	if ((cp = bozo_get_pref(prefs, "enable users")) != NULL &&
   2083 	    strcmp(cp, "true") == 0) {
   2084 		httpd->enable_users = 1;
   2085 	}
   2086 	if ((cp = bozo_get_pref(prefs, "dirty environment")) != NULL &&
   2087 	    strcmp(cp, "true") == 0) {
   2088 		dirtyenv = 1;
   2089 	}
   2090 	if ((cp = bozo_get_pref(prefs, "hide dots")) != NULL &&
   2091 	    strcmp(cp, "true") == 0) {
   2092 		httpd->hide_dots = 1;
   2093 	}
   2094 	if ((cp = bozo_get_pref(prefs, "directory indexing")) != NULL &&
   2095 	    strcmp(cp, "true") == 0) {
   2096 		httpd->dir_indexing = 1;
   2097 	}
   2098 	if ((cp = bozo_get_pref(prefs, "public_html")) != NULL) {
   2099 		httpd->public_html = strdup(cp);
   2100 	}
   2101 	httpd->server_software =
   2102 			strdup(bozo_get_pref(prefs, "server software"));
   2103 	httpd->index_html = strdup(bozo_get_pref(prefs, "index.html"));
   2104 
   2105 	/*
   2106 	 * initialise ssl and daemon mode if necessary.
   2107 	 */
   2108 	bozo_ssl_init(httpd);
   2109 	bozo_daemon_init(httpd);
   2110 
   2111 	if ((username = bozo_get_pref(prefs, "username")) == NULL) {
   2112 		if ((pw = getpwuid(uid = 0)) == NULL)
   2113 			bozo_err(httpd, 1, "getpwuid(0): %s", strerror(errno));
   2114 		httpd->username = strdup(pw->pw_name);
   2115 	} else {
   2116 		httpd->username = strdup(username);
   2117 		if ((pw = getpwnam(httpd->username)) == NULL)
   2118 			bozo_err(httpd, 1, "getpwnam(%s): %s", httpd->username,
   2119 					strerror(errno));
   2120 		if (initgroups(pw->pw_name, pw->pw_gid) == -1)
   2121 			bozo_err(httpd, 1, "initgroups: %s", strerror(errno));
   2122 		if (setgid(pw->pw_gid) == -1)
   2123 			bozo_err(httpd, 1, "setgid(%u): %s", pw->pw_gid,
   2124 					strerror(errno));
   2125 		uid = pw->pw_uid;
   2126 	}
   2127 	/*
   2128 	 * handle chroot.
   2129 	 */
   2130 	if ((chrootdir = bozo_get_pref(prefs, "chroot dir")) != NULL) {
   2131 		httpd->rootdir = strdup(chrootdir);
   2132 		if (chdir(httpd->rootdir) == -1)
   2133 			bozo_err(httpd, 1, "chdir(%s): %s", httpd->rootdir,
   2134 				strerror(errno));
   2135 		if (chroot(httpd->rootdir) == -1)
   2136 			bozo_err(httpd, 1, "chroot(%s): %s", httpd->rootdir,
   2137 				strerror(errno));
   2138 	}
   2139 
   2140 	if (username != NULL)
   2141 		if (setuid(uid) == -1)
   2142 			bozo_err(httpd, 1, "setuid(%d): %s", uid,
   2143 					strerror(errno));
   2144 
   2145 	/*
   2146 	 * prevent info leakage between different compartments.
   2147 	 * some PATH values in the environment would be invalided
   2148 	 * by chroot. cross-user settings might result in undesirable
   2149 	 * effects.
   2150 	 */
   2151 	if ((chrootdir != NULL || username != NULL) && !dirtyenv)
   2152 		environ = cleanenv;
   2153 
   2154 #ifdef _SC_PAGESIZE
   2155 	httpd->page_size = (long)sysconf(_SC_PAGESIZE);
   2156 #else
   2157 	httpd->page_size = 4096;
   2158 #endif
   2159 	debug((httpd, DEBUG_OBESE, "myname is %s, slashdir is %s",
   2160 			httpd->virthostname, httpd->slashdir));
   2161 
   2162 	return 1;
   2163 }
   2164