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