diff --git a/CMakeLists.txt b/CMakeLists.txt index 2cefd53..884b4c3 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -46,9 +46,12 @@ if(CMAKE_PROJECT_NAME STREQUAL PROJECT_NAME) include_directories(${catch_SOURCE_DIR}/single_include) add_executable(local_stress_test test/local_stress_test.cc test/test_httpd.cc test/test_httpd.h) target_link_libraries(local_stress_test PRIVATE sqlite3 curl microhttpd pthread dl) + add_executable(http_parse_test test/test_http_parse.cc) + target_link_libraries(http_parse_test PRIVATE pthread dl) include(CTest) enable_testing() add_test(NAME pytest COMMAND env SQLITE_VFS_LOG=99 python3 -m pytest -sv ${CMAKE_CURRENT_SOURCE_DIR}/test) add_test(NAME local_stress_test COMMAND local_stress_test) + add_test(NAME http_parse_test COMMAND http_parse_test) endif() diff --git a/src/HTTP.h b/src/HTTP.h index 46e3843..14af79b 100644 --- a/src/HTTP.h +++ b/src/HTTP.h @@ -3,6 +3,10 @@ #pragma once #include +#include +#include +#include +#include #include #include #include @@ -12,6 +16,7 @@ #include #include #include +#include #include #include #include @@ -232,9 +237,36 @@ std::string &rtrim(std::string &s) { std::string &trim(std::string &s) { return ltrim(rtrim(s)); } +// Per-request state for retaining only the final response's headers. +struct HeaderSink { + headers &out; + bool complete = false; + explicit HeaderSink(headers &o) : out(o) {} +}; + size_t headerfunction(char *ptr, size_t size, size_t nmemb, void *userdata) { size *= nmemb; - headers &h = *reinterpret_cast(userdata); + HeaderSink &sink = *reinterpret_cast(userdata); + headers &h = sink.out; + + const std::string line(ptr, size); + + // libcurl reports interim, redirect, CONNECT, and final responses here. + // Clear at each status line to retain only the final response's headers. + if (line.compare(0, 5, "HTTP/") == 0) { + h.clear(); + sink.complete = false; + return size; + } + + // The blank line ends the header section. Ignore subsequent trailer fields. + if (line == "\r\n" || line == "\n") { + sink.complete = true; + return size; + } + if (sink.complete) { + return size; + } size_t sep; for (sep = 0; sep < size; sep++) { @@ -271,14 +303,47 @@ long long ReadContentLengthHeader(const headers &response_headers) { } std::string size = size_it->second; size = trim(size); - const char *size_str = size.c_str(); - char *endptr = nullptr; + // strtoull accepts signs; require decimal digits first. + if (size.empty() || size.find_first_not_of("0123456789") != std::string::npos) { + return -2; + } errno = 0; - unsigned long long file_size = strtoull(size_str, &endptr, 10); - if (errno || endptr != size_str + size.size() || file_size > LLONG_MAX) { + unsigned long long v = strtoull(size.c_str(), nullptr, 10); + if (errno == ERANGE || v > (unsigned long long)LLONG_MAX) { return -2; } - return (long long)file_size; + return (long long)v; +} + +// Match a Content-Range header value against the expected range and +// total: RFC 7233 satisfied-range syntax, case-insensitive "bytes SP +// first-last/total" with surrounding SP/HTAB. Each numeric field, +// leading zeros stripped, must textually equal the expected value's +// decimal form. The total may instead be "*" iff allow_unknown_total. +bool MatchesContentRange(const std::string &value, uint64_t first, uint64_t last, + uint64_t expected_total, bool allow_unknown_total) { + // Some std::regex implementations recurse per input character. + // Reject values over 256 bytes to bound stack use. + if (value.size() > 256) { + return false; + } + static const std::regex re(R"([ \t]*bytes ([0-9]+)-([0-9]+)/([0-9]+|\*)[ \t]*)", + std::regex::ECMAScript | std::regex::icase); + std::smatch m; + if (!std::regex_match(value, m, re)) { + return false; + } + + auto normalize = [](std::string s) { + size_t i = s.find_first_not_of('0'); + return i == std::string::npos ? std::string("0") : s.substr(i); + }; + if (normalize(m[1].str()) != std::to_string(first) || + normalize(m[2].str()) != std::to_string(last)) { + return false; + } + return m[3].str() == "*" ? allow_unknown_total + : normalize(m[3].str()) == std::to_string(expected_total); } enum class Method { GET, HEAD }; @@ -319,7 +384,8 @@ CURLcode Request(Method method, const std::string &url, const headers &request_h CURLsetopt(*conn, CURLOPT_WRITEFUNCTION, writefunction); response_headers.clear(); - CURLsetopt(*conn, CURLOPT_WRITEHEADER, &response_headers); + HeaderSink header_sink(response_headers); + CURLsetopt(*conn, CURLOPT_WRITEHEADER, &header_sink); CURLsetopt(*conn, CURLOPT_HEADERFUNCTION, headerfunction); CURLsetopt(*conn, CURLOPT_FOLLOWLOCATION, 1); diff --git a/src/web_vfs.h b/src/web_vfs.h index 54db82a..8fe70bb 100644 --- a/src/web_vfs.h +++ b/src/web_vfs.h @@ -208,6 +208,23 @@ class File : public SQLiteVFS::File { << ", expected = " << extent.Bytes()) return SQLITE_IOERR_SHORT_READ; } + if (status == 206) { + // A 206 must confirm the requested range in Content-Range + // (RFC 7233). Length alone cannot detect a same-size + // response for the wrong range. + auto cr_it = reshdrs.find("content-range"); + if (cr_it == reshdrs.end() || body->size() == 0 || + !HTTP::MatchesContentRange(cr_it->second, extent.Offset(), + extent.Offset() + body->size() - 1, + uint64_t(file_size_), + /*allow_unknown_total=*/true)) { + SQLITE_WEB_LOG(1, protocol << " GET " << reqhdrs["range"] + << " invalid Content-Range = " + << (cr_it == reshdrs.end() ? std::string("") + : cr_it->second)) + return SQLITE_IOERR_READ; + } + } data = body; if (log_.level() >= 4) { SQLITE_WEB_LOG(4, protocol << " GET " << reqhdrs["range"] << " OK (" @@ -806,35 +823,8 @@ class VFS : public SQLiteVFS::Wrapper { return SQLITE_CORRUPT; } - // parse content-range - auto size_it = reshdrs.find("content-range"); - if (size_it != reshdrs.end()) { - SQLITE_VFS_LOG(5, "[" << filename << "] " << protocol - << " content-range: " << size_it->second) - const std::string &cr = size_it->second; - if (cr.substr(0, 6) == "bytes ") { - auto slash = cr.find('/'); - if (slash != std::string::npos) { - std::string size_txt = cr.substr(slash + 1); - const char *size_str = size_txt.c_str(); - char *endptr = nullptr; - errno = 0; - db_file_size = strtoull(size_str, &endptr, 10); - if (errno || endptr != size_str + size_txt.size()) { - db_file_size = 0; - } - } - } - } - if (!db_file_size) { - std::string err = "[" + filename + "] " + protocol + - " GET bytes=0-99: empty file or invalid content-range header"; - SetLastError(err); - SQLITE_VFS_LOG(1, err) - return SQLITE_IOERR_READ; - } - - // read the page size & page count from the header; their product should equal file size. + // Read the page size & page count from the header; their product is + // the expected file size, which Content-Range must confirm below. // https://github.com/sqlite/sqlite/blob/8d889afc0d81839bde67731d14263026facc89d1/src/shell.c.in#L5451-L5485 page_size = (uint8_t(db_header[16]) << 8) + uint8_t(db_header[17]); if (page_size == 1) { @@ -845,17 +835,32 @@ class VFS : public SQLiteVFS::Wrapper { page_count <<= 8; page_count += uint8_t(db_header[ofs]); } + if (page_size < 512 || page_size > 65536 || page_count == 0) { + std::string err = + "[" + filename + "] database corrupt or truncated; invalid in-header database size"; + SetLastError(err); + SQLITE_VFS_LOG(1, err) + return SQLITE_CORRUPT; + } + db_file_size = page_size * page_count; SQLITE_VFS_LOG(4, "[" << filename << "] database geometry detected: " << db_file_size << " bytes = " << page_size << " bytes/page * " << page_count << " pages (" << (t.micros() / 1000) << "ms)") - if (page_size < 512 || page_size > 65536 || page_count == 0 || - db_file_size != page_size * page_count) { - std::string err = "[" + filename + - "] database corrupt or truncated; content-range file size doesn't " - "match in-header database size"; + + // Require Content-Range to confirm bytes 0-99 and the expected total. + auto size_it = reshdrs.find("content-range"); + if (size_it != reshdrs.end()) { + SQLITE_VFS_LOG(5, "[" << filename << "] " << protocol + << " content-range: " << size_it->second) + } + if (size_it == reshdrs.end() || + !HTTP::MatchesContentRange(size_it->second, 0, 99, db_file_size, + /*allow_unknown_total=*/false)) { + std::string err = "[" + filename + "] " + protocol + + " GET bytes=0-99: missing or invalid Content-Range"; SetLastError(err); SQLITE_VFS_LOG(1, err) - return SQLITE_CORRUPT; + return SQLITE_IOERR_READ; } return SQLITE_OK; } diff --git a/test/test_content_range.py b/test/test_content_range.py new file mode 100644 index 0000000..a0b2ccb --- /dev/null +++ b/test/test_content_range.py @@ -0,0 +1,211 @@ +# Content-Range tests using a local raw-socket SQLite origin. +# Except for /badprobe.db, probes are valid; faults affect extents only. +# +# /good.db: correct responses. +# /wrong.db: correct body, range endpoints shifted by 4096 bytes. +# /nocr.db: missing Content-Range. +# /wrongtotal.db: correct endpoints, total increased by 4096. +# /badprobe.db: shifted probe endpoints; correct extent responses. +# /badtotal.db: correct probe endpoints, wrong total; correct extents. +# /interim.db: correct Content-Range in 103; none in final 206. +# /interimok.db: wrong Content-Range in 103; correct one in final 206. +# /trailer.db: correct Content-Range only in chunked trailers. +import os +import re +import socket +import sqlite3 +import threading +import urllib.parse + +import pytest + +HERE = os.path.dirname(__file__) +BUILD = os.path.abspath(os.path.join(HERE, "..", "build")) +ROWS = 400 + + +def _make_db_bytes(): + path = os.path.join(HERE, "_content_range_test.db") + try: + os.unlink(path) + except FileNotFoundError: + pass + con = sqlite3.connect(path) + con.execute("CREATE TABLE t (x TEXT)") + con.executemany("INSERT INTO t VALUES (?)", [("x" * 100 + str(i),) for i in range(ROWS)]) + con.commit() + con.close() + with open(path, "rb") as f: + data = f.read() + os.unlink(path) + return data + + +DB = _make_db_bytes() + + +def _respond(conn, status, headers, body): + lines = [f"HTTP/1.1 {status}"] + lines += [f"{k}: {v}" for k, v in headers] + lines.append(f"Content-Length: {len(body)}") + lines.append("") + lines.append("") + conn.sendall("\r\n".join(lines).encode() + body) + + +def _serve_range(conn, path, first, last): + body = DB[first : last + 1] + total = len(DB) + correct_cr = f"bytes {first}-{last}/{total}" + probe = (first, last) == (0, 99) + if path == "/badtotal.db" and probe: + wrong_total = f"bytes {first}-{last}/{total + 4096}" + _respond(conn, "206 Partial Content", [("Content-Range", wrong_total)], body) + elif path == "/badprobe.db" and probe: + shifted = f"bytes {first + 4096}-{last + 4096}/{total}" + _respond(conn, "206 Partial Content", [("Content-Range", shifted)], body) + elif probe or path in ("/good.db", "/badprobe.db"): + _respond(conn, "206 Partial Content", [("Content-Range", correct_cr)], body) + elif path == "/wrong.db": + shifted = f"bytes {first + 4096}-{last + 4096}/{total}" + _respond(conn, "206 Partial Content", [("Content-Range", shifted)], body) + elif path == "/nocr.db": + _respond(conn, "206 Partial Content", [], body) + elif path == "/wrongtotal.db": + wrong_total = f"bytes {first}-{last}/{total + 4096}" + _respond(conn, "206 Partial Content", [("Content-Range", wrong_total)], body) + elif path == "/interim.db": + interim = f"HTTP/1.1 103 Early Hints\r\nContent-Range: {correct_cr}\r\n\r\n" + conn.sendall(interim.encode()) + _respond(conn, "206 Partial Content", [], body) + elif path == "/interimok.db": + interim = ( + "HTTP/1.1 103 Early Hints\r\n" + f"Content-Range: bytes {first + 4096}-{last + 4096}/{total}\r\n" + "\r\n" + ) + conn.sendall(interim.encode()) + _respond(conn, "206 Partial Content", [("Content-Range", correct_cr)], body) + elif path == "/trailer.db": + chunked = ( + ( + "HTTP/1.1 206 Partial Content\r\n" + "Transfer-Encoding: chunked\r\n" + "\r\n" + f"{len(body):x}\r\n" + ).encode() + + body + + (f"\r\n0\r\nContent-Range: {correct_cr}\r\n\r\n").encode() + ) + conn.sendall(chunked) + else: + _respond(conn, "404 Not Found", [], b"") + + +def _handle_conn(conn): + buf = b"" + try: + while True: + while b"\r\n\r\n" not in buf: + chunk = conn.recv(65536) + if not chunk: + return + buf += chunk + request, buf = buf.split(b"\r\n\r\n", 1) + lines = request.decode("latin1").split("\r\n") + path = lines[0].split(" ")[1] + headers = {} + for line in lines[1:]: + if ": " in line: + k, v = line.split(": ", 1) + headers[k.lower()] = v + m = re.fullmatch(r"bytes=(\d+)-(\d+)", headers.get("range", "")) + if m: + _serve_range(conn, path, int(m.group(1)), int(m.group(2))) + elif path.endswith(".db"): + _respond(conn, "200 OK", [], DB) + else: + _respond(conn, "404 Not Found", [], b"") + except (ConnectionResetError, BrokenPipeError): + return + finally: + conn.close() + + +@pytest.fixture(scope="module") +def origin(): + srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + srv.bind(("127.0.0.1", 0)) + srv.listen(50) + port = srv.getsockname()[1] + + def accept_loop(): + while True: + try: + conn, _ = srv.accept() + except OSError: + return + threading.Thread(target=_handle_conn, args=(conn,), daemon=True).start() + + threading.Thread(target=accept_loop, daemon=True).start() + yield f"http://127.0.0.1:{port}" + srv.close() + + +def _count_rows(origin, path): + con = sqlite3.connect(":memory:") + con.enable_load_extension(True) + con.load_extension(os.path.join(BUILD, "web_vfs")) + url = urllib.parse.quote(f"{origin}{path}", safe="") + con = sqlite3.connect( + f"file:/__web__?vfs=web&mode=ro&immutable=1&web_url={url}&web_nodbi=1&web_small_KiB=4", + uri=True, + ) + try: + return con.execute("SELECT count(*) FROM t").fetchone()[0] + finally: + con.close() + + +def test_good_origin(origin): + assert _count_rows(origin, "/good.db") == ROWS + + +def test_wrong_content_range_rejected(origin): + with pytest.raises(sqlite3.Error): + _count_rows(origin, "/wrong.db") + + +def test_missing_content_range_rejected(origin): + with pytest.raises(sqlite3.Error): + _count_rows(origin, "/nocr.db") + + +def test_wrong_total_rejected(origin): + with pytest.raises(sqlite3.Error): + _count_rows(origin, "/wrongtotal.db") + + +def test_bad_probe_rejected(origin): + with pytest.raises(sqlite3.Error): + _count_rows(origin, "/badprobe.db") + + +def test_bad_probe_total_rejected(origin): + with pytest.raises(sqlite3.Error): + _count_rows(origin, "/badtotal.db") + + +def test_interim_headers_do_not_leak(origin): + with pytest.raises(sqlite3.Error): + _count_rows(origin, "/interim.db") + + +def test_final_response_headers_win(origin): + assert _count_rows(origin, "/interimok.db") == ROWS + + +def test_trailer_content_range_rejected(origin): + with pytest.raises(sqlite3.Error): + _count_rows(origin, "/trailer.db") diff --git a/test/test_http_parse.cc b/test/test_http_parse.cc new file mode 100644 index 0000000..9c06d34 --- /dev/null +++ b/test/test_http_parse.cc @@ -0,0 +1,191 @@ +// Tests for Content-Range and Content-Length parsing and for retaining +// only the final response's headers, excluding trailers. +#define CATCH_CONFIG_MAIN +#include "catch2/catch.hpp" + +#include "../src/HTTP.h" + +namespace { + +struct CRCase { + const char *input; + uint64_t first, last; // the range the caller expects the header to name + uint64_t expected_total; + bool allow_unknown_total; + bool ok; +}; + +} // namespace + +TEST_CASE("MatchesContentRange exact-match table") { + const CRCase cases[] = { + // the header names exactly the expected range and total + {"bytes 0-99/77824", 0, 99, 77824, false, true}, + {"bytes 65536-77823/77824", 65536, 77823, 77824, false, true}, + {"bytes 0-0/1", 0, 0, 1, false, true}, + {"BYTES 10-19/100", 10, 19, 100, false, true}, + {"bYtEs 10-19/100", 10, 19, 100, false, true}, + {" bytes 10-19/100 ", 10, 19, 100, false, true}, + {"\tbytes 10-19/100\t", 10, 19, 100, false, true}, + {"bytes 007-009/0100", 7, 9, 100, false, true}, // leading zeros are digits + {"bytes 0-99/100 ", 0, 99, 100, false, true}, // trailing OWS is allowed + {"bytes 0-99/18446744073709551615", 0, 99, UINT64_MAX, false, true}, + // "*" is accepted only where unknown totals are allowed + {"bytes 0-99/*", 0, 99, 77824, true, true}, + {"bytes 0-99/*", 0, 99, 77824, false, false}, + {"bytes 0-18446744073709551615/*", 0, UINT64_MAX, 0, true, true}, + {"bytes 18446744073709551615-18446744073709551615/*", UINT64_MAX, UINT64_MAX, 0, true, + true}, + // the header names a different range than expected + {"bytes 4096-8191/77824", 0, 4095, 77824, false, false}, + {"bytes 0-99/77824", 0, 98, 77824, false, false}, + {"bytes 0-99/77824", 1, 99, 77824, false, false}, + {"bytes 99-0/100", 0, 99, 100, false, false}, + // a present total must equal the expected total, "*" allowance or not + {"bytes 0-99/77825", 0, 99, 77824, false, false}, + {"bytes 0-99/77825", 0, 99, 77824, true, false}, + // a total beyond uint64 simply cannot equal the expectation + {"bytes 0-99/18446744073709551616", 0, 99, 77824, false, false}, + {"bytes 0-99/99999999999999999999999999", 0, 99, 77824, false, false}, + // malformed syntax (the expectation is arbitrary) + {"bytes 0-99", 0, 99, 100, false, false}, // missing /total + {"bytes 0-99/", 0, 99, 100, false, false}, // empty total + {"bytes /100", 0, 99, 100, false, false}, // missing range entirely + {"bytes -99/100", 0, 99, 100, false, false}, // empty first + {"bytes 0-/100", 0, 99, 100, false, false}, // empty last + {"bytes 0-99/100 x", 0, 99, 100, false, false}, // junk suffix + {"bytes 0-99/100x", 0, 99, 100, false, false}, // suffix junk + {"bytes 0-99/100,200-299/600", 0, 99, 100, false, false}, // multiple ranges + {"bytes 0-99, 200-299/600", 0, 99, 100, false, false}, + {"bytes +0-99/100", 0, 99, 100, false, false}, // sign + {"bytes 0-+99/100", 0, 99, 100, false, false}, + {"bytes 0-99/+100", 0, 99, 100, false, false}, + {"bytes -0-99/100", 0, 99, 100, false, false}, + {"bytes 0 -99/100", 0, 99, 100, false, false}, // embedded whitespace + {"bytes 0- 99/100", 0, 99, 100, false, false}, + {"bytes 0-99 /100", 0, 99, 100, false, false}, + {"bytes 0-99/ 100", 0, 99, 100, false, false}, + {"bytes 0-99/100", 0, 99, 100, false, false}, // two spaces after unit + {"bytes\t0-99/100", 0, 99, 100, false, false}, // tab is not the grammar's SP + {"byte 0-99/100", 0, 99, 100, false, false}, // wrong unit + {"bytesx 0-99/100", 0, 99, 100, false, false}, + {"items 0-99/100", 0, 99, 100, false, false}, + {"bytes 0.0-99/100", 0, 99, 100, false, false}, + {"bytes 0x0-99/100", 0, 99, 100, false, false}, + {"", 0, 99, 100, false, false}, + {" ", 0, 99, 100, false, false}, + {"bytes", 0, 99, 100, false, false}, + {"bytes ", 0, 99, 100, false, false}, + // range endpoints beyond uint64 match no expectation + {"bytes 18446744073709551616-18446744073709551617/*", 0, 99, 0, true, false}, + {"bytes 0-18446744073709551616/*", 0, 99, 0, true, false}, + {"bytes 99999999999999999999999999-99/100", 0, 99, 100, false, false}, + {"bytes */100", 0, 99, 100, false, false}, // unsatisfied form: not this matcher + {"bytes */*", 0, 99, 0, true, false}, + }; + for (size_t i = 0; i < sizeof(cases) / sizeof(cases[0]); ++i) { + const CRCase &c = cases[i]; + CAPTURE(i, c.input); + REQUIRE(HTTP::MatchesContentRange(c.input, c.first, c.last, c.expected_total, + c.allow_unknown_total) == c.ok); + } + + // Reject oversized values; accept leading zeros within the limit. + REQUIRE(!HTTP::MatchesContentRange("bytes " + std::string(300, '0') + "-99/77824", 0, 99, 77824, + false)); + REQUIRE(!HTTP::MatchesContentRange(std::string(300, ' ') + "bytes 0-99/77824", 0, 99, 77824, + false)); + REQUIRE( + HTTP::MatchesContentRange("bytes 000000000000000000000-99/077824", 0, 99, 77824, false)); +} + +TEST_CASE("ReadContentLengthHeader") { + HTTP::headers h; + h["content-length"] = "77824"; + REQUIRE(HTTP::ReadContentLengthHeader(h) == 77824); + h["content-length"] = " 42 "; + REQUIRE(HTTP::ReadContentLengthHeader(h) == 42); + h["content-length"] = "9223372036854775807"; // LLONG_MAX + REQUIRE(HTTP::ReadContentLengthHeader(h) == LLONG_MAX); + h["content-length"] = "9223372036854775808"; // LLONG_MAX + 1: unreadable + REQUIRE(HTTP::ReadContentLengthHeader(h) == -2); + h["content-length"] = "18446744073709551616"; // 2^64: overflow + REQUIRE(HTTP::ReadContentLengthHeader(h) == -2); + h["content-length"] = "+42"; // Reject signs, which strtoull accepts. + REQUIRE(HTTP::ReadContentLengthHeader(h) == -2); + h["content-length"] = "42x"; + REQUIRE(HTTP::ReadContentLengthHeader(h) == -2); + h["content-length"] = ""; + REQUIRE(HTTP::ReadContentLengthHeader(h) == -2); +} + +namespace { + +struct HeaderFeed { + HTTP::headers h; + HTTP::HeaderSink sink; + HeaderFeed() : sink(h) {} + void Feed(const char *line) { + std::string s(line); + HTTP::headerfunction(&s[0], 1, s.size(), &sink); + } + void Reset() { + h.clear(); + sink.complete = false; + } +}; + +} // namespace + +TEST_CASE("headerfunction keeps only the final response's headers") { + HeaderFeed f; + // one ordinary response + f.Feed("HTTP/1.1 206 Partial Content\r\n"); + f.Feed("Content-Range: bytes 0-99/77824\r\n"); + f.Feed("Content-Length: 100\r\n"); + f.Feed("\r\n"); + REQUIRE(f.h.size() == 2); + REQUIRE(f.h["content-range"] == "bytes 0-99/77824"); + + // an interim response's Content-Range must not leak into a final + // response that omits the header + f.Reset(); + f.Feed("HTTP/1.1 103 Early Hints\r\n"); + f.Feed("Content-Range: bytes 0-99/77824\r\n"); + f.Feed("\r\n"); + f.Feed("HTTP/1.1 206 Partial Content\r\n"); + f.Feed("Content-Length: 100\r\n"); + f.Feed("\r\n"); + REQUIRE(f.h.count("content-range") == 0); + REQUIRE(f.h["content-length"] == "100"); + + // when both responses carry the header, the final response's wins + f.Reset(); + f.Feed("HTTP/1.1 301 Moved Permanently\r\n"); + f.Feed("Content-Range: bytes 5-9/10\r\n"); + f.Feed("\r\n"); + f.Feed("HTTP/1.1 206 Partial Content\r\n"); + f.Feed("Content-Range: bytes 0-99/77824\r\n"); + f.Feed("\r\n"); + REQUIRE(f.h["content-range"] == "bytes 0-99/77824"); + + // a trailer (delivered after the header section's blank line) must + // not supply a header the final response omitted + f.Reset(); + f.Feed("HTTP/1.1 206 Partial Content\r\n"); + f.Feed("Transfer-Encoding: chunked\r\n"); + f.Feed("\r\n"); + f.Feed("Content-Range: bytes 0-99/77824\r\n"); // trailer + f.Feed("\r\n"); + REQUIRE(f.h.count("content-range") == 0); + REQUIRE(f.h["transfer-encoding"] == "chunked"); + + // nor overwrite one it carried + f.Reset(); + f.Feed("HTTP/1.1 206 Partial Content\r\n"); + f.Feed("Content-Range: bytes 5-9/10\r\n"); + f.Feed("\r\n"); + f.Feed("Content-Range: bytes 0-99/77824\r\n"); // trailer + f.Feed("\r\n"); + REQUIRE(f.h["content-range"] == "bytes 5-9/10"); +}