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