Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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()
80 changes: 73 additions & 7 deletions src/HTTP.h
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,10 @@
#pragma once

#include <algorithm>
#include <cctype>
#include <cerrno>
#include <cstdint>
#include <cstdlib>
#include <curl/curl.h>
#include <functional>
#include <iostream>
Expand All @@ -12,6 +16,7 @@
#include <memory>
#include <mutex>
#include <queue>
#include <regex>
#include <sstream>
#include <string>
#include <unistd.h>
Expand Down Expand Up @@ -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<headers *>(userdata);
HeaderSink &sink = *reinterpret_cast<HeaderSink *>(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++) {
Expand Down Expand Up @@ -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 };
Expand Down Expand Up @@ -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);
Expand Down
75 changes: 40 additions & 35 deletions src/web_vfs.h
Original file line number Diff line number Diff line change
Expand Up @@ -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");

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P1] reshdrs is accumulated by HTTP::headerfunction throughout one curl_easy_perform. libcurl invokes that callback for intermediate responses as well as the final one, but headerfunction does not clear the map when it sees a new HTTP status line. A final 206 without Content-Range can therefore inherit an earlier response's value and pass this check if the range and body length happen to match. Please clear response headers at each status line (or otherwise select the final response's headers) and add a redirect/intermediate-response regression test. libcurl documents this callback behavior: https://curl.se/libcurl/c/CURLOPT_HEADERFUNCTION.html

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("<absent>")
: cr_it->second))
return SQLITE_IOERR_READ;
}
}
data = body;
if (log_.level() >= 4) {
SQLITE_WEB_LOG(4, protocol << " GET " << reqhdrs["range"] << " OK ("
Expand Down Expand Up @@ -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) {
Expand All @@ -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;
}
Expand Down
Loading
Loading