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