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