feat(net): complete P2 M-NET-01..05 codec, pool, safe static open, redirects, and RFC 6455 WebSocket

This commit is contained in:
faumaray committed 2026-11-27 01:15:36 +03:00
1 parent 700024a24d
commit 86d777eae6
14 files changed
+4346 -19

No files matched your search

+172
View File
@@ -0,0 +1,172 @@
#pragma once
#include <Void/Functional/Error.hpp>
#include <Void/Functional/Result.hpp>
#include <Void/Net/Http.hpp>
#include <cstddef>
#include <cstdint>
#include <optional>
#include <span>
#include <string>
#include <string_view>
#include <vector>
namespace Void::Net
{
struct HttpCodecLimits {
std::size_t max_start_line_bytes{8ULL * 1024};
std::size_t max_header_bytes{32ULL * 1024};
std::size_t max_headers{100};
std::uint64_t max_body_bytes{8ULL * 1024 * 1024};
std::size_t max_chunk_line_bytes{1024};
std::size_t max_trailer_bytes{8ULL * 1024};
std::size_t max_informational_responses{8};
};
enum class HttpParseStatus : std::uint8_t {
NeedMoreData,
Complete,
};
struct ParsedHttpRequest {
Method method{Method::Get};
std::string target{};
std::uint8_t version_major{1};
std::uint8_t version_minor{1};
std::vector<Header> headers{};
std::string body{};
std::vector<Header> trailers{};
bool keep_alive{true};
bool chunked{false};
[[nodiscard]] std::optional<std::string_view>
header(std::string_view name) const noexcept;
};
struct ParsedHttpResponse {
std::uint16_t status{200};
std::string reason{};
std::uint8_t version_major{1};
std::uint8_t version_minor{1};
std::vector<Header> headers{};
std::string body{};
std::vector<Header> trailers{};
std::vector<std::uint16_t> informational_statuses{};
bool keep_alive{true};
bool chunked{false};
bool close_delimited{false};
[[nodiscard]] std::optional<std::string_view>
header(std::string_view name) const noexcept;
};
/// Native incremental RFC 9110/9112 HTTP/1.1 request parser.
/// Enforces strict CRLF framing, header/body limits, and rejects
/// Transfer-Encoding + Content-Length smuggling ambiguity and conflicting
/// Content-Length values.
class HttpRequestParser
{
public:
explicit HttpRequestParser(HttpCodecLimits limits = {}) noexcept;
void reset() noexcept;
/// Feed arbitrary byte chunks. Returns Complete once a full message
/// has been parsed; `consumed` reports bytes consumed from `input`.
[[nodiscard]] Void::Result::Result<HttpParseStatus>
feed(std::span<const std::byte> input, std::size_t& consumed);
[[nodiscard]] Void::Result::Result<HttpParseStatus>
feed(std::string_view input, std::size_t& consumed);
[[nodiscard]] bool complete() const noexcept;
[[nodiscard]] bool connection_reusable() const noexcept;
[[nodiscard]] const ParsedHttpRequest& request() const noexcept;
[[nodiscard]] ParsedHttpRequest take_request();
private:
enum class Phase : std::uint8_t {
Headers,
FixedBody,
ChunkSize,
ChunkData,
ChunkDataCrlf,
Trailers,
Complete,
Failed,
};
HttpCodecLimits m_limits{};
Phase m_phase{Phase::Headers};
std::string m_buf{};
std::size_t m_header_bytes_seen{0};
std::size_t m_trailer_bytes_seen{0};
std::uint64_t m_remaining{0};
std::uint64_t m_body_received{0};
ParsedHttpRequest m_req{};
[[nodiscard]] Void::Result::Result<void> parse_header_block(
std::string_view block);
};
/// Native incremental RFC 9110/9112 HTTP/1.1 response parser.
/// Supports 1xx informational responses, HEAD/204/304 no-body responses,
/// fixed Content-Length, chunked transfer encoding with extensions and
/// trailers, and close-delimited bodies (completed via `finish_eof()`).
class HttpResponseParser
{
public:
explicit HttpResponseParser(
HttpCodecLimits limits = {},
Method request_method = Method::Get) noexcept;
void reset(Method request_method = Method::Get) noexcept;
[[nodiscard]] Void::Result::Result<HttpParseStatus>
feed(std::span<const std::byte> input, std::size_t& consumed);
[[nodiscard]] Void::Result::Result<HttpParseStatus>
feed(std::string_view input, std::size_t& consumed);
/// Signal peer EOF. Completes close-delimited responses cleanly;
/// errors on truncated fixed-length, chunked, or header frames.
[[nodiscard]] Void::Result::Result<void> finish_eof();
[[nodiscard]] bool complete() const noexcept;
[[nodiscard]] bool connection_reusable() const noexcept;
[[nodiscard]] const ParsedHttpResponse& response() const noexcept;
[[nodiscard]] ParsedHttpResponse take_response();
private:
enum class Phase : std::uint8_t {
Headers,
FixedBody,
ChunkSize,
ChunkData,
ChunkDataCrlf,
Trailers,
CloseDelimitedBody,
Complete,
Failed,
};
HttpCodecLimits m_limits{};
Method m_request_method{Method::Get};
Phase m_phase{Phase::Headers};
std::string m_buf{};
std::size_t m_header_bytes_seen{0};
std::size_t m_trailer_bytes_seen{0};
std::uint64_t m_remaining{0};
std::uint64_t m_body_received{0};
ParsedHttpResponse m_resp{};
[[nodiscard]] Void::Result::Result<bool> parse_header_block(
std::string_view block);
};
} // namespace Void::Net
+9
View File
@@ -3,6 +3,7 @@
#include <Void/Functional/Result.hpp>
#include <Void/Net/Http.hpp>
#include <Void/Net/Server.hpp>
#include <Void/Net/WebSocket.hpp>
#include <chrono>
#include <cstddef>
@@ -89,6 +90,14 @@ namespace Void::Net
add_streaming_route(Method method, std::string pattern,
StreamingRouteHandler handler);
/// Register a RFC 6455 WebSocket upgrade endpoint backed by
/// `sessions` (caller must keep `sessions` alive until after
/// `shutdown()`).
[[nodiscard]] Void::Result::Result<void>
add_websocket_route(std::string pattern,
WebSocketSessions& sessions,
WebSocketUpgradeOptions options = {});
[[nodiscard]] Void::Result::Result<void> start();
void shutdown(std::chrono::milliseconds drain_timeout =
+142
View File
@@ -0,0 +1,142 @@
#pragma once
#include <Void/Functional/Error.hpp>
#include <Void/Functional/Result.hpp>
#include <Void/Net/Http.hpp>
#include <Void/Time/Clock.hpp>
#include <chrono>
#include <compare>
#include <cstddef>
#include <cstdint>
#include <functional>
#include <memory>
#include <string>
namespace Void::Net
{
struct PoolLimits {
std::size_t max_total_connections{256};
std::size_t max_per_origin{8};
std::size_t max_idle_connections{128};
std::chrono::milliseconds idle_timeout{std::chrono::seconds{30}};
};
/// Pool partition key isolating origins, proxy identity, and TLS/trust
/// policy generations so connections never cross trust boundaries.
struct PoolKey {
std::string scheme{};
std::string host{};
std::uint16_t port{0};
std::string proxy_identity{};
std::uint64_t tls_policy_generation{0};
[[nodiscard]] auto
operator<=>(const PoolKey&) const noexcept = default;
};
/// Abstract pooled transport entry owned by ConnectionPool / leases.
class PooledConnection
{
public:
virtual ~PooledConnection() = default;
[[nodiscard]] virtual bool is_open() const noexcept = 0;
virtual void close() noexcept = 0;
};
using ConnectionFactory =
std::function<Void::Result::Result<std::unique_ptr<PooledConnection>>(
const PoolKey&)>;
struct PoolStats {
std::size_t total_connections{0};
std::size_t active_leases{0};
std::size_t idle_connections{0};
std::uint64_t total_acquires{0};
std::uint64_t idle_hits{0};
std::uint64_t idle_evictions{0};
std::uint64_t closed_dirty{0};
};
class ConnectionPool;
/// Move-only RAII lease for one HTTP/1.1 exchange. Only leases explicitly
/// marked reusable via `mark_reusable(true)` (after full body+trailers)
/// return to the idle pool on destruction; unmarked or dirty leases close.
class ConnectionLease final
{
public:
ConnectionLease() noexcept = default;
~ConnectionLease() noexcept;
ConnectionLease(ConnectionLease&& other) noexcept;
ConnectionLease& operator=(ConnectionLease&& other) noexcept;
ConnectionLease(const ConnectionLease&) = delete;
ConnectionLease& operator=(const ConnectionLease&) = delete;
[[nodiscard]] bool valid() const noexcept;
[[nodiscard]] bool reused() const noexcept;
[[nodiscard]] const PoolKey& key() const noexcept;
[[nodiscard]] PooledConnection* get() const noexcept;
[[nodiscard]] PooledConnection& operator*() const noexcept;
[[nodiscard]] PooledConnection* operator->() const noexcept;
void mark_reusable(bool reusable = true) noexcept;
void release() noexcept;
private:
friend class ConnectionPool;
struct Impl;
std::shared_ptr<void> m_pool_state{};
PoolKey m_key{};
std::unique_ptr<PooledConnection> m_conn{};
bool m_reused{false};
bool m_reusable{false};
bool m_active{false};
};
/// Bounded HTTP/1.1 connection pool keyed by origin, proxy identity, and
/// TLS policy generation, with deterministic clock-driven idle eviction.
class ConnectionPool final
{
public:
explicit ConnectionPool(
PoolLimits limits = {},
const Void::Time::MonotonicClock& clock =
Void::Time::SystemMonotonicClock::instance());
~ConnectionPool() noexcept;
ConnectionPool(ConnectionPool&&) noexcept;
ConnectionPool& operator=(ConnectionPool&&) noexcept;
ConnectionPool(const ConnectionPool&) = delete;
ConnectionPool& operator=(const ConnectionPool&) = delete;
/// Acquire an idle connection for `key` or invoke `factory(key)`
/// outside pool locks while enforcing total and per-origin limits.
[[nodiscard]] Void::Result::Result<ConnectionLease>
acquire(const PoolKey& key, const ConnectionFactory& factory);
/// Evict all idle connections older than `idle_timeout` or closed.
std::size_t evict_expired();
/// Close all idle connections (e.g. on trust-store rotation).
std::size_t clear_idle();
/// Prevent new leases and close all currently idle connections.
void shutdown() noexcept;
[[nodiscard]] PoolStats stats() const;
private:
friend class ConnectionLease;
struct State;
std::shared_ptr<State> m_state;
};
} // namespace Void::Net
+62 -2
View File
@@ -98,6 +98,49 @@ namespace Void::Net
std::uintmax_t size{};
};
/// Move-only RAII handle for a regular file opened beneath a pinned root
/// directory descriptor using `openat(..., O_NOFOLLOW)` (zero TOCTOU).
class OpenedStaticFile final
{
public:
OpenedStaticFile() noexcept = default;
OpenedStaticFile(int fd, std::filesystem::path relative_path,
std::string_view content_type,
std::uint64_t size) noexcept;
~OpenedStaticFile() noexcept;
OpenedStaticFile(OpenedStaticFile&& other) noexcept;
OpenedStaticFile& operator=(OpenedStaticFile&& other) noexcept;
OpenedStaticFile(const OpenedStaticFile&) = delete;
OpenedStaticFile& operator=(const OpenedStaticFile&) = delete;
[[nodiscard]] bool valid() const noexcept { return fd_ >= 0; }
[[nodiscard]] int native_handle() const noexcept { return fd_; }
[[nodiscard]] const std::filesystem::path&
relative_path() const noexcept
{
return relative_path_;
}
[[nodiscard]] std::string_view content_type() const noexcept
{
return content_type_;
}
[[nodiscard]] std::uint64_t size() const noexcept { return size_; }
[[nodiscard]] Void::Result::Result<std::string>
read_all(std::uint64_t max_bytes = 64ULL * 1024 * 1024) const;
void close() noexcept;
private:
int fd_{-1};
std::filesystem::path relative_path_{};
std::string_view content_type_{};
std::uint64_t size_{0};
};
[[nodiscard]] std::string_view
content_type_for(const std::filesystem::path& path);
@@ -115,6 +158,12 @@ namespace Void::Net
[[nodiscard]] Void::Result::Result<std::optional<StaticFile>>
resolve(std::string_view request_path) const;
/// Descriptor-pinned open beneath the retained root directory
/// descriptor (`openat` + `O_NOFOLLOW` per component). Rejects
/// symlinks, traversal, and non-regular files without TOCTOU races.
[[nodiscard]] Void::Result::Result<std::optional<OpenedStaticFile>>
open_safe(std::string_view request_path) const;
[[nodiscard]] const std::filesystem::path& root() const noexcept
{
return root_;
@@ -122,14 +171,25 @@ namespace Void::Net
private:
struct DirHandle {
int fd{-1};
explicit DirHandle(int d) noexcept : fd(d) {}
~DirHandle() noexcept;
DirHandle(const DirHandle&) = delete;
DirHandle& operator=(const DirHandle&) = delete;
};
StaticFileResolver(std::filesystem::path root,
std::string index_file)
: root_(std::move(root)), index_file_(std::move(index_file))
std::string index_file,
std::shared_ptr<DirHandle> root_dir)
: root_(std::move(root)), index_file_(std::move(index_file)),
root_dir_(std::move(root_dir))
{
}
std::filesystem::path root_;
std::string index_file_;
std::shared_ptr<DirHandle> root_dir_;
};
struct WebSocketConnectionId {
+185
View File
@@ -0,0 +1,185 @@
#pragma once
#include <Void/Functional/Error.hpp>
#include <Void/Functional/Result.hpp>
#include <Void/Net/Http.hpp>
#include <Void/Net/Server.hpp>
#include <array>
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <memory>
#include <optional>
#include <span>
#include <string>
#include <string_view>
#include <vector>
namespace Void::Net
{
enum class WebSocketOpcode : std::uint8_t {
Continuation = 0x0,
Text = 0x1,
Binary = 0x2,
Close = 0x8,
Ping = 0x9,
Pong = 0xA,
};
struct WebSocketLimits {
std::size_t max_message_bytes{1024ULL * 1024};
std::size_t max_output_messages{64};
std::size_t max_output_bytes{4ULL * 1024 * 1024};
std::chrono::milliseconds io_timeout{std::chrono::seconds{30}};
};
struct WebSocketUpgradeOptions {
std::vector<std::string> allowed_origins{};
std::vector<std::string> supported_subprotocols{};
WebSocketLimits limits{};
};
struct WebSocketUpgradeHandshake {
std::string accept_key{};
std::optional<std::string> selected_subprotocol{};
};
struct WebSocketFrame {
bool fin{true};
WebSocketOpcode opcode{WebSocketOpcode::Text};
bool masked{false};
std::array<std::byte, 4> mask_key{};
std::vector<std::byte> payload{};
};
struct WebSocketMessage {
WebSocketOpcode opcode{WebSocketOpcode::Text};
std::vector<std::byte> payload{};
std::optional<WebSocketClose> close_info{};
[[nodiscard]] std::string_view text_view() const noexcept
{
return std::string_view{
reinterpret_cast<const char*>(payload.data()),
payload.size()};
}
};
/// Compute RFC 6455 Sec-WebSocket-Accept = Base64(SHA1(key + GUID)).
[[nodiscard]] std::string compute_websocket_accept(std::string_view key);
/// Validate strict RFC 3629 UTF-8 byte sequences (required for text frames
/// and close reasons by RFC 6455 section 5.6 / 8.1).
[[nodiscard]] bool is_valid_utf8(std::span<const std::byte> data) noexcept;
[[nodiscard]] bool is_valid_utf8(std::string_view data) noexcept;
/// Validate a client HTTP/1.1 Upgrade request per RFC 6455 section 4.2.1.
[[nodiscard]] Void::Result::Result<WebSocketUpgradeHandshake>
validate_websocket_upgrade_request(
const ServerRequest& request,
const WebSocketUpgradeOptions& options = {});
/// Encode a single RFC 6455 frame. When `masked == true`, applies
/// `mask_key` XOR masking to payload bytes.
[[nodiscard]] Void::Result::Result<std::vector<std::byte>>
encode_websocket_frame(const WebSocketFrame& frame);
/// Encode a RFC 6455 Close control frame (2-byte big-endian code + UTF-8
/// reason <= 123 bytes).
[[nodiscard]] Void::Result::Result<std::vector<std::byte>>
encode_websocket_close_frame(const WebSocketClose& close, bool masked,
std::array<std::byte, 4> mask_key = {});
/// Incremental RFC 6455 frame decoder & fragmented message assembler.
/// `expect_masked_incoming = true` for server side, `false` for client.
class WebSocketDecoder final
{
public:
explicit WebSocketDecoder(bool expect_masked_incoming,
WebSocketLimits limits = {}) noexcept;
void reset() noexcept;
/// Feed arbitrary bytes and append any completed data or control
/// messages (Text, Binary, Ping, Pong, Close) to `out_messages`.
[[nodiscard]] Void::Result::Result<void>
feed(std::span<const std::byte> input,
std::vector<WebSocketMessage>& out_messages);
[[nodiscard]] bool close_received() const noexcept
{
return m_close_received;
}
private:
bool m_expect_masked{true};
WebSocketLimits m_limits{};
std::vector<std::byte> m_buf{};
bool m_in_fragment{false};
WebSocketOpcode m_fragment_opcode{WebSocketOpcode::Text};
std::vector<std::byte> m_fragment_payload{};
bool m_close_received{false};
};
struct WebSocketConnectOptions {
std::vector<Header> extra_headers{};
std::optional<std::string> subprotocol{};
std::chrono::milliseconds timeout{std::chrono::seconds{10}};
WebSocketLimits limits{};
};
/// Synchronous RFC 6455 WebSocket client over loopback/TCP HTTP/1.1 Upgrade
/// (for direct ws:// endpoints and independent conformance testing).
class WebSocketClient final
{
public:
using ConnectOptions = WebSocketConnectOptions;
WebSocketClient() noexcept = default;
~WebSocketClient() noexcept;
WebSocketClient(WebSocketClient&&) noexcept;
WebSocketClient& operator=(WebSocketClient&&) noexcept;
WebSocketClient(const WebSocketClient&) = delete;
WebSocketClient& operator=(const WebSocketClient&) = delete;
[[nodiscard]] static Void::Result::Result<WebSocketClient>
connect(std::string_view ws_url,
const ConnectOptions& options = ConnectOptions{});
[[nodiscard]] bool is_open() const noexcept;
[[nodiscard]] const std::optional<std::string>&
selected_subprotocol() const noexcept;
[[nodiscard]] Void::Result::Result<void>
send_text(std::string_view text);
[[nodiscard]] Void::Result::Result<void>
send_binary(std::span<const std::byte> data);
[[nodiscard]] Void::Result::Result<void>
send_ping(std::span<const std::byte> payload = {});
[[nodiscard]] Void::Result::Result<void>
send_pong(std::span<const std::byte> payload = {});
[[nodiscard]] Void::Result::Result<void>
send_fragmented_text(std::span<const std::string_view> chunks);
/// Receive the next decoded WebSocket message (auto-answering Ping
/// when `auto_pong == true` unless callers want to inspect Ping).
[[nodiscard]] Void::Result::Result<WebSocketMessage>
receive(std::chrono::milliseconds timeout =
std::chrono::seconds{5});
[[nodiscard]] Void::Result::Result<void>
close(WebSocketClose close_info = {1000, ""});
private:
struct Impl;
std::unique_ptr<Impl> m_impl;
explicit WebSocketClient(std::unique_ptr<Impl> impl) noexcept;
};
} // namespace Void::Net