Compare commits

..
18 Commits
Author SHA1 Message Date
yhirose 1f59c57662 Release v0.70.0 2026-12-05 11:50:35 -06:00
yhirose d81a932f2a Bound what one stream read inflates when there is no payload limit
With a zero payload limit, StreamHandle::read_with_decompression() held
everything a compressed read inflated to in memory with no bound, and
SSEClient always reads its stream with a zero limit. Keep a single read
within the default payload limit, while the stream as a whole stays
unbounded.
2026-12-05 11:28:46 -06:00
Leng Niuandyhirose 5fd66e46df Compare the redirect host case-insensitively (#2708)
* Compare the redirect host case-insensitively

* Test a Unix socket redirect to LOCALHOST

---------

Co-authored-by: yhirose <yuji.hirose.bug@gmail.com>
2026-12-04 22:04:17 -05:00
Perfloop Agent c438858d92 Leave ranged set_content responses uncompressed (#2709)
A set_content() response to a request with Range plus Accept-Encoding was
sliced before compression, leaving Content-Range describing uncompressed
bytes. Serve ranged 206 responses from the identity representation, as
static files already are, by deciding no content coding for a partial
response.

Close #2709
2026-12-04 21:58:00 -05:00
yhirose 6c2324ee59 Track gzip member boundaries with a single state
Replace the three flags in gzip_decompressor with one State enum, so
combinations that cannot happen can no longer be written, and start
the next member as soon as both ID bytes have been seen. No behavior
change.
2026-12-04 21:51:47 -05:00
Faris Basha TM da4a0a6f33 Decode every member of a gzip body (#2710)
RFC 1952 2.2: a gzip body is a series of members. gzip_decompressor
stopped at the end of the first one and ignored the rest, so a body
made of several members came back cut short with no error.

After a member ends, bytes that start with ID1 ID2 begin the next
member; anything else is still ignored, as before.
2026-12-04 21:41:17 -05:00
Leng Niuandyhirose 4e6226d7af Match an If-Range date exactly against Last-Modified (#2707)
* Match an If-Range date exactly against Last-Modified

* Shorten the If-Range date comments

---------

Co-authored-by: yhirose <yuji.hirose.bug@gmail.com>
2026-12-03 14:28:25 -05:00
3091751b5d Add chunked_decoder_fuzzer and a seed corpus for multipart_parser_fuzzer (#2706)
* Add chunked_decoder_fuzzer and a seed corpus for multipart_parser_fuzzer

* Apply clang-format to chunked_decoder_fuzzer.cc

* Simplify chunked_decoder_fuzzer and tidy the seed corpora

read_content_chunked() only touches the trailers and headers, which
Request and Response share, so decoding into both ran the same code.
Decode into a Response only. Drop the SIZE_MAX limit as well: fuzz
inputs never get near the 100MB default, so both take the same branches.
Adjust the first byte of the chunked seeds to the new selector, and
remove the seed for SIZE_MAX.

Drop the duplicated number prefixes from the multipart seed names, run
both new corpora from the "all" target, and keep the fuzzer rules in
the order of FUZZERS.

---------

Co-authored-by: Sai Viswas Basetti <saiviswasbasettitw@gmail.com>
Co-authored-by: yhirose <yuji.hirose.bug@gmail.com>
2026-12-02 00:22:05 -05:00
doctor-claw a4697bd29d Use 64-bit stat in FileStat on Windows (#2705)
FileStat used struct _stat and _wstat on Windows, whose st_size is 32-bit, so _wstat failed with EOVERFLOW for a file of 2 GiB or more. is_file() then returned false, and set_mount_point served 404 for a file that exists; size() and mtime() had the same limit. struct _stat64 and _wstat64 have a 64-bit st_size.
2026-12-02 00:21:45 -05:00
Leng Niuandyhirose 852a66bcec Accept a language tag in a multipart filename* parameter (#2704)
* Accept a language tag in a multipart filename* parameter

RFC 8187 writes an ext-value as charset'[language]'value-chars. The parser
only took the "UTF-8''" form, so filename*=UTF-8'en'%41.txt made the whole
multipart body invalid and the request got 400. Skip the language tag and
decode the value as before.

* Shorten the comments and close the connection in the new test

Without Connection: close the server kept the connection open, so the
test waited for the 1-second read timeout of send_request().

---------

Co-authored-by: yhirose <yuji.hirose.bug@gmail.com>
2026-12-02 00:21:30 -05:00
yhirose 012a9871b1 Allow longer response header fields than request header fields
The client read response header fields under CPPHTTPLIB_HEADER_MAX_LENGTH
(8192), the limit meant for requests a server accepts. Real servers now
send longer fields: www.youtube.com returns a 13KB
connection-allowlist-report-only field, so every request to it failed
with Error::Read.

Read response headers under a separate CPPHTTPLIB_RESPONSE_HEADER_MAX_LENGTH,
32768 by default, and keep the request limit as it is.
2026-12-01 23:41:33 -05:00
Leng Niu a95f17cffa Skip unsatisfiable ranges instead of rejecting the whole Range set (#2703)
RFC 9110 14.1.1: a byte-range-set is satisfiable when any of its ranges is,
and 15.5.17 keeps 416 for when none of them are. range_error() answered 416
as soon as one range started past the end of the body. Leave such ranges
out and serve the rest.
2026-11-30 15:41:19 -05:00
yhirose 22a57ffeba Release v0.69.0 2026-11-29 10:32:58 -05:00
yhirose 30d5f21b43 Require Mbed TLS built with MBEDTLS_THREADING_C
SSLServer runs TLS handshakes on several pool threads, and SSLClients
may be used from several threads. Mbed TLS is thread-safe only when it
is built with MBEDTLS_THREADING_C, which its default configuration
leaves off. Without it, concurrent handshakes race on the PSA key store
and the shared CTR-DRBG and corrupt memory.

Stop the build with an #error when the option is missing, and document
the requirement in the README. Define CPPHTTPLIB_MBEDTLS_SINGLE_THREADED
to build anyway when Mbed TLS is only ever used from one thread.
Distribution packages (Debian, Ubuntu, Homebrew) already enable the
option, so builds against them are unaffected.
2026-11-29 10:14:56 -05:00
yhirose c76e1b6a98 Accept several spaces after the auth scheme
RFC 9110 allows 1*SP between the auth scheme and what follows it in both
challenges and credentials. parse_www_authenticate() took the scheme up
to the last whitespace before "=", so "Digest  realm=..." was not
recognized as Digest and the 401 was returned without a retry, and
get_bearer_token_auth() returned the token of "Bearer  abc" with a
leading space.

The scheme is now the text up to the first whitespace, with the key
after it trimmed, and get_bearer_token_auth() skips the extra spaces.
2026-11-28 20:47:13 -05:00
yhirose e22f398cf2 Prefer Digest qop=auth and skip challenges without a usable qop
When a server offered both qop=auth and qop=auth-int, the client chose
auth-int, which hashes req.body. That is empty when a content provider
streams the body, so the response was wrong and the request failed. A
challenge whose qop offered neither option (e.g. only auth-conf) was
answered without qop, although RFC 7616 makes qop mandatory and has the
client use the first challenge it supports.

select_digest_qop() now picks auth over auth-int, as curl does, and
parse_www_authenticate() treats a challenge whose qop offers neither as
unanswerable, so a later challenge is used or the 401 is returned. A
challenge without qop is still answered in the RFC 2069 form.
2026-11-28 20:38:11 -05:00
yhirose c5faf03dfe Match Digest algorithm and qop values case-insensitively
The Digest client compared the algorithm and qop values of a challenge
case-sensitively, so algorithm=sha-256 was answered with an MD5 hash and
qop="AUTH" without qop. A challenge whose algorithm it doesn't implement
(SHA-512-256, the -sess variants, or a value that isn't a token) was
answered with an MD5 hash under the server's algorithm name, and only the
first Digest challenge was ever looked at.

- Match algorithm and qop options case-insensitively. qop is split into
  tokens instead of searched as a substring, and sent as auth/auth-int.
- Collect params per Digest challenge and use the first one the client
  can answer (RFC 7616 Sections 3.3 and 3.7): realm and nonce present and
  an algorithm it implements. If there is none, the 401 is returned
  without a retry.
- digest_hash() is the single list of supported algorithms, used by both
  parse_www_authenticate() and make_digest_authentication_header(). The
  algorithm is sent back as the server wrote it (RFC 7616 Section 3.4).
  parse_www_authenticate() moves into the SSL block, next to the hash
  functions and its callers.
2026-11-28 20:30:40 -05:00
Leng Niu 58cd21449c Match Digest challenge parameter names case-insensitively (#2702) 2026-11-28 19:07:39 -05:00
41 changed files with 890 additions and 204 deletions

No files matched your search

+3
View File
@@ -70,6 +70,9 @@ cpp-httplib supports multiple TLS backends through an abstraction layer:
| Mbed TLS | `CPPHTTPLIB_MBEDTLS_SUPPORT` | `libmbedtls`, `libmbedx509`, `libmbedcrypto` | 2.x, 3.x, and 4.x supported (auto-detected); 4.x renames `libmbedcrypto` to `libtfpsacrypto` |
| wolfSSL | `CPPHTTPLIB_WOLFSSL_SUPPORT` | `libwolfssl` | 5.x supported; must build with `--enable-opensslall` |
> [!NOTE]
> **Mbed TLS threading:** Mbed TLS must be built with `MBEDTLS_THREADING_C`, because `SSLServer` handles connections on several threads and Mbed TLS is not thread-safe without it. Its default configuration leaves this option off, while distribution packages such as Debian, Ubuntu and Homebrew turn it on. Building against Mbed TLS without it stops with an `#error`. If Mbed TLS is only ever used from one thread, define `CPPHTTPLIB_MBEDTLS_SINGLE_THREADED` to build anyway.
> [!NOTE]
> **wolfSSL limitation:** `get_ca_certs()` and `get_ca_names()` only reflect CA certificates loaded via `load_ca_cert_store()` or `set_ca_cert_store()`. Certificates loaded through `set_ca_cert_path()` or system certificates (`load_system_certs`) are not enumerable.
>
+1 -1
View File
@@ -4,7 +4,7 @@ langs = ["en", "ja"]
[site]
title = "cpp-httplib"
version = "0.68.0"
version = "0.70.0"
hostname = "https://yhirose.github.io"
base_path = "/cpp-httplib"
footer_message = "© 2026 Yuji Hirose. All rights reserved."
+245 -132
View File
@@ -8,8 +8,8 @@
#ifndef CPPHTTPLIB_HTTPLIB_H
#define CPPHTTPLIB_HTTPLIB_H
#define CPPHTTPLIB_VERSION "0.68.0"
#define CPPHTTPLIB_VERSION_NUM "0x004400"
#define CPPHTTPLIB_VERSION "0.70.0"
#define CPPHTTPLIB_VERSION_NUM "0x004600"
#ifdef _WIN32
#if defined(_WIN32_WINNT) && _WIN32_WINNT < 0x0A00
@@ -127,6 +127,10 @@
#define CPPHTTPLIB_HEADER_MAX_LENGTH 8192
#endif
#ifndef CPPHTTPLIB_RESPONSE_HEADER_MAX_LENGTH
#define CPPHTTPLIB_RESPONSE_HEADER_MAX_LENGTH 32768
#endif
#ifndef CPPHTTPLIB_HEADER_MAX_COUNT
#define CPPHTTPLIB_HEADER_MAX_COUNT 100
#endif
@@ -243,6 +247,8 @@ static_assert(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH > 0,
"CPPHTTPLIB_REQUEST_URI_MAX_LENGTH must be positive");
static_assert(CPPHTTPLIB_HEADER_MAX_LENGTH > 0,
"CPPHTTPLIB_HEADER_MAX_LENGTH must be positive");
static_assert(CPPHTTPLIB_RESPONSE_HEADER_MAX_LENGTH > 0,
"CPPHTTPLIB_RESPONSE_HEADER_MAX_LENGTH must be positive");
static_assert(CPPHTTPLIB_HEADER_MAX_COUNT > 0,
"CPPHTTPLIB_HEADER_MAX_COUNT must be positive");
static_assert(CPPHTTPLIB_MAX_LINE_LENGTH > 0,
@@ -565,6 +571,13 @@ using socket_t = int;
#define CPPHTTPLIB_MBEDTLS_V3
#endif
// SSLServer (and SSLClients on several threads) use Mbed TLS concurrently.
#if !defined(MBEDTLS_THREADING_C) && \
!defined(CPPHTTPLIB_MBEDTLS_SINGLE_THREADED)
#error \
"Mbed TLS must be built with MBEDTLS_THREADING_C. Define CPPHTTPLIB_MBEDTLS_SINGLE_THREADED if it is only ever used from one thread."
#endif
#endif // CPPHTTPLIB_MBEDTLS_SUPPORT
#ifdef CPPHTTPLIB_WOLFSSL_SUPPORT
@@ -3885,7 +3898,7 @@ struct FileStat {
private:
#if defined(_WIN32)
struct _stat st_;
struct _stat64 st_;
#else
struct stat st_;
#endif
@@ -4174,6 +4187,10 @@ public:
private:
bool is_valid_ = false;
// RFC 1952 2.2: a gzip body is a series of members. After one ends, the next
// starts with ID1 ID2, and anything else is ignored.
enum class State { Inflating, MemberEnded, SawId1, Ignoring };
State state_ = State::Inflating;
z_stream strm_;
};
#endif
@@ -6451,7 +6468,7 @@ inline bool is_path_within_base(const std::string &resolved_path,
inline FileStat::FileStat(const std::string &path) {
#if defined(_WIN32)
auto wpath = u8string_to_wstring(path.c_str());
ret_ = _wstat(wpath.c_str(), &st_);
ret_ = _wstat64(wpath.c_str(), &st_);
#else
ret_ = stat(path.c_str(), &st_);
#endif
@@ -8876,6 +8893,8 @@ inline bool gzip_decompressor::decompress(const char *data, size_t data_length,
Callback callback) {
assert(is_valid_);
if (state_ == State::Ignoring) { return true; }
auto ret = Z_OK;
do {
@@ -8894,6 +8913,37 @@ inline bool gzip_decompressor::decompress(const char *data, size_t data_length,
strm_.avail_out = static_cast<uInt>(buff.size());
strm_.next_out = reinterpret_cast<Bytef *>(buff.data());
if (state_ != State::Inflating) {
static const Bytef id[] = {0x1f, 0x8b};
auto i = state_ == State::MemberEnded ? 0 : 1;
if (*strm_.next_in != id[i]) {
state_ = State::Ignoring;
return true;
}
strm_.next_in++;
strm_.avail_in--;
if (i == 0) {
state_ = State::SawId1;
continue;
}
// The ID bytes may have come split across calls, so feed them from id
inflateReset(&strm_);
auto next_in = strm_.next_in;
auto avail_in = strm_.avail_in;
strm_.next_in = const_cast<Bytef *>(id);
strm_.avail_in = sizeof(id);
ret = inflate(&strm_, Z_NO_FLUSH);
strm_.next_in = next_in;
strm_.avail_in = avail_in;
state_ = State::Inflating;
if (ret != Z_OK) {
inflateEnd(&strm_);
return false;
}
continue;
}
ret = inflate(&strm_, Z_NO_FLUSH);
assert(ret != Z_STREAM_ERROR);
@@ -8906,6 +8956,11 @@ inline bool gzip_decompressor::decompress(const char *data, size_t data_length,
if (!callback(buff.data(), buff.size() - strm_.avail_out)) {
return false;
}
if (ret == Z_STREAM_END) {
state_ = State::MemberEnded;
ret = Z_OK;
}
}
if (ret != Z_OK && ret != Z_STREAM_END) { return false; }
@@ -9217,7 +9272,8 @@ inline void erase_invalid_fields(Headers &headers) {
}
}
inline bool read_headers(Stream &strm, Headers &headers) {
inline bool read_headers(Stream &strm, Headers &headers,
size_t max_field_length) {
const auto bufsiz = 2048;
char buf[bufsiz];
stream_line_reader line_reader(strm, buf, bufsiz);
@@ -9242,7 +9298,7 @@ inline bool read_headers(Stream &strm, Headers &headers) {
#endif
}
if (line_reader.size() > CPPHTTPLIB_HEADER_MAX_LENGTH) { return false; }
if (line_reader.size() > max_field_length) { return false; }
// Check header count limit
if (header_count >= CPPHTTPLIB_HEADER_MAX_COUNT) { return false; }
@@ -9327,7 +9383,7 @@ inline bool read_response_head(Stream &strm, int &status, Headers &headers) {
if (!parse_status_line(line_reader.ptr(), version, status, reason)) {
return true;
}
return read_headers(strm, headers);
return read_headers(strm, headers, CPPHTTPLIB_RESPONSE_HEADER_MAX_LENGTH);
}
inline bool
@@ -10502,14 +10558,17 @@ public:
it = params.find("filename*");
if (it != params.end()) {
// RFC 5987: only UTF-8 encoding is allowed
// RFC 8187: UTF-8'[language]'value-chars
const auto &val = it->second;
constexpr const char utf8_prefix[] = "UTF-8''";
constexpr const char utf8_prefix[] = "UTF-8'";
constexpr size_t prefix_len = str_len(utf8_prefix);
if (val.size() > prefix_len &&
start_with_case_ignore(val, utf8_prefix)) {
const auto value_pos = start_with_case_ignore(val, utf8_prefix)
? val.find('\'', prefix_len)
: std::string::npos;
if (value_pos != std::string::npos &&
value_pos + 1 < val.size()) {
file_.filename = decode_path_component(
val.substr(prefix_len)); // override...
val.substr(value_pos + 1)); // override...
} else {
is_valid_ = false;
return false;
@@ -10987,7 +11046,7 @@ inline bool range_error(Request &req, Response &res) {
ssize_t content_len = static_cast<ssize_t>(
res.content_length_ ? res.content_length_ : res.body.size());
std::vector<std::pair<ssize_t, ssize_t>> processed_ranges;
Ranges satisfiable_ranges;
size_t overwrapping_count = 0;
// NOTE: The following Range check is based on '14.2. Range' in RFC 9110
@@ -11000,7 +11059,9 @@ inline bool range_error(Request &req, Response &res) {
return true;
}
for (auto &r : req.ranges) {
satisfiable_ranges.reserve(req.ranges.size());
for (auto r : req.ranges) {
auto &first_pos = r.first;
auto &last_pos = r.second;
@@ -11029,25 +11090,28 @@ inline bool range_error(Request &req, Response &res) {
last_pos = content_len - 1;
}
// Range must be within content length
// Skip an unsatisfiable range (RFC 9110 14.1.1)
if (!(0 <= first_pos && first_pos <= last_pos &&
last_pos <= content_len - 1)) {
return true;
continue;
}
// Request must not have more than two overlapping ranges
for (const auto &processed_range : processed_ranges) {
if (!(last_pos < processed_range.first ||
first_pos > processed_range.second)) {
for (const auto &prev : satisfiable_ranges) {
if (!(last_pos < prev.first || first_pos > prev.second)) {
overwrapping_count++;
if (overwrapping_count > 2) { return true; }
break; // Only count once per range
}
}
processed_ranges.emplace_back(first_pos, last_pos);
satisfiable_ranges.push_back(r);
}
// 416 only when no range is satisfiable (RFC 9110 15.5.17)
if (satisfiable_ranges.empty()) { return true; }
req.ranges = std::move(satisfiable_ranges);
// After validation, coalesce overlapping ranges as per RFC 9110
coalesce_ranges(req.ranges, static_cast<size_t>(content_len));
}
@@ -11224,75 +11288,6 @@ inline std::string escape_quoted_pairs(const std::string &s) {
return out;
}
// RFC 9110 Section 11.6.1 defines a challenge list as
// WWW-Authenticate = #challenge
// challenge = auth-scheme [ 1*SP ( token68 / [ #auth-param ] ) ]
// auth-param = token BWS "=" BWS ( token / quoted-string )
// so a server may offer several schemes, each with its own comma-separated
// auth-param list, in either order and either as separate field lines or
// packed into one. Splitting on every comma would break apart a challenge's
// own param list; splitting only on the first space would miss a Digest
// challenge that isn't first. Split on commas that aren't inside a
// quoted-string instead (split_unquoted), then track which scheme each
// resulting segment belongs to: a segment whose text before "=" contains
// whitespace (or that has no "=" at all) starts a new challenge named by its
// leading token.
inline bool parse_www_authenticate(const Response &res,
std::map<std::string, std::string> &auth,
bool is_proxy) {
auto auth_key = is_proxy ? "Proxy-Authenticate" : "WWW-Authenticate";
auto combined = get_combined_header_value(res.headers, auth_key);
if (combined.empty()) { return false; }
auto found_digest = false;
auto in_digest_challenge = false;
split_unquoted(
combined.data(), combined.data() + combined.size(), ',',
[&](const char *b, const char *e) {
std::string segment(b, e);
auto eq_pos = segment.find('=');
// BWS is allowed on both sides of "=", so the text naming the key (or,
// for the first segment of a challenge, "<scheme> <key>") must be
// trimmed before its boundaries are inspected.
auto key_part = trim_copy(
eq_pos == std::string::npos ? segment : segment.substr(0, eq_pos));
auto space_pos = key_part.find_last_of(" \t");
if (space_pos != std::string::npos || eq_pos == std::string::npos) {
// "<scheme>[ <key>]" starts a new challenge.
auto scheme_end =
space_pos == std::string::npos ? key_part.size() : space_pos;
// RFC 7616 Section 3.7: a server may offer more than one Digest
// challenge (e.g. SHA-256 and MD5); keep only the first so a nonce
// from one challenge is never paired with another's algorithm.
in_digest_challenge =
!found_digest &&
case_ignore::equal(key_part.substr(0, scheme_end), "Digest");
if (in_digest_challenge) { found_digest = true; }
if (space_pos == std::string::npos) {
// Bare scheme (or a token68), no auth-param on this segment.
return;
}
key_part = key_part.substr(space_pos + 1);
}
if (!in_digest_challenge) { return; }
auto val = trim_copy(segment.substr(eq_pos + 1));
auto unquoted = trim_double_quotes_copy(val);
if (unquoted.size() != val.size()) {
unquoted = unescape_quoted_pairs(unquoted);
}
auth[std::move(key_part)] = std::move(unquoted);
});
// RFC 7616 Section 3.3 requires realm and nonce on every Digest challenge;
// make_digest_authentication_header() dereferences both unconditionally, so
// a challenge missing either can't produce a usable Authorization header.
// Treat it the same as no Digest challenge at all.
return found_digest && auth.find("realm") != auth.end() &&
auth.find("nonce") != auth.end();
}
class ContentProviderAdapter {
public:
explicit ContentProviderAdapter(
@@ -11761,6 +11756,121 @@ inline bool process_client_socket_ssl(
return callback(strm);
}
using DigestHash = std::string (*)(const std::string &);
// The Digest algorithms the client implements, matched case-insensitively;
// nullptr for any other.
inline DigestHash digest_hash(const std::string &algorithm) {
if (case_ignore::equal(algorithm, "MD5")) { return detail::MD5; }
if (case_ignore::equal(algorithm, "SHA-256")) { return detail::SHA_256; }
if (case_ignore::equal(algorithm, "SHA-512")) { return detail::SHA_512; }
return nullptr;
}
// Picks auth over auth-int from the qop options a server offers, as curl does:
// auth-int hashes req.body, which is empty when a content provider streams the
// body. Empty when it offers neither.
inline std::string select_digest_qop(const std::string &options) {
std::string qop;
split(options.data(), options.data() + options.size(), ',',
[&](const char *b, const char *e) {
std::string option(b, e);
if (case_ignore::equal(option, "auth")) {
qop = "auth";
} else if (qop.empty() && case_ignore::equal(option, "auth-int")) {
qop = "auth-int";
}
});
return qop;
}
// RFC 9110 Section 11.6.1 defines a challenge list as
// WWW-Authenticate = #challenge
// challenge = auth-scheme [ 1*SP ( token68 / [ #auth-param ] ) ]
// auth-param = token BWS "=" BWS ( token / quoted-string )
// so a server may offer several schemes, each with its own comma-separated
// auth-param list, in either order and either as separate field lines or
// packed into one. Splitting on every comma would break apart a challenge's
// own param list; splitting only on the first space would miss a Digest
// challenge that isn't first. Split on commas that aren't inside a
// quoted-string instead (split_unquoted), then track which scheme each
// resulting segment belongs to: a segment whose text before "=" contains
// whitespace (or that has no "=" at all) starts a new challenge named by its
// leading token.
inline bool parse_www_authenticate(const Response &res,
std::map<std::string, std::string> &auth,
bool is_proxy) {
auto auth_key = is_proxy ? "Proxy-Authenticate" : "WWW-Authenticate";
auto combined = get_combined_header_value(res.headers, auth_key);
if (combined.empty()) { return false; }
// RFC 7616 Section 3.7: a server may offer more than one Digest challenge
// (e.g. SHA-256 and MD5), and the client uses the first one it supports.
// A challenge whose algorithm the client doesn't implement is ignored
// (Section 3.3), as is one whose qop offers neither auth nor auth-int, and
// one without realm and nonce can't be answered. Params are collected per
// challenge, so a nonce from one is never paired with another's algorithm.
auto answerable = [](const std::map<std::string, std::string> &c) {
if (c.find("realm") == c.end() || c.find("nonce") == c.end()) {
return false;
}
auto algo_it = c.find("algorithm");
if (algo_it != c.end() && !digest_hash(algo_it->second)) { return false; }
auto qop_it = c.find("qop");
return qop_it == c.end() || !select_digest_qop(qop_it->second).empty();
};
auto found = false;
auto in_digest_challenge = false;
std::map<std::string, std::string> challenge;
auto take_challenge_if_answerable = [&] {
if (!found && in_digest_challenge && answerable(challenge)) {
auth = std::move(challenge);
found = true;
}
challenge.clear();
};
split_unquoted(
combined.data(), combined.data() + combined.size(), ',',
[&](const char *b, const char *e) {
std::string segment(b, e);
auto eq_pos = segment.find('=');
// BWS is allowed on both sides of "=", so the text naming the key (or,
// for the first segment of a challenge, "<scheme> <key>") must be
// trimmed before its boundaries are inspected.
auto key_part = trim_copy(
eq_pos == std::string::npos ? segment : segment.substr(0, eq_pos));
auto space_pos = key_part.find_first_of(" \t");
if (space_pos != std::string::npos || eq_pos == std::string::npos) {
// "<scheme>[ <key>]" starts a new challenge.
take_challenge_if_answerable();
auto scheme_end =
space_pos == std::string::npos ? key_part.size() : space_pos;
in_digest_challenge =
case_ignore::equal(key_part.substr(0, scheme_end), "Digest");
if (space_pos == std::string::npos) {
// Bare scheme (or a token68), no auth-param on this segment.
return;
}
key_part = trim_copy(key_part.substr(space_pos + 1));
}
if (!in_digest_challenge) { return; }
auto val = trim_copy(segment.substr(eq_pos + 1));
auto unquoted = trim_double_quotes_copy(val);
if (unquoted.size() != val.size()) {
unquoted = unescape_quoted_pairs(unquoted);
}
// auth-param names are case-insensitive (RFC 9110 Section 11.2)
challenge[case_ignore::to_lower(key_part)] = std::move(unquoted);
});
take_challenge_if_answerable();
return found;
}
// `uri` is req's request-target in origin form, as curl sends it, also when
// the request line carries the absolute form for a proxy.
inline std::pair<std::string, std::string> make_digest_authentication_header(
@@ -11775,33 +11885,21 @@ inline std::pair<std::string, std::string> make_digest_authentication_header(
nc = ss.str();
}
std::string qop;
if (auth.find("qop") != auth.end()) {
qop = auth.at("qop");
if (qop.find("auth-int") != std::string::npos) {
qop = "auth-int";
} else if (qop.find("auth") != std::string::npos) {
qop = "auth";
} else {
qop.clear();
}
}
// Without qop, the RFC 2069 form is used.
auto qop_it = auth.find("qop");
auto qop =
qop_it == auth.end() ? std::string() : select_digest_qop(qop_it->second);
assert(qop_it == auth.end() || !qop.empty());
std::string algo = "MD5";
if (auth.find("algorithm") != auth.end()) {
// algorithm is an unquoted token (RFC 7616 §3.4). A server value that is
// not a token would otherwise be emitted verbatim and could carry commas
// or quotes that inject further auth-params into the header below.
const auto &a = auth.at("algorithm");
if (fields::is_token(a)) { algo = a; }
}
// Sent back as the server wrote it (RFC 7616 Section 3.4).
// parse_www_authenticate() accepts only one digest_hash() knows.
auto algo_it = auth.find("algorithm");
auto algo = algo_it == auth.end() ? std::string("MD5") : algo_it->second;
auto H = digest_hash(algo);
assert(H);
std::string response;
{
auto H = algo == "SHA-256" ? detail::SHA_256
: algo == "SHA-512" ? detail::SHA_512
: detail::MD5;
auto A1 = username + ":" + auth.at("realm") + ":" + password;
auto A2 = req.method + ":" + uri;
@@ -12296,15 +12394,16 @@ inline bool set_socket_opt(socket_t sock, int level, int optname, int optval) {
}
inline std::string get_bearer_token_auth(const Request &req) {
// The auth scheme is case-insensitive (RFC 9110 11.1), and a value shorter
// than the prefix carries no token.
// The auth scheme is case-insensitive (RFC 9110 11.1) and followed by 1*SP,
// and a value shorter than the prefix carries no token.
constexpr const char bearer_prefix[] = "Bearer ";
constexpr auto bearer_prefix_len = detail::str_len(bearer_prefix);
auto value = req.get_header_value("Authorization");
if (value.size() >= bearer_prefix_len &&
detail::case_ignore::equal(value.substr(0, bearer_prefix_len),
bearer_prefix)) {
return value.substr(bearer_prefix_len);
auto pos = value.find_first_not_of(' ', bearer_prefix_len);
if (pos != std::string::npos) { return value.substr(pos); }
}
return "";
}
@@ -15594,9 +15693,9 @@ inline bool Server::check_if_range(Request &req, const std::string &etag,
// Weak ETags are not valid for If-Range (RFC 9110 Section 13.1.5)
return false;
} else {
// HTTP-date comparison
// HTTP-date must exactly match Last-Modified (RFC 9110 Section 13.1.5)
auto t = detail::parse_http_date(val);
return (t != static_cast<time_t>(-1) && mtime <= t);
return (t != static_cast<time_t>(-1) && mtime == t);
}
};
@@ -16001,8 +16100,9 @@ inline void Server::apply_ranges(const Request &req, Response &res,
"multipart/byteranges; boundary=" + boundary);
}
auto type =
compress_ ? detail::encoding_type(req, res) : detail::EncodingType::None;
auto type = compress_ && !detail::is_partial_content(req, res)
? detail::encoding_type(req, res)
: detail::EncodingType::None;
if (res.body.empty()) {
if (res.content_length_ > 0 && req.ranges.size() == 1 &&
@@ -16174,7 +16274,7 @@ Server::process_request(Stream &strm, const std::string &remote_addr,
}
// Request headers
if (!detail::read_headers(strm, req.headers)) {
if (!detail::read_headers(strm, req.headers, CPPHTTPLIB_HEADER_MAX_LENGTH)) {
connection_closed = true;
res.status = StatusCode::BadRequest_400;
output_error_log(Error::InvalidHeaders, &req);
@@ -16978,7 +17078,10 @@ inline bool ClientImpl::read_response_line(Stream &strm, const Request &req,
return false;
}
Headers interim_headers;
if (!detail::read_headers(strm, interim_headers)) { return false; }
if (!detail::read_headers(strm, interim_headers,
CPPHTTPLIB_RESPONSE_HEADER_MAX_LENGTH)) {
return false;
}
if (!line_reader.getline()) { return false; } // next response line
if (!detail::parse_status_line(line_reader.ptr(), res.version, res.status,
@@ -17268,7 +17371,8 @@ inline ClientImpl::StreamHandle ClientImpl::open_stream_(Request &req) {
}
if (!read_response_line(strm, req, *handle.response) ||
!detail::read_headers(strm, handle.response->headers)) {
!detail::read_headers(strm, handle.response->headers,
CPPHTTPLIB_RESPONSE_HEADER_MAX_LENGTH)) {
handle.error = Error::Read;
handle.response.reset();
return handle;
@@ -17359,6 +17463,14 @@ inline ssize_t ClientImpl::StreamHandle::read_with_decompression(char *buf,
constexpr size_t kDecompressionBufferSize = 8192;
char compressed_buf[kDecompressionBufferSize];
auto limit = body_reader_.payload_max_length;
auto counted = decompressed_bytes_read_;
if (limit == 0) {
// The stream is unbounded, but one read holds all it inflates at once
limit = CPPHTTPLIB_PAYLOAD_MAX_LENGTH;
counted = 0;
}
while (true) {
auto n = detail::read_body_content(stream_, body_reader_, compressed_buf,
sizeof(compressed_buf));
@@ -17370,10 +17482,7 @@ inline ssize_t ClientImpl::StreamHandle::read_with_decompression(char *buf,
compressed_buf, static_cast<size_t>(n),
[&](const char *data, size_t data_len) {
decompress_buffer_.append(data, data_len);
auto limit = body_reader_.payload_max_length;
exceeded =
limit > 0 &&
decompressed_bytes_read_ + decompress_buffer_.size() > limit;
exceeded = limit > 0 && counted + decompress_buffer_.size() > limit;
return !exceeded;
});
@@ -17683,10 +17792,12 @@ inline bool ClientImpl::redirect(Request &req, Response &res, Error &error) {
auto path = std::move(next_path) + next_query;
// A Unix socket client sends "Host: localhost", so a Location naming
// localhost names this client too.
auto is_same_host = next_host == host_ ||
(address_family_ == AF_UNIX && next_host == "localhost");
// Host names are case-insensitive (RFC 3986 3.2.2). A Unix socket client
// sends "Host: localhost", so a Location naming localhost names this client
// too.
auto is_same_host = detail::case_ignore::equal(next_host, host_) ||
(address_family_ == AF_UNIX &&
detail::case_ignore::equal(next_host, "localhost"));
// Same host redirect - use current client
if (next_scheme == scheme && is_same_host && next_port == port_) {
@@ -18302,7 +18413,8 @@ inline bool ClientImpl::process_request(Stream &strm, Request &req,
// When using Expect: 100-continue, don't auto-skip `100 Continue` response
if ((!status_line_read &&
!read_response_line(strm, req, res, !expect_100_continue)) ||
!detail::read_headers(strm, res.headers)) {
!detail::read_headers(strm, res.headers,
CPPHTTPLIB_RESPONSE_HEADER_MAX_LENGTH)) {
if (write_request_success) { error = Error::Read; }
return false;
}
@@ -18319,7 +18431,8 @@ inline bool ClientImpl::process_request(Stream &strm, Request &req,
res.headers.clear();
res.body.clear();
if (!read_response_line(strm, req, res) ||
!detail::read_headers(strm, res.headers)) {
!detail::read_headers(strm, res.headers,
CPPHTTPLIB_RESPONSE_HEADER_MAX_LENGTH)) {
error = Error::Read;
return false;
}
+8 -1
View File
@@ -13,12 +13,14 @@ ZLIB_SUPPORT = -DCPPHTTPLIB_ZLIB_SUPPORT -lz
BROTLI_DIR = /usr/local/opt/brotli
# BROTLI_SUPPORT = -DCPPHTTPLIB_BROTLI_SUPPORT -I$(BROTLI_DIR)/include -L$(BROTLI_DIR)/lib -lbrotlicommon -lbrotlienc -lbrotlidec
FUZZERS = server_fuzzer url_parser_fuzzer header_parser_fuzzer client_fuzzer multipart_parser_fuzzer websocket_fuzzer sse_parser_fuzzer server_mount_fuzzer
FUZZERS = server_fuzzer url_parser_fuzzer header_parser_fuzzer client_fuzzer multipart_parser_fuzzer websocket_fuzzer sse_parser_fuzzer server_mount_fuzzer chunked_decoder_fuzzer
# Runs all the tests and also fuzz tests against seed corpus.
all : $(FUZZERS)
./server_fuzzer corpus/*
./server_mount_fuzzer corpus_mount/*
./multipart_parser_fuzzer corpus_multipart/*
./chunked_decoder_fuzzer corpus_chunked/*
# Fuzz target, so that you can choose which $(LIB_FUZZING_ENGINE) to use.
server_fuzzer : server_fuzzer.cc fuzzed_stream.h ../../httplib.h
@@ -38,6 +40,7 @@ url_parser_fuzzer : url_parser_fuzzer.cc ../../httplib.h
multipart_parser_fuzzer : multipart_parser_fuzzer.cc ../../httplib.h
$(CXX) $(CXXFLAGS) -o $@ $< $(ZLIB_SUPPORT) $(LIB_FUZZING_ENGINE) -pthread -lanl
zip -q -r multipart_parser_fuzzer_seed_corpus.zip corpus_multipart
websocket_fuzzer : websocket_fuzzer.cc ../../httplib.h
$(CXX) $(CXXFLAGS) -o $@ $< $(ZLIB_SUPPORT) $(LIB_FUZZING_ENGINE) -pthread -lanl
@@ -49,5 +52,9 @@ server_mount_fuzzer : server_mount_fuzzer.cc fuzzed_stream.h ../../httplib.h
$(CXX) $(CXXFLAGS) -o $@ $< $(ZLIB_SUPPORT) $(LIB_FUZZING_ENGINE) -pthread -lanl
zip -q -r server_mount_fuzzer_seed_corpus.zip corpus_mount
chunked_decoder_fuzzer : chunked_decoder_fuzzer.cc fuzzed_stream.h ../../httplib.h
$(CXX) $(CXXFLAGS) -o $@ $< $(ZLIB_SUPPORT) $(LIB_FUZZING_ENGINE) -pthread -lanl
zip -q -r chunked_decoder_fuzzer_seed_corpus.zip corpus_chunked
clean:
rm -f server_fuzzer pem *.0 *.o *.1 *.srl *.zip
+36
View File
@@ -0,0 +1,36 @@
#include <cstdint>
#include "fuzzed_stream.h"
namespace {
void decode(const uint8_t *data, size_t size, size_t payload_max_length) {
FuzzedStream strm(data, size);
httplib::Response res;
httplib::detail::read_content_chunked(
strm, res, payload_max_length,
[](const char *, size_t, uint64_t, uint64_t) { return true; });
}
} // namespace
// The first decode initializes function-local statics, which in a persistent
// fuzzer would otherwise show up as unstable coverage on the first input only.
extern "C" int LLVMFuzzerInitialize(int * /*argc*/, char *** /*argv*/) {
static const char warm_up[] =
"5;ext=1\r\nhello\r\n0\r\nX-Trailer: 1\r\nExpires: 0\r\n\r\n";
decode(reinterpret_cast<const uint8_t *>(warm_up), sizeof(warm_up) - 1, 0);
return 0;
}
extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
if (size < 2) { return 0; }
// The first byte selects the payload limit, 0 meaning none
static const size_t max_lens[] = {0, 1, 16, 4096,
CPPHTTPLIB_PAYLOAD_MAX_LENGTH};
auto n = sizeof(max_lens) / sizeof(max_lens[0]);
decode(data + 1, size - 1, max_lens[data[0] % n]);
return 0;
}
+9
View File
@@ -0,0 +1,9 @@
crlf="\x0d\x0a"
last_chunk="0\x0d\x0a\x0d\x0a"
ext=";"
ext_kv=";name=value"
ext_quoted=";name=\"a;b\""
hex_max="ffffffffffffffff"
hex_over="10000000000000000"
trailer="X-Trailer: 1\x0d\x0a"
expires="Expires: 0\x0d\x0a"
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,4 @@
10
0123456789abcdef
0
@@ -0,0 +1,6 @@
10
0123456789abcdef
1
X
0
@@ -0,0 +1,4 @@
5
hello
0
@@ -0,0 +1,4 @@
5
hello
0
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,5 @@
1234567890123456--1234567890123456
Content-Disposition: form-data; name="f"
v
--1234567890123456--
Binary file not shown.
@@ -0,0 +1,5 @@
BOUND--BOUND
Content-Disposition: form-data; name="a"
text contains --BOUND here
--BOUND--
@@ -0,0 +1,13 @@
XYZ123--XYZ123
Content-Disposition: form-data; name="t"
--XYZ123 not after CRLF
--XYZ12
-XYZ123
--xyz123
--XYZ_123␍ tail
--XYZ123--
@@ -0,0 +1,13 @@
cdBad--cdBad
Content-Disposition: form-data; filename="noname.txt"
missing name
--cdBad
Content-Disposition: form-data; name="x"; filename*=ISO-8859-1''abc
bad charset
--cdBad
Bad Header Without Colon
z
--cdBad--
@@ -0,0 +1,22 @@
cdVar--cdVar
content-disposition:FORM-DATA;name=bare
1
--cdVar
Content-Disposition: form-data; name="semi;colon"; filename="a\"b.txt"
2
--cdVar
Content-Disposition: form-data; name="u"; filename="x.txt"; filename*=UTF-8''%E2%82%AC%20rates.txt
3
--cdVar
Content-Disposition: form-data; name="dup"; name="dup"; name="other"
4
--cdVar
Content-Disposition: attachment; name="ignored"
CONTENT-TYPE: text/html
5
--cdVar--
+11
View File
@@ -0,0 +1,11 @@
empty--empty
--empty
Content-Disposition: form-data; name="e"
--empty
--empty--
@@ -0,0 +1,6 @@
BOUND--BOUND
Content-Disposition: form-data; name="a"
X-Custom: test
val
--BOUND--
Binary file not shown.
@@ -0,0 +1,9 @@
pad--pad
Content-Disposition: form-data; name="a"
ok
--pad
Content-Disposition: form-data; name="b"
x
--pad--
@@ -0,0 +1,6 @@
BOUND
--BOUND
Content-Disposition: form-data; name="a"
val
--BOUND--
@@ -0,0 +1,9 @@
unclosed--unclosed
Content-Disposition: form-data; name="a"
first
--unclosed
Content-Disposition: form-data; name="b"
truncated content with no final delimiter
--unclo
@@ -0,0 +1,5 @@
BOUND--BOUND
Content-Disposition: form-data; name="a"
val
--BOUND--
@@ -0,0 +1,4 @@
nocrlf--nocrlfContent-Disposition: form-data; name="x"
data
--nocrlf--
@@ -0,0 +1,4 @@
hdrEnd--hdrEnd
Content-Disposition: form-data; name="h"
Content-Type: text/plain
content right after headers--hdrEnd--
@@ -0,0 +1,9 @@
BOUND--BOUND
Content-Disposition: form-data; name="a"
1
--BOUND
Content-Disposition: form-data; name="b"
2
--BOUND--
@@ -0,0 +1,5 @@
BOUND--BOUND
Content-Type: text/plain
orphaned data
--BOUND--
@@ -0,0 +1,15 @@
sev3ral--sev3ral
Content-Disposition: form-data; name="a"
alpha
--sev3ral
Content-Disposition: form-data; name="b"
bravo
second line
--sev3ral
Content-Disposition: form-data; name="c"
Content-Type: application/json
{"k":[1,2,3]}
--sev3ral--
@@ -0,0 +1,5 @@
AaB03x--AaB03x
Content-Disposition: form-data; name="field1"
value1
--AaB03x--
@@ -0,0 +1,5 @@
BOUND--BOUND
Content-Disposition: form-data; name="user"
Alice
--BOUND--
@@ -0,0 +1,5 @@
BOUND--BOUND
Content-Disposition : form-data ; name = "a"
val
--BOUND--
+414 -70
View File
@@ -347,6 +347,9 @@ TEST_F(UnixSocketTest, RedirectStaysOnSocket) {
// An absolute Location naming the Host this client sends
res.set_redirect("http://localhost" + pattern_);
});
svr.Get("/upper", [&](const httplib::Request &, httplib::Response &res) {
res.set_redirect("http://LOCALHOST" + pattern_);
});
svr.Get("/cross", [&](const httplib::Request &, httplib::Response &res) {
res.set_redirect("http://" + other_path + pattern_);
});
@@ -399,6 +402,13 @@ TEST_F(UnixSocketTest, RedirectStaysOnSocket) {
EXPECT_EQ(content_, res->body);
EXPECT_EQ("Bearer token", res->get_header_value("X-Auth"));
// in any case
res = cli.Get("/upper");
ASSERT_TRUE(res) << "error: " << res.error();
EXPECT_EQ(StatusCode::OK_200, res->status);
EXPECT_EQ(content_, res->body);
EXPECT_EQ("Bearer token", res->get_header_value("X-Auth"));
// A host the caller mapped to a socket goes there
cli.set_direct_hostname_addr_map({{"mapped.test", other_path}});
res = cli.Get("/mapped");
@@ -2340,7 +2350,8 @@ TEST(BearerTokenAuthTest, SchemeValidation) {
{"x", ""},
{"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", ""},
{"Bearer abc123", "abc123"},
{"bearer abc123", "abc123"}, // scheme match is case-insensitive
{"bearer abc123", "abc123"}, // scheme match is case-insensitive
{"Bearer abc123", "abc123"}, // 1*SP after the scheme
};
for (const auto &c : cases) {
@@ -3963,17 +3974,13 @@ TEST(DigestAuthTest, FromHTTPWatch_Online) {
}
}
// RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
// comma-separated list of challenges, and each challenge may itself carry a
// comma-separated auth-param list, so a server can legally offer Basic
// before Digest, either as two field lines or packed into one. Runs one 401
// -> Digest-retry round trip with the given field lines (get_combined_header_
// value() joins them in receipt order) and checks that the retry carries a
// well-formed Digest Authorization header naming expected_realm.
static void
run_digest_challenge_list_test(const std::vector<std::string> &challenges,
const std::string &expected_realm) {
// Runs one 401 -> Digest-retry round trip with the given WWW-Authenticate
// field lines (get_combined_header_value() joins them in receipt order) and
// returns the Authorization header of the retry.
static std::string
get_digest_retry_authorization(const std::vector<std::string> &challenges) {
std::atomic<int> hits{0};
std::string authorization;
Server svr;
svr.Get("/x", [&](const Request &req, Response &res) {
@@ -3983,11 +3990,7 @@ run_digest_challenge_list_test(const std::vector<std::string> &challenges,
res.set_header("WWW-Authenticate", challenge);
}
} else {
auto authorization = req.get_header_value("Authorization");
EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
EXPECT_NE(std::string::npos,
authorization.find("realm=\"" + expected_realm + "\""));
EXPECT_EQ(std::string::npos, authorization.find("Basic"));
authorization = req.get_header_value("Authorization");
res.set_content("ok", "text/plain");
}
});
@@ -4003,9 +4006,25 @@ run_digest_challenge_list_test(const std::vector<std::string> &challenges,
Client cli(HOST, port);
cli.set_digest_auth("hello", "world");
auto res = cli.Get("/x");
ASSERT_TRUE(res) << "Error: " << to_string(res.error());
EXPECT_TRUE(res) << "Error: " << to_string(res.error());
EXPECT_EQ(2, hits.load());
return authorization;
}
// RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
// comma-separated list of challenges, and each challenge may itself carry a
// comma-separated auth-param list, so a server can legally offer Basic
// before Digest, either as two field lines or packed into one. Checks that
// the retry carries a well-formed Digest Authorization header naming
// expected_realm.
static void
run_digest_challenge_list_test(const std::vector<std::string> &challenges,
const std::string &expected_realm) {
auto authorization = get_digest_retry_authorization(challenges);
EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
EXPECT_NE(std::string::npos,
authorization.find("realm=\"" + expected_realm + "\""));
EXPECT_EQ(std::string::npos, authorization.find("Basic"));
}
static const char *kBasicChallenge = "Basic realm=\"decoy\"";
@@ -4034,6 +4053,70 @@ TEST(DigestAuthTest, RealmContainingCommaIsNotSplit) {
"test,realm");
}
// RFC 9110 11.6.1: 1*SP separates the scheme from its first auth-param.
TEST(DigestAuthTest, SeveralSpacesAfterScheme) {
auto authorization =
get_digest_retry_authorization({"Digest realm=\"r\", nonce=\"n\""});
EXPECT_NE(std::string::npos, authorization.find("nonce=\"n\""));
}
// RFC 9110 11.2: auth-param names are matched case-insensitively.
TEST(DigestAuthTest, ParamNamesAreCaseInsensitive) {
auto authorization = get_digest_retry_authorization(
{"Digest Realm=\"testrealm\", QOP=\"auth\", Nonce=\"abc123\", "
"Algorithm=SHA-256, OPAQUE=\"op\""});
EXPECT_NE(std::string::npos, authorization.find("realm=\"testrealm\""));
EXPECT_NE(std::string::npos, authorization.find("nonce=\"abc123\""));
EXPECT_NE(std::string::npos, authorization.find("algorithm=SHA-256"));
EXPECT_NE(std::string::npos, authorization.find("qop=auth"));
EXPECT_NE(std::string::npos, authorization.find("opaque=\"op\""));
}
// The algorithm is matched case-insensitively and sent back as the server
// wrote it (RFC 7616 3.4).
TEST(DigestAuthTest, AlgorithmValueIsCaseInsensitive) {
auto authorization = get_digest_retry_authorization(
{"Digest realm=\"r\", nonce=\"n\", qop=\"auth\", algorithm=sha-256"});
EXPECT_NE(std::string::npos, authorization.find("algorithm=sha-256"));
const std::string prefix = "response=\"";
auto b = authorization.find(prefix);
ASSERT_NE(std::string::npos, b);
b += prefix.size();
EXPECT_EQ(64u, authorization.find('"', b) - b); // SHA-256, not MD5
}
// qop options are matched case-insensitively.
TEST(DigestAuthTest, QopValueIsCaseInsensitive) {
auto authorization = get_digest_retry_authorization(
{"Digest realm=\"r\", nonce=\"n\", qop=\"AUTH\""});
EXPECT_NE(std::string::npos, authorization.find("qop=auth,"));
}
// auth-int hashes req.body, which is empty when a content provider streams the
// body, so it is chosen only when the server offers no auth.
TEST(DigestAuthTest, PrefersQopAuthOverAuthInt) {
auto authorization = get_digest_retry_authorization(
{"Digest realm=\"r\", nonce=\"n\", qop=\"auth-int, auth\""});
EXPECT_NE(std::string::npos, authorization.find("qop=auth,"));
authorization = get_digest_retry_authorization(
{"Digest realm=\"r\", nonce=\"n\", qop=\"Auth-Int\""});
EXPECT_NE(std::string::npos, authorization.find("qop=auth-int,"));
}
// RFC 7616 3.7: the client uses the first Digest challenge it can answer.
TEST(DigestAuthTest, SkipsUnanswerableDigestChallenges) {
auto authorization = get_digest_retry_authorization(
{"Digest realm=\"r\", nonce=\"n1\", algorithm=SHA-512-256, "
"Digest realm=\"r\", nonce=\"n2\", algorithm=SHA-256"});
EXPECT_NE(std::string::npos, authorization.find("nonce=\"n2\""));
EXPECT_NE(std::string::npos, authorization.find("algorithm=SHA-256"));
authorization = get_digest_retry_authorization(
{"Digest realm=\"r\", qop=\"auth\", Digest realm=\"r\", nonce=\"n2\""});
EXPECT_NE(std::string::npos, authorization.find("nonce=\"n2\""));
}
// RFC 7616 3.4: uri is the request-target as sent, which is encoded, carries
// the params and leaves out the fragment.
TEST(DigestAuthTest, UriIsTheRequestTargetSent) {
@@ -4068,13 +4151,16 @@ TEST(DigestAuthTest, UriIsTheRequestTargetSent) {
EXPECT_EQ(target, uri);
}
// RFC 7616 Section 3.3 requires realm and nonce on every Digest challenge.
// make_digest_authentication_header() dereferences both unconditionally, so
// a server sending a challenge missing either one must not be treated as
// usable -- doing so used to crash the client with std::out_of_range.
static void run_digest_challenge_missing_field_test(const char *challenge) {
// A Digest challenge the client can't answer (realm or nonce missing, or no
// algorithm or qop option it implements) must leave the 401 as it is, without
// a retry.
static void
run_unanswerable_digest_challenge_test(const std::string &challenge) {
std::atomic<int> hits{0};
Server svr;
svr.Get("/x", [&](const Request & /*req*/, Response &res) {
++hits;
res.status = StatusCode::Unauthorized_401;
res.set_header("WWW-Authenticate", challenge);
});
@@ -4092,65 +4178,56 @@ static void run_digest_challenge_missing_field_test(const char *challenge) {
auto res = cli.Get("/x");
ASSERT_TRUE(res) << "Error: " << to_string(res.error());
EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
EXPECT_EQ(1, hits.load());
}
TEST(DigestAuthTest, ChallengeMissingRealmAndNonceDoesNotCrash) {
run_digest_challenge_missing_field_test("Digest qop=\"auth\"");
run_unanswerable_digest_challenge_test("Digest qop=\"auth\"");
}
TEST(DigestAuthTest, ChallengeMissingNonceDoesNotCrash) {
run_digest_challenge_missing_field_test("Digest realm=\"r\", qop=\"auth\"");
run_unanswerable_digest_challenge_test("Digest realm=\"r\", qop=\"auth\"");
}
TEST(DigestAuthTest, ChallengeMissingRealmDoesNotCrash) {
run_digest_challenge_missing_field_test("Digest nonce=\"n\", qop=\"auth\"");
run_unanswerable_digest_challenge_test("Digest nonce=\"n\", qop=\"auth\"");
}
// A hostile server can put a '"' in realm/nonce/opaque, or a non-token
// algorithm, in its challenge. parse_www_authenticate() de-escapes quoted-pairs
// when storing the values, so the header builder has to re-escape them (and
// keep algorithm a bare token); otherwise the value breaks out of its
// quoted-string and injects extra auth-params into the client's Authorization.
// RFC 7616 3.3: a challenge with an algorithm the client doesn't implement is
// ignored. The last value isn't a token and would otherwise inject auth-params
// into the Authorization header.
TEST(DigestAuthTest, UnsupportedAlgorithmIsIgnored) {
for (auto algorithm :
{"SHA-512-256", "MD5-sess", "\"MD5, injected=\\\"y\\\"\""}) {
SCOPED_TRACE(algorithm);
run_unanswerable_digest_challenge_test(
std::string("Digest realm=\"r\", nonce=\"n\", qop=\"auth\", "
"algorithm=") +
algorithm);
}
}
// RFC 7616 3.3: qop options the client doesn't implement are ignored, and a
// challenge that offers no other can't be answered.
TEST(DigestAuthTest, UnsupportedQopIsIgnored) {
run_unanswerable_digest_challenge_test(
"Digest realm=\"r\", nonce=\"n\", qop=\"auth-conf\"");
}
// A hostile server can put a '"' in realm/nonce/opaque in its challenge.
// parse_www_authenticate() de-escapes quoted-pairs when storing the values, so
// the header builder has to re-escape them; otherwise the value breaks out of
// its quoted-string and injects extra auth-params into the Authorization.
TEST(DigestAuthTest, EscapesInjectedAuthParams) {
std::atomic<int> hits{0};
std::string authorization;
Server svr;
svr.Get("/x", [&](const Request &req, Response &res) {
if (++hits == 1) {
res.status = StatusCode::Unauthorized_401;
// On the wire the quotes embedded in the values are backslash-escaped.
res.set_header("WWW-Authenticate",
"Digest realm=\"testrealm\", "
"nonce=\"n\\\"; injected=\\\"x\", "
"algorithm=\"MD5, injected2=\\\"y\\\"\", qop=\"auth\"");
} else {
authorization = req.get_header_value("Authorization");
res.set_content("ok", "text/plain");
}
});
auto port = svr.bind_to_any_port(HOST);
std::thread t([&]() { svr.listen_after_bind(); });
auto se = detail::scope_exit([&] {
svr.stop();
t.join();
});
svr.wait_until_ready();
Client cli(HOST, port);
cli.set_digest_auth("hello", "world");
auto res = cli.Get("/x");
ASSERT_TRUE(res) << "Error: " << to_string(res.error());
EXPECT_EQ(2, hits.load());
// On the wire the quotes embedded in the value are backslash-escaped.
auto authorization = get_digest_retry_authorization(
{"Digest realm=\"testrealm\", nonce=\"n\\\"; injected=\\\"x\", "
"qop=\"auth\""});
EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
// The nonce (de-escaped to n"; injected="x ) must be re-escaped so it stays
// inside its quoted-string rather than starting an "injected" auth-param.
EXPECT_NE(std::string::npos,
authorization.find("nonce=\"n\\\"; injected=\\\"x\""));
// A non-token algorithm falls back to a bare MD5 token, dropping the payload.
EXPECT_EQ(std::string::npos, authorization.find("injected2"));
}
#endif
@@ -4677,6 +4754,45 @@ TEST(RedirectToSamePort, ForwardCookie) {
EXPECT_EQ("session_id=SECRET", captured_cookie);
}
TEST(RedirectToSamePort, HostNameIsCaseInsensitive) {
// "LOCALHOST" names the same host as "localhost" (RFC 3986 3.2.2), so the
// redirect stays on this origin and keeps its credentials and cookies.
Server svr;
std::string captured_authorization;
std::string captured_cookie;
int port = 0;
svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
res.set_redirect("http://LOCALHOST:" + std::to_string(port) + "/target",
302);
});
svr.Get("/target", [&](const Request &req, Response &res) {
captured_authorization = req.get_header_value("Authorization");
captured_cookie = req.get_header_value("Cookie");
res.set_content("OK", "text/plain");
});
port = svr.bind_to_any_port(HOST);
auto thread = std::thread([&]() { svr.listen_after_bind(); });
auto se = detail::scope_exit([&] {
svr.stop();
thread.join();
ASSERT_FALSE(svr.is_running());
});
svr.wait_until_ready();
Client cli(HOST, port);
cli.set_follow_location(true);
cli.set_basic_auth("admin", "secret");
Headers headers = {{"Cookie", "session_id=SECRET"}};
auto res = cli.Get("/redir", headers);
ASSERT_TRUE(res) << "Error: " << to_string(res.error());
EXPECT_EQ(StatusCode::OK_200, res->status);
EXPECT_EQ("Basic YWRtaW46c2VjcmV0", captured_authorization);
EXPECT_EQ("session_id=SECRET", captured_cookie);
}
TEST(RedirectTest, DoNotCarryRequestParamsToLocation) {
// The Location alone names the next target, on any origin.
Server target_svr;
@@ -9325,6 +9441,20 @@ TEST_F(ServerTest, GetWithRange5) {
EXPECT_EQ(std::string("abcdef"), res->body);
}
#ifdef CPPHTTPLIB_ZLIB_SUPPORT
TEST_F(ServerTest, GetWithRangeAcceptEncoding) {
cli_.set_decompress(false);
auto res = cli_.Get("/with-range", Headers{{"Range", "bytes=1-3"},
{"Accept-Encoding", "gzip"}});
ASSERT_TRUE(res) << "Error: " << to_string(res.error());
EXPECT_EQ(StatusCode::PartialContent_206, res->status);
EXPECT_EQ("bytes 1-3/7", res->get_header_value("Content-Range"));
EXPECT_EQ("3", res->get_header_value("Content-Length"));
EXPECT_EQ("bcd", res->body);
EXPECT_FALSE(res->has_header("Content-Encoding"));
}
#endif
TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
auto res =
cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
@@ -9343,10 +9473,47 @@ TEST_F(ServerTest, GetWithRangeMultipart) {
}
TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
// RFC 9110 14.1.1: the set is satisfiable when any of its ranges is, and the
// unsatisfiable ones are left out of the response.
auto res = cli_.Get("/with-range",
Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
Headers{make_range_header({{-1, 2}, {10000, 30000}}),
{"Accept-Encoding", ""}});
ASSERT_TRUE(res) << "Error: " << to_string(res.error());
EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
EXPECT_EQ(StatusCode::PartialContent_206, res->status);
EXPECT_EQ("2", res->get_header_value("Content-Length"));
EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
EXPECT_EQ(std::string("fg"), res->body);
}
TEST_F(ServerTest, GetWithRangeMultipartSkipsUnsatisfiableRange) {
auto res =
cli_.Get("/with-range",
Headers{{make_range_header({{1, 2}, {10000, 30000}, {4, 5}})}});
ASSERT_TRUE(res) << "Error: " << to_string(res.error());
EXPECT_EQ(StatusCode::PartialContent_206, res->status);
EXPECT_EQ("267", res->get_header_value("Content-Length"));
EXPECT_EQ(false, res->has_header("Content-Range"));
EXPECT_EQ(267U, res->body.size());
EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
}
TEST_F(ServerTest, GetWithRangeMultipartNoneSatisfiable) {
for (auto range : {"bytes=7-, -0", "bytes=10000-30000, 7-8"}) {
auto res = cli_.Get("/with-range", Headers{{"Range", range}});
ASSERT_TRUE(res) << "Error: " << to_string(res.error());
EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status) << range;
}
}
TEST_F(ServerTest, GetStreamedWithRangeSkipsUnsatisfiableRange) {
auto res =
cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=7-, 2-3"}});
ASSERT_TRUE(res) << "Error: " << to_string(res.error());
EXPECT_EQ(StatusCode::PartialContent_206, res->status);
EXPECT_EQ("2", res->get_header_value("Content-Length"));
EXPECT_EQ("bytes 2-3/7", res->get_header_value("Content-Range"));
EXPECT_EQ(std::string("cd"), res->body);
}
TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
@@ -9892,6 +10059,50 @@ TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
ASSERT_EQ(original_text, decompressed_data);
}
TEST(GzipDecompressor, MultipleMembers) {
auto gzip = [](const std::string &data) {
std::string out;
httplib::detail::gzip_compressor compressor;
compressor.compress(data.data(), data.size(), /*last=*/true,
[&](const char *chunk, size_t n) {
out.append(chunk, n);
return true;
});
return out;
};
// Decompresses `data` handed over in two calls, the first `split` bytes long
auto decompress = [](const std::string &data, size_t split,
std::string &out) {
httplib::detail::gzip_decompressor decompressor;
auto callback = [&](const char *chunk, size_t n) {
out.append(chunk, n);
return true;
};
return decompressor.decompress(data.data(), split, callback) &&
decompressor.decompress(data.data() + split, data.size() - split,
callback);
};
// RFC 1952 2.2: a gzip body is a series of members, an empty one included.
// Bytes after the last member that start no other one are still ignored.
const auto members = gzip("Hello, ") + gzip("") + gzip("World!");
for (const auto &body : {members, members + std::string(8, '\0')}) {
for (size_t split = 0; split <= body.size(); split++) {
std::string out;
ASSERT_TRUE(decompress(body, split, out)) << "split at " << split;
EXPECT_EQ("Hello, World!", out) << "split at " << split;
}
}
// A broken later member fails like a broken first one
auto broken = gzip("Hello, ") + gzip("World!");
auto crc_pos = broken.size() - 8;
broken[crc_pos] = static_cast<char>(broken[crc_pos] ^ 0x01);
std::string out;
EXPECT_FALSE(decompress(broken, broken.size(), out));
}
#endif
#ifdef CPPHTTPLIB_BROTLI_SUPPORT
@@ -16767,6 +16978,43 @@ TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
}
#endif
#ifdef CPPHTTPLIB_BROTLI_SUPPORT
// A zero limit leaves a stream unbounded, but a body of a few bytes must not
// inflate past the default limit in a single read
TEST(ClientVulnerabilityTest, BrotliBombInStreamWithoutPayloadLimit) {
std::string bomb(1024, '\0');
{
std::string body(CPPHTTPLIB_PAYLOAD_MAX_LENGTH + 1024 * 1024, 'A');
auto size = bomb.size();
ASSERT_TRUE(BrotliEncoderCompress(
5, BROTLI_DEFAULT_WINDOW, BROTLI_MODE_GENERIC, body.size(),
reinterpret_cast<const uint8_t *>(body.data()), &size,
reinterpret_cast<uint8_t *>(&bomb[0])));
bomb.resize(size);
}
Server svr;
svr.Get("/", [&](const Request &, Response &res) {
res.set_header("Content-Encoding", "br");
res.set_content(bomb, "text/plain");
});
auto port = svr.bind_to_any_port(HOST);
std::thread t([&] { svr.listen_after_bind(); });
auto se = detail::scope_exit([&] {
svr.stop();
t.join();
});
svr.wait_until_ready();
Client cli(HOST, port);
cli.set_payload_max_length(0);
auto result = stream::Get(cli, "/");
ASSERT_TRUE(result.is_valid());
while (result.next()) {}
EXPECT_EQ(Error::ExceedMaxPayloadSize, result.read_error());
}
#endif
TEST(HostAndPortPropertiesTest, NoSSL) {
httplib::Client cli("www.google.com", 1234);
ASSERT_EQ("www.google.com", cli.host());
@@ -20340,6 +20588,50 @@ TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
ASSERT_TRUE(send_request(1, req));
}
TEST(MultipartFormDataTest, AlternateFilenameWithLanguageTag) {
auto handled = false;
Server svr;
svr.Post("/test", [&](const Request &req, Response &res) {
ASSERT_EQ("A.txt", req.form.get_file("file1").filename);
ASSERT_EQ("na\xC3\xAFve.txt", req.form.get_file("file2").filename);
res.set_content("ok", "text/plain");
handled = true;
});
thread t = thread([&] { svr.listen(HOST, PORT); });
auto se = detail::scope_exit([&] {
svr.stop();
t.join();
ASSERT_FALSE(svr.is_running());
ASSERT_TRUE(handled);
});
svr.wait_until_ready();
std::string body = "----------\r\n"
"Content-Disposition: form-data; name=\"file1\"; "
"filename*=UTF-8'en'%41.txt\r\n"
"\r\n"
"hello\r\n"
"----------\r\n"
"Content-Disposition: form-data; name=\"file2\"; "
"filename*=utf-8'fr-CA'na%C3%AFve.txt\r\n"
"\r\n"
"bonjour\r\n"
"------------\r\n";
auto req = "POST /test HTTP/1.1\r\n"
"Host: localhost\r\n"
"Connection: close\r\n"
"Content-Type: multipart/form-data;boundary=--------\r\n"
"Content-Length: " +
std::to_string(body.size()) + "\r\n\r\n" + body;
ASSERT_TRUE(send_request(1, req));
}
TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
auto handled = false;
@@ -25311,6 +25603,36 @@ TEST(SSLClientTest, UnframedBodyEndsOnlyAtCloseNotify) {
}
#endif
TEST(ResponseHeaderLengthTest, ClientReadsLongerFieldsThanServer) {
const auto value = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH * 2, 'a');
const auto response = "HTTP/1.1 200 OK\r\n"
"X-Long: " +
value +
"\r\n"
"Content-Length: 2\r\n"
"Connection: close\r\n\r\nok";
with_single_response(response, [&](Client &cli) {
auto res = cli.Get("/");
ASSERT_TRUE(res) << to_string(res.error());
EXPECT_EQ(value, res->get_header_value("X-Long"));
});
with_single_response(response, [&](Client &cli) {
auto handle = cli.open_stream("GET", "/");
ASSERT_TRUE(handle.is_valid()) << to_string(handle.error);
EXPECT_EQ(value, handle.response->get_header_value("X-Long"));
});
std::string out;
test_raw_request("GET /hi HTTP/1.1\r\n"
"Host: localhost\r\n"
"X-Long: " +
value + "\r\n\r\n",
&out);
EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
}
TEST(InterimResponseTest, SkippedWithTheirHeaderFields) {
const char *responses[] = {
"HTTP/1.1 103 Early Hints\r\n"
@@ -26966,13 +27288,35 @@ TEST(ETagTest, IfRangeWithDate) {
EXPECT_EQ(200, res3->status);
EXPECT_EQ(content, res3->body);
// Range request with future If-Range date: should get 206
// Range request with future If-Range date: should get 200 (full content)
Headers h4 = {{"Range", "bytes=0-4"},
{"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
ASSERT_TRUE(res4);
EXPECT_EQ(206, res4->status);
EXPECT_EQ("ABCDE", res4->body);
EXPECT_EQ(200, res4->status);
EXPECT_EQ(content, res4->body);
#if defined(__APPLE__) || defined(__linux__)
// File replaced by one with an older mtime: should get 200 (full content)
const std::string replaced = "abcdefghij9876543210";
{
std::ofstream ofs(fname);
ofs << replaced;
ASSERT_TRUE(ofs.good());
}
struct timeval times[2];
times[0].tv_sec = time(nullptr);
times[0].tv_usec = 0;
times[1].tv_sec = time(nullptr) - 3600;
times[1].tv_usec = 0;
ASSERT_EQ(0, utimes(fname, times));
Headers h5 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
auto res5 = cli.Get("/static/if_range_date_testfile.txt", h5);
ASSERT_TRUE(res5);
EXPECT_EQ(200, res5->status);
EXPECT_EQ(replaced, res5->body);
#endif
svr.stop();
t.join();