Net: pinned resolver callback and cancellation for HttpClient::send (closes #55)
This commit is contained in:
1 parent
5c5fe96f11
commit
4a820748dd
3 files changed
+230
-6
No files matched your search
@@ -101,8 +101,18 @@ namespace Void::Net
|
|||||||
std::vector<Header> headers;
|
std::vector<Header> headers;
|
||||||
std::optional<std::string> body;
|
std::optional<std::string> body;
|
||||||
std::chrono::seconds timeout{30};
|
std::chrono::seconds timeout{30};
|
||||||
|
/// Cancels an in-flight request; the call returns a cancelled error.
|
||||||
|
std::stop_token stop{};
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/// Resolve-then-connect hook. Receives the host and port and returns the
|
||||||
|
/// addresses (IPv4/IPv6 literals) the client must connect to. This lets a
|
||||||
|
/// caller validate every resolved answer and pin it, closing the DNS
|
||||||
|
/// rebinding window between validation and connect. An empty result is a
|
||||||
|
/// connect failure.
|
||||||
|
using ResolveHook = std::function<Void::Result::Result<std::vector<std::string>>(
|
||||||
|
std::string_view host, std::uint16_t port)>;
|
||||||
|
|
||||||
struct Response {
|
struct Response {
|
||||||
std::uint16_t status = 0;
|
std::uint16_t status = 0;
|
||||||
std::vector<Header> headers;
|
std::vector<Header> headers;
|
||||||
@@ -146,6 +156,8 @@ namespace Void::Net
|
|||||||
std::uint64_t max_body_size{64ULL * 1024 * 1024};
|
std::uint64_t max_body_size{64ULL * 1024 * 1024};
|
||||||
int max_redirects{0};
|
int max_redirects{0};
|
||||||
bool allow_insecure_redirects{false};
|
bool allow_insecure_redirects{false};
|
||||||
|
/// Optional pinned resolver applied to direct connections.
|
||||||
|
ResolveHook resolve{};
|
||||||
};
|
};
|
||||||
|
|
||||||
struct TransferProgress {
|
struct TransferProgress {
|
||||||
@@ -311,6 +323,7 @@ namespace Void::Net
|
|||||||
std::uint64_t m_max_body = 64ull * 1024 * 1024;
|
std::uint64_t m_max_body = 64ull * 1024 * 1024;
|
||||||
int m_max_redirects = 0;
|
int m_max_redirects = 0;
|
||||||
bool m_allow_insecure_redirects = false;
|
bool m_allow_insecure_redirects = false;
|
||||||
|
ResolveHook m_resolve{};
|
||||||
};
|
};
|
||||||
|
|
||||||
} // namespace Void::Net
|
} // namespace Void::Net
|
||||||
+59
-6
@@ -257,6 +257,51 @@ namespace Void::Net
|
|||||||
return convert(parser.get());
|
return convert(parser.get());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Connect directly, honoring a pinned resolver when one is configured.
|
||||||
|
// The hook returns already-validated addresses, so the connect uses
|
||||||
|
// exactly those and no second DNS lookup can rebind them.
|
||||||
|
[[nodiscard]] Void::Result::Result<void>
|
||||||
|
connect_direct(tcp::socket& socket, tcp::resolver& resolver,
|
||||||
|
const Url& url, const ResolveHook& hook)
|
||||||
|
{
|
||||||
|
if (!hook) {
|
||||||
|
asio::connect(socket, resolver.resolve(url.host, url.port));
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
unsigned int port_value = 0;
|
||||||
|
const auto parsed_port = std::from_chars(
|
||||||
|
url.port.data(), url.port.data() + url.port.size(), port_value);
|
||||||
|
if (parsed_port.ec != std::errc{} || port_value > 65535U) {
|
||||||
|
return std::unexpected{make_net_error(
|
||||||
|
NetErrorCode::invalid_url,
|
||||||
|
std::format("Net: invalid port '{}'", url.port))};
|
||||||
|
}
|
||||||
|
const auto port = static_cast<std::uint16_t>(port_value);
|
||||||
|
auto pinned = hook(url.host, port);
|
||||||
|
if (!pinned) {
|
||||||
|
return std::unexpected{pinned.error()};
|
||||||
|
}
|
||||||
|
if (pinned->empty()) {
|
||||||
|
return std::unexpected{make_net_error(
|
||||||
|
NetErrorCode::connect_failed,
|
||||||
|
"Net: pinned resolver returned no addresses")};
|
||||||
|
}
|
||||||
|
std::vector<tcp::endpoint> endpoints;
|
||||||
|
endpoints.reserve(pinned->size());
|
||||||
|
for (const auto& literal : *pinned) {
|
||||||
|
boost::system::error_code ec;
|
||||||
|
const auto address = asio::ip::make_address(literal, ec);
|
||||||
|
if (ec) {
|
||||||
|
return std::unexpected{make_net_error(
|
||||||
|
NetErrorCode::invalid_argument,
|
||||||
|
std::format("Net: invalid pinned address '{}'", literal))};
|
||||||
|
}
|
||||||
|
endpoints.emplace_back(address, port);
|
||||||
|
}
|
||||||
|
asio::connect(socket, endpoints);
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
|
||||||
void socks5_connect(tcp::socket& socket, const Url& url,
|
void socks5_connect(tcp::socket& socket, const Url& url,
|
||||||
const ProxyConfig& proxy)
|
const ProxyConfig& proxy)
|
||||||
{
|
{
|
||||||
@@ -990,7 +1035,8 @@ namespace Void::Net
|
|||||||
m_ca_file(std::move(options.ca_file)),
|
m_ca_file(std::move(options.ca_file)),
|
||||||
m_max_body(options.max_body_size),
|
m_max_body(options.max_body_size),
|
||||||
m_max_redirects(options.max_redirects),
|
m_max_redirects(options.max_redirects),
|
||||||
m_allow_insecure_redirects(options.allow_insecure_redirects)
|
m_allow_insecure_redirects(options.allow_insecure_redirects),
|
||||||
|
m_resolve(std::move(options.resolve))
|
||||||
{
|
{
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1018,6 +1064,10 @@ namespace Void::Net
|
|||||||
Void::Result::Result<Response, Void::Result::Error>
|
Void::Result::Result<Response, Void::Result::Error>
|
||||||
HttpClient::send(const Request& req) const
|
HttpClient::send(const Request& req) const
|
||||||
{
|
{
|
||||||
|
if (req.stop.stop_requested()) {
|
||||||
|
return std::unexpected{make_net_error(
|
||||||
|
NetErrorCode::cancelled, "Net: request cancelled before send")};
|
||||||
|
}
|
||||||
std::string target_url = req.url;
|
std::string target_url = req.url;
|
||||||
Method active_method = req.method;
|
Method active_method = req.method;
|
||||||
std::optional<std::string> active_body = req.body;
|
std::optional<std::string> active_body = req.body;
|
||||||
@@ -1067,7 +1117,7 @@ namespace Void::Net
|
|||||||
asio::connect(socket, resolver.resolve(
|
asio::connect(socket, resolver.resolve(
|
||||||
m_proxy.host,
|
m_proxy.host,
|
||||||
std::to_string(m_proxy.port)));
|
std::to_string(m_proxy.port)));
|
||||||
DeadlineGuard deadline{socket, remaining_timeout};
|
DeadlineGuard deadline{socket, remaining_timeout, req.stop};
|
||||||
if (m_proxy.kind == ProxyConfig::Kind::Socks5) {
|
if (m_proxy.kind == ProxyConfig::Kind::Socks5) {
|
||||||
socks5_connect(socket, *url, m_proxy);
|
socks5_connect(socket, *url, m_proxy);
|
||||||
response = finish(socket, tls, ctx, *url, active_method,
|
response = finish(socket, tls, ctx, *url, active_method,
|
||||||
@@ -1101,9 +1151,12 @@ namespace Void::Net
|
|||||||
timed_out = deadline.timed_out();
|
timed_out = deadline.timed_out();
|
||||||
cancelled = deadline.cancelled();
|
cancelled = deadline.cancelled();
|
||||||
} else {
|
} else {
|
||||||
asio::connect(socket,
|
if (auto connected =
|
||||||
resolver.resolve(url->host, url->port));
|
connect_direct(socket, resolver, *url, m_resolve);
|
||||||
DeadlineGuard deadline{socket, remaining_timeout};
|
!connected) {
|
||||||
|
return std::unexpected{std::move(connected).error()};
|
||||||
|
}
|
||||||
|
DeadlineGuard deadline{socket, remaining_timeout, req.stop};
|
||||||
response =
|
response =
|
||||||
finish(socket, tls, ctx, *url, active_method,
|
finish(socket, tls, ctx, *url, active_method,
|
||||||
active_headers, active_body, m_user_agent,
|
active_headers, active_body, m_user_agent,
|
||||||
@@ -1168,7 +1221,7 @@ namespace Void::Net
|
|||||||
std::format("Net: TLS request to '{}' failed: {}",
|
std::format("Net: TLS request to '{}' failed: {}",
|
||||||
sanitize_url_for_log(target_url), e.what()))};
|
sanitize_url_for_log(target_url), e.what()))};
|
||||||
} catch (const std::exception& e) {
|
} catch (const std::exception& e) {
|
||||||
if (cancelled) {
|
if (cancelled || req.stop.stop_requested()) {
|
||||||
return std::unexpected{make_net_error(
|
return std::unexpected{make_net_error(
|
||||||
NetErrorCode::cancelled,
|
NetErrorCode::cancelled,
|
||||||
std::format("Net: request to '{}' cancelled",
|
std::format("Net: request to '{}' cancelled",
|
||||||
|
|||||||
@@ -0,0 +1,158 @@
|
|||||||
|
#include <Void/Net/Http.hpp>
|
||||||
|
#include <Void/Net/HttpServer.hpp>
|
||||||
|
#include <Void/Testing/Assert.hpp>
|
||||||
|
#include <Void/Testing/Test.hpp>
|
||||||
|
|
||||||
|
#include <atomic>
|
||||||
|
#include <chrono>
|
||||||
|
#include <cstdint>
|
||||||
|
#include <memory>
|
||||||
|
#include <stop_token>
|
||||||
|
#include <string>
|
||||||
|
#include <string_view>
|
||||||
|
#include <thread>
|
||||||
|
#include <utility>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
namespace
|
||||||
|
{
|
||||||
|
using namespace Void::Net;
|
||||||
|
using namespace std::chrono_literals;
|
||||||
|
|
||||||
|
std::unique_ptr<HttpServer> start_server()
|
||||||
|
{
|
||||||
|
auto server = std::make_unique<HttpServer>(
|
||||||
|
HttpServerOptions{.bind_host = "127.0.0.1", .port = 0});
|
||||||
|
(void)server->add_route(Method::Get, "/hi", [](const ServerRequest&) {
|
||||||
|
ServerResponse response;
|
||||||
|
response.status = 200;
|
||||||
|
response.body = "hello";
|
||||||
|
return RouteResult{std::move(response)};
|
||||||
|
});
|
||||||
|
(void)server->add_route(Method::Get, "/slow", [](const ServerRequest&) {
|
||||||
|
std::this_thread::sleep_for(300ms);
|
||||||
|
ServerResponse response;
|
||||||
|
response.status = 200;
|
||||||
|
response.body = "late";
|
||||||
|
return RouteResult{std::move(response)};
|
||||||
|
});
|
||||||
|
(void)server->start();
|
||||||
|
return server;
|
||||||
|
}
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
Void::Testing::Test net_pinned_resolver_receives_host_and_is_used()
|
||||||
|
{
|
||||||
|
auto server = start_server();
|
||||||
|
const auto port = server->bound_port();
|
||||||
|
|
||||||
|
std::atomic<int> calls{0};
|
||||||
|
std::string seen_host;
|
||||||
|
std::uint16_t seen_port = 0;
|
||||||
|
HttpClient client{HttpClientOptions{
|
||||||
|
.resolve = [&](std::string_view host, std::uint16_t target)
|
||||||
|
-> Void::Result::Result<std::vector<std::string>> {
|
||||||
|
++calls;
|
||||||
|
seen_host = std::string{host};
|
||||||
|
seen_port = target;
|
||||||
|
return std::vector<std::string>{"127.0.0.1"};
|
||||||
|
}}};
|
||||||
|
|
||||||
|
Request request;
|
||||||
|
request.url = "http://pinned.example:" + std::to_string(port) + "/hi";
|
||||||
|
auto response = client.send(request);
|
||||||
|
Void::Testing::require(response.has_value());
|
||||||
|
Void::Testing::expect_eq(response->status, std::uint16_t{200});
|
||||||
|
Void::Testing::expect_eq(response->body, std::string{"hello"});
|
||||||
|
// The hook resolved the logical host and the client connected to the pin.
|
||||||
|
Void::Testing::expect_eq(calls.load(), 1);
|
||||||
|
Void::Testing::expect_eq(seen_host, std::string{"pinned.example"});
|
||||||
|
Void::Testing::expect_eq(seen_port, port);
|
||||||
|
|
||||||
|
server->shutdown();
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test net_pinned_resolver_rejects_bad_results()
|
||||||
|
{
|
||||||
|
auto server = start_server();
|
||||||
|
const auto port = server->bound_port();
|
||||||
|
const std::string url =
|
||||||
|
"http://pinned.example:" + std::to_string(port) + "/hi";
|
||||||
|
|
||||||
|
// An empty answer is a connect failure, never a fallback to DNS.
|
||||||
|
HttpClient empty{HttpClientOptions{
|
||||||
|
.resolve = [](std::string_view, std::uint16_t)
|
||||||
|
-> Void::Result::Result<std::vector<std::string>> {
|
||||||
|
return std::vector<std::string>{};
|
||||||
|
}}};
|
||||||
|
Request request;
|
||||||
|
request.url = url;
|
||||||
|
auto empty_result = empty.send(request);
|
||||||
|
Void::Testing::require(!empty_result.has_value());
|
||||||
|
Void::Testing::expect_eq(
|
||||||
|
empty_result.error().code().value,
|
||||||
|
static_cast<std::int32_t>(NetErrorCode::connect_failed));
|
||||||
|
|
||||||
|
// An invalid literal is rejected before connecting.
|
||||||
|
HttpClient invalid{HttpClientOptions{
|
||||||
|
.resolve = [](std::string_view, std::uint16_t)
|
||||||
|
-> Void::Result::Result<std::vector<std::string>> {
|
||||||
|
return std::vector<std::string>{"not-an-address"};
|
||||||
|
}}};
|
||||||
|
auto invalid_result = invalid.send(request);
|
||||||
|
Void::Testing::require(!invalid_result.has_value());
|
||||||
|
Void::Testing::expect_eq(
|
||||||
|
invalid_result.error().code().value,
|
||||||
|
static_cast<std::int32_t>(NetErrorCode::invalid_argument));
|
||||||
|
|
||||||
|
server->shutdown();
|
||||||
|
}
|
||||||
|
|
||||||
|
Void::Testing::Test net_stop_token_aborts_send()
|
||||||
|
{
|
||||||
|
auto server = start_server();
|
||||||
|
const auto port = server->bound_port();
|
||||||
|
const std::string url =
|
||||||
|
"http://127.0.0.1:" + std::to_string(port) + "/slow";
|
||||||
|
HttpClient client;
|
||||||
|
|
||||||
|
// An already-requested token fails without any I/O.
|
||||||
|
{
|
||||||
|
std::stop_source source;
|
||||||
|
source.request_stop();
|
||||||
|
Request request;
|
||||||
|
request.url = url;
|
||||||
|
request.stop = source.get_token();
|
||||||
|
const auto started = std::chrono::steady_clock::now();
|
||||||
|
auto result = client.send(request);
|
||||||
|
const auto elapsed = std::chrono::steady_clock::now() - started;
|
||||||
|
Void::Testing::require(!result.has_value());
|
||||||
|
Void::Testing::expect_eq(
|
||||||
|
result.error().code().value,
|
||||||
|
static_cast<std::int32_t>(NetErrorCode::cancelled));
|
||||||
|
Void::Testing::expect(elapsed < 200ms);
|
||||||
|
}
|
||||||
|
|
||||||
|
// A token requested while the request is in flight aborts it promptly,
|
||||||
|
// well before the 300ms server response.
|
||||||
|
{
|
||||||
|
std::stop_source source;
|
||||||
|
std::jthread canceller{[&source] {
|
||||||
|
std::this_thread::sleep_for(50ms);
|
||||||
|
source.request_stop();
|
||||||
|
}};
|
||||||
|
Request request;
|
||||||
|
request.url = url;
|
||||||
|
request.stop = source.get_token();
|
||||||
|
const auto started = std::chrono::steady_clock::now();
|
||||||
|
auto result = client.send(request);
|
||||||
|
const auto elapsed = std::chrono::steady_clock::now() - started;
|
||||||
|
Void::Testing::require(!result.has_value());
|
||||||
|
Void::Testing::expect_eq(
|
||||||
|
result.error().code().value,
|
||||||
|
static_cast<std::int32_t>(NetErrorCode::cancelled));
|
||||||
|
Void::Testing::expect(elapsed < 250ms);
|
||||||
|
}
|
||||||
|
|
||||||
|
server->shutdown();
|
||||||
|
}
|
||||||
Reference in new issue
Block a user