1 #include "first.h" 2 3 #include "base.h" 4 #include "array.h" 5 #include "buffer.h" 6 #include "fdevent.h" 7 #include "log.h" 8 #include "etag.h" 9 #include "http_chunk.h" 10 #include "http_header.h" 11 #include "response.h" 12 #include "sock_addr.h" 13 #include "stat_cache.h" 14 #include "settings.h" /* MAX_HTTP_REQUEST_HEADER MAX_READ_LIMIT */ 15 16 #include <stdlib.h> 17 #include <string.h> 18 #include <errno.h> 19 #include <fcntl.h> 20 21 #include <time.h> 22 23 #include "sys-socket.h" 24 #include <unistd.h> 25 26 27 static int http_response_buffer_append_authority(request_st * const r, buffer * const o) { 28 if (!buffer_string_is_empty(&r->uri.authority)) { 29 buffer_append_string_buffer(o, &r->uri.authority); 30 } else { 31 /* get the name of the currently connected socket */ 32 sock_addr our_addr; 33 socklen_t our_addr_len; 34 35 our_addr.plain.sa_family = 0; 36 our_addr_len = sizeof(our_addr); 37 38 if (-1 == getsockname(r->con->fd, (struct sockaddr *)&our_addr, &our_addr_len) 39 || our_addr_len > (socklen_t)sizeof(our_addr)) { 40 r->http_status = 500; 41 log_perror(r->conf.errh, __FILE__, __LINE__, "can't get sockname"); 42 return -1; 43 } 44 45 if (our_addr.plain.sa_family == AF_INET 46 && our_addr.ipv4.sin_addr.s_addr == htonl(INADDR_LOOPBACK)) { 47 static char lhost[32]; 48 static size_t lhost_len = 0; 49 if (0 != lhost_len) { 50 buffer_append_string_len(o, lhost, lhost_len); 51 } 52 else { 53 size_t olen = buffer_string_length(o); 54 if (0 == sock_addr_nameinfo_append_buffer(o, &our_addr, r->conf.errh)) { 55 lhost_len = buffer_string_length(o) - olen; 56 if (lhost_len < sizeof(lhost)) { 57 memcpy(lhost, o->ptr+olen, lhost_len+1); /*(+1 for '\0')*/ 58 } 59 else { 60 lhost_len = 0; 61 } 62 } 63 else { 64 lhost_len = sizeof("localhost")-1; 65 memcpy(lhost, "localhost", lhost_len+1); /*(+1 for '\0')*/ 66 buffer_append_string_len(o, lhost, lhost_len); 67 } 68 } 69 } else if (!buffer_string_is_empty(r->server_name)) { 70 buffer_append_string_buffer(o, r->server_name); 71 } else 72 /* Lookup name: secondly try to get hostname for bind address */ 73 if (0 != sock_addr_nameinfo_append_buffer(o, &our_addr, r->conf.errh)) { 74 r->http_status = 500; 75 return -1; 76 } 77 78 { 79 unsigned short listen_port = sock_addr_get_port(&our_addr); 80 unsigned short default_port = 80; 81 if (buffer_is_equal_string(&r->uri.scheme, CONST_STR_LEN("https"))) { 82 default_port = 443; 83 } 84 if (0 == listen_port) listen_port = r->con->srv->srvconf.port; 85 if (default_port != listen_port) { 86 buffer_append_string_len(o, CONST_STR_LEN(":")); 87 buffer_append_int(o, listen_port); 88 } 89 } 90 } 91 return 0; 92 } 93 94 int http_response_redirect_to_directory(request_st * const r, int status) { 95 buffer *o = r->tmp_buf; 96 buffer_copy_buffer(o, &r->uri.scheme); 97 buffer_append_string_len(o, CONST_STR_LEN("://")); 98 if (0 != http_response_buffer_append_authority(r, o)) { 99 return -1; 100 } 101 buffer_append_string_encoded(o, CONST_BUF_LEN(&r->uri.path), ENCODING_REL_URI); 102 buffer_append_string_len(o, CONST_STR_LEN("/")); 103 if (!buffer_string_is_empty(&r->uri.query)) { 104 buffer_append_string_len(o, CONST_STR_LEN("?")); 105 buffer_append_string_buffer(o, &r->uri.query); 106 } 107 108 if (status >= 300) { 109 http_header_response_set(r, HTTP_HEADER_LOCATION, CONST_STR_LEN("Location"), CONST_BUF_LEN(o)); 110 r->http_status = status; 111 r->resp_body_finished = 1; 112 } 113 else { 114 http_header_response_set(r, HTTP_HEADER_CONTENT_LOCATION, CONST_STR_LEN("Content-Location"), CONST_BUF_LEN(o)); 115 } 116 117 return 0; 118 } 119 120 #define MTIME_CACHE_MAX 16 121 struct mtime_cache_type { 122 time_t mtime; /* key */ 123 buffer str; /* buffer for string representation */ 124 }; 125 static struct mtime_cache_type mtime_cache[MTIME_CACHE_MAX]; 126 static char mtime_cache_str[MTIME_CACHE_MAX][30]; 127 /* 30-chars for "%a, %d %b %Y %H:%M:%S GMT" */ 128 129 void strftime_cache_reset(void) { 130 for (int i = 0; i < MTIME_CACHE_MAX; ++i) { 131 mtime_cache[i].mtime = (time_t)-1; 132 mtime_cache[i].str.ptr = mtime_cache_str[i]; 133 mtime_cache[i].str.used = sizeof(mtime_cache_str[0]); 134 mtime_cache[i].str.size = sizeof(mtime_cache_str[0]); 135 } 136 } 137 138 const buffer * strftime_cache_get(const time_t last_mod) { 139 static int mtime_cache_idx; 140 141 for (int j = 0; j < MTIME_CACHE_MAX; ++j) { 142 if (mtime_cache[j].mtime == last_mod) 143 return &mtime_cache[j].str; /* found cache-entry */ 144 } 145 146 if (++mtime_cache_idx == MTIME_CACHE_MAX) mtime_cache_idx = 0; 147 148 const int i = mtime_cache_idx; 149 mtime_cache[i].mtime = last_mod; 150 strftime(mtime_cache[i].str.ptr, sizeof(mtime_cache_str[0]), 151 "%a, %d %b %Y %H:%M:%S GMT", gmtime(&mtime_cache[i].mtime)); 152 153 return &mtime_cache[i].str; 154 } 155 156 157 int http_response_handle_cachable(request_st * const r, const buffer * const mtime) { 158 const buffer *vb; 159 160 /* 161 * 14.26 If-None-Match 162 * [...] 163 * If none of the entity tags match, then the server MAY perform the 164 * requested method as if the If-None-Match header field did not exist, 165 * but MUST also ignore any If-Modified-Since header field(s) in the 166 * request. That is, if no entity tags match, then the server MUST NOT 167 * return a 304 (Not Modified) response. 168 */ 169 170 if ((vb = http_header_request_get(r, HTTP_HEADER_IF_NONE_MATCH, CONST_STR_LEN("If-None-Match")))) { 171 /*(weak etag comparison must not be used for ranged requests)*/ 172 int range_request = 173 (r->conf.range_requests 174 && (200 == r->http_status || 0 == r->http_status) 175 && NULL != http_header_request_get(r, HTTP_HEADER_RANGE, CONST_STR_LEN("Range"))); 176 if (etag_is_equal(&r->physical.etag, vb->ptr, !range_request)) { 177 if (http_method_get_or_head(r->http_method)) { 178 r->http_status = 304; 179 return HANDLER_FINISHED; 180 } else { 181 r->http_status = 412; 182 r->handler_module = NULL; 183 return HANDLER_FINISHED; 184 } 185 } 186 } else if (http_method_get_or_head(r->http_method) 187 && (vb = http_header_request_get(r, HTTP_HEADER_IF_MODIFIED_SINCE, CONST_STR_LEN("If-Modified-Since")))) { 188 /* last-modified handling */ 189 size_t used_len; 190 char *semicolon; 191 192 if (NULL == (semicolon = strchr(vb->ptr, ';'))) { 193 used_len = buffer_string_length(vb); 194 } else { 195 used_len = semicolon - vb->ptr; 196 } 197 198 if (buffer_is_equal_string(mtime, vb->ptr, used_len)) { 199 if ('\0' == mtime->ptr[used_len]) r->http_status = 304; 200 return HANDLER_FINISHED; 201 } else { 202 char buf[sizeof("Sat, 23 Jul 2005 21:20:01 GMT")]; 203 time_t t_header, t_file; 204 struct tm tm; 205 206 /* convert to timestamp */ 207 if (used_len >= sizeof(buf)) return HANDLER_GO_ON; 208 209 memcpy(buf, vb->ptr, used_len); 210 buf[used_len] = '\0'; 211 212 if (NULL == strptime(buf, "%a, %d %b %Y %H:%M:%S GMT", &tm)) { 213 /** 214 * parsing failed, let's get out of here 215 */ 216 return HANDLER_GO_ON; 217 } 218 tm.tm_isdst = 0; 219 t_header = mktime(&tm); 220 221 strptime(mtime->ptr, "%a, %d %b %Y %H:%M:%S GMT", &tm); 222 tm.tm_isdst = 0; 223 t_file = mktime(&tm); 224 225 if (t_file > t_header) return HANDLER_GO_ON; 226 227 r->http_status = 304; 228 return HANDLER_FINISHED; 229 } 230 } 231 232 return HANDLER_GO_ON; 233 } 234 235 236 void http_response_body_clear (request_st * const r, int preserve_length) { 237 r->resp_send_chunked = 0; 238 if (r->resp_htags & HTTP_HEADER_TRANSFER_ENCODING) { 239 http_header_response_unset(r, HTTP_HEADER_TRANSFER_ENCODING, CONST_STR_LEN("Transfer-Encoding")); 240 } 241 if (!preserve_length) { /* preserve for HEAD responses and no-content responses (204, 205, 304) */ 242 r->content_length = -1; 243 if (r->resp_htags & HTTP_HEADER_CONTENT_LENGTH) { 244 http_header_response_unset(r, HTTP_HEADER_CONTENT_LENGTH, CONST_STR_LEN("Content-Length")); 245 } 246 } 247 chunkqueue_reset(r->write_queue); 248 } 249 250 251 static int http_response_parse_range(request_st * const r, buffer * const path, stat_cache_entry * const sce, const char * const range) { 252 int multipart = 0; 253 int error; 254 off_t start, end; 255 const char *s, *minus; 256 static const char boundary[] = "fkj49sn38dcn3"; 257 const buffer *content_type = http_header_response_get(r, HTTP_HEADER_CONTENT_TYPE, CONST_STR_LEN("Content-Type")); 258 259 start = 0; 260 end = sce->st.st_size - 1; 261 262 r->content_length = 0; 263 264 for (s = range, error = 0; 265 !error && *s && NULL != (minus = strchr(s, '-')); ) { 266 char *err; 267 off_t la = 0, le; 268 *((const char **)&err) = s; /*(quiet clang --analyze)*/ 269 270 if (s != minus) { 271 la = strtoll(s, &err, 10); 272 if (err != minus) { 273 /* should not have multiple range-unit in Range, but 274 * handle just in case multiple Range headers merged */ 275 while (*s == ' ' || *s == '\t') ++s; 276 if (0 != strncmp(s, "bytes=", 6)) return -1; 277 s += 6; 278 if (s != minus) { 279 la = strtoll(s, &err, 10); 280 if (err != minus) return -1; 281 } 282 } 283 } 284 285 if (s == minus) { 286 /* -<stop> */ 287 288 le = strtoll(s, &err, 10); 289 290 if (le == 0) { 291 /* RFC 2616 - 14.35.1 */ 292 293 r->http_status = 416; 294 error = 1; 295 } else if (*err == '\0') { 296 /* end */ 297 s = err; 298 299 end = sce->st.st_size - 1; 300 start = sce->st.st_size + le; 301 } else if (*err == ',') { 302 multipart = 1; 303 s = err + 1; 304 305 end = sce->st.st_size - 1; 306 start = sce->st.st_size + le; 307 } else { 308 error = 1; 309 } 310 311 } else if (*(minus+1) == '\0' || *(minus+1) == ',') { 312 /* <start>- */ 313 314 /* ok */ 315 316 if (*(err + 1) == '\0') { 317 s = err + 1; 318 319 end = sce->st.st_size - 1; 320 start = la; 321 322 } else if (*(err + 1) == ',') { 323 multipart = 1; 324 s = err + 2; 325 326 end = sce->st.st_size - 1; 327 start = la; 328 } else { 329 error = 1; 330 } 331 } else { 332 /* <start>-<stop> */ 333 334 le = strtoll(minus+1, &err, 10); 335 336 /* RFC 2616 - 14.35.1 */ 337 if (la > le) { 338 error = 1; 339 } 340 341 if (*err == '\0') { 342 /* ok, end*/ 343 s = err; 344 345 end = le; 346 start = la; 347 } else if (*err == ',') { 348 multipart = 1; 349 s = err + 1; 350 351 end = le; 352 start = la; 353 } else { 354 /* error */ 355 356 error = 1; 357 } 358 } 359 360 if (!error) { 361 if (start < 0) start = 0; 362 363 /* RFC 2616 - 14.35.1 */ 364 if (end > sce->st.st_size - 1) end = sce->st.st_size - 1; 365 366 if (start > sce->st.st_size - 1) { 367 error = 1; 368 369 r->http_status = 416; 370 } 371 } 372 373 if (!error) { 374 if (multipart) { 375 /* write boundary-header */ 376 buffer *b = r->tmp_buf; 377 buffer_copy_string_len(b, CONST_STR_LEN("\r\n--")); 378 buffer_append_string_len(b, boundary, sizeof(boundary)-1); 379 380 /* write Content-Range */ 381 buffer_append_string_len(b, CONST_STR_LEN("\r\nContent-Range: bytes ")); 382 buffer_append_int(b, start); 383 buffer_append_string_len(b, CONST_STR_LEN("-")); 384 buffer_append_int(b, end); 385 buffer_append_string_len(b, CONST_STR_LEN("/")); 386 buffer_append_int(b, sce->st.st_size); 387 388 if (content_type) { 389 buffer_append_string_len(b, CONST_STR_LEN("\r\nContent-Type: ")); 390 buffer_append_string_buffer(b, content_type); 391 } 392 393 /* write END-OF-HEADER */ 394 buffer_append_string_len(b, CONST_STR_LEN("\r\n\r\n")); 395 396 r->content_length += buffer_string_length(b); 397 chunkqueue_append_mem(r->write_queue, CONST_BUF_LEN(b)); 398 } 399 400 chunkqueue_append_file(r->write_queue, path, start, end - start + 1); 401 r->content_length += end - start + 1; 402 } 403 } 404 405 /* something went wrong */ 406 if (error) return -1; 407 408 buffer * const tb = r->tmp_buf; 409 410 if (multipart) { 411 /* add boundary end */ 412 buffer_copy_string_len(tb, "\r\n--", 4); 413 buffer_append_string_len(tb, boundary, sizeof(boundary)-1); 414 buffer_append_string_len(tb, "--\r\n", 4); 415 416 r->content_length += buffer_string_length(tb); 417 chunkqueue_append_mem(r->write_queue, CONST_BUF_LEN(tb)); 418 419 /* set header-fields */ 420 421 buffer_copy_string_len(tb, CONST_STR_LEN("multipart/byteranges; boundary=")); 422 buffer_append_string_len(tb, boundary, sizeof(boundary)-1); 423 424 /* overwrite content-type */ 425 http_header_response_set(r, HTTP_HEADER_CONTENT_TYPE, CONST_STR_LEN("Content-Type"), CONST_BUF_LEN(tb)); 426 } else { 427 /* add Content-Range-header */ 428 429 buffer_copy_string_len(tb, CONST_STR_LEN("bytes ")); 430 buffer_append_int(tb, start); 431 buffer_append_string_len(tb, CONST_STR_LEN("-")); 432 buffer_append_int(tb, end); 433 buffer_append_string_len(tb, CONST_STR_LEN("/")); 434 buffer_append_int(tb, sce->st.st_size); 435 436 http_header_response_set(r, HTTP_HEADER_OTHER, CONST_STR_LEN("Content-Range"), CONST_BUF_LEN(tb)); 437 } 438 439 /* ok, the file is set-up */ 440 return 0; 441 } 442 443 444 void http_response_send_file (request_st * const r, buffer * const path) { 445 stat_cache_entry * const sce = stat_cache_get_entry(path); 446 const buffer *mtime = NULL; 447 const buffer *vb; 448 int allow_caching = (0 == r->http_status || 200 == r->http_status); 449 450 if (NULL == sce) { 451 r->http_status = (errno == ENOENT) ? 404 : 403; 452 log_error(r->conf.errh, __FILE__, __LINE__, 453 "not a regular file: %s -> %s", r->uri.path.ptr, path->ptr); 454 return; 455 } 456 457 if (!r->conf.follow_symlink 458 && 0 != stat_cache_path_contains_symlink(path, r->conf.errh)) { 459 r->http_status = 403; 460 if (r->conf.log_request_handling) { 461 log_error(r->conf.errh, __FILE__, __LINE__, 462 "-- access denied due symlink restriction"); 463 log_error(r->conf.errh, __FILE__, __LINE__, 464 "Path : %s", path->ptr); 465 } 466 return; 467 } 468 469 /* we only handle regular files */ 470 if (!S_ISREG(sce->st.st_mode)) { 471 r->http_status = 403; 472 if (r->conf.log_file_not_found) { 473 log_error(r->conf.errh, __FILE__, __LINE__, 474 "not a regular file: %s -> %s", 475 r->uri.path.ptr, path->ptr); 476 } 477 return; 478 } 479 480 /*(Note: O_NOFOLLOW affects only the final path segment, 481 * the target file, not any intermediate symlinks along path)*/ 482 const int fd = (0 != sce->st.st_size) 483 ? fdevent_open_cloexec(path->ptr, r->conf.follow_symlink, O_RDONLY, 0) 484 : -1; 485 if (fd < 0 && 0 != sce->st.st_size) { 486 r->http_status = (errno == ENOENT) ? 404 : 403; 487 if (r->conf.log_request_handling) { 488 log_perror(r->conf.errh, __FILE__, __LINE__, 489 "file open failed: %s", path->ptr); 490 } 491 return; 492 } 493 494 /* mod_compress might set several data directly, don't overwrite them */ 495 496 /* set response content-type, if not set already */ 497 498 if (NULL == http_header_response_get(r, HTTP_HEADER_CONTENT_TYPE, CONST_STR_LEN("Content-Type"))) { 499 const buffer *content_type = stat_cache_content_type_get(sce, r); 500 if (buffer_string_is_empty(content_type)) { 501 /* we are setting application/octet-stream, but also announce that 502 * this header field might change in the seconds few requests 503 * 504 * This should fix the aggressive caching of FF and the script download 505 * seen by the first installations 506 */ 507 http_header_response_set(r, HTTP_HEADER_CONTENT_TYPE, CONST_STR_LEN("Content-Type"), CONST_STR_LEN("application/octet-stream")); 508 509 allow_caching = 0; 510 } else { 511 http_header_response_set(r, HTTP_HEADER_CONTENT_TYPE, CONST_STR_LEN("Content-Type"), CONST_BUF_LEN(content_type)); 512 } 513 } 514 515 if (r->conf.range_requests) { 516 http_header_response_append(r, HTTP_HEADER_OTHER, CONST_STR_LEN("Accept-Ranges"), CONST_STR_LEN("bytes")); 517 } 518 519 if (allow_caching) { 520 const buffer *etag = (0 != r->conf.etag_flags) 521 ? stat_cache_etag_get(sce, r->conf.etag_flags) 522 : NULL; 523 if (!buffer_string_is_empty(etag)) { 524 if (NULL == http_header_response_get(r, HTTP_HEADER_ETAG, CONST_STR_LEN("ETag"))) { 525 /* generate e-tag */ 526 etag_mutate(&r->physical.etag, etag); 527 528 http_header_response_set(r, HTTP_HEADER_ETAG, CONST_STR_LEN("ETag"), CONST_BUF_LEN(&r->physical.etag)); 529 } 530 } 531 532 /* prepare header */ 533 if (NULL == (mtime = http_header_response_get(r, HTTP_HEADER_LAST_MODIFIED, CONST_STR_LEN("Last-Modified")))) { 534 mtime = strftime_cache_get(sce->st.st_mtime); 535 http_header_response_set(r, HTTP_HEADER_LAST_MODIFIED, CONST_STR_LEN("Last-Modified"), CONST_BUF_LEN(mtime)); 536 } 537 538 if (HANDLER_FINISHED == http_response_handle_cachable(r, mtime)) { 539 if (fd >= 0) close(fd); 540 return; 541 } 542 } 543 544 if (fd < 0) { /* 0-length file */ 545 r->http_status = 200; 546 r->resp_body_finished = 1; 547 return; 548 } 549 550 if (r->conf.range_requests 551 && (200 == r->http_status || 0 == r->http_status) 552 && NULL != (vb = http_header_request_get(r, HTTP_HEADER_RANGE, CONST_STR_LEN("Range"))) 553 && NULL == http_header_response_get(r, HTTP_HEADER_CONTENT_ENCODING, CONST_STR_LEN("Content-Encoding"))) { 554 const buffer *range = vb; 555 int do_range_request = 1; 556 /* check if we have a conditional GET */ 557 558 if (NULL != (vb = http_header_request_get(r, HTTP_HEADER_OTHER, CONST_STR_LEN("If-Range")))) { 559 /* if the value is the same as our ETag, we do a Range-request, 560 * otherwise a full 200 */ 561 562 if (vb->ptr[0] == '"') { 563 /** 564 * client wants a ETag 565 */ 566 if (!buffer_is_equal(vb, &r->physical.etag)) { 567 do_range_request = 0; 568 } 569 } else if (!mtime) { 570 /** 571 * we don't have a Last-Modified and can match the If-Range: 572 * 573 * sending all 574 */ 575 do_range_request = 0; 576 } else if (!buffer_is_equal(vb, mtime)) { 577 do_range_request = 0; 578 } 579 } 580 581 if (do_range_request 582 && !buffer_string_is_empty(range) 583 && 0 == strncmp(range->ptr, "bytes=", 6)) { 584 /* support only "bytes" byte-unit */ 585 /* content prepared, I'm done */ 586 r->resp_body_finished = 1; 587 588 if (0 == http_response_parse_range(r, path, sce, range->ptr+6)) { 589 r->http_status = 206; 590 } 591 close(fd); 592 return; 593 } 594 } 595 596 /* if we are still here, prepare body */ 597 598 /* we add it here for all requests 599 * the HEAD request will drop it afterwards again 600 */ 601 602 if (0 == http_chunk_append_file_fd(r, path, fd, sce->st.st_size)) { 603 r->http_status = 200; 604 r->resp_body_finished = 1; 605 } 606 else { 607 r->http_status = 500; 608 } 609 } 610 611 612 static void http_response_xsendfile (request_st * const r, buffer * const path, const array * const xdocroot) { 613 const int status = r->http_status; 614 int valid = 1; 615 616 /* reset Content-Length, if set by backend 617 * Content-Length might later be set to size of X-Sendfile static file, 618 * determined by open(), fstat() to reduces race conditions if the file 619 * is modified between stat() (stat_cache_get_entry()) and open(). */ 620 if (r->resp_htags & HTTP_HEADER_CONTENT_LENGTH) { 621 http_header_response_unset(r, HTTP_HEADER_CONTENT_LENGTH, CONST_STR_LEN("Content-Length")); 622 r->content_length = -1; 623 } 624 625 buffer_urldecode_path(path); 626 if (!buffer_is_valid_UTF8(path)) { 627 log_error(r->conf.errh, __FILE__, __LINE__, 628 "X-Sendfile invalid UTF-8 after url-decode: %s", path->ptr); 629 if (r->http_status < 400) { 630 r->http_status = 502; 631 r->handler_module = NULL; 632 } 633 return; 634 } 635 buffer_path_simplify(path, path); 636 if (r->conf.force_lowercase_filenames) { 637 buffer_to_lower(path); 638 } 639 640 /* check that path is under xdocroot(s) 641 * - xdocroot should have trailing slash appended at config time 642 * - r->conf.force_lowercase_filenames is not a server-wide setting, 643 * and so can not be definitively applied to xdocroot at config time*/ 644 if (xdocroot) { 645 size_t i, xlen = buffer_string_length(path); 646 for (i = 0; i < xdocroot->used; ++i) { 647 data_string *ds = (data_string *)xdocroot->data[i]; 648 size_t dlen = buffer_string_length(&ds->value); 649 if (dlen <= xlen 650 && (!r->conf.force_lowercase_filenames 651 ? 0 == memcmp(path->ptr, ds->value.ptr, dlen) 652 : buffer_eq_icase_ssn(path->ptr, ds->value.ptr, dlen))) { 653 break; 654 } 655 } 656 if (i == xdocroot->used && 0 != i) { 657 log_error(r->conf.errh, __FILE__, __LINE__, 658 "X-Sendfile (%s) not under configured x-sendfile-docroot(s)", path->ptr); 659 r->http_status = 403; 660 valid = 0; 661 } 662 } 663 664 if (valid) http_response_send_file(r, path); 665 666 if (r->http_status >= 400 && status < 300) { 667 r->handler_module = NULL; 668 } else if (0 != status && 200 != status) { 669 r->http_status = status; 670 } 671 } 672 673 674 static void http_response_xsendfile2(request_st * const r, const buffer * const value, const array * const xdocroot) { 675 const char *pos = value->ptr; 676 buffer * const b = r->tmp_buf; 677 const int status = r->http_status; 678 679 /* reset Content-Length, if set by backend */ 680 if (r->resp_htags & HTTP_HEADER_CONTENT_LENGTH) { 681 http_header_response_unset(r, HTTP_HEADER_CONTENT_LENGTH, CONST_STR_LEN("Content-Length")); 682 r->content_length = -1; 683 } 684 685 while (*pos) { 686 const char *filename, *range; 687 stat_cache_entry *sce; 688 off_t begin_range, end_range, range_len; 689 690 while (' ' == *pos) pos++; 691 if (!*pos) break; 692 693 filename = pos; 694 if (NULL == (range = strchr(pos, ' '))) { 695 /* missing range */ 696 log_error(r->conf.errh, __FILE__, __LINE__, 697 "Couldn't find range after filename: %s", filename); 698 r->http_status = 502; 699 break; 700 } 701 buffer_copy_string_len(b, filename, range - filename); 702 703 /* find end of range */ 704 for (pos = ++range; *pos && *pos != ' ' && *pos != ','; pos++) ; 705 706 buffer_urldecode_path(b); 707 if (!buffer_is_valid_UTF8(b)) { 708 log_error(r->conf.errh, __FILE__, __LINE__, 709 "X-Sendfile2 invalid UTF-8 after url-decode: %s", b->ptr); 710 r->http_status = 502; 711 break; 712 } 713 buffer_path_simplify(b, b); 714 if (r->conf.force_lowercase_filenames) { 715 buffer_to_lower(b); 716 } 717 if (xdocroot) { 718 size_t i, xlen = buffer_string_length(b); 719 for (i = 0; i < xdocroot->used; ++i) { 720 data_string *ds = (data_string *)xdocroot->data[i]; 721 size_t dlen = buffer_string_length(&ds->value); 722 if (dlen <= xlen 723 && (!r->conf.force_lowercase_filenames 724 ? 0 == memcmp(b->ptr, ds->value.ptr, dlen) 725 : buffer_eq_icase_ssn(b->ptr, ds->value.ptr, dlen))) { 726 break; 727 } 728 } 729 if (i == xdocroot->used && 0 != i) { 730 log_error(r->conf.errh, __FILE__, __LINE__, 731 "X-Sendfile2 (%s) not under configured x-sendfile-docroot(s)", 732 b->ptr); 733 r->http_status = 403; 734 break; 735 } 736 } 737 738 sce = stat_cache_get_entry(b); 739 if (NULL == sce) { 740 log_error(r->conf.errh, __FILE__, __LINE__, 741 "send-file error: couldn't get stat_cache entry for " 742 "X-Sendfile2: %s", b->ptr); 743 r->http_status = 404; 744 break; 745 } else if (!S_ISREG(sce->st.st_mode)) { 746 log_error(r->conf.errh, __FILE__, __LINE__, 747 "send-file error: wrong filetype for X-Sendfile2: %s", b->ptr); 748 r->http_status = 502; 749 break; 750 } 751 /* found the file */ 752 753 /* parse range */ 754 end_range = sce->st.st_size - 1; 755 { 756 char *rpos = NULL; 757 errno = 0; 758 begin_range = strtoll(range, &rpos, 10); 759 if (errno != 0 || begin_range < 0 || rpos == range) 760 goto range_failed; 761 if ('-' != *rpos++) goto range_failed; 762 if (rpos != pos) { 763 range = rpos; 764 end_range = strtoll(range, &rpos, 10); 765 if (errno != 0 || end_range < 0 || rpos == range) 766 goto range_failed; 767 } 768 if (rpos != pos) goto range_failed; 769 770 goto range_success; 771 772 range_failed: 773 log_error(r->conf.errh, __FILE__, __LINE__, 774 "Couldn't decode range after filename: %s", filename); 775 r->http_status = 502; 776 break; 777 778 range_success: ; 779 } 780 781 /* no parameters accepted */ 782 783 while (*pos == ' ') pos++; 784 if (*pos != '\0' && *pos != ',') { 785 r->http_status = 502; 786 break; 787 } 788 789 range_len = end_range - begin_range + 1; 790 if (range_len < 0) { 791 r->http_status = 502; 792 break; 793 } 794 if (range_len != 0) { 795 if (0 != 796 http_chunk_append_file_range(r, b, begin_range, range_len)) { 797 r->http_status = 502; 798 break; 799 } 800 } 801 802 if (*pos == ',') pos++; 803 } 804 805 if (r->http_status >= 400 && status < 300) { 806 r->handler_module = NULL; 807 } else if (0 != status && 200 != status) { 808 r->http_status = status; 809 } 810 } 811 812 813 void http_response_backend_error (request_st * const r) { 814 if (r->resp_body_started) { 815 /*(response might have been already started, kill the connection)*/ 816 /*(mode == DIRECT to avoid later call to http_response_backend_done())*/ 817 r->handler_module = NULL; /*(avoid sending final chunked block)*/ 818 r->keep_alive = 0; 819 r->resp_body_finished = 1; 820 } /*(else error status set later by http_response_backend_done())*/ 821 } 822 823 void http_response_backend_done (request_st * const r) { 824 /* (not CON_STATE_ERROR and not CON_STATE_RESPONSE_END, 825 * i.e. not called from handle_connection_close or connection_reset 826 * hooks, except maybe from errdoc handler, which later resets state)*/ 827 switch (r->state) { 828 case CON_STATE_HANDLE_REQUEST: 829 case CON_STATE_READ_POST: 830 if (!r->resp_body_started) { 831 /* Send an error if we haven't sent any data yet */ 832 r->http_status = 500; 833 r->handler_module = NULL; 834 break; 835 } /* else fall through */ 836 case CON_STATE_WRITE: 837 if (!r->resp_body_finished) { 838 http_chunk_close(r); 839 r->resp_body_finished = 1; 840 } 841 default: 842 break; 843 } 844 } 845 846 847 void http_response_upgrade_read_body_unknown(request_st * const r) { 848 /* act as transparent proxy */ 849 if (!(r->conf.stream_request_body & FDEVENT_STREAM_REQUEST)) 850 r->conf.stream_request_body |= 851 (FDEVENT_STREAM_REQUEST_BUFMIN | FDEVENT_STREAM_REQUEST); 852 if (!(r->conf.stream_response_body & FDEVENT_STREAM_RESPONSE)) 853 r->conf.stream_response_body |= 854 (FDEVENT_STREAM_RESPONSE_BUFMIN | FDEVENT_STREAM_RESPONSE); 855 r->conf.stream_request_body |= FDEVENT_STREAM_REQUEST_POLLIN; 856 r->reqbody_length = -2; 857 r->keep_alive = 0; 858 } 859 860 861 static handler_t http_response_process_local_redir(request_st * const r, size_t blen) { 862 /* [RFC3875] The Common Gateway Interface (CGI) Version 1.1 863 * [RFC3875] 6.2.2 Local Redirect Response 864 * 865 * The CGI script can return a URI path and query-string 866 * ('local-pathquery') for a local resource in a Location header field. 867 * This indicates to the server that it should reprocess the request 868 * using the path specified. 869 * 870 * local-redir-response = local-Location NL 871 * 872 * The script MUST NOT return any other header fields or a message-body, 873 * and the server MUST generate the response that it would have produced 874 * in response to a request containing the URL 875 * 876 * scheme "://" server-name ":" server-port local-pathquery 877 * 878 * (Might not have begun to receive body yet, but do skip local-redir 879 * if we already have started receiving a response body (blen > 0)) 880 * (Also, while not required by the RFC, do not send local-redir back 881 * to same URL, since CGI should have handled it internally if it 882 * really wanted to do that internally) 883 */ 884 885 /* r->http_status >= 300 && r->http_status < 400) */ 886 size_t ulen = buffer_string_length(&r->uri.path); 887 const buffer *vb = http_header_response_get(r, HTTP_HEADER_LOCATION, CONST_STR_LEN("Location")); 888 if (NULL != vb 889 && vb->ptr[0] == '/' 890 && (0 != strncmp(vb->ptr, r->uri.path.ptr, ulen) 891 || ( vb->ptr[ulen] != '\0' 892 && vb->ptr[ulen] != '/' 893 && vb->ptr[ulen] != '?')) 894 && 0 == blen 895 && !(r->resp_htags & HTTP_HEADER_STATUS) /*no "Status" or NPH response*/ 896 && 1 == r->resp_headers.used) { 897 if (++r->loops_per_request > 5) { 898 log_error(r->conf.errh, __FILE__, __LINE__, 899 "too many internal loops while processing request: %s", 900 r->target_orig.ptr); 901 r->http_status = 500; /* Internal Server Error */ 902 r->handler_module = NULL; 903 return HANDLER_FINISHED; 904 } 905 906 buffer_copy_buffer(&r->target, vb); 907 908 if (r->reqbody_length) { 909 if (r->reqbody_length 910 != r->reqbody_queue->bytes_in) { 911 r->keep_alive = 0; 912 } 913 r->reqbody_length = 0; 914 chunkqueue_reset(r->reqbody_queue); 915 } 916 917 if (r->http_status != 307 && r->http_status != 308) { 918 /* Note: request body (if any) sent to initial dynamic handler 919 * and is not available to the internal redirect */ 920 r->http_method = HTTP_METHOD_GET; 921 } 922 923 /*(caller must reset request as follows)*/ 924 /*connection_response_reset(r);*/ /*(sets r->http_status = 0)*/ 925 /*plugins_call_connection_reset(r);*/ 926 927 return HANDLER_COMEBACK; 928 } 929 930 return HANDLER_GO_ON; 931 } 932 933 934 static int http_response_process_headers(request_st * const r, http_response_opts * const opts, buffer * const hdrs) { 935 char *ns; 936 const char *s; 937 int line = 0; 938 int status_is_set = 0; 939 940 for (s = hdrs->ptr; NULL != (ns = strchr(s, '\n')); s = ns + 1, ++line) { 941 const char *key, *value; 942 int key_len; 943 enum http_header_e id; 944 945 /* strip the \n */ 946 ns[0] = '\0'; 947 if (ns > s && ns[-1] == '\r') ns[-1] = '\0'; 948 949 if (0 == line && 0 == strncmp(s, "HTTP/1.", 7)) { 950 /* non-parsed headers ... we parse them anyway */ 951 if ((s[7] == '1' || s[7] == '0') && s[8] == ' ') { 952 /* after the space should be a status code for us */ 953 int status = strtol(s+9, NULL, 10); 954 if (status >= 100 && status < 1000) { 955 status_is_set = 1; 956 r->resp_htags |= HTTP_HEADER_STATUS; 957 r->http_status = status; 958 } /* else we expected 3 digits and didn't get them */ 959 } 960 961 if (0 == r->http_status) { 962 log_error(r->conf.errh, __FILE__, __LINE__, 963 "invalid HTTP status line: %s", s); 964 r->http_status = 502; /* Bad Gateway */ 965 r->handler_module = NULL; 966 return -1; 967 } 968 969 continue; 970 } 971 972 /* parse the headers */ 973 key = s; 974 if (NULL == (value = strchr(s, ':'))) { 975 /* we expect: "<key>: <value>\r\n" */ 976 continue; 977 } 978 979 key_len = value - key; 980 do { ++value; } while (*value == ' ' || *value == '\t'); /* skip LWS */ 981 id = http_header_hkey_get(key, key_len); 982 983 if (opts->authorizer) { 984 if (0 == r->http_status || 200 == r->http_status) { 985 if (id == HTTP_HEADER_STATUS) { 986 int status = strtol(value, NULL, 10); 987 if (status >= 100 && status < 1000) { 988 r->http_status = status; 989 } else { 990 r->http_status = 502; /* Bad Gateway */ 991 break; 992 } 993 } 994 else if (id == HTTP_HEADER_OTHER && key_len > 9 995 && (key[0] & 0xdf) == 'V' 996 && buffer_eq_icase_ssn(key, 997 CONST_STR_LEN("Variable-"))) { 998 http_header_env_append(r, key + 9, key_len - 9, value, strlen(value)); 999 } 1000 continue; 1001 } 1002 } 1003 1004 switch (id) { 1005 case HTTP_HEADER_STATUS: 1006 { 1007 int status; 1008 if (opts->backend == BACKEND_PROXY) break; /*(pass w/o parse)*/ 1009 status = strtol(value, NULL, 10); 1010 if (status >= 100 && status < 1000) { 1011 r->http_status = status; 1012 status_is_set = 1; 1013 } else { 1014 r->http_status = 502; 1015 r->handler_module = NULL; 1016 } 1017 continue; /* do not send Status to client */ 1018 } 1019 break; 1020 case HTTP_HEADER_UPGRADE: 1021 /*(technically, should also verify Connection: upgrade)*/ 1022 /*(flag only for mod_proxy and mod_cgi (for now))*/ 1023 if (opts->backend != BACKEND_PROXY 1024 && opts->backend != BACKEND_CGI) { 1025 id = HTTP_HEADER_OTHER; 1026 } 1027 break; 1028 case HTTP_HEADER_CONNECTION: 1029 if (opts->backend == BACKEND_PROXY) continue; 1030 /*(should parse for tokens and do case-insensitive match for "close" 1031 * but this is an imperfect though simplistic attempt to honor 1032 * backend request to close)*/ 1033 if (NULL != strstr(value, "lose")) r->keep_alive = 0; 1034 break; 1035 case HTTP_HEADER_CONTENT_LENGTH: 1036 r->content_length = strtoul(value, NULL, 10); 1037 break; 1038 case HTTP_HEADER_TRANSFER_ENCODING: 1039 if (opts->backend == BACKEND_PROXY) { 1040 log_error(r->conf.errh, __FILE__, __LINE__, 1041 "proxy backend sent invalid response header " 1042 "(Transfer-Encoding) to HTTP/1.0 request"); 1043 r->http_status = 502; /* Bad Gateway */ 1044 r->handler_module = NULL; 1045 return -1; 1046 } 1047 break; 1048 default: 1049 break; 1050 } 1051 1052 http_header_response_insert(r, id, key, key_len, value, strlen(value)); 1053 } 1054 1055 /* CGI/1.1 rev 03 - 7.2.1.2 */ 1056 /* (proxy requires Status-Line, so never true for proxy)*/ 1057 if (!status_is_set && (r->resp_htags & HTTP_HEADER_LOCATION)) { 1058 r->http_status = 302; 1059 } 1060 1061 return 0; 1062 } 1063 1064 1065 handler_t http_response_parse_headers(request_st * const r, http_response_opts * const opts, buffer * const b) { 1066 /** 1067 * possible formats of response headers: 1068 * 1069 * proxy or NPH (non-parsed headers): 1070 * 1071 * HTTP/1.0 200 Ok\n 1072 * Header: Value\n 1073 * \n 1074 * 1075 * CGI: 1076 * 1077 * Header: Value\n 1078 * Status: 200\n 1079 * \n 1080 * 1081 * and different mixes of \n and \r\n combinations 1082 * 1083 * Some users also forget about CGI and just send a response 1084 * and hope we handle it. No headers, no header-content separator 1085 */ 1086 1087 int is_nph = (0 == strncmp(b->ptr, "HTTP/1.", 7)); /*nph (non-parsed hdrs)*/ 1088 int is_header_end = 0; 1089 size_t last_eol = 0; 1090 size_t i = 0, header_len = buffer_string_length(b); 1091 const char *bstart; 1092 size_t blen; 1093 1094 if (b->ptr[0] == '\n' || (b->ptr[0] == '\r' && b->ptr[1] == '\n')) { 1095 /* no HTTP headers */ 1096 i = (b->ptr[0] == '\n') ? 0 : 1; 1097 is_header_end = 1; 1098 } else if (is_nph || b->ptr[(i = strcspn(b->ptr, ":\n"))] == ':') { 1099 /* HTTP headers */ 1100 ++i; 1101 for (char *c; NULL != (c = strchr(b->ptr+i, '\n')); ++i) { 1102 i = (uintptr_t)(c - b->ptr); 1103 /** 1104 * check if we saw a \n(\r)?\n sequence 1105 */ 1106 if (last_eol > 0 && 1107 ((i - last_eol == 1) || 1108 (i - last_eol == 2 && b->ptr[i - 1] == '\r'))) { 1109 is_header_end = 1; 1110 break; 1111 } 1112 1113 last_eol = i; 1114 } 1115 } else if (i == header_len) { /* (no newline yet; partial header line?) */ 1116 } else if (opts->backend == BACKEND_CGI) { 1117 /* no HTTP headers, but a body (special-case for CGI compat) */ 1118 /* no colon found; does not appear to be HTTP headers */ 1119 if (0 != http_chunk_append_buffer(r, b)) { 1120 return HANDLER_ERROR; 1121 } 1122 r->http_status = 200; /* OK */ 1123 r->resp_body_started = 1; 1124 return HANDLER_GO_ON; 1125 } else { 1126 /* invalid response headers */ 1127 r->http_status = 502; /* Bad Gateway */ 1128 r->handler_module = NULL; 1129 return HANDLER_FINISHED; 1130 } 1131 1132 if (!is_header_end) { 1133 /*(reuse MAX_HTTP_REQUEST_HEADER as max size 1134 * for response headers from backends)*/ 1135 if (header_len > MAX_HTTP_REQUEST_HEADER) { 1136 log_error(r->conf.errh, __FILE__, __LINE__, 1137 "response headers too large for %s", r->uri.path.ptr); 1138 r->http_status = 502; /* Bad Gateway */ 1139 r->handler_module = NULL; 1140 return HANDLER_FINISHED; 1141 } 1142 return HANDLER_GO_ON; 1143 } 1144 1145 /* the body starts after the EOL */ 1146 bstart = b->ptr + (i + 1); 1147 blen = header_len - (i + 1); 1148 1149 /* strip the last \r?\n */ 1150 if (i > 0 && (b->ptr[i - 1] == '\r')) { 1151 i--; 1152 } 1153 1154 buffer_string_set_length(b, i); 1155 1156 if (opts->backend == BACKEND_PROXY && !is_nph) { 1157 /* invalid response Status-Line from HTTP proxy */ 1158 r->http_status = 502; /* Bad Gateway */ 1159 r->handler_module = NULL; 1160 return HANDLER_FINISHED; 1161 } 1162 1163 if (0 != http_response_process_headers(r, opts, b)) { 1164 return HANDLER_ERROR; 1165 } 1166 1167 r->resp_body_started = 1; 1168 1169 if (opts->authorizer 1170 && (r->http_status == 0 || r->http_status == 200)) { 1171 return HANDLER_GO_ON; 1172 } 1173 1174 if (NULL == r->handler_module) { 1175 return HANDLER_FINISHED; 1176 } 1177 1178 if (opts->local_redir && r->http_status >= 300 && r->http_status < 400){ 1179 /*(r->resp_htags & HTTP_HEADER_LOCATION)*/ 1180 handler_t rc = http_response_process_local_redir(r, blen); 1181 if (NULL == r->handler_module) 1182 r->resp_body_started = 0; 1183 if (rc != HANDLER_GO_ON) return rc; 1184 } 1185 1186 if (opts->xsendfile_allow) { 1187 buffer *vb; 1188 /* X-Sendfile2 is deprecated; historical for fastcgi */ 1189 if (opts->backend == BACKEND_FASTCGI 1190 && NULL != (vb = http_header_response_get(r, HTTP_HEADER_OTHER, CONST_STR_LEN("X-Sendfile2")))) { 1191 http_response_xsendfile2(r, vb, opts->xsendfile_docroot); 1192 /* http_header_response_unset() shortcut for HTTP_HEADER_OTHER */ 1193 buffer_clear(vb); /*(do not send to client)*/ 1194 if (NULL == r->handler_module) 1195 r->resp_body_started = 0; 1196 return HANDLER_FINISHED; 1197 } else if (NULL != (vb = http_header_response_get(r, HTTP_HEADER_OTHER, CONST_STR_LEN("X-Sendfile"))) 1198 || (opts->backend == BACKEND_FASTCGI /* X-LIGHTTPD-send-file is deprecated; historical for fastcgi */ 1199 && NULL != (vb = http_header_response_get(r, HTTP_HEADER_OTHER, CONST_STR_LEN("X-LIGHTTPD-send-file"))))) { 1200 http_response_xsendfile(r, vb, opts->xsendfile_docroot); 1201 /* http_header_response_unset() shortcut for HTTP_HEADER_OTHER */ 1202 buffer_clear(vb); /*(do not send to client)*/ 1203 if (NULL == r->handler_module) 1204 r->resp_body_started = 0; 1205 return HANDLER_FINISHED; 1206 } 1207 } 1208 1209 if (blen > 0) { 1210 if (0 != http_chunk_append_mem(r, bstart, blen)) { 1211 return HANDLER_ERROR; 1212 } 1213 } 1214 1215 /* (callback for response headers complete) */ 1216 return (opts->headers) ? opts->headers(r, opts) : HANDLER_GO_ON; 1217 } 1218 1219 1220 handler_t http_response_read(request_st * const r, http_response_opts * const opts, buffer * const b, fdnode * const fdn) { 1221 const int fd = fdn->fd; 1222 while (1) { 1223 ssize_t n; 1224 size_t avail = buffer_string_space(b); 1225 unsigned int toread = 0; 1226 1227 if (0 == fdevent_ioctl_fionread(fd, opts->fdfmt, (int *)&toread)) { 1228 if (avail < toread) { 1229 size_t blen = buffer_string_length(b); 1230 if (toread + blen < 4096) 1231 toread = 4095 - blen; 1232 else if (toread > MAX_READ_LIMIT) 1233 toread = MAX_READ_LIMIT; 1234 } 1235 else if (0 == toread) { 1236 #if 0 1237 return (fdevent_fdnode_interest(fdn) & FDEVENT_IN) 1238 ? HANDLER_FINISHED /* read finished */ 1239 : HANDLER_GO_ON; /* optimistic read; data not ready */ 1240 #else 1241 if (!(fdevent_fdnode_interest(fdn) & FDEVENT_IN)) { 1242 if (!(r->conf.stream_response_body 1243 & FDEVENT_STREAM_RESPONSE_POLLRDHUP)) 1244 return HANDLER_GO_ON;/*optimistic read; data not ready*/ 1245 } 1246 if (0 == avail) /* let read() below indicate if EOF or EAGAIN */ 1247 toread = 1024; 1248 #endif 1249 } 1250 } 1251 else if (avail < 1024) { 1252 toread = 4095 - avail; 1253 } 1254 1255 if (r->conf.stream_response_body & FDEVENT_STREAM_RESPONSE_BUFMIN) { 1256 off_t cqlen = chunkqueue_length(r->write_queue); 1257 if (cqlen + (off_t)toread > 65536 - 4096) { 1258 if (!r->con->is_writable) { 1259 /*(defer removal of FDEVENT_IN interest since 1260 * connection_state_machine() might be able to send data 1261 * immediately, unless !con->is_writable, where 1262 * connection_state_machine() might not loop back to call 1263 * mod_proxy_handle_subrequest())*/ 1264 fdevent_fdnode_event_clr(r->con->srv->ev, fdn, FDEVENT_IN); 1265 } 1266 if (cqlen >= 65536-1) return HANDLER_GO_ON; 1267 toread = 65536 - 1 - (unsigned int)cqlen; 1268 /* Note: heuristic is fuzzy in that it limits how much to read 1269 * from backend based on how much is pending to write to client. 1270 * Modules where data from backend is framed (e.g. FastCGI) may 1271 * want to limit how much is buffered from backend while waiting 1272 * for a complete data frame or data packet from backend. */ 1273 } 1274 } 1275 1276 if (avail < toread) { 1277 /*(add avail+toread to reduce allocations when ioctl EOPNOTSUPP)*/ 1278 avail = avail ? avail - 1 + toread : toread; 1279 buffer_string_prepare_append(b, avail); 1280 } 1281 1282 n = read(fd, b->ptr+buffer_string_length(b), avail); 1283 1284 if (n < 0) { 1285 switch (errno) { 1286 case EAGAIN: 1287 #ifdef EWOULDBLOCK 1288 #if EWOULDBLOCK != EAGAIN 1289 case EWOULDBLOCK: 1290 #endif 1291 #endif 1292 case EINTR: 1293 return HANDLER_GO_ON; 1294 default: 1295 log_perror(r->conf.errh, __FILE__, __LINE__, 1296 "read() %d %d", r->con->fd, fd); 1297 return HANDLER_ERROR; 1298 } 1299 } 1300 1301 buffer_commit(b, (size_t)n); 1302 1303 if (NULL != opts->parse) { 1304 handler_t rc = opts->parse(r, opts, b, (size_t)n); 1305 if (rc != HANDLER_GO_ON) return rc; 1306 } else if (0 == n) { 1307 /* note: no further data is sent to backend after read EOF on socket 1308 * (not checking for half-closed TCP socket) 1309 * (backend should read all data desired prior to closing socket, 1310 * though might send app-level close data frame, if applicable) */ 1311 return HANDLER_FINISHED; /* read finished */ 1312 } else if (0 == r->resp_body_started) { 1313 /* split header from body */ 1314 handler_t rc = http_response_parse_headers(r, opts, b); 1315 if (rc != HANDLER_GO_ON) return rc; 1316 /* accumulate response in b until headers completed (or error) */ 1317 if (r->resp_body_started) buffer_clear(b); 1318 } else { 1319 if (0 != http_chunk_append_buffer(r, b)) { 1320 /* error writing to tempfile; 1321 * truncate response or send 500 if nothing sent yet */ 1322 return HANDLER_ERROR; 1323 } 1324 buffer_clear(b); 1325 } 1326 1327 if (r->conf.stream_response_body & FDEVENT_STREAM_RESPONSE_BUFMIN) { 1328 if (chunkqueue_length(r->write_queue) > 65536 - 4096) { 1329 /*(defer removal of FDEVENT_IN interest since 1330 * connection_state_machine() might be able to send 1331 * data immediately, unless !con->is_writable, where 1332 * connection_state_machine() might not loop back to 1333 * call the subrequest handler)*/ 1334 if (!r->con->is_writable) 1335 fdevent_fdnode_event_clr(r->con->srv->ev, fdn, FDEVENT_IN); 1336 break; 1337 } 1338 } 1339 1340 if ((size_t)n < avail) 1341 break; /* emptied kernel read buffer or partial read */ 1342 } 1343 1344 return HANDLER_GO_ON; 1345 } 1346 1347 1348 int http_cgi_headers (request_st * const r, http_cgi_opts * const opts, http_cgi_header_append_cb cb, void *vdata) { 1349 1350 /* CGI-SPEC 6.1.2, FastCGI spec 6.3 and SCGI spec */ 1351 1352 int rc = 0; 1353 const connection * const con = r->con; 1354 server_socket * const srv_sock = con->srv_socket; 1355 buffer * const tb = r->tmp_buf; 1356 const char *s; 1357 size_t n; 1358 char buf[LI_ITOSTRING_LENGTH]; 1359 sock_addr *addr; 1360 sock_addr addrbuf; 1361 char b2[INET6_ADDRSTRLEN + 1]; 1362 1363 /* (CONTENT_LENGTH must be first for SCGI) */ 1364 if (!opts->authorizer) { 1365 rc |= cb(vdata, CONST_STR_LEN("CONTENT_LENGTH"), 1366 buf, li_itostrn(buf,sizeof(buf),r->reqbody_length)); 1367 } 1368 1369 if (!buffer_string_is_empty(&r->uri.query)) { 1370 rc |= cb(vdata, CONST_STR_LEN("QUERY_STRING"), 1371 CONST_BUF_LEN(&r->uri.query)); 1372 } else { 1373 rc |= cb(vdata, CONST_STR_LEN("QUERY_STRING"), 1374 CONST_STR_LEN("")); 1375 } 1376 if (!buffer_string_is_empty(opts->strip_request_uri)) { 1377 /** 1378 * /app1/index/list 1379 * 1380 * stripping /app1 or /app1/ should lead to 1381 * 1382 * /index/list 1383 * 1384 */ 1385 size_t len = buffer_string_length(opts->strip_request_uri); 1386 if ('/' == opts->strip_request_uri->ptr[len-1]) { 1387 --len; 1388 } 1389 1390 if (buffer_string_length(&r->target_orig) >= len 1391 && 0 == memcmp(r->target_orig.ptr, 1392 opts->strip_request_uri->ptr, len) 1393 && r->target_orig.ptr[len] == '/') { 1394 rc |= cb(vdata, CONST_STR_LEN("REQUEST_URI"), 1395 r->target_orig.ptr+len, 1396 buffer_string_length(&r->target_orig)-len); 1397 } else { 1398 rc |= cb(vdata, CONST_STR_LEN("REQUEST_URI"), 1399 CONST_BUF_LEN(&r->target_orig)); 1400 } 1401 } else { 1402 rc |= cb(vdata, CONST_STR_LEN("REQUEST_URI"), 1403 CONST_BUF_LEN(&r->target_orig)); 1404 } 1405 if (!buffer_is_equal(&r->target, &r->target_orig)) { 1406 rc |= cb(vdata, CONST_STR_LEN("REDIRECT_URI"), 1407 CONST_BUF_LEN(&r->target)); 1408 } 1409 /* set REDIRECT_STATUS for php compiled with --force-redirect 1410 * (if REDIRECT_STATUS has not already been set by error handler) */ 1411 if (0 == r->error_handler_saved_status) { 1412 rc |= cb(vdata, CONST_STR_LEN("REDIRECT_STATUS"), 1413 CONST_STR_LEN("200")); 1414 } 1415 1416 /* 1417 * SCRIPT_NAME, PATH_INFO and PATH_TRANSLATED according to 1418 * http://cgi-spec.golux.com/draft-coar-cgi-v11-03-clean.html 1419 * (6.1.14, 6.1.6, 6.1.7) 1420 */ 1421 if (!opts->authorizer) { 1422 rc |= cb(vdata, CONST_STR_LEN("SCRIPT_NAME"), 1423 CONST_BUF_LEN(&r->uri.path)); 1424 if (!buffer_string_is_empty(&r->pathinfo)) { 1425 rc |= cb(vdata, CONST_STR_LEN("PATH_INFO"), 1426 CONST_BUF_LEN(&r->pathinfo)); 1427 /* PATH_TRANSLATED is only defined if PATH_INFO is set */ 1428 if (!buffer_string_is_empty(opts->docroot)) { 1429 buffer_copy_buffer(tb, opts->docroot); 1430 } else { 1431 buffer_copy_buffer(tb, &r->physical.basedir); 1432 } 1433 buffer_append_string_buffer(tb, &r->pathinfo); 1434 rc |= cb(vdata, CONST_STR_LEN("PATH_TRANSLATED"), 1435 CONST_BUF_LEN(tb)); 1436 } 1437 } 1438 1439 /* 1440 * SCRIPT_FILENAME and DOCUMENT_ROOT for php 1441 * The PHP manual http://www.php.net/manual/en/reserved.variables.php 1442 * treatment of PATH_TRANSLATED is different from the one of CGI specs. 1443 * (see php.ini cgi.fix_pathinfo = 1 config parameter) 1444 */ 1445 1446 if (!buffer_string_is_empty(opts->docroot)) { 1447 /* alternate docroot, e.g. for remote FastCGI or SCGI server */ 1448 buffer_copy_buffer(tb, opts->docroot); 1449 buffer_append_string_buffer(tb, &r->uri.path); 1450 rc |= cb(vdata, CONST_STR_LEN("SCRIPT_FILENAME"), 1451 CONST_BUF_LEN(tb)); 1452 rc |= cb(vdata, CONST_STR_LEN("DOCUMENT_ROOT"), 1453 CONST_BUF_LEN(opts->docroot)); 1454 } else { 1455 if (opts->break_scriptfilename_for_php) { 1456 /* php.ini config cgi.fix_pathinfo = 1 need a broken SCRIPT_FILENAME 1457 * to find out what PATH_INFO is itself 1458 * 1459 * see src/sapi/cgi_main.c, init_request_info() 1460 */ 1461 buffer_copy_buffer(tb, &r->physical.path); 1462 buffer_append_string_buffer(tb, &r->pathinfo); 1463 rc |= cb(vdata, CONST_STR_LEN("SCRIPT_FILENAME"), 1464 CONST_BUF_LEN(tb)); 1465 } else { 1466 rc |= cb(vdata, CONST_STR_LEN("SCRIPT_FILENAME"), 1467 CONST_BUF_LEN(&r->physical.path)); 1468 } 1469 rc |= cb(vdata, CONST_STR_LEN("DOCUMENT_ROOT"), 1470 CONST_BUF_LEN(&r->physical.basedir)); 1471 } 1472 1473 s = get_http_method_name(r->http_method); 1474 force_assert(s); 1475 rc |= cb(vdata, CONST_STR_LEN("REQUEST_METHOD"), s, strlen(s)); 1476 1477 s = get_http_version_name(r->http_version); 1478 force_assert(s); 1479 rc |= cb(vdata, CONST_STR_LEN("SERVER_PROTOCOL"), s, strlen(s)); 1480 1481 rc |= cb(vdata, CONST_STR_LEN("SERVER_SOFTWARE"), 1482 CONST_BUF_LEN(r->conf.server_tag)); 1483 1484 rc |= cb(vdata, CONST_STR_LEN("GATEWAY_INTERFACE"), 1485 CONST_STR_LEN("CGI/1.1")); 1486 1487 rc |= cb(vdata, CONST_STR_LEN("REQUEST_SCHEME"), 1488 CONST_BUF_LEN(&r->uri.scheme)); 1489 1490 if (buffer_is_equal_string(&r->uri.scheme, CONST_STR_LEN("https"))) { 1491 rc |= cb(vdata, CONST_STR_LEN("HTTPS"), CONST_STR_LEN("on")); 1492 } 1493 1494 addr = &srv_sock->addr; 1495 rc |= cb(vdata, CONST_STR_LEN("SERVER_PORT"), 1496 buf, li_utostrn(buf,sizeof(buf),sock_addr_get_port(addr))); 1497 1498 switch (addr->plain.sa_family) { 1499 case AF_INET: 1500 case AF_INET6: 1501 if (sock_addr_is_addr_wildcard(addr)) { 1502 socklen_t addrlen = sizeof(addrbuf); 1503 if (0 == getsockname(con->fd,(struct sockaddr *)&addrbuf,&addrlen)){ 1504 addr = &addrbuf; 1505 } else { 1506 s = ""; 1507 break; 1508 } 1509 } 1510 s = sock_addr_inet_ntop(addr, b2, sizeof(b2)-1); 1511 if (NULL == s) s = ""; 1512 break; 1513 default: 1514 s = ""; 1515 break; 1516 } 1517 force_assert(s); 1518 rc |= cb(vdata, CONST_STR_LEN("SERVER_ADDR"), s, strlen(s)); 1519 1520 if (!buffer_string_is_empty(r->server_name)) { 1521 size_t len = buffer_string_length(r->server_name); 1522 1523 if (r->server_name->ptr[0] == '[') { 1524 const char *colon = strstr(r->server_name->ptr, "]:"); 1525 if (colon) len = (colon + 1) - r->server_name->ptr; 1526 } else { 1527 const char *colon = strchr(r->server_name->ptr, ':'); 1528 if (colon) len = colon - r->server_name->ptr; 1529 } 1530 1531 rc |= cb(vdata, CONST_STR_LEN("SERVER_NAME"), 1532 r->server_name->ptr, len); 1533 } else { 1534 /* set to be same as SERVER_ADDR (above) */ 1535 rc |= cb(vdata, CONST_STR_LEN("SERVER_NAME"), s, strlen(s)); 1536 } 1537 1538 rc |= cb(vdata, CONST_STR_LEN("REMOTE_ADDR"), 1539 CONST_BUF_LEN(con->dst_addr_buf)); 1540 1541 rc |= cb(vdata, CONST_STR_LEN("REMOTE_PORT"), buf, 1542 li_utostrn(buf,sizeof(buf),sock_addr_get_port(&con->dst_addr))); 1543 1544 for (n = 0; n < r->rqst_headers.used; n++) { 1545 data_string *ds = (data_string *)r->rqst_headers.data[n]; 1546 if (!buffer_string_is_empty(&ds->value) && !buffer_is_empty(&ds->key)) { 1547 /* Security: Do not emit HTTP_PROXY in environment. 1548 * Some executables use HTTP_PROXY to configure 1549 * outgoing proxy. See also https://httpoxy.org/ */ 1550 if (buffer_is_equal_caseless_string(&ds->key, 1551 CONST_STR_LEN("Proxy"))) { 1552 continue; 1553 } 1554 buffer_copy_string_encoded_cgi_varnames(tb, 1555 CONST_BUF_LEN(&ds->key), 1); 1556 rc |= cb(vdata, CONST_BUF_LEN(tb), 1557 CONST_BUF_LEN(&ds->value)); 1558 } 1559 } 1560 1561 con->srv->request_env(r); 1562 1563 for (n = 0; n < r->env.used; n++) { 1564 data_string *ds = (data_string *)r->env.data[n]; 1565 if (!buffer_is_empty(&ds->value) && !buffer_is_empty(&ds->key)) { 1566 buffer_copy_string_encoded_cgi_varnames(tb, 1567 CONST_BUF_LEN(&ds->key), 0); 1568 rc |= cb(vdata, CONST_BUF_LEN(tb), 1569 CONST_BUF_LEN(&ds->value)); 1570 } 1571 } 1572 1573 return rc; 1574 } 1575