feat(net): complete P2 M-NET-01..05 codec, pool, safe static open, redirects, and RFC 6455 WebSocket
This commit is contained in:
1 parent
700024a24d
commit
86d777eae6
14 files changed
+4346
-19
No files matched your search
@@ -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
|
||||
@@ -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 =
|
||||
|
||||
@@ -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
|
||||
@@ -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 {
|
||||
|
||||
@@ -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
|
||||
+54
-15
@@ -917,9 +917,15 @@ namespace Void::Net
|
||||
HttpClient::send(const Request& req) const
|
||||
{
|
||||
std::string target_url = req.url;
|
||||
Method active_method = req.method;
|
||||
std::optional<std::string> active_body = req.body;
|
||||
std::vector<Header> active_headers = req.headers;
|
||||
int redirects = 0;
|
||||
|
||||
const auto overall_start = std::chrono::steady_clock::now();
|
||||
const bool has_deadline = req.timeout > std::chrono::seconds::zero();
|
||||
const auto overall_deadline = overall_start + req.timeout;
|
||||
|
||||
while (true) {
|
||||
const auto url = Url::parse(target_url);
|
||||
if (!url) {
|
||||
@@ -928,11 +934,25 @@ namespace Void::Net
|
||||
std::format("Net: invalid URL '{}'",
|
||||
sanitize_url_for_log(target_url)))};
|
||||
}
|
||||
std::chrono::seconds remaining_timeout = req.timeout;
|
||||
if (has_deadline) {
|
||||
const auto now = std::chrono::steady_clock::now();
|
||||
if (now >= overall_deadline) {
|
||||
return std::unexpected{make_net_error(
|
||||
NetErrorCode::timeout,
|
||||
std::format("Net: request to '{}' timed out across "
|
||||
"redirects",
|
||||
sanitize_url_for_log(target_url)))};
|
||||
}
|
||||
const auto rem_ms =
|
||||
std::chrono::duration_cast<std::chrono::milliseconds>(
|
||||
overall_deadline - now);
|
||||
remaining_timeout = std::chrono::seconds{
|
||||
std::max<long long>(1, (rem_ms.count() + 999) / 1000)};
|
||||
}
|
||||
bool cancelled = false;
|
||||
bool timed_out = false;
|
||||
try {
|
||||
const auto start = std::chrono::steady_clock::now();
|
||||
|
||||
asio::io_context ioc;
|
||||
ssl::context ctx = make_ssl_context(m_verify_tls, m_ca_file);
|
||||
|
||||
@@ -945,26 +965,26 @@ namespace Void::Net
|
||||
asio::connect(socket, resolver.resolve(
|
||||
m_proxy.host,
|
||||
std::to_string(m_proxy.port)));
|
||||
DeadlineGuard deadline{socket, req.timeout};
|
||||
DeadlineGuard deadline{socket, remaining_timeout};
|
||||
if (m_proxy.kind == ProxyConfig::Kind::Socks5) {
|
||||
socks5_connect(socket, *url, m_proxy);
|
||||
response = finish(socket, tls, ctx, *url, req.method,
|
||||
active_headers, req.body,
|
||||
response = finish(socket, tls, ctx, *url, active_method,
|
||||
active_headers, active_body,
|
||||
m_user_agent, m_max_body,
|
||||
m_verify_tls);
|
||||
} else {
|
||||
if (url->is_tls) {
|
||||
http_connect_tunnel(socket, *url, m_proxy);
|
||||
response = finish(socket, tls, ctx, *url,
|
||||
req.method, active_headers,
|
||||
req.body, m_user_agent,
|
||||
active_method, active_headers,
|
||||
active_body, m_user_agent,
|
||||
m_max_body, m_verify_tls);
|
||||
} else {
|
||||
const std::string absolute = std::format(
|
||||
"{}://{}{}", url->scheme, url->host,
|
||||
url->target);
|
||||
auto rq = build_request(*url, req.method,
|
||||
active_headers, req.body,
|
||||
auto rq = build_request(*url, active_method,
|
||||
active_headers, active_body,
|
||||
m_user_agent, absolute);
|
||||
if (m_proxy.has_auth()) {
|
||||
const auto enc = Void::Encoding::Base64::encode(
|
||||
@@ -981,17 +1001,21 @@ namespace Void::Net
|
||||
} else {
|
||||
asio::connect(socket,
|
||||
resolver.resolve(url->host, url->port));
|
||||
DeadlineGuard deadline{socket, req.timeout};
|
||||
DeadlineGuard deadline{socket, remaining_timeout};
|
||||
response =
|
||||
finish(socket, tls, ctx, *url, req.method,
|
||||
active_headers, req.body, m_user_agent,
|
||||
finish(socket, tls, ctx, *url, active_method,
|
||||
active_headers, active_body, m_user_agent,
|
||||
m_max_body, m_verify_tls);
|
||||
timed_out = deadline.timed_out();
|
||||
cancelled = deadline.cancelled();
|
||||
}
|
||||
|
||||
if (m_max_redirects > 0 && response.status >= 300 &&
|
||||
response.status < 400 && redirects < m_max_redirects) {
|
||||
const bool is_redirect_status =
|
||||
response.status == 301 || response.status == 302 ||
|
||||
response.status == 303 || response.status == 307 ||
|
||||
response.status == 308;
|
||||
if (m_max_redirects > 0 && is_redirect_status &&
|
||||
redirects < m_max_redirects) {
|
||||
if (auto loc = response.header("location")) {
|
||||
const std::string next_url =
|
||||
resolve_redirect(*url, *loc);
|
||||
@@ -1011,6 +1035,21 @@ namespace Void::Net
|
||||
if (!same_origin(*url, *next_parsed)) {
|
||||
strip_sensitive_headers(active_headers);
|
||||
}
|
||||
// RFC 9110 §15.4.4: 303 changes non-HEAD to GET and
|
||||
// drops body + representation headers.
|
||||
if (response.status == 303 &&
|
||||
active_method != Method::Head) {
|
||||
active_method = Method::Get;
|
||||
active_body.reset();
|
||||
std::erase_if(active_headers, [](const Header& h) {
|
||||
return equal_ascii_ci(h.name,
|
||||
"Content-Length") ||
|
||||
equal_ascii_ci(h.name,
|
||||
"Content-Type") ||
|
||||
equal_ascii_ci(h.name,
|
||||
"Transfer-Encoding");
|
||||
});
|
||||
}
|
||||
target_url = next_url;
|
||||
++redirects;
|
||||
continue;
|
||||
@@ -1019,7 +1058,7 @@ namespace Void::Net
|
||||
|
||||
response.elapsed =
|
||||
std::chrono::duration_cast<std::chrono::milliseconds>(
|
||||
std::chrono::steady_clock::now() - start);
|
||||
std::chrono::steady_clock::now() - overall_start);
|
||||
return response;
|
||||
} catch (const TlsError& e) {
|
||||
return std::unexpected{make_net_error(
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -882,6 +882,138 @@ namespace Void::Net
|
||||
std::atomic<bool> finished{false};
|
||||
std::thread thread{};
|
||||
};
|
||||
|
||||
struct WebSocketRoute {
|
||||
std::string pattern;
|
||||
std::vector<std::string> segments;
|
||||
WebSocketSessions* sessions{nullptr};
|
||||
WebSocketUpgradeOptions options{};
|
||||
};
|
||||
|
||||
class TcpWebSocketConnection final : public WebSocketConnection
|
||||
{
|
||||
public:
|
||||
|
||||
TcpWebSocketConnection(WebSocketConnectionId id, int fd,
|
||||
WebSocketLimits limits) noexcept
|
||||
: m_id(id), m_fd(fd), m_limits(limits)
|
||||
{
|
||||
}
|
||||
|
||||
[[nodiscard]] WebSocketConnectionId id() const noexcept override
|
||||
{
|
||||
return m_id;
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
send_text(std::string_view message) override
|
||||
{
|
||||
if (!is_valid_utf8(message)) {
|
||||
return std::unexpected{make_net_error(
|
||||
NetErrorCode::invalid_argument,
|
||||
"Net::WebSocket: invalid UTF-8 in server text")};
|
||||
}
|
||||
if (message.size() > m_limits.max_message_bytes) {
|
||||
return std::unexpected{make_net_error(
|
||||
NetErrorCode::payload_too_large,
|
||||
"Net::WebSocket: message exceeds max_message_bytes")};
|
||||
}
|
||||
WebSocketFrame f;
|
||||
f.fin = true;
|
||||
f.opcode = WebSocketOpcode::Text;
|
||||
f.masked = false;
|
||||
f.payload.resize(message.size());
|
||||
if (!message.empty()) {
|
||||
std::memcpy(f.payload.data(), message.data(),
|
||||
message.size());
|
||||
}
|
||||
return send_frame(f);
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
send_binary(std::span<const std::byte> message) override
|
||||
{
|
||||
if (message.size() > m_limits.max_message_bytes) {
|
||||
return std::unexpected{make_net_error(
|
||||
NetErrorCode::payload_too_large,
|
||||
"Net::WebSocket: binary message exceeds limit")};
|
||||
}
|
||||
WebSocketFrame f;
|
||||
f.fin = true;
|
||||
f.opcode = WebSocketOpcode::Binary;
|
||||
f.masked = false;
|
||||
f.payload.assign(message.begin(), message.end());
|
||||
return send_frame(f);
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
send_pong(std::span<const std::byte> payload)
|
||||
{
|
||||
WebSocketFrame f;
|
||||
f.fin = true;
|
||||
f.opcode = WebSocketOpcode::Pong;
|
||||
f.masked = false;
|
||||
f.payload.assign(payload.begin(), payload.end());
|
||||
return send_frame(f);
|
||||
}
|
||||
|
||||
void close(const WebSocketClose& close_info) noexcept override
|
||||
{
|
||||
std::lock_guard lock{m_io_mutex};
|
||||
if (m_closed || m_fd < 0) {
|
||||
m_closed = true;
|
||||
return;
|
||||
}
|
||||
m_closed = true;
|
||||
if (!m_close_sent) {
|
||||
m_close_sent = true;
|
||||
auto cf = encode_websocket_close_frame(close_info, false);
|
||||
if (cf.has_value()) {
|
||||
(void)send_all(m_fd, *cf,
|
||||
std::chrono::milliseconds{500});
|
||||
}
|
||||
}
|
||||
(void)::shutdown(m_fd, SHUT_RDWR);
|
||||
}
|
||||
|
||||
void detach_fd() noexcept
|
||||
{
|
||||
std::lock_guard lock{m_io_mutex};
|
||||
m_closed = true;
|
||||
m_fd = -1;
|
||||
}
|
||||
|
||||
[[nodiscard]] bool is_closed() const noexcept
|
||||
{
|
||||
std::lock_guard lock{m_io_mutex};
|
||||
return m_closed || m_fd < 0;
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
send_frame(const WebSocketFrame& frame)
|
||||
{
|
||||
auto encoded = encode_websocket_frame(frame);
|
||||
if (!encoded.has_value()) {
|
||||
return std::unexpected{std::move(encoded.error())};
|
||||
}
|
||||
std::lock_guard lock{m_io_mutex};
|
||||
if (m_closed || m_fd < 0) {
|
||||
return std::unexpected{make_net_error(
|
||||
NetErrorCode::io_error,
|
||||
"Net::WebSocket: connection closed")};
|
||||
}
|
||||
return send_all(m_fd, *encoded, m_limits.io_timeout);
|
||||
}
|
||||
|
||||
WebSocketConnectionId m_id{};
|
||||
mutable std::mutex m_io_mutex{};
|
||||
int m_fd{-1};
|
||||
bool m_closed{false};
|
||||
bool m_close_sent{false};
|
||||
WebSocketLimits m_limits{};
|
||||
};
|
||||
} // namespace
|
||||
|
||||
struct HttpServer::Impl {
|
||||
@@ -891,6 +1023,8 @@ namespace Void::Net
|
||||
|
||||
mutable std::shared_mutex stream_mutex{};
|
||||
std::vector<StreamingRoute> streaming_routes{};
|
||||
std::vector<WebSocketRoute> ws_routes{};
|
||||
std::atomic<std::uint64_t> next_ws_id{1};
|
||||
|
||||
std::atomic<bool> running{false};
|
||||
std::atomic<bool> stopping{false};
|
||||
@@ -958,6 +1092,157 @@ namespace Void::Net
|
||||
best->handler, std::move(best_params)};
|
||||
}
|
||||
|
||||
[[nodiscard]] std::optional<WebSocketRoute>
|
||||
match_websocket(std::string_view path_view) const
|
||||
{
|
||||
const auto segments = split_path(path_view);
|
||||
std::shared_lock lock{stream_mutex};
|
||||
const WebSocketRoute* best = nullptr;
|
||||
for (const auto& r : ws_routes) {
|
||||
if (!match_segments(r.segments, segments).has_value()) {
|
||||
continue;
|
||||
}
|
||||
if (best == nullptr ||
|
||||
more_specific_route(r.segments, best->segments)) {
|
||||
best = &r;
|
||||
}
|
||||
}
|
||||
if (best == nullptr) {
|
||||
return std::nullopt;
|
||||
}
|
||||
return *best;
|
||||
}
|
||||
|
||||
void run_websocket_session(int fd, const WebSocketRoute& route,
|
||||
const WebSocketUpgradeHandshake& hs,
|
||||
std::string& rx_buf,
|
||||
std::size_t& rx_off)
|
||||
{
|
||||
std::string resp = std::format(
|
||||
"HTTP/1.1 101 Switching Protocols\r\n"
|
||||
"Upgrade: websocket\r\n"
|
||||
"Connection: Upgrade\r\n"
|
||||
"Sec-WebSocket-Accept: {}\r\n",
|
||||
hs.accept_key);
|
||||
if (hs.selected_subprotocol.has_value()) {
|
||||
resp += std::format("Sec-WebSocket-Protocol: {}\r\n",
|
||||
*hs.selected_subprotocol);
|
||||
}
|
||||
resp += "\r\n";
|
||||
if (!send_str(fd, resp, options.write_timeout).has_value()) {
|
||||
return;
|
||||
}
|
||||
|
||||
const WebSocketConnectionId cid{
|
||||
next_ws_id.fetch_add(1, std::memory_order_relaxed)};
|
||||
auto conn = std::make_shared<TcpWebSocketConnection>(
|
||||
cid, fd, route.options.limits);
|
||||
auto opened = route.sessions->open(conn);
|
||||
if (!opened.has_value() || !(*opened)) {
|
||||
conn->close({1001, "session rejected"});
|
||||
conn->detach_fd();
|
||||
return;
|
||||
}
|
||||
|
||||
WebSocketDecoder decoder{true, route.options.limits};
|
||||
WebSocketClose final_close{1000, ""};
|
||||
bool protocol_failed = false;
|
||||
|
||||
auto process_messages =
|
||||
[&](const std::vector<WebSocketMessage>& messages) -> bool {
|
||||
for (const auto& msg : messages) {
|
||||
switch (msg.opcode) {
|
||||
case WebSocketOpcode::Text:
|
||||
(void)route.sessions->receive_text(
|
||||
cid, msg.text_view());
|
||||
break;
|
||||
case WebSocketOpcode::Binary:
|
||||
(void)route.sessions->receive_binary(
|
||||
cid, msg.payload);
|
||||
break;
|
||||
case WebSocketOpcode::Ping:
|
||||
if (!conn->send_pong(msg.payload).has_value()) {
|
||||
return false;
|
||||
}
|
||||
break;
|
||||
case WebSocketOpcode::Pong:
|
||||
break;
|
||||
case WebSocketOpcode::Close:
|
||||
final_close = msg.close_info.value_or(
|
||||
WebSocketClose{1000, ""});
|
||||
conn->close(final_close);
|
||||
return false;
|
||||
case WebSocketOpcode::Continuation:
|
||||
break;
|
||||
}
|
||||
}
|
||||
return !conn->is_closed();
|
||||
};
|
||||
|
||||
bool active = true;
|
||||
if (rx_off < rx_buf.size()) {
|
||||
const auto tail = std::span<const std::byte>{
|
||||
reinterpret_cast<const std::byte*>(rx_buf.data()) +
|
||||
rx_off,
|
||||
rx_buf.size() - rx_off};
|
||||
std::vector<WebSocketMessage> msgs;
|
||||
auto dr = decoder.feed(tail, msgs);
|
||||
rx_buf.clear();
|
||||
rx_off = 0;
|
||||
if (!dr.has_value()) {
|
||||
protocol_failed = true;
|
||||
(void)route.sessions->fail(cid, dr.error());
|
||||
final_close = {1002, "protocol error"};
|
||||
conn->close(final_close);
|
||||
active = false;
|
||||
} else {
|
||||
active = process_messages(msgs);
|
||||
}
|
||||
}
|
||||
|
||||
std::array<char, 8192> buf{};
|
||||
while (active && !stopping.load(std::memory_order_acquire) &&
|
||||
!conn->is_closed()) {
|
||||
auto nr = recv_slice(fd, buf, stopping,
|
||||
route.options.limits.io_timeout);
|
||||
if (!nr.has_value()) {
|
||||
if (stopping.load(std::memory_order_acquire)) {
|
||||
final_close = {1001, "server shutdown"};
|
||||
conn->close(final_close);
|
||||
} else if (nr.error().kind() !=
|
||||
Void::Result::ErrorKind::cancelled) {
|
||||
(void)route.sessions->fail(cid, nr.error());
|
||||
final_close = {1006, "transport error"};
|
||||
}
|
||||
break;
|
||||
}
|
||||
if (*nr == 0) {
|
||||
if (!decoder.close_received()) {
|
||||
final_close = {1006, "peer closed"};
|
||||
}
|
||||
break;
|
||||
}
|
||||
std::vector<WebSocketMessage> msgs;
|
||||
auto dr = decoder.feed(
|
||||
std::span<const std::byte>{
|
||||
reinterpret_cast<const std::byte*>(buf.data()),
|
||||
*nr},
|
||||
msgs);
|
||||
if (!dr.has_value()) {
|
||||
protocol_failed = true;
|
||||
(void)route.sessions->fail(cid, dr.error());
|
||||
final_close = {1002, "protocol error"};
|
||||
conn->close(final_close);
|
||||
break;
|
||||
}
|
||||
active = process_messages(msgs);
|
||||
}
|
||||
|
||||
(void)protocol_failed;
|
||||
conn->detach_fd();
|
||||
(void)route.sessions->disconnect(cid, final_close);
|
||||
}
|
||||
|
||||
[[nodiscard]] std::vector<Method>
|
||||
collect_allowed_methods(std::string_view path_view) const
|
||||
{
|
||||
@@ -1289,6 +1574,26 @@ namespace Void::Net
|
||||
keep_alive = false;
|
||||
}
|
||||
|
||||
// 3b. Check RFC 6455 WebSocket upgrade route.
|
||||
if (auto ws_match = match_websocket(raw_path);
|
||||
ws_match.has_value()) {
|
||||
ServerRequest ws_req;
|
||||
ws_req.method = *method_opt;
|
||||
ws_req.path = std::string{raw_path};
|
||||
ws_req.headers = std::move(headers);
|
||||
ws_req.query = std::string{raw_query};
|
||||
auto hs = validate_websocket_upgrade_request(
|
||||
ws_req, ws_match->options);
|
||||
if (!hs.has_value()) {
|
||||
send_error_close(fd_guard.get(), 400,
|
||||
"Bad Request");
|
||||
break;
|
||||
}
|
||||
run_websocket_session(fd_guard.get(), *ws_match, *hs,
|
||||
rx_buf, rx_off);
|
||||
break;
|
||||
}
|
||||
|
||||
// 4. Check streaming route vs buffered Router.
|
||||
auto streaming_match =
|
||||
match_streaming(*method_opt, raw_path);
|
||||
@@ -1681,6 +1986,31 @@ namespace Void::Net
|
||||
return {};
|
||||
}
|
||||
|
||||
Void::Result::Result<void>
|
||||
HttpServer::add_websocket_route(std::string pattern,
|
||||
WebSocketSessions& sessions,
|
||||
WebSocketUpgradeOptions options)
|
||||
{
|
||||
auto compiled = compile_route_pattern(pattern);
|
||||
if (!compiled.has_value()) {
|
||||
return std::unexpected{std::move(compiled.error())};
|
||||
}
|
||||
std::unique_lock lock{m_impl->stream_mutex};
|
||||
const auto dup = std::ranges::find_if(
|
||||
m_impl->ws_routes, [&](const WebSocketRoute& r) {
|
||||
return same_route_shape(r.segments, *compiled);
|
||||
});
|
||||
if (dup != m_impl->ws_routes.end()) {
|
||||
return std::unexpected{make_net_error(
|
||||
NetErrorCode::invalid_argument,
|
||||
"Net::HttpServer: duplicate WebSocket route")};
|
||||
}
|
||||
m_impl->ws_routes.push_back(WebSocketRoute{
|
||||
std::move(pattern), std::move(*compiled), &sessions,
|
||||
std::move(options)});
|
||||
return {};
|
||||
}
|
||||
|
||||
Void::Result::Result<void> HttpServer::start()
|
||||
{
|
||||
if (m_impl->running.load(std::memory_order_acquire)) {
|
||||
|
||||
@@ -0,0 +1,492 @@
|
||||
#include <Void/Net/Pool.hpp>
|
||||
|
||||
#include <deque>
|
||||
#include <map>
|
||||
#include <mutex>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
namespace Void::Net
|
||||
{
|
||||
struct ConnectionPool::State {
|
||||
struct IdleEntry {
|
||||
std::unique_ptr<PooledConnection> conn;
|
||||
Void::Time::MonotonicClock::time_point idle_since;
|
||||
};
|
||||
|
||||
PoolLimits limits{};
|
||||
const Void::Time::MonotonicClock* clock{nullptr};
|
||||
|
||||
mutable std::mutex mutex{};
|
||||
bool shut_down{false};
|
||||
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};
|
||||
std::map<PoolKey, std::size_t> per_origin_count{};
|
||||
std::map<PoolKey, std::deque<IdleEntry>> idle_by_key{};
|
||||
|
||||
void evict_expired_locked(
|
||||
Void::Time::MonotonicClock::time_point now,
|
||||
std::vector<std::unique_ptr<PooledConnection>>& to_close)
|
||||
{
|
||||
for (auto it = idle_by_key.begin(); it != idle_by_key.end();) {
|
||||
auto& dq = it->second;
|
||||
while (!dq.empty()) {
|
||||
const bool expired =
|
||||
limits.idle_timeout >
|
||||
std::chrono::milliseconds::zero() &&
|
||||
(now - dq.front().idle_since) >=
|
||||
limits.idle_timeout;
|
||||
const bool closed =
|
||||
!dq.front().conn || !dq.front().conn->is_open();
|
||||
if (!expired && !closed) {
|
||||
break;
|
||||
}
|
||||
to_close.push_back(std::move(dq.front().conn));
|
||||
dq.pop_front();
|
||||
--idle_connections;
|
||||
--total_connections;
|
||||
++idle_evictions;
|
||||
auto oit = per_origin_count.find(it->first);
|
||||
if (oit != per_origin_count.end()) {
|
||||
if (--oit->second == 0) {
|
||||
per_origin_count.erase(oit);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (dq.empty()) {
|
||||
it = idle_by_key.erase(it);
|
||||
} else {
|
||||
++it;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void evict_oldest_idle_locked(
|
||||
std::vector<std::unique_ptr<PooledConnection>>& to_close)
|
||||
{
|
||||
auto oldest_it = idle_by_key.end();
|
||||
for (auto it = idle_by_key.begin(); it != idle_by_key.end();
|
||||
++it) {
|
||||
if (it->second.empty()) {
|
||||
continue;
|
||||
}
|
||||
if (oldest_it == idle_by_key.end() ||
|
||||
it->second.front().idle_since <
|
||||
oldest_it->second.front().idle_since) {
|
||||
oldest_it = it;
|
||||
}
|
||||
}
|
||||
if (oldest_it == idle_by_key.end()) {
|
||||
return;
|
||||
}
|
||||
to_close.push_back(std::move(oldest_it->second.front().conn));
|
||||
oldest_it->second.pop_front();
|
||||
--idle_connections;
|
||||
--total_connections;
|
||||
++idle_evictions;
|
||||
auto oit = per_origin_count.find(oldest_it->first);
|
||||
if (oit != per_origin_count.end()) {
|
||||
if (--oit->second == 0) {
|
||||
per_origin_count.erase(oit);
|
||||
}
|
||||
}
|
||||
if (oldest_it->second.empty()) {
|
||||
idle_by_key.erase(oldest_it);
|
||||
}
|
||||
}
|
||||
|
||||
void return_lease(const PoolKey& key,
|
||||
std::unique_ptr<PooledConnection> conn,
|
||||
bool reusable) noexcept
|
||||
{
|
||||
std::vector<std::unique_ptr<PooledConnection>> to_close;
|
||||
{
|
||||
std::lock_guard lock{mutex};
|
||||
const auto now = clock->now();
|
||||
if (active_leases > 0) {
|
||||
--active_leases;
|
||||
}
|
||||
evict_expired_locked(now, to_close);
|
||||
|
||||
const bool can_keep = !shut_down && reusable &&
|
||||
conn != nullptr && conn->is_open() &&
|
||||
limits.max_idle_connections > 0;
|
||||
if (can_keep) {
|
||||
while (idle_connections >=
|
||||
limits.max_idle_connections) {
|
||||
evict_oldest_idle_locked(to_close);
|
||||
}
|
||||
idle_by_key[key].push_back(
|
||||
IdleEntry{std::move(conn), now});
|
||||
++idle_connections;
|
||||
} else {
|
||||
if (conn != nullptr) {
|
||||
to_close.push_back(std::move(conn));
|
||||
}
|
||||
if (!reusable) {
|
||||
++closed_dirty;
|
||||
}
|
||||
if (total_connections > 0) {
|
||||
--total_connections;
|
||||
}
|
||||
auto oit = per_origin_count.find(key);
|
||||
if (oit != per_origin_count.end()) {
|
||||
if (--oit->second == 0) {
|
||||
per_origin_count.erase(oit);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for (auto& c : to_close) {
|
||||
if (c) {
|
||||
c->close();
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// ── ConnectionLease ─────────────────────────────────────────────────────
|
||||
|
||||
ConnectionLease::~ConnectionLease() noexcept { release(); }
|
||||
|
||||
ConnectionLease::ConnectionLease(ConnectionLease&& other) noexcept
|
||||
: m_pool_state(std::move(other.m_pool_state)),
|
||||
m_key(std::move(other.m_key)), m_conn(std::move(other.m_conn)),
|
||||
m_reused(std::exchange(other.m_reused, false)),
|
||||
m_reusable(std::exchange(other.m_reusable, false)),
|
||||
m_active(std::exchange(other.m_active, false))
|
||||
{
|
||||
}
|
||||
|
||||
ConnectionLease& ConnectionLease::operator=(ConnectionLease&& other) noexcept
|
||||
{
|
||||
if (this != &other) {
|
||||
release();
|
||||
m_pool_state = std::move(other.m_pool_state);
|
||||
m_key = std::move(other.m_key);
|
||||
m_conn = std::move(other.m_conn);
|
||||
m_reused = std::exchange(other.m_reused, false);
|
||||
m_reusable = std::exchange(other.m_reusable, false);
|
||||
m_active = std::exchange(other.m_active, false);
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
bool ConnectionLease::valid() const noexcept
|
||||
{
|
||||
return m_active && m_conn != nullptr;
|
||||
}
|
||||
|
||||
bool ConnectionLease::reused() const noexcept { return m_reused; }
|
||||
|
||||
const PoolKey& ConnectionLease::key() const noexcept { return m_key; }
|
||||
|
||||
PooledConnection* ConnectionLease::get() const noexcept
|
||||
{
|
||||
return m_conn.get();
|
||||
}
|
||||
|
||||
PooledConnection& ConnectionLease::operator*() const noexcept
|
||||
{
|
||||
return *m_conn;
|
||||
}
|
||||
|
||||
PooledConnection* ConnectionLease::operator->() const noexcept
|
||||
{
|
||||
return m_conn.get();
|
||||
}
|
||||
|
||||
void ConnectionLease::mark_reusable(bool reusable) noexcept
|
||||
{
|
||||
m_reusable = reusable;
|
||||
}
|
||||
|
||||
void ConnectionLease::release() noexcept
|
||||
{
|
||||
if (!m_active) {
|
||||
return;
|
||||
}
|
||||
m_active = false;
|
||||
auto state = std::static_pointer_cast<ConnectionPool::State>(
|
||||
std::move(m_pool_state));
|
||||
auto conn = std::move(m_conn);
|
||||
const bool reusable = std::exchange(m_reusable, false);
|
||||
if (state) {
|
||||
state->return_lease(m_key, std::move(conn), reusable);
|
||||
} else if (conn) {
|
||||
conn->close();
|
||||
}
|
||||
}
|
||||
|
||||
// ── ConnectionPool ──────────────────────────────────────────────────────
|
||||
|
||||
ConnectionPool::ConnectionPool(PoolLimits limits,
|
||||
const Void::Time::MonotonicClock& clock)
|
||||
: m_state(std::make_shared<State>())
|
||||
{
|
||||
m_state->limits = limits;
|
||||
m_state->clock = &clock;
|
||||
}
|
||||
|
||||
ConnectionPool::~ConnectionPool() noexcept { shutdown(); }
|
||||
ConnectionPool::ConnectionPool(ConnectionPool&&) noexcept = default;
|
||||
ConnectionPool&
|
||||
ConnectionPool::operator=(ConnectionPool&&) noexcept = default;
|
||||
|
||||
Void::Result::Result<ConnectionLease>
|
||||
ConnectionPool::acquire(const PoolKey& key,
|
||||
const ConnectionFactory& factory)
|
||||
{
|
||||
if (!m_state) {
|
||||
return std::unexpected{make_net_error(
|
||||
NetErrorCode::invalid_argument,
|
||||
"Net::ConnectionPool: moved-from pool")};
|
||||
}
|
||||
if (!factory) {
|
||||
return std::unexpected{make_net_error(
|
||||
NetErrorCode::invalid_argument,
|
||||
"Net::ConnectionPool: empty connection factory")};
|
||||
}
|
||||
if (key.host.empty() || key.port == 0) {
|
||||
return std::unexpected{make_net_error(
|
||||
NetErrorCode::invalid_argument,
|
||||
"Net::ConnectionPool: invalid pool key")};
|
||||
}
|
||||
|
||||
std::vector<std::unique_ptr<PooledConnection>> to_close;
|
||||
std::unique_ptr<PooledConnection> reused_conn;
|
||||
{
|
||||
std::lock_guard lock{m_state->mutex};
|
||||
if (m_state->shut_down) {
|
||||
return std::unexpected{make_net_error(
|
||||
NetErrorCode::cancelled,
|
||||
"Net::ConnectionPool: pool is shut down")};
|
||||
}
|
||||
const auto now = m_state->clock->now();
|
||||
m_state->evict_expired_locked(now, to_close);
|
||||
|
||||
// Try LIFO idle connection for this exact key.
|
||||
auto it = m_state->idle_by_key.find(key);
|
||||
if (it != m_state->idle_by_key.end()) {
|
||||
while (!it->second.empty()) {
|
||||
auto cand = std::move(it->second.back().conn);
|
||||
it->second.pop_back();
|
||||
--m_state->idle_connections;
|
||||
if (cand && cand->is_open()) {
|
||||
reused_conn = std::move(cand);
|
||||
++m_state->active_leases;
|
||||
++m_state->total_acquires;
|
||||
++m_state->idle_hits;
|
||||
break;
|
||||
}
|
||||
to_close.push_back(std::move(cand));
|
||||
--m_state->total_connections;
|
||||
++m_state->idle_evictions;
|
||||
auto oit = m_state->per_origin_count.find(key);
|
||||
if (oit != m_state->per_origin_count.end()) {
|
||||
if (--oit->second == 0) {
|
||||
m_state->per_origin_count.erase(oit);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (it->second.empty()) {
|
||||
m_state->idle_by_key.erase(it);
|
||||
}
|
||||
}
|
||||
|
||||
if (!reused_conn) {
|
||||
// Enforce per-origin and total connection capacity.
|
||||
const std::size_t cur_origin =
|
||||
m_state->per_origin_count[key];
|
||||
if (cur_origin >= m_state->limits.max_per_origin) {
|
||||
return std::unexpected{Void::Result::Error{
|
||||
Void::Result::ErrorKind::overloaded,
|
||||
"Net::ConnectionPool: per-origin connection limit "
|
||||
"reached",
|
||||
Void::Result::ErrorCode{
|
||||
Void::Result::kNetErrorDomain,
|
||||
static_cast<std::int32_t>(
|
||||
NetErrorCode::quota_exceeded)}}};
|
||||
}
|
||||
if (m_state->total_connections >=
|
||||
m_state->limits.max_total_connections) {
|
||||
// Evict an idle connection from another origin if possible.
|
||||
if (m_state->idle_connections > 0) {
|
||||
m_state->evict_oldest_idle_locked(to_close);
|
||||
}
|
||||
}
|
||||
if (m_state->total_connections >=
|
||||
m_state->limits.max_total_connections) {
|
||||
return std::unexpected{Void::Result::Error{
|
||||
Void::Result::ErrorKind::overloaded,
|
||||
"Net::ConnectionPool: total connection limit reached",
|
||||
Void::Result::ErrorCode{
|
||||
Void::Result::kNetErrorDomain,
|
||||
static_cast<std::int32_t>(
|
||||
NetErrorCode::quota_exceeded)}}};
|
||||
}
|
||||
// Reserve slot before calling factory outside lock.
|
||||
++m_state->total_connections;
|
||||
++m_state->active_leases;
|
||||
++m_state->per_origin_count[key];
|
||||
++m_state->total_acquires;
|
||||
}
|
||||
}
|
||||
|
||||
for (auto& c : to_close) {
|
||||
if (c) {
|
||||
c->close();
|
||||
}
|
||||
}
|
||||
|
||||
if (reused_conn) {
|
||||
ConnectionLease lease;
|
||||
lease.m_pool_state = m_state;
|
||||
lease.m_key = key;
|
||||
lease.m_conn = std::move(reused_conn);
|
||||
lease.m_reused = true;
|
||||
lease.m_reusable = false;
|
||||
lease.m_active = true;
|
||||
return lease;
|
||||
}
|
||||
|
||||
// Create new connection outside pool lock.
|
||||
auto created = factory(key);
|
||||
if (!created.has_value() || !(*created) || !(*created)->is_open()) {
|
||||
// Roll back reservation.
|
||||
std::lock_guard lock{m_state->mutex};
|
||||
if (m_state->active_leases > 0) {
|
||||
--m_state->active_leases;
|
||||
}
|
||||
if (m_state->total_connections > 0) {
|
||||
--m_state->total_connections;
|
||||
}
|
||||
auto oit = m_state->per_origin_count.find(key);
|
||||
if (oit != m_state->per_origin_count.end()) {
|
||||
if (--oit->second == 0) {
|
||||
m_state->per_origin_count.erase(oit);
|
||||
}
|
||||
}
|
||||
if (!created.has_value()) {
|
||||
return std::unexpected{std::move(created.error())};
|
||||
}
|
||||
return std::unexpected{make_net_error(
|
||||
NetErrorCode::connect_failed,
|
||||
"Net::ConnectionPool: factory returned closed/null "
|
||||
"connection")};
|
||||
}
|
||||
|
||||
ConnectionLease lease;
|
||||
lease.m_pool_state = m_state;
|
||||
lease.m_key = key;
|
||||
lease.m_conn = std::move(*created);
|
||||
lease.m_reused = false;
|
||||
lease.m_reusable = false;
|
||||
lease.m_active = true;
|
||||
return lease;
|
||||
}
|
||||
|
||||
std::size_t ConnectionPool::evict_expired()
|
||||
{
|
||||
if (!m_state) {
|
||||
return 0;
|
||||
}
|
||||
std::vector<std::unique_ptr<PooledConnection>> to_close;
|
||||
{
|
||||
std::lock_guard lock{m_state->mutex};
|
||||
m_state->evict_expired_locked(m_state->clock->now(), to_close);
|
||||
}
|
||||
for (auto& c : to_close) {
|
||||
if (c) {
|
||||
c->close();
|
||||
}
|
||||
}
|
||||
return to_close.size();
|
||||
}
|
||||
|
||||
std::size_t ConnectionPool::clear_idle()
|
||||
{
|
||||
if (!m_state) {
|
||||
return 0;
|
||||
}
|
||||
std::vector<std::unique_ptr<PooledConnection>> to_close;
|
||||
{
|
||||
std::lock_guard lock{m_state->mutex};
|
||||
for (auto& [key, dq] : m_state->idle_by_key) {
|
||||
for (auto& entry : dq) {
|
||||
to_close.push_back(std::move(entry.conn));
|
||||
--m_state->idle_connections;
|
||||
--m_state->total_connections;
|
||||
++m_state->idle_evictions;
|
||||
auto oit = m_state->per_origin_count.find(key);
|
||||
if (oit != m_state->per_origin_count.end()) {
|
||||
if (--oit->second == 0) {
|
||||
m_state->per_origin_count.erase(oit);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
m_state->idle_by_key.clear();
|
||||
}
|
||||
for (auto& c : to_close) {
|
||||
if (c) {
|
||||
c->close();
|
||||
}
|
||||
}
|
||||
return to_close.size();
|
||||
}
|
||||
|
||||
void ConnectionPool::shutdown() noexcept
|
||||
{
|
||||
if (!m_state) {
|
||||
return;
|
||||
}
|
||||
std::vector<std::unique_ptr<PooledConnection>> to_close;
|
||||
{
|
||||
std::lock_guard lock{m_state->mutex};
|
||||
m_state->shut_down = true;
|
||||
for (auto& [key, dq] : m_state->idle_by_key) {
|
||||
for (auto& entry : dq) {
|
||||
to_close.push_back(std::move(entry.conn));
|
||||
--m_state->idle_connections;
|
||||
--m_state->total_connections;
|
||||
auto oit = m_state->per_origin_count.find(key);
|
||||
if (oit != m_state->per_origin_count.end()) {
|
||||
if (--oit->second == 0) {
|
||||
m_state->per_origin_count.erase(oit);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
m_state->idle_by_key.clear();
|
||||
}
|
||||
for (auto& c : to_close) {
|
||||
if (c) {
|
||||
c->close();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
PoolStats ConnectionPool::stats() const
|
||||
{
|
||||
if (!m_state) {
|
||||
return {};
|
||||
}
|
||||
std::lock_guard lock{m_state->mutex};
|
||||
return PoolStats{
|
||||
.total_connections = m_state->total_connections,
|
||||
.active_leases = m_state->active_leases,
|
||||
.idle_connections = m_state->idle_connections,
|
||||
.total_acquires = m_state->total_acquires,
|
||||
.idle_hits = m_state->idle_hits,
|
||||
.idle_evictions = m_state->idle_evictions,
|
||||
.closed_dirty = m_state->closed_dirty,
|
||||
};
|
||||
}
|
||||
|
||||
} // namespace Void::Net
|
||||
+271
-1
@@ -1,9 +1,20 @@
|
||||
#include <Void/Net/Server.hpp>
|
||||
|
||||
#if !defined(_WIN32)
|
||||
#include <fcntl.h>
|
||||
#include <sys/stat.h>
|
||||
#include <unistd.h>
|
||||
#endif
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <cctype>
|
||||
#include <cerrno>
|
||||
#include <cstring>
|
||||
#include <format>
|
||||
#include <set>
|
||||
#include <system_error>
|
||||
#include <utility>
|
||||
|
||||
namespace Void::Net
|
||||
{
|
||||
@@ -440,6 +451,106 @@ namespace Void::Net
|
||||
return "application/octet-stream";
|
||||
}
|
||||
|
||||
OpenedStaticFile::OpenedStaticFile(int fd,
|
||||
std::filesystem::path relative_path,
|
||||
std::string_view content_type,
|
||||
std::uint64_t size) noexcept
|
||||
: fd_(fd), relative_path_(std::move(relative_path)),
|
||||
content_type_(content_type), size_(size)
|
||||
{
|
||||
}
|
||||
|
||||
OpenedStaticFile::~OpenedStaticFile() noexcept { close(); }
|
||||
|
||||
OpenedStaticFile::OpenedStaticFile(OpenedStaticFile&& other) noexcept
|
||||
: fd_(std::exchange(other.fd_, -1)),
|
||||
relative_path_(std::move(other.relative_path_)),
|
||||
content_type_(std::exchange(other.content_type_, {})),
|
||||
size_(std::exchange(other.size_, 0))
|
||||
{
|
||||
}
|
||||
|
||||
OpenedStaticFile&
|
||||
OpenedStaticFile::operator=(OpenedStaticFile&& other) noexcept
|
||||
{
|
||||
if (this != &other) {
|
||||
close();
|
||||
fd_ = std::exchange(other.fd_, -1);
|
||||
relative_path_ = std::move(other.relative_path_);
|
||||
content_type_ = std::exchange(other.content_type_, {});
|
||||
size_ = std::exchange(other.size_, 0);
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
void OpenedStaticFile::close() noexcept
|
||||
{
|
||||
#if !defined(_WIN32)
|
||||
if (fd_ >= 0) {
|
||||
(void)::close(fd_);
|
||||
fd_ = -1;
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
Void::Result::Result<std::string>
|
||||
OpenedStaticFile::read_all(std::uint64_t max_bytes) const
|
||||
{
|
||||
#if !defined(_WIN32)
|
||||
if (fd_ < 0) {
|
||||
return Void::Result::fail(
|
||||
"Net::OpenedStaticFile: file descriptor is closed");
|
||||
}
|
||||
if (size_ > max_bytes) {
|
||||
return std::unexpected{make_net_error(
|
||||
NetErrorCode::payload_too_large,
|
||||
"Net::OpenedStaticFile: file size exceeds max_bytes")};
|
||||
}
|
||||
std::string out;
|
||||
out.reserve(static_cast<std::size_t>(size_));
|
||||
std::array<char, 32 * 1024> buf{};
|
||||
std::uint64_t offset = 0;
|
||||
for (;;) {
|
||||
const ssize_t n = ::pread(fd_, buf.data(), buf.size(),
|
||||
static_cast<off_t>(offset));
|
||||
if (n < 0) {
|
||||
if (errno == EINTR) continue;
|
||||
return std::unexpected{make_net_error(
|
||||
NetErrorCode::io_error,
|
||||
std::format("Net::OpenedStaticFile: pread failed: {}",
|
||||
std::strerror(errno)),
|
||||
std::error_code{errno, std::generic_category()})};
|
||||
}
|
||||
if (n == 0) {
|
||||
break;
|
||||
}
|
||||
const auto un = static_cast<std::uint64_t>(n);
|
||||
if (un > max_bytes || offset > max_bytes - un) {
|
||||
return std::unexpected{make_net_error(
|
||||
NetErrorCode::payload_too_large,
|
||||
"Net::OpenedStaticFile: read exceeds max_bytes")};
|
||||
}
|
||||
out.append(buf.data(), static_cast<std::size_t>(n));
|
||||
offset += un;
|
||||
}
|
||||
return out;
|
||||
#else
|
||||
(void)max_bytes;
|
||||
return Void::Result::fail(
|
||||
"Net::OpenedStaticFile: unsupported platform");
|
||||
#endif
|
||||
}
|
||||
|
||||
StaticFileResolver::DirHandle::~DirHandle() noexcept
|
||||
{
|
||||
#if !defined(_WIN32)
|
||||
if (fd >= 0) {
|
||||
(void)::close(fd);
|
||||
fd = -1;
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
Void::Result::Result<StaticFileResolver>
|
||||
StaticFileResolver::create(std::filesystem::path root,
|
||||
std::string index_file)
|
||||
@@ -458,8 +569,167 @@ namespace Void::Net
|
||||
return Void::Result::fail(
|
||||
"Net::StaticFileResolver: document root is not a directory");
|
||||
}
|
||||
std::shared_ptr<DirHandle> root_handle;
|
||||
#if !defined(_WIN32)
|
||||
const int dir_fd =
|
||||
::open(canonical_root.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC);
|
||||
if (dir_fd < 0) {
|
||||
return std::unexpected{make_net_error(
|
||||
NetErrorCode::io_error,
|
||||
std::format(
|
||||
"Net::StaticFileResolver: cannot open root directory: {}",
|
||||
std::strerror(errno)),
|
||||
std::error_code{errno, std::generic_category()})};
|
||||
}
|
||||
root_handle = std::make_shared<DirHandle>(dir_fd);
|
||||
#endif
|
||||
return StaticFileResolver{std::move(canonical_root),
|
||||
std::move(index_file)};
|
||||
std::move(index_file),
|
||||
std::move(root_handle)};
|
||||
}
|
||||
|
||||
Void::Result::Result<std::optional<OpenedStaticFile>>
|
||||
StaticFileResolver::open_safe(std::string_view request_path) const
|
||||
{
|
||||
#if !defined(_WIN32)
|
||||
if (!root_dir_ || root_dir_->fd < 0) {
|
||||
return Void::Result::fail(
|
||||
"Net::StaticFileResolver: root directory handle unavailable");
|
||||
}
|
||||
auto decoded = decode_url_path(request_path);
|
||||
if (!decoded) {
|
||||
return Void::Result::fail(std::move(decoded).error());
|
||||
}
|
||||
|
||||
const auto segments = split_path(*decoded);
|
||||
for (const auto& seg : segments) {
|
||||
if (seg == "." || seg == ".." ||
|
||||
seg.find('/') != std::string::npos) {
|
||||
return Void::Result::fail(
|
||||
"Net::StaticFileResolver: path traversal rejected");
|
||||
}
|
||||
}
|
||||
|
||||
struct ScopedFd {
|
||||
int fd{-1};
|
||||
bool owned{false};
|
||||
~ScopedFd() noexcept
|
||||
{
|
||||
if (owned && fd >= 0) {
|
||||
(void)::close(fd);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
ScopedFd cur{root_dir_->fd, false};
|
||||
std::filesystem::path rel_path;
|
||||
|
||||
// Walk intermediate directories strictly via openat + O_NOFOLLOW.
|
||||
for (std::size_t i = 0; i + 1U < segments.size(); ++i) {
|
||||
const int next =
|
||||
::openat(cur.fd, segments[i].c_str(),
|
||||
O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC);
|
||||
if (next < 0) {
|
||||
const int err = errno;
|
||||
if (err == ENOENT || err == ENOTDIR) {
|
||||
return std::optional<OpenedStaticFile>{};
|
||||
}
|
||||
if (err == ELOOP) {
|
||||
return Void::Result::fail(
|
||||
"Net::StaticFileResolver: symlink directory rejected");
|
||||
}
|
||||
return std::unexpected{make_net_error(
|
||||
NetErrorCode::io_error,
|
||||
std::format("Net::StaticFileResolver: openat dir failed: "
|
||||
"{}",
|
||||
std::strerror(err)),
|
||||
std::error_code{err, std::generic_category()})};
|
||||
}
|
||||
if (cur.owned && cur.fd >= 0) {
|
||||
(void)::close(cur.fd);
|
||||
}
|
||||
cur.fd = next;
|
||||
cur.owned = true;
|
||||
rel_path /= segments[i];
|
||||
}
|
||||
|
||||
// Open leaf (or index_file_ if root or directory).
|
||||
int file_fd = -1;
|
||||
if (segments.empty()) {
|
||||
file_fd = ::openat(cur.fd, index_file_.c_str(),
|
||||
O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
|
||||
rel_path /= index_file_;
|
||||
} else {
|
||||
const std::string& leaf = segments.back();
|
||||
file_fd = ::openat(cur.fd, leaf.c_str(),
|
||||
O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
|
||||
if (file_fd >= 0) {
|
||||
struct stat st{};
|
||||
if (::fstat(file_fd, &st) == 0 && S_ISDIR(st.st_mode)) {
|
||||
const int idx_fd = ::openat(
|
||||
file_fd, index_file_.c_str(),
|
||||
O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
|
||||
(void)::close(file_fd);
|
||||
file_fd = idx_fd;
|
||||
rel_path /= leaf;
|
||||
rel_path /= index_file_;
|
||||
} else {
|
||||
rel_path /= leaf;
|
||||
}
|
||||
} else if (errno == EISDIR) {
|
||||
const int dir_fd =
|
||||
::openat(cur.fd, leaf.c_str(),
|
||||
O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC);
|
||||
if (dir_fd >= 0) {
|
||||
file_fd = ::openat(dir_fd, index_file_.c_str(),
|
||||
O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
|
||||
(void)::close(dir_fd);
|
||||
rel_path /= leaf;
|
||||
rel_path /= index_file_;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (file_fd < 0) {
|
||||
const int err = errno;
|
||||
if (err == ENOENT || err == ENOTDIR) {
|
||||
return std::optional<OpenedStaticFile>{};
|
||||
}
|
||||
if (err == ELOOP) {
|
||||
return Void::Result::fail(
|
||||
"Net::StaticFileResolver: symlink file rejected");
|
||||
}
|
||||
return std::unexpected{make_net_error(
|
||||
NetErrorCode::io_error,
|
||||
std::format("Net::StaticFileResolver: openat file failed: {}",
|
||||
std::strerror(err)),
|
||||
std::error_code{err, std::generic_category()})};
|
||||
}
|
||||
|
||||
struct stat st{};
|
||||
if (::fstat(file_fd, &st) != 0) {
|
||||
const int err = errno;
|
||||
(void)::close(file_fd);
|
||||
return std::unexpected{make_net_error(
|
||||
NetErrorCode::io_error,
|
||||
std::format("Net::StaticFileResolver: fstat failed: {}",
|
||||
std::strerror(err)),
|
||||
std::error_code{err, std::generic_category()})};
|
||||
}
|
||||
if (!S_ISREG(st.st_mode)) {
|
||||
(void)::close(file_fd);
|
||||
return std::optional<OpenedStaticFile>{};
|
||||
}
|
||||
|
||||
const auto ct = content_type_for(rel_path);
|
||||
return std::optional<OpenedStaticFile>{OpenedStaticFile{
|
||||
file_fd, std::move(rel_path), ct,
|
||||
static_cast<std::uint64_t>(st.st_size)}};
|
||||
#else
|
||||
(void)request_path;
|
||||
return Void::Result::fail(
|
||||
"Net::StaticFileResolver::open_safe: unsupported platform");
|
||||
#endif
|
||||
}
|
||||
|
||||
Void::Result::Result<std::optional<StaticFile>>
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,5 +1,5 @@
|
||||
void_add_module(Net
|
||||
INTERNAL_DEPS Functional Text
|
||||
INTERNAL_DEPS Functional Text Time
|
||||
EXTERNAL_DEPS
|
||||
Boost::headers
|
||||
Boost::beast
|
||||
|
||||
@@ -1,10 +1,29 @@
|
||||
#include <Void/Net/Http.hpp>
|
||||
#include <Void/Net/HttpCodec.hpp>
|
||||
#include <Void/Net/HttpServer.hpp>
|
||||
#include <Void/Net/Pool.hpp>
|
||||
#include <Void/Net/WebSocket.hpp>
|
||||
|
||||
#include <string>
|
||||
|
||||
int main()
|
||||
{
|
||||
if (Void::Net::compute_websocket_accept("dGhlIHNhbXBsZSBub25jZQ==") !=
|
||||
"s3pPLMBiTxaQ9kYGzzhZRbK+xOo=") {
|
||||
return 10;
|
||||
}
|
||||
Void::Net::HttpRequestParser parser;
|
||||
std::size_t consumed = 0;
|
||||
auto pr = parser.feed("GET /ping HTTP/1.1\r\nHost: localhost\r\n\r\n",
|
||||
consumed);
|
||||
if (!pr.has_value() || *pr != Void::Net::HttpParseStatus::Complete) {
|
||||
return 11;
|
||||
}
|
||||
Void::Net::ConnectionPool pool;
|
||||
if (pool.stats().total_connections != 0) {
|
||||
return 12;
|
||||
}
|
||||
|
||||
Void::Net::HttpServer server;
|
||||
if (!server
|
||||
.add_route(Void::Net::Method::Get, "/ping",
|
||||
|
||||
@@ -0,0 +1,469 @@
|
||||
#include <Void/Net/Http.hpp>
|
||||
#include <Void/Net/HttpCodec.hpp>
|
||||
#include <Void/Net/HttpServer.hpp>
|
||||
#include <Void/Net/Pool.hpp>
|
||||
#include <Void/Net/Server.hpp>
|
||||
#include <Void/Net/WebSocket.hpp>
|
||||
#include <Void/System/TempDir.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
#include <Void/Time/Clock.hpp>
|
||||
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <cstddef>
|
||||
#include <filesystem>
|
||||
#include <fstream>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
namespace
|
||||
{
|
||||
struct FakeConn final : Void::Net::PooledConnection {
|
||||
std::atomic<bool> open{true};
|
||||
std::atomic<int>* close_counter{nullptr};
|
||||
std::uint64_t id{0};
|
||||
|
||||
FakeConn(std::uint64_t cid, std::atomic<int>* closes)
|
||||
: close_counter(closes), id(cid)
|
||||
{
|
||||
}
|
||||
|
||||
[[nodiscard]] bool is_open() const noexcept override
|
||||
{
|
||||
return open.load(std::memory_order_acquire);
|
||||
}
|
||||
|
||||
void close() noexcept override
|
||||
{
|
||||
if (open.exchange(false, std::memory_order_acq_rel) &&
|
||||
close_counter != nullptr) {
|
||||
close_counter->fetch_add(1, std::memory_order_relaxed);
|
||||
}
|
||||
}
|
||||
};
|
||||
} // namespace
|
||||
|
||||
Void::Testing::Test net_http_codec_incremental_chunked_trailers_and_smuggling()
|
||||
{
|
||||
// 1. Feed chunked request with chunk extension + trailer byte-by-byte.
|
||||
const std::string raw_req =
|
||||
"POST /upload?x=1 HTTP/1.1\r\n"
|
||||
"Host: example.test\r\n"
|
||||
"Transfer-Encoding: chunked\r\n"
|
||||
"\r\n"
|
||||
"5;ext=1\r\n"
|
||||
"hello\r\n"
|
||||
"6\r\n"
|
||||
" world\r\n"
|
||||
"0;final=yes\r\n"
|
||||
"X-Checksum: abc123\r\n"
|
||||
"\r\n";
|
||||
|
||||
Void::Net::HttpRequestParser req_parser;
|
||||
std::size_t total_consumed = 0;
|
||||
for (std::size_t i = 0; i < raw_req.size(); ++i) {
|
||||
std::size_t c = 0;
|
||||
auto res = req_parser.feed(std::string_view{raw_req.data() + i, 1}, c);
|
||||
Void::Testing::require(res.has_value());
|
||||
total_consumed += c;
|
||||
if (i + 1 < raw_req.size()) {
|
||||
Void::Testing::expect(*res == Void::Net::HttpParseStatus::NeedMoreData);
|
||||
} else {
|
||||
Void::Testing::expect(*res == Void::Net::HttpParseStatus::Complete);
|
||||
}
|
||||
}
|
||||
Void::Testing::expect_eq(total_consumed, raw_req.size());
|
||||
Void::Testing::expect(req_parser.connection_reusable());
|
||||
const auto req = req_parser.take_request();
|
||||
Void::Testing::expect(req.method == Void::Net::Method::Post);
|
||||
Void::Testing::expect_eq(req.target, std::string{"/upload?x=1"});
|
||||
Void::Testing::expect_eq(req.body, std::string{"hello world"});
|
||||
Void::Testing::require(req.trailers.size() == 1U);
|
||||
Void::Testing::expect_eq(req.trailers[0].name, std::string{"X-Checksum"});
|
||||
Void::Testing::expect_eq(req.trailers[0].value, std::string{"abc123"});
|
||||
|
||||
// 2. Reject smuggling combinations (TE+CL, duplicate CL, bare LF, missing Host).
|
||||
const std::vector<std::string> bad_requests{
|
||||
"POST /a HTTP/1.1\r\nHost: x\r\nContent-Length: 4\r\nTransfer-Encoding: chunked\r\n\r\n0\r\n\r\n",
|
||||
"POST /a HTTP/1.1\r\nHost: x\r\nContent-Length: 4\r\nContent-Length: 4\r\n\r\nabcd",
|
||||
"GET /a HTTP/1.1\r\nHost: x\nX-Bad: 1\r\n\r\n",
|
||||
"GET /a HTTP/1.1\r\nUser-Agent: test\r\n\r\n",
|
||||
};
|
||||
for (const auto& bad : bad_requests) {
|
||||
Void::Net::HttpRequestParser p;
|
||||
std::size_t c = 0;
|
||||
auto r = p.feed(bad, c);
|
||||
Void::Testing::expect(!r.has_value());
|
||||
Void::Testing::expect(!p.connection_reusable());
|
||||
}
|
||||
|
||||
// 3. Response parser: 100 Continue + 103 Early Hints + 200 OK with body.
|
||||
const std::string raw_resp =
|
||||
"HTTP/1.1 100 Continue\r\n\r\n"
|
||||
"HTTP/1.1 103 Early Hints\r\nLink: </style.css>; rel=preload\r\n\r\n"
|
||||
"HTTP/1.1 200 OK\r\nContent-Length: 4\r\n\r\ndone";
|
||||
Void::Net::HttpResponseParser resp_parser;
|
||||
std::size_t rc = 0;
|
||||
auto rr = resp_parser.feed(raw_resp, rc);
|
||||
Void::Testing::require(rr.has_value());
|
||||
Void::Testing::expect(*rr == Void::Net::HttpParseStatus::Complete);
|
||||
Void::Testing::expect(resp_parser.connection_reusable());
|
||||
const auto resp = resp_parser.take_response();
|
||||
Void::Testing::expect_eq(resp.status, std::uint16_t{200});
|
||||
Void::Testing::expect_eq(resp.body, std::string{"done"});
|
||||
Void::Testing::require(resp.informational_statuses.size() == 2U);
|
||||
Void::Testing::expect_eq(resp.informational_statuses[0], std::uint16_t{100});
|
||||
Void::Testing::expect_eq(resp.informational_statuses[1], std::uint16_t{103});
|
||||
|
||||
// 4. HEAD response with non-zero Content-Length completes with zero body.
|
||||
Void::Net::HttpResponseParser head_parser{{}, Void::Net::Method::Head};
|
||||
auto hr = head_parser.feed(
|
||||
"HTTP/1.1 200 OK\r\nContent-Length: 9999\r\n\r\n", rc);
|
||||
Void::Testing::require(hr.has_value());
|
||||
Void::Testing::expect(*hr == Void::Net::HttpParseStatus::Complete);
|
||||
Void::Testing::expect(head_parser.response().body.empty());
|
||||
|
||||
// 5. Close-delimited response completes on EOF and is non-reusable.
|
||||
Void::Net::HttpResponseParser close_parser;
|
||||
auto cr = close_parser.feed("HTTP/1.1 200 OK\r\n\r\nstreamed", rc);
|
||||
Void::Testing::require(cr.has_value());
|
||||
Void::Testing::expect(*cr == Void::Net::HttpParseStatus::NeedMoreData);
|
||||
Void::Testing::require(close_parser.finish_eof().has_value());
|
||||
Void::Testing::expect(close_parser.complete());
|
||||
Void::Testing::expect(!close_parser.connection_reusable());
|
||||
Void::Testing::expect_eq(close_parser.response().body, std::string{"streamed"});
|
||||
}
|
||||
|
||||
Void::Testing::Test net_connection_pool_isolation_limits_and_clock_eviction()
|
||||
{
|
||||
Void::Time::ManualClock clock;
|
||||
Void::Net::PoolLimits limits;
|
||||
limits.max_total_connections = 3;
|
||||
limits.max_per_origin = 2;
|
||||
limits.max_idle_connections = 2;
|
||||
limits.idle_timeout = std::chrono::seconds{10};
|
||||
|
||||
Void::Net::ConnectionPool pool{limits, clock};
|
||||
std::atomic<std::uint64_t> next_id{1};
|
||||
std::atomic<int> closes{0};
|
||||
|
||||
auto factory = [&](const Void::Net::PoolKey&)
|
||||
-> Void::Result::Result<std::unique_ptr<Void::Net::PooledConnection>> {
|
||||
return std::make_unique<FakeConn>(
|
||||
next_id.fetch_add(1, std::memory_order_relaxed), &closes);
|
||||
};
|
||||
|
||||
const Void::Net::PoolKey k1{"https", "api.example", 443, "", 1};
|
||||
const Void::Net::PoolKey k1_gen2{"https", "api.example", 443, "", 2};
|
||||
const Void::Net::PoolKey k2{"https", "cdn.example", 443, "", 1};
|
||||
|
||||
// Acquire, mark reusable, return -> second acquire reuses same ID.
|
||||
std::uint64_t first_id = 0;
|
||||
{
|
||||
auto l1 = pool.acquire(k1, factory);
|
||||
Void::Testing::require(l1.has_value());
|
||||
Void::Testing::expect(!l1->reused());
|
||||
first_id = static_cast<FakeConn*>(l1->get())->id;
|
||||
l1->mark_reusable(true);
|
||||
}
|
||||
{
|
||||
auto l2 = pool.acquire(k1, factory);
|
||||
Void::Testing::require(l2.has_value());
|
||||
Void::Testing::expect(l2->reused());
|
||||
Void::Testing::expect_eq(static_cast<FakeConn*>(l2->get())->id, first_id);
|
||||
// Do NOT mark reusable -> closes dirty on release.
|
||||
}
|
||||
Void::Testing::expect_eq(closes.load(), 1);
|
||||
Void::Testing::expect_eq(pool.stats().closed_dirty, std::uint64_t{1});
|
||||
|
||||
// Different TLS generation must NOT reuse k1's idle connection.
|
||||
{
|
||||
auto a = pool.acquire(k1, factory);
|
||||
Void::Testing::require(a.has_value());
|
||||
a->mark_reusable(true);
|
||||
}
|
||||
{
|
||||
auto b = pool.acquire(k1_gen2, factory);
|
||||
Void::Testing::require(b.has_value());
|
||||
Void::Testing::expect(!b->reused());
|
||||
b->mark_reusable(true);
|
||||
}
|
||||
|
||||
// Deterministic idle timeout eviction via ManualClock.
|
||||
Void::Testing::expect_eq(pool.stats().idle_connections, std::size_t{2});
|
||||
Void::Testing::require(clock.advance(std::chrono::seconds{11}).has_value());
|
||||
Void::Testing::expect_eq(pool.evict_expired(), std::size_t{2});
|
||||
Void::Testing::expect_eq(pool.stats().idle_connections, std::size_t{0});
|
||||
|
||||
// Per-origin limit = 2 rejects 3rd simultaneous active lease on k2.
|
||||
auto c1 = pool.acquire(k2, factory);
|
||||
auto c2 = pool.acquire(k2, factory);
|
||||
auto c3 = pool.acquire(k2, factory);
|
||||
Void::Testing::require(c1.has_value());
|
||||
Void::Testing::require(c2.has_value());
|
||||
Void::Testing::expect(!c3.has_value());
|
||||
Void::Testing::expect(c3.error().kind() == Void::Result::ErrorKind::overloaded);
|
||||
|
||||
pool.shutdown();
|
||||
c1->release();
|
||||
c2->release();
|
||||
Void::Testing::expect_eq(pool.stats().total_connections, std::size_t{0});
|
||||
}
|
||||
|
||||
Void::Testing::Test net_static_file_resolver_open_safe_pins_root_and_rejects_symlinks()
|
||||
{
|
||||
Void::FileSystem::TempDir tmp{"void_net_static_"};
|
||||
const auto root = tmp / "www";
|
||||
const auto secret = tmp / "secret.txt";
|
||||
std::filesystem::create_directories(root / "sub");
|
||||
{
|
||||
std::ofstream f{root / "sub" / "index.html"};
|
||||
f << "<h1>hello</h1>";
|
||||
}
|
||||
{
|
||||
std::ofstream f{secret};
|
||||
f << "top-secret";
|
||||
}
|
||||
std::filesystem::create_symlink(secret, root / "escape.txt");
|
||||
|
||||
auto resolver = Void::Net::StaticFileResolver::create(root);
|
||||
Void::Testing::require(resolver.has_value());
|
||||
|
||||
// Directory open resolves index.html beneath pinned descriptor.
|
||||
auto opened = resolver->open_safe("/sub/");
|
||||
Void::Testing::require(opened.has_value());
|
||||
Void::Testing::require(opened->has_value());
|
||||
Void::Testing::expect_eq((*opened)->content_type(),
|
||||
std::string_view{"text/html; charset=utf-8"});
|
||||
auto data = (*opened)->read_all();
|
||||
Void::Testing::require(data.has_value());
|
||||
Void::Testing::expect_eq(*data, std::string{"<h1>hello</h1>"});
|
||||
|
||||
// Missing file returns empty optional (not error).
|
||||
auto missing = resolver->open_safe("/nope.txt");
|
||||
Void::Testing::require(missing.has_value());
|
||||
Void::Testing::expect(!missing->has_value());
|
||||
|
||||
// Symlink inside root is rejected by O_NOFOLLOW.
|
||||
auto sym = resolver->open_safe("/escape.txt");
|
||||
Void::Testing::expect(!sym.has_value());
|
||||
|
||||
// Traversal rejected.
|
||||
auto trav = resolver->open_safe("/../secret.txt");
|
||||
Void::Testing::expect(!trav.has_value());
|
||||
}
|
||||
|
||||
Void::Testing::Test net_http_client_redirects_303_307_and_cross_origin_strip()
|
||||
{
|
||||
Void::Net::HttpServer server1;
|
||||
Void::Net::HttpServer server2;
|
||||
|
||||
std::atomic<bool> got_auth_on_s2{false};
|
||||
Void::Testing::require(
|
||||
server2
|
||||
.add_route(Void::Net::Method::Get, "/landing",
|
||||
[&](const Void::Net::ServerRequest& req)
|
||||
-> Void::Net::RouteResult {
|
||||
if (req.header("Authorization").has_value()) {
|
||||
got_auth_on_s2.store(true);
|
||||
}
|
||||
return Void::Net::ServerResponse{
|
||||
.status = 200, .body = "from-s2"};
|
||||
})
|
||||
.has_value());
|
||||
Void::Testing::require(server2.start().has_value());
|
||||
|
||||
// 303 on POST -> GET to relative location without body.
|
||||
Void::Testing::require(
|
||||
server1
|
||||
.add_route(Void::Net::Method::Post, "/submit",
|
||||
[](const Void::Net::ServerRequest&)
|
||||
-> Void::Net::RouteResult {
|
||||
return Void::Net::ServerResponse{
|
||||
.status = 303,
|
||||
.headers = {{"Location", "/done"}},
|
||||
.body = ""};
|
||||
})
|
||||
.has_value());
|
||||
Void::Testing::require(
|
||||
server1
|
||||
.add_route(Void::Net::Method::Get, "/done",
|
||||
[](const Void::Net::ServerRequest& req)
|
||||
-> Void::Net::RouteResult {
|
||||
return Void::Net::ServerResponse{
|
||||
.status = 200,
|
||||
.body = "get-done:" + req.body};
|
||||
})
|
||||
.has_value());
|
||||
// 307 on POST -> preserves POST + body.
|
||||
Void::Testing::require(
|
||||
server1
|
||||
.add_route(Void::Net::Method::Post, "/temp",
|
||||
[](const Void::Net::ServerRequest&)
|
||||
-> Void::Net::RouteResult {
|
||||
return Void::Net::ServerResponse{
|
||||
.status = 307,
|
||||
.headers = {{"Location", "/temp-dst"}},
|
||||
.body = ""};
|
||||
})
|
||||
.has_value());
|
||||
Void::Testing::require(
|
||||
server1
|
||||
.add_route(Void::Net::Method::Post, "/temp-dst",
|
||||
[](const Void::Net::ServerRequest& req)
|
||||
-> Void::Net::RouteResult {
|
||||
return Void::Net::ServerResponse{
|
||||
.status = 200, .body = "post:" + req.body};
|
||||
})
|
||||
.has_value());
|
||||
// Cross-origin redirect from server1 -> server2.
|
||||
Void::Testing::require(
|
||||
server1
|
||||
.add_route(Void::Net::Method::Get, "/cross",
|
||||
[dst = server2.base_url() + "/landing"](
|
||||
const Void::Net::ServerRequest&)
|
||||
-> Void::Net::RouteResult {
|
||||
return Void::Net::ServerResponse{
|
||||
.status = 302,
|
||||
.headers = {{"Location", dst}},
|
||||
.body = ""};
|
||||
})
|
||||
.has_value());
|
||||
Void::Testing::require(server1.start().has_value());
|
||||
|
||||
Void::Net::HttpClient client;
|
||||
client.set_max_redirects(5);
|
||||
|
||||
auto r303 = client.post(server1.base_url() + "/submit", "payload");
|
||||
Void::Testing::require(r303.has_value());
|
||||
Void::Testing::expect_eq(r303->status, std::uint16_t{200});
|
||||
Void::Testing::expect_eq(r303->body, std::string{"get-done:"});
|
||||
|
||||
auto r307 = client.post(server1.base_url() + "/temp", "keepme");
|
||||
Void::Testing::require(r307.has_value());
|
||||
Void::Testing::expect_eq(r307->status, std::uint16_t{200});
|
||||
Void::Testing::expect_eq(r307->body, std::string{"post:keepme"});
|
||||
|
||||
auto rcross = client.get(server1.base_url() + "/cross",
|
||||
{{"Authorization", "Bearer top-secret"}});
|
||||
Void::Testing::require(rcross.has_value());
|
||||
Void::Testing::expect_eq(rcross->status, std::uint16_t{200});
|
||||
Void::Testing::expect_eq(rcross->body, std::string{"from-s2"});
|
||||
Void::Testing::expect(!got_auth_on_s2.load());
|
||||
|
||||
server1.shutdown();
|
||||
server2.shutdown();
|
||||
}
|
||||
|
||||
Void::Testing::Test net_websocket_rfc6455_codec_and_live_server_roundtrip()
|
||||
{
|
||||
// 1. RFC 6455 §1.3 official Sec-WebSocket-Accept vector.
|
||||
Void::Testing::expect_eq(
|
||||
Void::Net::compute_websocket_accept("dGhlIHNhbXBsZSBub25jZQ=="),
|
||||
std::string{"s3pPLMBiTxaQ9kYGzzhZRbK+xOo="});
|
||||
|
||||
// 2. Decoder enforces client masking & strict UTF-8 on text frames.
|
||||
Void::Net::WebSocketDecoder server_dec{true};
|
||||
Void::Net::WebSocketFrame unmasked;
|
||||
unmasked.opcode = Void::Net::WebSocketOpcode::Text;
|
||||
unmasked.masked = false;
|
||||
auto raw_unmasked = Void::Net::encode_websocket_frame(unmasked);
|
||||
Void::Testing::require(raw_unmasked.has_value());
|
||||
std::vector<Void::Net::WebSocketMessage> msgs;
|
||||
Void::Testing::expect(!server_dec.feed(*raw_unmasked, msgs).has_value());
|
||||
|
||||
Void::Net::WebSocketDecoder bad_utf8_dec{true};
|
||||
Void::Net::WebSocketFrame bad_txt;
|
||||
bad_txt.opcode = Void::Net::WebSocketOpcode::Text;
|
||||
bad_txt.masked = true;
|
||||
bad_txt.mask_key = {std::byte{1}, std::byte{2}, std::byte{3}, std::byte{4}};
|
||||
bad_txt.payload = {std::byte{0xFF}, std::byte{0xFE}};
|
||||
auto raw_bad_txt = Void::Net::encode_websocket_frame(bad_txt);
|
||||
Void::Testing::require(raw_bad_txt.has_value());
|
||||
Void::Testing::expect(!bad_utf8_dec.feed(*raw_bad_txt, msgs).has_value());
|
||||
|
||||
// 3. Live loopback HttpServer WebSocket upgrade + WebSocketClient.
|
||||
Void::Net::WebSocketSessions sessions;
|
||||
std::atomic<int> closed_count{0};
|
||||
sessions.set_events(Void::Net::WebSocketEvents{
|
||||
.opened = {},
|
||||
.text =
|
||||
[](const std::shared_ptr<Void::Net::WebSocketConnection>& conn,
|
||||
std::string_view text) {
|
||||
(void)conn->send_text("echo:" + std::string{text});
|
||||
},
|
||||
.binary =
|
||||
[](const std::shared_ptr<Void::Net::WebSocketConnection>& conn,
|
||||
std::span<const std::byte> data) {
|
||||
(void)conn->send_binary(data);
|
||||
},
|
||||
.closed =
|
||||
[&](Void::Net::WebSocketConnectionId,
|
||||
const Void::Net::WebSocketClose&) {
|
||||
closed_count.fetch_add(1, std::memory_order_relaxed);
|
||||
},
|
||||
.error = {},
|
||||
});
|
||||
|
||||
Void::Net::HttpServer server;
|
||||
Void::Net::WebSocketUpgradeOptions ws_opts;
|
||||
ws_opts.supported_subprotocols = {"void.rpc.v1", "chat"};
|
||||
Void::Testing::require(
|
||||
server.add_websocket_route("/ws/echo", sessions, ws_opts).has_value());
|
||||
Void::Testing::require(server.start().has_value());
|
||||
|
||||
const std::string ws_url =
|
||||
"ws://127.0.0.1:" + std::to_string(server.bound_port()) + "/ws/echo";
|
||||
Void::Net::WebSocketClient::ConnectOptions copts;
|
||||
copts.subprotocol = "void.rpc.v1";
|
||||
auto client = Void::Net::WebSocketClient::connect(ws_url, copts);
|
||||
Void::Testing::require(client.has_value());
|
||||
Void::Testing::require(client->selected_subprotocol().has_value());
|
||||
Void::Testing::expect_eq(*client->selected_subprotocol(),
|
||||
std::string{"void.rpc.v1"});
|
||||
|
||||
// Text round-trip.
|
||||
Void::Testing::require(client->send_text("hello ws").has_value());
|
||||
auto m1 = client->receive();
|
||||
Void::Testing::require(m1.has_value());
|
||||
Void::Testing::expect(m1->opcode == Void::Net::WebSocketOpcode::Text);
|
||||
Void::Testing::expect_eq(std::string{m1->text_view()},
|
||||
std::string{"echo:hello ws"});
|
||||
|
||||
// Fragmented UTF-8 text round-trip (split multi-byte UTF-8 sequence across
|
||||
// frames).
|
||||
const std::array<std::string_view, 3> frags{"frag-", "\xE2\x9C", "\x94!"};
|
||||
Void::Testing::require(client->send_fragmented_text(frags).has_value());
|
||||
auto m2 = client->receive();
|
||||
Void::Testing::require(m2.has_value());
|
||||
Void::Testing::expect_eq(std::string{m2->text_view()},
|
||||
std::string{"echo:frag-\xE2\x9C\x94!"});
|
||||
|
||||
// Binary round-trip.
|
||||
const std::array<std::byte, 4> bin{std::byte{0x00}, std::byte{0xDE},
|
||||
std::byte{0xAD}, std::byte{0xFF}};
|
||||
Void::Testing::require(client->send_binary(bin).has_value());
|
||||
auto m3 = client->receive();
|
||||
Void::Testing::require(m3.has_value());
|
||||
Void::Testing::expect(m3->opcode == Void::Net::WebSocketOpcode::Binary);
|
||||
Void::Testing::expect_eq(m3->payload.size(), std::size_t{4});
|
||||
Void::Testing::expect(m3->payload[1] == std::byte{0xDE});
|
||||
|
||||
// Ping -> automatic server Pong echoing payload.
|
||||
const std::array<std::byte, 3> ping_bytes{std::byte{'p'}, std::byte{'n'},
|
||||
std::byte{'g'}};
|
||||
Void::Testing::require(client->send_ping(ping_bytes).has_value());
|
||||
auto m4 = client->receive();
|
||||
Void::Testing::require(m4.has_value());
|
||||
Void::Testing::expect(m4->opcode == Void::Net::WebSocketOpcode::Pong);
|
||||
Void::Testing::expect_eq(m4->payload.size(), std::size_t{3});
|
||||
|
||||
// Graceful close handshake.
|
||||
Void::Testing::require(client->close({1000, "done"}).has_value());
|
||||
server.shutdown();
|
||||
Void::Testing::expect(closed_count.load() >= 1);
|
||||
}
|
||||
Reference in new issue
Block a user