feat(net): implement VL-004 HttpServer and VL-005 streaming HttpClient with secure TLS

This commit is contained in:
faumaray committed 2026-11-26 21:47:15 +03:00
1 parent 22c8538754
commit 66baae74a0
12 files changed
+3984 -119

No files matched your search

+182 -2
View File
@@ -4,13 +4,79 @@
#include <Void/Functional/Result.hpp>
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <filesystem>
#include <functional>
#include <optional>
#include <span>
#include <stop_token>
#include <string>
#include <string_view>
#include <system_error>
#include <vector>
namespace Void::Net
{
enum class NetErrorCode : std::int32_t {
none = 0,
invalid_url = 1,
invalid_argument = 2,
connect_failed = 3,
tls_error = 4,
protocol_error = 5,
timeout = 6,
cancelled = 7,
quota_exceeded = 8,
io_error = 9,
redirect_blocked = 10,
payload_too_large = 11,
headers_too_large = 12
};
[[nodiscard]] inline Void::Result::Error
make_net_error(NetErrorCode code, std::string message = {},
std::error_code sys_err = {})
{
using Void::Result::Error;
using Void::Result::ErrorCode;
using Void::Result::ErrorKind;
ErrorKind kind = ErrorKind::internal;
switch (code) {
case NetErrorCode::none:
kind = ErrorKind::internal;
break;
case NetErrorCode::invalid_url:
case NetErrorCode::invalid_argument:
case NetErrorCode::redirect_blocked:
kind = ErrorKind::invalid_argument;
break;
case NetErrorCode::connect_failed:
case NetErrorCode::io_error:
kind = ErrorKind::io;
break;
case NetErrorCode::tls_error:
case NetErrorCode::protocol_error:
kind = ErrorKind::corrupt;
break;
case NetErrorCode::timeout:
kind = ErrorKind::timeout;
break;
case NetErrorCode::cancelled:
kind = ErrorKind::cancelled;
break;
case NetErrorCode::quota_exceeded:
case NetErrorCode::payload_too_large:
case NetErrorCode::headers_too_large:
kind = ErrorKind::exhausted;
break;
}
return Error{kind, std::move(message),
ErrorCode{Void::Result::kNetErrorDomain,
static_cast<std::int32_t>(code)},
sys_err};
}
enum class Method { Get, Post, Put, Delete, Patch, Head, Options };
@@ -62,6 +128,54 @@ namespace Void::Net
}
};
struct HttpClientOptions {
ProxyConfig proxy{};
std::string user_agent{"Void.Net/1.0"};
bool verify_tls{true};
std::string ca_file{};
std::uint64_t max_body_size{64ULL * 1024 * 1024};
int max_redirects{0};
bool allow_insecure_redirects{false};
};
struct TransferProgress {
std::uint64_t bytes_transferred{0};
std::optional<std::uint64_t> total_bytes{};
};
struct DownloadOptions {
std::vector<Header> headers{};
std::chrono::seconds timeout{30};
std::uint64_t max_bytes{0};
std::stop_token stop{};
std::function<void(std::span<const std::byte>)> on_chunk{};
std::function<void(const TransferProgress&)> on_progress{};
};
struct DownloadResult {
std::uint16_t status{0};
std::vector<Header> headers{};
std::uint64_t bytes_written{0};
std::chrono::milliseconds elapsed{0};
[[nodiscard]] bool ok() const noexcept
{
return status >= 200 && status < 300;
}
[[nodiscard]] std::optional<std::string_view>
header(std::string_view name) const;
};
struct UploadOptions {
Method method{Method::Put};
std::vector<Header> headers{};
std::string content_type{"application/octet-stream"};
std::chrono::seconds timeout{30};
std::uint64_t max_upload_bytes{0};
std::stop_token stop{};
std::function<void(const TransferProgress&)> on_progress{};
};
/// Synchronous HTTP/HTTPS client built on Boost.Beast/Asio + OpenSSL.
/// Supports direct connections, HTTP-CONNECT and SOCKS5 proxies, and TLS.
/// Generic: no application-specific defaults beyond a configurable
@@ -73,6 +187,12 @@ namespace Void::Net
HttpClient() = default;
explicit HttpClient(ProxyConfig proxy) : m_proxy(std::move(proxy)) {}
explicit HttpClient(HttpClientOptions options);
/// Preset with TLS peer & hostname certificate verification enabled
/// by default (`verify_tls = true`).
[[nodiscard]] static HttpClient
secure(ProxyConfig proxy = {});
void set_proxy(ProxyConfig proxy) { m_proxy = std::move(proxy); }
[[nodiscard]] const ProxyConfig& proxy() const noexcept
@@ -83,9 +203,33 @@ namespace Void::Net
/// Default User-Agent applied when a request sets none.
void set_user_agent(std::string ua) { m_user_agent = std::move(ua); }
/// Verify TLS peer certificates (default: false, matching common
/// scraping/proxy use; enable for security-sensitive callers).
/// Verify TLS peer certificates (default constructor keeps `false`
/// for 1.x compatibility; `HttpClient::secure()` defaults `true`).
void set_verify_tls(bool on) noexcept { m_verify_tls = on; }
[[nodiscard]] bool verify_tls() const noexcept
{
return m_verify_tls;
}
/// Optional custom PEM CA bundle/certificate file used when
/// `verify_tls` is enabled.
void set_ca_file(std::string ca_file)
{
m_ca_file = std::move(ca_file);
}
[[nodiscard]] const std::string& ca_file() const noexcept
{
return m_ca_file;
}
void set_allow_insecure_redirects(bool allow) noexcept
{
m_allow_insecure_redirects = allow;
}
[[nodiscard]] bool allow_insecure_redirects() const noexcept
{
return m_allow_insecure_redirects;
}
/// Maximum response body size in bytes. 0 means unlimited. Default
/// is 64 MiB (Beast's own default of ~1 MiB is too small for binary
@@ -100,12 +244,34 @@ namespace Void::Net
/// header). Opt-in so callers that inspect redirects keep working.
void set_max_redirects(int n) noexcept { m_max_redirects = n; }
/// Format request method, scrubbed URL, and headers for logs while
/// redacting `Authorization`, `Proxy-Authorization`, `Cookie`, and
/// `X-Api-Key`.
[[nodiscard]] static std::string
format_request_diagnostics(const Request& req);
/// Execute a request. A per-request `Request::proxy` is not modelled;
/// the client-level proxy applies. Returns an Error only on transport
/// failure — a non-2xx HTTP response is a successful Result.
[[nodiscard]] Void::Result::Result<Response, Void::Result::Error>
send(const Request& req) const;
/// Stream response body directly to `destination` without buffering
/// the full payload in memory, enforcing `options.max_bytes` and
/// `options.stop` cancellation.
[[nodiscard]] Void::Result::Result<DownloadResult,
Void::Result::Error>
download_to_file(std::string_view url,
const std::filesystem::path& destination,
const DownloadOptions& options = {}) const;
/// Stream a regular file directly as the HTTP request body without
/// buffering the full file in memory.
[[nodiscard]] Void::Result::Result<Response, Void::Result::Error>
upload_file(std::string_view url,
const std::filesystem::path& source_path,
const UploadOptions& options = {}) const;
// Convenience wrappers.
[[nodiscard]] Void::Result::Result<Response, Void::Result::Error>
get(std::string_view url,
@@ -113,14 +279,28 @@ namespace Void::Net
[[nodiscard]] Void::Result::Result<Response, Void::Result::Error>
post(std::string_view url, std::string body,
std::vector<Header> headers = {}) const;
[[nodiscard]] Void::Result::Result<Response, Void::Result::Error>
put_file(std::string_view url,
const std::filesystem::path& source_path,
std::vector<Header> headers = {},
std::string content_type =
"application/octet-stream") const;
[[nodiscard]] Void::Result::Result<Response, Void::Result::Error>
post_file(std::string_view url,
const std::filesystem::path& source_path,
std::vector<Header> headers = {},
std::string content_type =
"application/octet-stream") const;
private:
ProxyConfig m_proxy{};
std::string m_user_agent = "Void.Net/1.0";
bool m_verify_tls = false;
std::string m_ca_file{};
std::uint64_t m_max_body = 64ull * 1024 * 1024;
int m_max_redirects = 0;
bool m_allow_insecure_redirects = false;
};
} // namespace Void::Net
+108
View File
@@ -0,0 +1,108 @@
#pragma once
#include <Void/Functional/Result.hpp>
#include <Void/Net/Http.hpp>
#include <Void/Net/Server.hpp>
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <filesystem>
#include <functional>
#include <memory>
#include <optional>
#include <span>
#include <string>
namespace Void::Net
{
struct HttpServerOptions {
std::string bind_host{"127.0.0.1"};
std::uint16_t port{0};
std::size_t max_header_bytes{64ULL * 1024};
std::size_t max_headers{128};
std::uint64_t max_body_bytes{16ULL * 1024 * 1024};
std::uint64_t max_streaming_body_bytes{512ULL * 1024 * 1024};
std::size_t max_concurrent_connections{64};
std::chrono::milliseconds read_timeout{std::chrono::seconds{30}};
std::chrono::milliseconds write_timeout{std::chrono::seconds{30}};
int listen_backlog{128};
};
/// Streaming request body reader passed to streaming HTTP route handlers.
class BodyReader
{
public:
struct State;
explicit BodyReader(State& state) noexcept : m_state(&state) {}
BodyReader(const BodyReader&) = delete;
BodyReader& operator=(const BodyReader&) = delete;
[[nodiscard]] std::optional<std::uint64_t>
content_length() const noexcept;
[[nodiscard]] bool is_chunked() const noexcept;
[[nodiscard]] std::uint64_t bytes_read() const noexcept;
/// Read up to dst.size() decoded body bytes. Returns 0 at EOF.
[[nodiscard]] Void::Result::Result<std::size_t>
read_some(std::span<std::byte> dst);
/// Stream the request body atomically to `destination`, enforcing
/// `max_bytes` (or server max_streaming_body_bytes when 0).
[[nodiscard]] Void::Result::Result<std::uint64_t>
read_to_file(const std::filesystem::path& destination,
std::uint64_t max_bytes = 0);
private:
State* m_state{nullptr};
};
using StreamingRouteHandler =
std::function<RouteResult(const ServerRequest&, BodyReader&)>;
/// Concrete POSIX TCP HTTP/1.1 listener dispatching buffered routes through
/// `Void::Net::Router` and streaming routes via `BodyReader`.
class HttpServer
{
public:
explicit HttpServer(HttpServerOptions options = {});
explicit HttpServer(Router& external_router,
HttpServerOptions options = {});
~HttpServer() noexcept;
HttpServer(HttpServer&&) noexcept;
HttpServer& operator=(HttpServer&&) noexcept;
HttpServer(const HttpServer&) = delete;
HttpServer& operator=(const HttpServer&) = delete;
[[nodiscard]] Router& router() noexcept;
[[nodiscard]] Void::Result::Result<void>
add_route(Method method, std::string pattern,
RouteHandler handler);
[[nodiscard]] Void::Result::Result<void>
add_streaming_route(Method method, std::string pattern,
StreamingRouteHandler handler);
[[nodiscard]] Void::Result::Result<void> start();
void shutdown(std::chrono::milliseconds drain_timeout =
std::chrono::seconds{5}) noexcept;
[[nodiscard]] bool running() const noexcept;
[[nodiscard]] std::uint16_t bound_port() const noexcept;
[[nodiscard]] std::string bind_address() const;
[[nodiscard]] std::string base_url() const;
private:
struct Impl;
std::unique_ptr<Impl> m_impl;
};
} // namespace Void::Net
+10
View File
@@ -30,6 +30,7 @@ namespace Void::Net
std::vector<Header> headers;
std::string body;
RouteParameters parameters;
std::string query{};
[[nodiscard]] std::optional<std::string_view>
header(std::string_view name) const noexcept;
@@ -39,6 +40,12 @@ namespace Void::Net
std::uint16_t status{200};
std::vector<Header> headers;
std::string body;
std::optional<std::filesystem::path> file_body{};
[[nodiscard]] static ServerResponse
from_file(std::filesystem::path path,
std::string content_type = {},
std::uint16_t status = 200);
[[nodiscard]] std::optional<std::string_view>
header(std::string_view name) const noexcept;
@@ -67,6 +74,9 @@ namespace Void::Net
[[nodiscard]] Void::Result::Result<std::optional<ServerResponse>>
dispatch(ServerRequest request) const;
[[nodiscard]] std::vector<Method>
allowed_methods(std::string_view path) const;
[[nodiscard]] std::size_t size() const;
private: