diff --git a/include/Void/Net/Http.hpp b/include/Void/Net/Http.hpp index 7fe1b30..293c909 100644 --- a/include/Void/Net/Http.hpp +++ b/include/Void/Net/Http.hpp @@ -4,13 +4,79 @@ #include #include +#include #include +#include +#include #include +#include +#include #include +#include +#include #include namespace Void::Net { + enum class NetErrorCode : std::int32_t { + none = 0, + invalid_url = 1, + invalid_argument = 2, + connect_failed = 3, + tls_error = 4, + protocol_error = 5, + timeout = 6, + cancelled = 7, + quota_exceeded = 8, + io_error = 9, + redirect_blocked = 10, + payload_too_large = 11, + headers_too_large = 12 + }; + + [[nodiscard]] inline Void::Result::Error + make_net_error(NetErrorCode code, std::string message = {}, + std::error_code sys_err = {}) + { + using Void::Result::Error; + using Void::Result::ErrorCode; + using Void::Result::ErrorKind; + + ErrorKind kind = ErrorKind::internal; + switch (code) { + case NetErrorCode::none: + kind = ErrorKind::internal; + break; + case NetErrorCode::invalid_url: + case NetErrorCode::invalid_argument: + case NetErrorCode::redirect_blocked: + kind = ErrorKind::invalid_argument; + break; + case NetErrorCode::connect_failed: + case NetErrorCode::io_error: + kind = ErrorKind::io; + break; + case NetErrorCode::tls_error: + case NetErrorCode::protocol_error: + kind = ErrorKind::corrupt; + break; + case NetErrorCode::timeout: + kind = ErrorKind::timeout; + break; + case NetErrorCode::cancelled: + kind = ErrorKind::cancelled; + break; + case NetErrorCode::quota_exceeded: + case NetErrorCode::payload_too_large: + case NetErrorCode::headers_too_large: + kind = ErrorKind::exhausted; + break; + } + return Error{kind, std::move(message), + ErrorCode{Void::Result::kNetErrorDomain, + static_cast(code)}, + sys_err}; + } enum class Method { Get, Post, Put, Delete, Patch, Head, Options }; @@ -62,6 +128,54 @@ namespace Void::Net } }; + struct HttpClientOptions { + ProxyConfig proxy{}; + std::string user_agent{"Void.Net/1.0"}; + bool verify_tls{true}; + std::string ca_file{}; + std::uint64_t max_body_size{64ULL * 1024 * 1024}; + int max_redirects{0}; + bool allow_insecure_redirects{false}; + }; + + struct TransferProgress { + std::uint64_t bytes_transferred{0}; + std::optional total_bytes{}; + }; + + struct DownloadOptions { + std::vector
headers{}; + std::chrono::seconds timeout{30}; + std::uint64_t max_bytes{0}; + std::stop_token stop{}; + std::function)> on_chunk{}; + std::function on_progress{}; + }; + + struct DownloadResult { + std::uint16_t status{0}; + std::vector
headers{}; + std::uint64_t bytes_written{0}; + std::chrono::milliseconds elapsed{0}; + + [[nodiscard]] bool ok() const noexcept + { + return status >= 200 && status < 300; + } + [[nodiscard]] std::optional + header(std::string_view name) const; + }; + + struct UploadOptions { + Method method{Method::Put}; + std::vector
headers{}; + std::string content_type{"application/octet-stream"}; + std::chrono::seconds timeout{30}; + std::uint64_t max_upload_bytes{0}; + std::stop_token stop{}; + std::function on_progress{}; + }; + /// Synchronous HTTP/HTTPS client built on Boost.Beast/Asio + OpenSSL. /// Supports direct connections, HTTP-CONNECT and SOCKS5 proxies, and TLS. /// Generic: no application-specific defaults beyond a configurable @@ -73,6 +187,12 @@ namespace Void::Net HttpClient() = default; explicit HttpClient(ProxyConfig proxy) : m_proxy(std::move(proxy)) {} + explicit HttpClient(HttpClientOptions options); + + /// Preset with TLS peer & hostname certificate verification enabled + /// by default (`verify_tls = true`). + [[nodiscard]] static HttpClient + secure(ProxyConfig proxy = {}); void set_proxy(ProxyConfig proxy) { m_proxy = std::move(proxy); } [[nodiscard]] const ProxyConfig& proxy() const noexcept @@ -83,9 +203,33 @@ namespace Void::Net /// Default User-Agent applied when a request sets none. void set_user_agent(std::string ua) { m_user_agent = std::move(ua); } - /// Verify TLS peer certificates (default: false, matching common - /// scraping/proxy use; enable for security-sensitive callers). + /// Verify TLS peer certificates (default constructor keeps `false` + /// for 1.x compatibility; `HttpClient::secure()` defaults `true`). void set_verify_tls(bool on) noexcept { m_verify_tls = on; } + [[nodiscard]] bool verify_tls() const noexcept + { + return m_verify_tls; + } + + /// Optional custom PEM CA bundle/certificate file used when + /// `verify_tls` is enabled. + void set_ca_file(std::string ca_file) + { + m_ca_file = std::move(ca_file); + } + [[nodiscard]] const std::string& ca_file() const noexcept + { + return m_ca_file; + } + + void set_allow_insecure_redirects(bool allow) noexcept + { + m_allow_insecure_redirects = allow; + } + [[nodiscard]] bool allow_insecure_redirects() const noexcept + { + return m_allow_insecure_redirects; + } /// Maximum response body size in bytes. 0 means unlimited. Default /// is 64 MiB (Beast's own default of ~1 MiB is too small for binary @@ -100,12 +244,34 @@ namespace Void::Net /// header). Opt-in so callers that inspect redirects keep working. void set_max_redirects(int n) noexcept { m_max_redirects = n; } + /// Format request method, scrubbed URL, and headers for logs while + /// redacting `Authorization`, `Proxy-Authorization`, `Cookie`, and + /// `X-Api-Key`. + [[nodiscard]] static std::string + format_request_diagnostics(const Request& req); + /// Execute a request. A per-request `Request::proxy` is not modelled; /// the client-level proxy applies. Returns an Error only on transport /// failure — a non-2xx HTTP response is a successful Result. [[nodiscard]] Void::Result::Result send(const Request& req) const; + /// Stream response body directly to `destination` without buffering + /// the full payload in memory, enforcing `options.max_bytes` and + /// `options.stop` cancellation. + [[nodiscard]] Void::Result::Result + download_to_file(std::string_view url, + const std::filesystem::path& destination, + const DownloadOptions& options = {}) const; + + /// Stream a regular file directly as the HTTP request body without + /// buffering the full file in memory. + [[nodiscard]] Void::Result::Result + upload_file(std::string_view url, + const std::filesystem::path& source_path, + const UploadOptions& options = {}) const; + // Convenience wrappers. [[nodiscard]] Void::Result::Result get(std::string_view url, @@ -113,14 +279,28 @@ namespace Void::Net [[nodiscard]] Void::Result::Result post(std::string_view url, std::string body, std::vector
headers = {}) const; + [[nodiscard]] Void::Result::Result + put_file(std::string_view url, + const std::filesystem::path& source_path, + std::vector
headers = {}, + std::string content_type = + "application/octet-stream") const; + [[nodiscard]] Void::Result::Result + post_file(std::string_view url, + const std::filesystem::path& source_path, + std::vector
headers = {}, + std::string content_type = + "application/octet-stream") const; private: ProxyConfig m_proxy{}; std::string m_user_agent = "Void.Net/1.0"; bool m_verify_tls = false; + std::string m_ca_file{}; std::uint64_t m_max_body = 64ull * 1024 * 1024; int m_max_redirects = 0; + bool m_allow_insecure_redirects = false; }; } // namespace Void::Net diff --git a/include/Void/Net/HttpServer.hpp b/include/Void/Net/HttpServer.hpp new file mode 100644 index 0000000..e97c43d --- /dev/null +++ b/include/Void/Net/HttpServer.hpp @@ -0,0 +1,108 @@ +#pragma once + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Void::Net +{ + struct HttpServerOptions { + std::string bind_host{"127.0.0.1"}; + std::uint16_t port{0}; + std::size_t max_header_bytes{64ULL * 1024}; + std::size_t max_headers{128}; + std::uint64_t max_body_bytes{16ULL * 1024 * 1024}; + std::uint64_t max_streaming_body_bytes{512ULL * 1024 * 1024}; + std::size_t max_concurrent_connections{64}; + std::chrono::milliseconds read_timeout{std::chrono::seconds{30}}; + std::chrono::milliseconds write_timeout{std::chrono::seconds{30}}; + int listen_backlog{128}; + }; + + /// Streaming request body reader passed to streaming HTTP route handlers. + class BodyReader + { + public: + + struct State; + + explicit BodyReader(State& state) noexcept : m_state(&state) {} + BodyReader(const BodyReader&) = delete; + BodyReader& operator=(const BodyReader&) = delete; + + [[nodiscard]] std::optional + content_length() const noexcept; + [[nodiscard]] bool is_chunked() const noexcept; + [[nodiscard]] std::uint64_t bytes_read() const noexcept; + + /// Read up to dst.size() decoded body bytes. Returns 0 at EOF. + [[nodiscard]] Void::Result::Result + read_some(std::span dst); + + /// Stream the request body atomically to `destination`, enforcing + /// `max_bytes` (or server max_streaming_body_bytes when 0). + [[nodiscard]] Void::Result::Result + read_to_file(const std::filesystem::path& destination, + std::uint64_t max_bytes = 0); + + private: + + State* m_state{nullptr}; + }; + + using StreamingRouteHandler = + std::function; + + /// Concrete POSIX TCP HTTP/1.1 listener dispatching buffered routes through + /// `Void::Net::Router` and streaming routes via `BodyReader`. + class HttpServer + { + public: + + explicit HttpServer(HttpServerOptions options = {}); + explicit HttpServer(Router& external_router, + HttpServerOptions options = {}); + ~HttpServer() noexcept; + + HttpServer(HttpServer&&) noexcept; + HttpServer& operator=(HttpServer&&) noexcept; + HttpServer(const HttpServer&) = delete; + HttpServer& operator=(const HttpServer&) = delete; + + [[nodiscard]] Router& router() noexcept; + + [[nodiscard]] Void::Result::Result + add_route(Method method, std::string pattern, + RouteHandler handler); + + [[nodiscard]] Void::Result::Result + add_streaming_route(Method method, std::string pattern, + StreamingRouteHandler handler); + + [[nodiscard]] Void::Result::Result start(); + + void shutdown(std::chrono::milliseconds drain_timeout = + std::chrono::seconds{5}) noexcept; + + [[nodiscard]] bool running() const noexcept; + [[nodiscard]] std::uint16_t bound_port() const noexcept; + [[nodiscard]] std::string bind_address() const; + [[nodiscard]] std::string base_url() const; + + private: + + struct Impl; + std::unique_ptr m_impl; + }; + +} // namespace Void::Net diff --git a/include/Void/Net/Server.hpp b/include/Void/Net/Server.hpp index 7120b30..993f3aa 100644 --- a/include/Void/Net/Server.hpp +++ b/include/Void/Net/Server.hpp @@ -30,6 +30,7 @@ namespace Void::Net std::vector
headers; std::string body; RouteParameters parameters; + std::string query{}; [[nodiscard]] std::optional header(std::string_view name) const noexcept; @@ -39,6 +40,12 @@ namespace Void::Net std::uint16_t status{200}; std::vector
headers; std::string body; + std::optional file_body{}; + + [[nodiscard]] static ServerResponse + from_file(std::filesystem::path path, + std::string content_type = {}, + std::uint16_t status = 200); [[nodiscard]] std::optional header(std::string_view name) const noexcept; @@ -67,6 +74,9 @@ namespace Void::Net [[nodiscard]] Void::Result::Result> dispatch(ServerRequest request) const; + [[nodiscard]] std::vector + allowed_methods(std::string_view path) const; + [[nodiscard]] std::size_t size() const; private: diff --git a/src/Net/Http.cpp b/src/Net/Http.cpp index 84134c7..2ce3345 100644 --- a/src/Net/Http.cpp +++ b/src/Net/Http.cpp @@ -4,36 +4,48 @@ #include #include +#include #include #include #include #include #include #include +#include #include +#include #include +#include #if !defined(_WIN32) +#include #include +#include #include +#include #endif +#include +#include +#include #include +#include #include #include #include +#include #include #include #include #include #include +#include #include #include namespace Void::Net { - namespace { namespace asio = boost::asio; @@ -42,6 +54,72 @@ namespace Void::Net namespace ssl = boost::asio::ssl; using tcp = boost::asio::ip::tcp; + std::atomic g_dl_temp_seq{0}; + + [[nodiscard]] bool + equal_ascii_ci(std::string_view a, std::string_view b) noexcept + { + return a.size() == b.size() && + std::ranges::equal(a, b, [](char x, char y) { + return std::tolower(static_cast(x)) == + std::tolower(static_cast(y)); + }); + } + + [[nodiscard]] bool is_sensitive_header(std::string_view name) noexcept + { + return equal_ascii_ci(name, "Authorization") || + equal_ascii_ci(name, "Proxy-Authorization") || + equal_ascii_ci(name, "Cookie") || + equal_ascii_ci(name, "Set-Cookie") || + equal_ascii_ci(name, "X-Api-Key"); + } + + [[nodiscard]] std::optional + find_header_ci(const std::vector
& headers, + std::string_view name) noexcept + { + for (const auto& h : headers) { + if (equal_ascii_ci(h.name, name)) { + return h.value; + } + } + return std::nullopt; + } + + [[nodiscard]] std::string sanitize_url_for_log(std::string_view raw) + { + const std::size_t scheme_end = raw.find("://"); + if (scheme_end == std::string_view::npos) { + return std::string{raw}; + } + const std::size_t auth_start = scheme_end + 3U; + const std::size_t slash = raw.find('/', auth_start); + const std::size_t at = raw.find('@', auth_start); + if (at != std::string_view::npos && + (slash == std::string_view::npos || at < slash)) { + std::string out{raw.substr(0, auth_start)}; + out += "@"; + out += raw.substr(at + 1U); + return out; + } + return std::string{raw}; + } + + [[nodiscard]] std::string_view method_to_str(Method m) noexcept + { + switch (m) { + case Method::Get: return "GET"; + case Method::Post: return "POST"; + case Method::Put: return "PUT"; + case Method::Delete: return "DELETE"; + case Method::Patch: return "PATCH"; + case Method::Head: return "HEAD"; + case Method::Options: return "OPTIONS"; + } + return "GET"; + } + [[nodiscard]] http::verb to_verb(Method m) { switch (m) { @@ -56,38 +134,76 @@ namespace Void::Net return http::verb::get; } - // Build the Beast request for an origin-form target (direct / tunnelled). - http::request - build_request(const Url& url, const Request& req, - std::string_view default_ua, std::string_view target) + [[nodiscard]] bool same_origin(const Url& a, const Url& b) noexcept { - http::request r{to_verb(req.method), - std::string{target}, 11}; - r.set(http::field::host, url.host); + return equal_ascii_ci(a.scheme, b.scheme) && + equal_ascii_ci(a.host, b.host) && a.port == b.port; + } + + void strip_sensitive_headers(std::vector
& headers) + { + std::erase_if(headers, [](const Header& h) { + return is_sensitive_header(h.name); + }); + } + + template + void populate_common_headers(RequestMsg& rq, const Url& url, + const std::vector
& headers, + std::string_view default_ua) + { + const bool std_port = + (url.is_tls && url.port == "443") || + (!url.is_tls && url.port == "80") || url.port.empty(); + if (std_port) { + rq.set(http::field::host, url.host); + } else { + rq.set(http::field::host, url.host + ":" + url.port); + } bool has_ua = false; - for (const auto& h : req.headers) { - r.set(h.name, h.value); - if (!has_ua && h.name == "User-Agent") has_ua = true; + for (const auto& h : headers) { + rq.set(h.name, h.value); + if (!has_ua && equal_ascii_ci(h.name, "User-Agent")) { + has_ua = true; + } } if (!has_ua) { - r.set(http::field::user_agent, std::string{default_ua}); + rq.set(http::field::user_agent, std::string{default_ua}); } - if (req.body) { - r.body() = *req.body; + } + + http::request + build_request(const Url& url, Method method, + const std::vector
& headers, + const std::optional& body, + std::string_view default_ua, std::string_view target) + { + http::request r{to_verb(method), + std::string{target}, 11}; + populate_common_headers(r, url, headers, default_ua); + if (body) { + r.body() = *body; r.prepare_payload(); } return r; } + std::vector
extract_headers(const http::fields& fields) + { + std::vector
out; + for (const auto& f : fields) { + out.push_back( + {std::string{f.name_string()}, std::string{f.value()}}); + } + return out; + } + Response convert(const http::response& src) { Response out; out.status = static_cast(src.result_int()); out.body = beast::buffers_to_string(src.body().data()); - for (const auto& f : src.base()) { - out.headers.push_back( - {std::string{f.name_string()}, std::string{f.value()}}); - } + out.headers = extract_headers(src.base()); return out; } @@ -97,10 +213,10 @@ namespace Void::Net { http::write(stream, rq); beast::flat_buffer buffer; - // Use a parser so the body limit is configurable. Beast's default - // (~1 MiB) is too small for binary downloads (release artifacts); - // max_body == 0 means unlimited. http::response_parser parser; + if (rq.method() == http::verb::head) { + parser.skip(true); + } parser.body_limit(max_body == 0 ? std::numeric_limits::max() : max_body); @@ -108,7 +224,6 @@ namespace Void::Net return convert(parser.get()); } - // SOCKS5 CONNECT handshake on an already-connected socket. void socks5_connect(tcp::socket& socket, const Url& url, const ProxyConfig& proxy) { @@ -131,9 +246,11 @@ namespace Void::Net } std::vector a{0x01}; a.push_back(static_cast(proxy.username->size())); - a.insert(a.end(), proxy.username->begin(), proxy.username->end()); + a.insert(a.end(), proxy.username->begin(), + proxy.username->end()); a.push_back(static_cast(proxy.password->size())); - a.insert(a.end(), proxy.password->begin(), proxy.password->end()); + a.insert(a.end(), proxy.password->begin(), + proxy.password->end()); asio::write(socket, asio::buffer(a)); std::vector ar(2); asio::read(socket, asio::buffer(ar)); @@ -175,7 +292,6 @@ namespace Void::Net throw std::runtime_error(std::format( "SOCKS5: connect failed (code {})", int(cres[1]))); } - // Drain the bound address. switch (cres[3]) { case 0x01: { std::vector b(6); @@ -198,7 +314,6 @@ namespace Void::Net } } - // HTTP CONNECT tunnel for TLS targets on a connected proxy socket. void http_connect_tunnel(tcp::socket& socket, const Url& url, const ProxyConfig& proxy) { @@ -213,10 +328,6 @@ namespace Void::Net } http::write(socket, creq); beast::flat_buffer buffer; - // A 2xx CONNECT reply has no body; the socket then becomes a raw - // tunnel. Some proxies attach a body to non-2xx replies, which an - // empty_body reader rejects ("unexpected body") before we can even - // read the status. skip(true) + read_header reads only the headers. http::response_parser cparser; cparser.skip(true); http::read_header(socket, buffer, cparser); @@ -227,35 +338,109 @@ namespace Void::Net } } - void tls_handshake(ssl::stream& stream, const Url& url) + struct TlsError : std::runtime_error { + using std::runtime_error::runtime_error; + }; + + struct QuotaError : std::runtime_error { + using std::runtime_error::runtime_error; + }; + + struct CancelledError : std::runtime_error { + using std::runtime_error::runtime_error; + }; + + ssl::context make_ssl_context(bool verify_tls, + const std::string& ca_file) { - if (!SSL_set_tlsext_host_name(stream.native_handle(), - url.host.c_str())) { - throw std::runtime_error("TLS: failed to set SNI host"); + ssl::context ctx{ssl::context::tls_client}; + (void)SSL_CTX_set_min_proto_version(ctx.native_handle(), + TLS1_2_VERSION); + if (verify_tls) { + if (!ca_file.empty()) { + boost::system::error_code ec; + ctx.load_verify_file(ca_file, ec); + if (ec) { + throw TlsError(std::format( + "TLS: failed to load CA file '{}': {}", ca_file, + ec.message())); + } + } else { + ctx.set_default_verify_paths(); + } + ctx.set_verify_mode(ssl::verify_peer | + ssl::verify_fail_if_no_peer_cert); + } else { + ctx.set_verify_mode(ssl::verify_none); + } + return ctx; + } + + void tls_handshake(ssl::stream& stream, const Url& url, + bool verify_tls) + { + std::string clean_host = url.host; + if (clean_host.size() >= 2 && clean_host.front() == '[' && + clean_host.back() == ']') { + clean_host = clean_host.substr(1, clean_host.size() - 2); + } + boost::system::error_code ip_ec; + (void)asio::ip::make_address(clean_host, ip_ec); + const bool is_ip = !ip_ec; + + if (!is_ip && + !SSL_set_tlsext_host_name(stream.native_handle(), + clean_host.c_str())) { + throw TlsError("TLS: failed to set SNI hostname"); + } + if (verify_tls) { + X509_VERIFY_PARAM* param = SSL_get0_param(stream.native_handle()); + if (param == nullptr) { + throw TlsError("TLS: X509_VERIFY_PARAM unavailable"); + } + if (is_ip) { + if (X509_VERIFY_PARAM_set1_ip_asc( + param, clean_host.c_str()) != 1) { + throw TlsError( + "TLS: failed to set peer IP verification target"); + } + } else { + X509_VERIFY_PARAM_set_hostflags( + param, X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS); + if (X509_VERIFY_PARAM_set1_host(param, clean_host.c_str(), + clean_host.size()) != 1) { + throw TlsError( + "TLS: failed to set peer hostname verification"); + } + } + } + + boost::system::error_code hs_ec; + stream.handshake(ssl::stream_base::client, hs_ec); + if (hs_ec) { + throw TlsError(std::format("TLS handshake failed: {}", + hs_ec.message())); } - stream.handshake(ssl::stream_base::client); } - // Bounds every sync operation on an open socket with the request - // timeout. Asio's synchronous ops cannot be bounded any other way - // short of going fully async: SO_RCVTIMEO merely makes recv return - // EAGAIN, which the sync emulation treats as would-block and then - // poll()s without a deadline. On expiry the watchdog ::shutdown()s - // the descriptor — shutdown (unlike close) is safe against a - // concurrent blocked op and wakes it with EOF, so the op fails and - // the request errors out instead of hanging the calling thread - // forever. The descriptor must stay open for the guard's lifetime - // (declare the guard after the connected socket, in the same scope). - // Name resolution and connect() are not covered (kernel defaults). class DeadlineGuard { public: DeadlineGuard(tcp::socket& socket, - std::chrono::seconds timeout) + std::chrono::seconds timeout, + std::stop_token stop = {}) + : m_stop(std::move(stop)), + m_stop_cb(socket.is_open() ? m_stop : std::stop_token{}, + StopShutdown{ + &m_cancelled, + socket.is_open() + ? socket.native_handle() + : tcp::socket::native_handle_type{}, + socket.is_open()}) { - if (timeout <= std::chrono::seconds::zero() || - !socket.is_open()) { + if (!socket.is_open() || + timeout <= std::chrono::seconds::zero()) { return; } const auto fd = socket.native_handle(); @@ -268,7 +453,7 @@ namespace Void::Net #else ::shutdown(fd, SHUT_RDWR); #endif - m_timed_out = true; + m_timed_out.store(true, std::memory_order_release); } }); } @@ -291,60 +476,378 @@ namespace Void::Net [[nodiscard]] bool timed_out() const noexcept { - return m_timed_out; + return m_timed_out.load(std::memory_order_acquire); + } + [[nodiscard]] bool cancelled() const noexcept + { + return m_cancelled.load(std::memory_order_acquire); } private: + struct StopShutdown { + std::atomic* cancelled{nullptr}; + tcp::socket::native_handle_type fd{}; + bool has_fd{false}; + + void operator()() const noexcept + { + if (cancelled != nullptr) { + cancelled->store(true, + std::memory_order_release); + } + if (has_fd) { +#if defined(_WIN32) + ::shutdown(fd, SD_BOTH); +#else + ::shutdown(fd, SHUT_RDWR); +#endif + } + } + }; + std::thread m_worker; std::mutex m_mutex; std::condition_variable m_cv; bool m_done{false}; - bool m_timed_out{false}; + std::atomic m_timed_out{false}; + std::atomic m_cancelled{false}; + std::stop_token m_stop{}; + std::stop_callback m_stop_cb; }; - // Perform the request over an already-connected plain socket, doing a - // TLS upgrade in place when the target is https. The TLS stream is an - // out-parameter declared in the caller's scope so the descriptor - // outlives the caller's DeadlineGuard (declaration order there is - // socket, stream, guard — the guard is destroyed first). Response finish(tcp::socket& socket, std::optional>& tls, - ssl::context& ctx, const Url& url, const Request& req, - std::string_view ua, std::uint64_t max_body) + ssl::context& ctx, const Url& url, Method method, + const std::vector
& headers, + const std::optional& body, + std::string_view ua, std::uint64_t max_body, + bool verify_tls) { if (url.is_tls) { tls.emplace(std::move(socket), ctx); - tls_handshake(*tls, url); - auto rq = build_request(url, req, ua, url.target); + tls_handshake(*tls, url, verify_tls); + auto rq = + build_request(url, method, headers, body, ua, url.target); return write_read(*tls, rq, max_body); } - auto rq = build_request(url, req, ua, url.target); + auto rq = build_request(url, method, headers, body, ua, url.target); return write_read(socket, rq, max_body); } - } // namespace - std::optional - Response::header(std::string_view name) const - { - for (const auto& h : headers) { - if (h.name.size() == name.size()) { - bool eq = true; - for (std::size_t i = 0; i < name.size(); ++i) { - const char a = static_cast(std::tolower(h.name[i])); - const char b = static_cast(std::tolower(name[i])); - if (a != b) { eq = false; break; } + class OwnedTempFile + { + public: + + static Void::Result::Result + create(const std::filesystem::path& destination) + { + std::filesystem::path parent = destination.parent_path(); + if (parent.empty()) { + parent = "."; + } + std::error_code ec; + std::filesystem::create_directories(parent, ec); + if (ec) { + return std::unexpected{make_net_error( + NetErrorCode::io_error, + std::format("Net: create_directories failed: {}", + ec.message()), + ec)}; + } + const std::filesystem::path tmp_path = + parent / std::format(".void-dl-{}-{}", + static_cast(::getpid()), + g_dl_temp_seq.fetch_add( + 1, std::memory_order_relaxed)); + const int fd = ::open( + tmp_path.c_str(), + O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC | O_NOFOLLOW, + 0644); + if (fd < 0) { + return std::unexpected{make_net_error( + NetErrorCode::io_error, + std::format("Net: create temp download file failed: " + "{}", + std::strerror(errno)), + std::error_code{errno, std::generic_category()})}; + } + return OwnedTempFile{fd, tmp_path, destination}; } - if (eq) return h.value; - } - } - return std::nullopt; - } - namespace - { - // Resolve a redirect Location against the URL it came from. Handles - // absolute URLs and host-relative ("/path") and bare-relative targets. + OwnedTempFile(OwnedTempFile&& o) noexcept + : m_fd(std::exchange(o.m_fd, -1)), + m_tmp(std::move(o.m_tmp)), + m_dest(std::move(o.m_dest)), + m_committed(std::exchange(o.m_committed, true)) + { + } + OwnedTempFile& operator=(OwnedTempFile&&) = delete; + OwnedTempFile(const OwnedTempFile&) = delete; + OwnedTempFile& operator=(const OwnedTempFile&) = delete; + + ~OwnedTempFile() noexcept { discard(); } + + [[nodiscard]] Void::Result::Result + write_all(std::span data) + { + std::size_t off = 0; + while (off < data.size()) { + const ssize_t w = ::write( + m_fd, + reinterpret_cast(data.data()) + off, + data.size() - off); + if (w < 0 && errno == EINTR) { + continue; + } + if (w <= 0) { + return std::unexpected{make_net_error( + NetErrorCode::io_error, + std::format("Net: write download file failed: " + "{}", + std::strerror(errno)), + std::error_code{errno, + std::generic_category()})}; + } + off += static_cast(w); + } + return {}; + } + + [[nodiscard]] Void::Result::Result commit() + { + if (::fsync(m_fd) != 0) { + return std::unexpected{make_net_error( + NetErrorCode::io_error, + std::format("Net: fsync download file failed: {}", + std::strerror(errno)), + std::error_code{errno, std::generic_category()})}; + } + const int raw = std::exchange(m_fd, -1); + if (::close(raw) != 0) { + discard(); + return std::unexpected{make_net_error( + NetErrorCode::io_error, + std::format("Net: close download file failed: {}", + std::strerror(errno)), + std::error_code{errno, std::generic_category()})}; + } + std::error_code ec; + std::filesystem::rename(m_tmp, m_dest, ec); + if (ec) { + discard(); + return std::unexpected{make_net_error( + NetErrorCode::io_error, + std::format("Net: rename download file failed: {}", + ec.message()), + ec)}; + } + m_committed = true; + return {}; + } + + void discard() noexcept + { + if (m_fd >= 0) { + (void)::close(m_fd); + m_fd = -1; + } + if (!m_committed && !m_tmp.empty()) { + std::error_code ec; + std::filesystem::remove(m_tmp, ec); + } + m_committed = true; + } + + private: + + OwnedTempFile(int fd, std::filesystem::path tmp, + std::filesystem::path dest) + : m_fd(fd), m_tmp(std::move(tmp)), m_dest(std::move(dest)) + { + } + + int m_fd{-1}; + std::filesystem::path m_tmp{}; + std::filesystem::path m_dest{}; + bool m_committed{false}; + }; + + template + DownloadResult read_stream_to_file( + Stream& stream, const Url& url, const std::vector
& headers, + std::string_view ua, std::string_view target, + const std::filesystem::path& destination, + const DownloadOptions& options) + { + auto rq = build_request(url, Method::Get, headers, std::nullopt, ua, + target); + http::write(stream, rq); + + beast::flat_buffer rx_buf; + http::response_parser parser; + parser.body_limit(std::numeric_limits::max()); + http::read_header(stream, rx_buf, parser); + + const auto status = + static_cast(parser.get().result_int()); + auto resp_headers = extract_headers(parser.get().base()); + const auto boost_cl = parser.content_length(); + const std::optional declared_total = + boost_cl.has_value() + ? std::optional{*boost_cl} + : std::nullopt; + + if (options.max_bytes > 0 && declared_total.has_value() && + *declared_total > options.max_bytes) { + throw QuotaError(std::format( + "Net: Content-Length {} exceeds max_bytes quota {}", + *declared_total, options.max_bytes)); + } + + auto tmp = OwnedTempFile::create(destination); + if (!tmp.has_value()) { + throw std::runtime_error(tmp.error().message()); + } + + std::vector chunk(64ULL * 1024U); + std::uint64_t total_written = 0; + while (!parser.is_done()) { + if (options.stop.stop_requested()) { + throw CancelledError("Net: download cancelled"); + } + parser.get().body().data = chunk.data(); + parser.get().body().size = chunk.size(); + beast::error_code ec; + (void)http::read_some(stream, rx_buf, parser, ec); + const bool eof_ok = + (ec == http::error::end_of_stream && + !declared_total.has_value()); + if (ec && ec != http::error::need_buffer && !eof_ok) { + throw boost::system::system_error{ec}; + } + const std::size_t got = + chunk.size() - parser.get().body().size; + if (got > 0) { + const auto amt = static_cast(got); + if (options.max_bytes > 0 && + amt > options.max_bytes - total_written) { + throw QuotaError(std::format( + "Net: download exceeded max_bytes quota {}", + options.max_bytes)); + } + const auto slice = + std::span{chunk.data(), got}; + if (auto wr = tmp->write_all(slice); !wr.has_value()) { + throw std::runtime_error(wr.error().message()); + } + total_written += amt; + if (options.on_chunk) { + options.on_chunk(slice); + } + if (options.on_progress) { + options.on_progress(TransferProgress{ + .bytes_transferred = total_written, + .total_bytes = declared_total}); + } + } + if (eof_ok) { + break; + } + } + + if (auto cm = tmp->commit(); !cm.has_value()) { + throw std::runtime_error(cm.error().message()); + } + + return DownloadResult{ + .status = status, + .headers = std::move(resp_headers), + .bytes_written = total_written, + .elapsed = {}, + }; + } + + template + Response stream_file_request(Stream& stream, const Url& url, + std::string_view target, int file_fd, + std::uint64_t file_size, + const UploadOptions& options, + std::string_view default_ua, + std::uint64_t max_response_body) + { + http::request rq{to_verb(options.method), + std::string{target}, 11}; + populate_common_headers(rq, url, options.headers, default_ua); + if (!find_header_ci(options.headers, "Content-Type").has_value() && + !options.content_type.empty()) { + rq.set(http::field::content_type, options.content_type); + } + rq.content_length(file_size); + rq.body().data = nullptr; + rq.body().size = 0; + rq.body().more = (file_size > 0); + + http::request_serializer sr{rq}; + http::write_header(stream, sr); + + if (file_size > 0) { + std::array buf{}; + std::uint64_t sent_total = 0; + while (sent_total < file_size) { + if (options.stop.stop_requested()) { + throw CancelledError("Net: upload cancelled"); + } + const std::size_t want = static_cast( + std::min(buf.size(), + file_size - sent_total)); + const ssize_t r = ::read(file_fd, buf.data(), want); + if (r < 0 && errno == EINTR) { + continue; + } + if (r <= 0) { + throw std::runtime_error( + "Net: source file shrunk or read failed during " + "upload"); + } + const auto amt = static_cast(r); + rq.body().data = buf.data(); + rq.body().size = static_cast(r); + rq.body().more = (sent_total + amt < file_size); + + beast::error_code ec; + (void)http::write(stream, sr, ec); + if (ec == http::error::need_buffer) { + ec = {}; + } + if (ec) { + throw boost::system::system_error{ec}; + } + sent_total += amt; + if (options.on_progress) { + options.on_progress(TransferProgress{ + .bytes_transferred = sent_total, + .total_bytes = file_size}); + } + } + } else { + beast::error_code ec; + (void)http::write(stream, sr, ec); + if (ec && ec != http::error::need_buffer) { + throw boost::system::system_error{ec}; + } + } + + beast::flat_buffer rx_buf; + http::response_parser parser; + parser.body_limit( + max_response_body == 0 + ? std::numeric_limits::max() + : max_response_body); + http::read(stream, rx_buf, parser); + return convert(parser.get()); + } + std::string resolve_redirect(const Url& base, std::string_view location) { if (location.starts_with("http://") || @@ -366,33 +869,75 @@ namespace Void::Net } } // namespace + std::optional + Response::header(std::string_view name) const + { + return find_header_ci(headers, name); + } + + std::optional + DownloadResult::header(std::string_view name) const + { + return find_header_ci(headers, name); + } + + HttpClient::HttpClient(HttpClientOptions options) + : m_proxy(std::move(options.proxy)), + m_user_agent(std::move(options.user_agent)), + m_verify_tls(options.verify_tls), + m_ca_file(std::move(options.ca_file)), + m_max_body(options.max_body_size), + m_max_redirects(options.max_redirects), + m_allow_insecure_redirects(options.allow_insecure_redirects) + { + } + + HttpClient HttpClient::secure(ProxyConfig proxy) + { + return HttpClient{HttpClientOptions{ + .proxy = std::move(proxy), + .verify_tls = true, + }}; + } + + std::string HttpClient::format_request_diagnostics(const Request& req) + { + std::string out = std::format("{} {}", method_to_str(req.method), + sanitize_url_for_log(req.url)); + for (const auto& h : req.headers) { + out += "\n "; + out += h.name; + out += ": "; + out += is_sensitive_header(h.name) ? "" : h.value; + } + return out; + } + Void::Result::Result HttpClient::send(const Request& req) const { std::string target_url = req.url; + std::vector
active_headers = req.headers; int redirects = 0; while (true) { const auto url = Url::parse(target_url); if (!url) { - return Void::Result::fail( - std::format("Net: invalid URL '{}'", target_url)); + return std::unexpected{make_net_error( + NetErrorCode::invalid_url, + std::format("Net: invalid URL '{}'", + sanitize_url_for_log(target_url)))}; } + bool cancelled = false; + bool timed_out = false; try { const auto start = std::chrono::steady_clock::now(); asio::io_context ioc; - ssl::context ctx{ssl::context::tlsv12_client}; - ctx.set_default_verify_paths(); - ctx.set_verify_mode(m_verify_tls ? ssl::verify_peer - : ssl::verify_none); + ssl::context ctx = make_ssl_context(m_verify_tls, m_ca_file); Response response; tcp::resolver resolver{ioc}; - - // Declaration order matters: the DeadlineGuard must be - // destroyed (and its watchdog joined) BEFORE the objects - // that own the descriptor it may shut down. tcp::socket socket{ioc}; std::optional> tls; @@ -403,42 +948,70 @@ namespace Void::Net DeadlineGuard deadline{socket, req.timeout}; if (m_proxy.kind == ProxyConfig::Kind::Socks5) { socks5_connect(socket, *url, m_proxy); - response = finish(socket, tls, ctx, *url, req, - m_user_agent, m_max_body); - } else { // Http proxy + response = finish(socket, tls, ctx, *url, req.method, + active_headers, req.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, - m_user_agent, m_max_body); + response = finish(socket, tls, ctx, *url, + req.method, active_headers, + req.body, m_user_agent, + m_max_body, m_verify_tls); } else { - // Plain HTTP through proxy: absolute-form target. const std::string absolute = std::format( "{}://{}{}", url->scheme, url->host, url->target); - auto rq = build_request(*url, req, m_user_agent, - absolute); + auto rq = build_request(*url, req.method, + active_headers, req.body, + m_user_agent, absolute); if (m_proxy.has_auth()) { const auto enc = Void::Encoding::Base64::encode( - *m_proxy.username + ":" + *m_proxy.password); + *m_proxy.username + ":" + + *m_proxy.password); rq.set(http::field::proxy_authorization, "Basic " + enc); } response = write_read(socket, rq, m_max_body); } } + timed_out = deadline.timed_out(); + cancelled = deadline.cancelled(); } else { asio::connect(socket, resolver.resolve(url->host, url->port)); DeadlineGuard deadline{socket, req.timeout}; - response = finish(socket, tls, ctx, *url, req, - m_user_agent, m_max_body); + response = + finish(socket, tls, ctx, *url, req.method, + active_headers, req.body, m_user_agent, + m_max_body, m_verify_tls); + timed_out = deadline.timed_out(); + cancelled = deadline.cancelled(); } - // Transparently follow redirects when enabled. if (m_max_redirects > 0 && response.status >= 300 && response.status < 400 && redirects < m_max_redirects) { if (auto loc = response.header("location")) { - target_url = resolve_redirect(*url, *loc); + const std::string next_url = + resolve_redirect(*url, *loc); + const auto next_parsed = Url::parse(next_url); + if (!next_parsed) { + return std::unexpected{make_net_error( + NetErrorCode::invalid_url, + "Net: invalid redirect Location URL")}; + } + if (url->is_tls && !next_parsed->is_tls && + m_verify_tls && !m_allow_insecure_redirects) { + return std::unexpected{make_net_error( + NetErrorCode::redirect_blocked, + "Net: blocked HTTPS to HTTP downgrade " + "redirect")}; + } + if (!same_origin(*url, *next_parsed)) { + strip_sensitive_headers(active_headers); + } + target_url = next_url; ++redirects; continue; } @@ -448,14 +1021,316 @@ namespace Void::Net std::chrono::duration_cast( std::chrono::steady_clock::now() - start); return response; + } catch (const TlsError& e) { + return std::unexpected{make_net_error( + NetErrorCode::tls_error, + std::format("Net: TLS request to '{}' failed: {}", + sanitize_url_for_log(target_url), e.what()))}; } catch (const std::exception& e) { - return Void::Result::fail( - std::format("Net: request to '{}' failed: {}", target_url, - e.what())); + if (cancelled) { + return std::unexpected{make_net_error( + NetErrorCode::cancelled, + std::format("Net: request to '{}' cancelled", + sanitize_url_for_log(target_url)))}; + } + if (timed_out) { + return std::unexpected{make_net_error( + NetErrorCode::timeout, + std::format("Net: request to '{}' timed out: {}", + sanitize_url_for_log(target_url), + e.what()))}; + } + return std::unexpected{make_net_error( + NetErrorCode::connect_failed, + std::format("Net: request to '{}' failed: {}", + sanitize_url_for_log(target_url), e.what()))}; } } } + Void::Result::Result + HttpClient::download_to_file(std::string_view url_str, + const std::filesystem::path& destination, + const DownloadOptions& options) const + { + if (options.stop.stop_requested()) { + return std::unexpected{make_net_error( + NetErrorCode::cancelled, "Net: download cancelled")}; + } + std::string target_url{url_str}; + std::vector
active_headers = options.headers; + int redirects = 0; + + while (true) { + if (options.stop.stop_requested()) { + return std::unexpected{make_net_error( + NetErrorCode::cancelled, "Net: download cancelled")}; + } + const auto url = Url::parse(target_url); + if (!url) { + return std::unexpected{make_net_error( + NetErrorCode::invalid_url, + std::format("Net: invalid URL '{}'", + sanitize_url_for_log(target_url)))}; + } + bool timed_out = false; + bool cancelled = 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); + tcp::resolver resolver{ioc}; + tcp::socket socket{ioc}; + std::optional> tls; + + if (m_proxy.enabled()) { + asio::connect(socket, resolver.resolve( + m_proxy.host, + std::to_string(m_proxy.port))); + } else { + asio::connect(socket, + resolver.resolve(url->host, url->port)); + } + + DeadlineGuard deadline{socket, options.timeout, options.stop}; + DownloadResult result; + const auto finish_stream = [&]() { + if (m_proxy.enabled()) { + if (m_proxy.kind == ProxyConfig::Kind::Socks5) { + socks5_connect(socket, *url, m_proxy); + } else if (url->is_tls) { + http_connect_tunnel(socket, *url, m_proxy); + } else { + const std::string absolute = std::format( + "{}://{}{}", url->scheme, url->host, + url->target); + auto h = active_headers; + if (m_proxy.has_auth()) { + const auto enc = Void::Encoding::Base64::encode( + *m_proxy.username + ":" + + *m_proxy.password); + h.push_back(Header{"Proxy-Authorization", + "Basic " + enc}); + } + result = read_stream_to_file( + socket, *url, h, m_user_agent, absolute, + destination, options); + return; + } + } + if (url->is_tls) { + tls.emplace(std::move(socket), ctx); + tls_handshake(*tls, *url, m_verify_tls); + result = read_stream_to_file( + *tls, *url, active_headers, m_user_agent, + url->target, destination, options); + } else { + result = read_stream_to_file( + socket, *url, active_headers, m_user_agent, + url->target, destination, options); + } + }; + finish_stream(); + timed_out = deadline.timed_out(); + cancelled = deadline.cancelled(); + + if (m_max_redirects > 0 && result.status >= 300 && + result.status < 400 && redirects < m_max_redirects) { + if (auto loc = result.header("location")) { + const std::string next_url = + resolve_redirect(*url, *loc); + const auto next_parsed = Url::parse(next_url); + if (!next_parsed) { + return std::unexpected{make_net_error( + NetErrorCode::invalid_url, + "Net: invalid redirect Location URL")}; + } + if (url->is_tls && !next_parsed->is_tls && + m_verify_tls && !m_allow_insecure_redirects) { + return std::unexpected{make_net_error( + NetErrorCode::redirect_blocked, + "Net: blocked HTTPS to HTTP downgrade " + "redirect")}; + } + if (!same_origin(*url, *next_parsed)) { + strip_sensitive_headers(active_headers); + } + std::error_code rm_ec; + std::filesystem::remove(destination, rm_ec); + target_url = next_url; + ++redirects; + continue; + } + } + + result.elapsed = + std::chrono::duration_cast( + std::chrono::steady_clock::now() - start); + return result; + } catch (const QuotaError& e) { + return std::unexpected{ + make_net_error(NetErrorCode::quota_exceeded, e.what())}; + } catch (const CancelledError& e) { + return std::unexpected{ + make_net_error(NetErrorCode::cancelled, e.what())}; + } catch (const TlsError& e) { + return std::unexpected{make_net_error( + NetErrorCode::tls_error, + std::format("Net: TLS download '{}' failed: {}", + sanitize_url_for_log(target_url), e.what()))}; + } catch (const std::exception& e) { + if (cancelled || options.stop.stop_requested()) { + return std::unexpected{make_net_error( + NetErrorCode::cancelled, "Net: download cancelled")}; + } + if (timed_out) { + return std::unexpected{make_net_error( + NetErrorCode::timeout, + std::format("Net: download '{}' timed out: {}", + sanitize_url_for_log(target_url), + e.what()))}; + } + return std::unexpected{make_net_error( + NetErrorCode::io_error, + std::format("Net: download '{}' failed: {}", + sanitize_url_for_log(target_url), e.what()))}; + } + } + } + + Void::Result::Result + HttpClient::upload_file(std::string_view url_str, + const std::filesystem::path& source_path, + const UploadOptions& options) const + { + if (options.stop.stop_requested()) { + return std::unexpected{ + make_net_error(NetErrorCode::cancelled, "Net: upload cancelled")}; + } + const int raw_fd = + ::open(source_path.c_str(), O_RDONLY | O_CLOEXEC); + if (raw_fd < 0) { + return std::unexpected{make_net_error( + NetErrorCode::io_error, + std::format("Net: cannot open upload file '{}': {}", + source_path.string(), std::strerror(errno)), + std::error_code{errno, std::generic_category()})}; + } + struct FdClose { + int fd; + ~FdClose() noexcept + { + if (fd >= 0) (void)::close(fd); + } + } fd_guard{raw_fd}; + + struct stat st{}; + if (::fstat(raw_fd, &st) != 0 || !S_ISREG(st.st_mode)) { + return std::unexpected{make_net_error( + NetErrorCode::invalid_argument, + std::format("Net: upload source '{}' is not a regular file", + source_path.string()))}; + } + const auto file_size = static_cast(st.st_size); + if (options.max_upload_bytes > 0 && + file_size > options.max_upload_bytes) { + return std::unexpected{make_net_error( + NetErrorCode::quota_exceeded, + std::format("Net: upload file size {} exceeds limit {}", + file_size, options.max_upload_bytes))}; + } + + const auto url = Url::parse(url_str); + if (!url) { + return std::unexpected{make_net_error( + NetErrorCode::invalid_url, + std::format("Net: invalid URL '{}'", + sanitize_url_for_log(url_str)))}; + } + + bool timed_out = false; + bool cancelled = 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); + tcp::resolver resolver{ioc}; + tcp::socket socket{ioc}; + std::optional> tls; + + if (m_proxy.enabled()) { + asio::connect(socket, + resolver.resolve(m_proxy.host, + std::to_string(m_proxy.port))); + } else { + asio::connect(socket, resolver.resolve(url->host, url->port)); + } + + DeadlineGuard deadline{socket, options.timeout, options.stop}; + Response response; + if (m_proxy.enabled()) { + if (m_proxy.kind == ProxyConfig::Kind::Socks5) { + socks5_connect(socket, *url, m_proxy); + } else if (url->is_tls) { + http_connect_tunnel(socket, *url, m_proxy); + } else { + const std::string absolute = std::format( + "{}://{}{}", url->scheme, url->host, url->target); + response = stream_file_request( + socket, *url, absolute, raw_fd, file_size, options, + m_user_agent, m_max_body); + timed_out = deadline.timed_out(); + cancelled = deadline.cancelled(); + response.elapsed = + std::chrono::duration_cast( + std::chrono::steady_clock::now() - start); + return response; + } + } + + if (url->is_tls) { + tls.emplace(std::move(socket), ctx); + tls_handshake(*tls, *url, m_verify_tls); + response = stream_file_request( + *tls, *url, url->target, raw_fd, file_size, options, + m_user_agent, m_max_body); + } else { + response = stream_file_request( + socket, *url, url->target, raw_fd, file_size, options, + m_user_agent, m_max_body); + } + timed_out = deadline.timed_out(); + cancelled = deadline.cancelled(); + response.elapsed = + std::chrono::duration_cast( + std::chrono::steady_clock::now() - start); + return response; + } catch (const CancelledError& e) { + return std::unexpected{ + make_net_error(NetErrorCode::cancelled, e.what())}; + } catch (const TlsError& e) { + return std::unexpected{make_net_error( + NetErrorCode::tls_error, + std::format("Net: TLS upload '{}' failed: {}", + sanitize_url_for_log(url_str), e.what()))}; + } catch (const std::exception& e) { + if (cancelled || options.stop.stop_requested()) { + return std::unexpected{make_net_error( + NetErrorCode::cancelled, "Net: upload cancelled")}; + } + if (timed_out) { + return std::unexpected{make_net_error( + NetErrorCode::timeout, + std::format("Net: upload '{}' timed out: {}", + sanitize_url_for_log(url_str), e.what()))}; + } + return std::unexpected{make_net_error( + NetErrorCode::io_error, + std::format("Net: upload '{}' failed: {}", + sanitize_url_for_log(url_str), e.what()))}; + } + } + Void::Result::Result HttpClient::get(std::string_view url, std::vector
headers) const { @@ -478,4 +1353,30 @@ namespace Void::Net return send(r); } + Void::Result::Result + HttpClient::put_file(std::string_view url, + const std::filesystem::path& source_path, + std::vector
headers, + std::string content_type) const + { + UploadOptions opts; + opts.method = Method::Put; + opts.headers = std::move(headers); + opts.content_type = std::move(content_type); + return upload_file(url, source_path, opts); + } + + Void::Result::Result + HttpClient::post_file(std::string_view url, + const std::filesystem::path& source_path, + std::vector
headers, + std::string content_type) const + { + UploadOptions opts; + opts.method = Method::Post; + opts.headers = std::move(headers); + opts.content_type = std::move(content_type); + return upload_file(url, source_path, opts); + } + } // namespace Void::Net diff --git a/src/Net/HttpServer.cpp b/src/Net/HttpServer.cpp new file mode 100644 index 0000000..5fb219d --- /dev/null +++ b/src/Net/HttpServer.cpp @@ -0,0 +1,1837 @@ +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Void::Net +{ + namespace + { + std::atomic g_temp_upload_seq{0}; + + [[nodiscard]] bool + equal_ascii_ci(std::string_view a, std::string_view b) noexcept + { + return a.size() == b.size() && + std::ranges::equal(a, b, [](char x, char y) { + return std::tolower(static_cast(x)) == + std::tolower(static_cast(y)); + }); + } + + [[nodiscard]] bool + contains_ascii_ci(std::string_view haystack, + std::string_view needle) noexcept + { + if (needle.empty() || needle.size() > haystack.size()) { + return false; + } + for (std::size_t i = 0; i + needle.size() <= haystack.size(); ++i) { + if (equal_ascii_ci(haystack.substr(i, needle.size()), needle)) { + return true; + } + } + return false; + } + + [[nodiscard]] std::string_view trim_ows(std::string_view s) noexcept + { + while (!s.empty() && (s.front() == ' ' || s.front() == '\t')) { + s.remove_prefix(1); + } + while (!s.empty() && (s.back() == ' ' || s.back() == '\t')) { + s.remove_suffix(1); + } + return s; + } + + [[nodiscard]] std::optional + parse_method(std::string_view token) noexcept + { + if (token == "GET") return Method::Get; + if (token == "HEAD") return Method::Head; + if (token == "POST") return Method::Post; + if (token == "PUT") return Method::Put; + if (token == "DELETE") return Method::Delete; + if (token == "PATCH") return Method::Patch; + if (token == "OPTIONS") return Method::Options; + return std::nullopt; + } + + [[nodiscard]] std::string_view method_string(Method m) noexcept + { + switch (m) { + case Method::Get: return "GET"; + case Method::Head: return "HEAD"; + case Method::Post: return "POST"; + case Method::Put: return "PUT"; + case Method::Delete: return "DELETE"; + case Method::Patch: return "PATCH"; + case Method::Options: return "OPTIONS"; + } + return "GET"; + } + + [[nodiscard]] std::string_view reason_phrase(std::uint16_t code) noexcept + { + switch (code) { + case 100: return "Continue"; + case 200: return "OK"; + case 201: return "Created"; + case 204: return "No Content"; + case 301: return "Moved Permanently"; + case 302: return "Found"; + case 304: return "Not Modified"; + case 400: return "Bad Request"; + case 401: return "Unauthorized"; + case 403: return "Forbidden"; + case 404: return "Not Found"; + case 405: return "Method Not Allowed"; + case 408: return "Request Timeout"; + case 413: return "Payload Too Large"; + case 415: return "Unsupported Media Type"; + case 431: return "Request Header Fields Too Large"; + case 500: return "Internal Server Error"; + case 501: return "Not Implemented"; + case 503: return "Service Unavailable"; + default: return "OK"; + } + } + + [[nodiscard]] bool has_crlf_or_nul(std::string_view s) noexcept + { + for (const unsigned char ch : s) { + if (ch == '\r' || ch == '\n' || ch == '\0') { + return true; + } + } + return false; + } + + [[nodiscard]] bool is_valid_token(std::string_view s) noexcept + { + if (s.empty()) { + return false; + } + for (const unsigned char ch : s) { + if (ch <= 0x20 || ch >= 0x7F || ch == ':' || ch == '(' || + ch == ')' || ch == '<' || ch == '>' || ch == '@' || + ch == ',' || ch == ';' || ch == '\\' || ch == '"' || + ch == '/' || ch == '[' || ch == ']' || ch == '?' || + ch == '=' || ch == '{' || ch == '}') { + return false; + } + } + return true; + } + + [[nodiscard]] bool parse_u64_decimal(std::string_view s, + std::uint64_t& out) noexcept + { + if (s.empty()) { + return false; + } + for (const unsigned char ch : s) { + if (ch < '0' || ch > '9') { + return false; + } + } + const auto res = std::from_chars(s.data(), s.data() + s.size(), out); + return res.ec == std::errc{} && res.ptr == s.data() + s.size(); + } + + [[nodiscard]] std::vector split_path(std::string_view path) + { + std::vector segments; + std::size_t begin = path.starts_with('/') ? 1 : 0; + while (begin < path.size()) { + const auto end = path.find('/', begin); + const auto segment = path.substr(begin, end - begin); + if (!segment.empty()) { + segments.emplace_back(segment); + } + if (end == std::string_view::npos) { + break; + } + begin = end + 1; + } + return segments; + } + + [[nodiscard]] bool valid_param_name(std::string_view name) noexcept + { + return !name.empty() && std::ranges::all_of(name, [](char v) { + const auto c = static_cast(v); + return std::isalnum(c) != 0 || v == '_'; + }); + } + + [[nodiscard]] Void::Result::Result> + compile_route_pattern(std::string_view pattern) + { + if (pattern.empty() || !pattern.starts_with('/') || + pattern.find_first_of("?#") != std::string_view::npos) { + return std::unexpected{make_net_error( + NetErrorCode::invalid_argument, + "Net::HttpServer: route patterns must be absolute paths")}; + } + auto segments = split_path(pattern); + std::set> names; + for (std::size_t i = 0; i < segments.size(); ++i) { + const auto& seg = segments[i]; + if (!seg.starts_with(':') && !seg.starts_with('*')) { + continue; + } + const auto name = std::string_view{seg}.substr(1); + if (!valid_param_name(name) || !names.emplace(name).second || + (seg.starts_with('*') && i + 1 != segments.size())) { + return std::unexpected{make_net_error( + NetErrorCode::invalid_argument, + "Net::HttpServer: invalid streaming route pattern")}; + } + } + return segments; + } + + [[nodiscard]] std::optional + match_segments(const std::vector& pattern, + const std::vector& path) + { + RouteParameters params; + std::size_t pi = 0; + for (const auto& seg : pattern) { + if (seg.starts_with('*')) { + std::string val; + for (; pi < path.size(); ++pi) { + if (!val.empty()) { + val.push_back('/'); + } + val += path[pi]; + } + params.emplace(seg.substr(1), std::move(val)); + return params; + } + if (pi >= path.size()) { + return std::nullopt; + } + if (seg.starts_with(':')) { + params.emplace(seg.substr(1), path[pi]); + } else if (seg != path[pi]) { + return std::nullopt; + } + ++pi; + } + if (pi != path.size()) { + return std::nullopt; + } + return params; + } + + [[nodiscard]] int segment_rank(std::string_view s) noexcept + { + if (s.starts_with('*')) return 0; + if (s.starts_with(':')) return 1; + return 2; + } + + [[nodiscard]] bool + more_specific_route(const std::vector& cand, + const std::vector& cur) noexcept + { + const std::size_t n = std::min(cand.size(), cur.size()); + for (std::size_t i = 0; i < n; ++i) { + const int cr = segment_rank(cand[i]); + const int br = segment_rank(cur[i]); + if (cr != br) { + return cr > br; + } + } + return cand.size() > cur.size(); + } + + [[nodiscard]] bool + same_route_shape(const std::vector& lhs, + const std::vector& rhs) noexcept + { + if (lhs.size() != rhs.size()) { + return false; + } + for (std::size_t i = 0; i < lhs.size(); ++i) { + const int lr = segment_rank(lhs[i]); + const int rr = segment_rank(rhs[i]); + if (lr != rr || (lr == 2 && lhs[i] != rhs[i])) { + return false; + } + } + return true; + } + + class OwnedFd + { + public: + + explicit OwnedFd(int fd = -1) noexcept : m_fd(fd) {} + ~OwnedFd() noexcept { reset(); } + OwnedFd(OwnedFd&& other) noexcept + : m_fd(std::exchange(other.m_fd, -1)) + { + } + OwnedFd& operator=(OwnedFd&& other) noexcept + { + if (this != &other) { + reset(std::exchange(other.m_fd, -1)); + } + return *this; + } + OwnedFd(const OwnedFd&) = delete; + OwnedFd& operator=(const OwnedFd&) = delete; + + [[nodiscard]] int get() const noexcept { return m_fd; } + [[nodiscard]] explicit operator bool() const noexcept + { + return m_fd >= 0; + } + [[nodiscard]] int release() noexcept + { + return std::exchange(m_fd, -1); + } + void reset(int fd = -1) noexcept + { + if (m_fd >= 0) { + (void)::close(m_fd); + } + m_fd = fd; + } + + private: + + int m_fd{-1}; + }; + + [[nodiscard]] Void::Result::Result + recv_slice(int fd, std::span dst, + const std::atomic& stopping, + std::chrono::milliseconds timeout) + { + const auto deadline = std::chrono::steady_clock::now() + timeout; + for (;;) { + if (stopping.load(std::memory_order_acquire)) { + return std::unexpected{make_net_error( + NetErrorCode::cancelled, + "Net::HttpServer: server shutting down")}; + } + const auto now = std::chrono::steady_clock::now(); + if (timeout > std::chrono::milliseconds::zero() && + now >= deadline) { + return std::unexpected{make_net_error( + NetErrorCode::timeout, "Net::HttpServer: read timeout")}; + } + int wait_ms = 50; + if (timeout > std::chrono::milliseconds::zero()) { + const auto rem = std::chrono::duration_cast< + std::chrono::milliseconds>(deadline - now) + .count(); + wait_ms = static_cast(std::clamp(rem, 1, 50)); + } + + struct pollfd pfd{}; + pfd.fd = fd; + pfd.events = POLLIN; + const int pr = ::poll(&pfd, 1, wait_ms); + if (pr < 0) { + if (errno == EINTR) { + continue; + } + return std::unexpected{make_net_error( + NetErrorCode::io_error, + std::format("Net::HttpServer: poll failed: {}", + std::strerror(errno)), + std::error_code{errno, std::generic_category()})}; + } + if (pr == 0) { + continue; + } + const ssize_t n = ::recv(fd, dst.data(), dst.size(), 0); + if (n < 0) { + if (errno == EINTR || errno == EAGAIN || + errno == EWOULDBLOCK) { + continue; + } + return std::unexpected{make_net_error( + NetErrorCode::io_error, + std::format("Net::HttpServer: recv failed: {}", + std::strerror(errno)), + std::error_code{errno, std::generic_category()})}; + } + return static_cast(n); + } + } + + [[nodiscard]] Void::Result::Result + send_all(int fd, std::span data, + std::chrono::milliseconds timeout) + { + std::size_t off = 0; + const auto deadline = std::chrono::steady_clock::now() + timeout; + while (off < data.size()) { + const auto now = std::chrono::steady_clock::now(); + if (timeout > std::chrono::milliseconds::zero() && + now >= deadline) { + return std::unexpected{make_net_error( + NetErrorCode::timeout, + "Net::HttpServer: write timeout")}; + } + int wait_ms = 100; + if (timeout > std::chrono::milliseconds::zero()) { + const auto rem = std::chrono::duration_cast< + std::chrono::milliseconds>(deadline - now) + .count(); + wait_ms = + static_cast(std::clamp(rem, 1, 100)); + } + + struct pollfd pfd{}; + pfd.fd = fd; + pfd.events = POLLOUT; + const int pr = ::poll(&pfd, 1, wait_ms); + if (pr < 0) { + if (errno == EINTR) { + continue; + } + return std::unexpected{make_net_error( + NetErrorCode::io_error, "Net::HttpServer: send poll failed")}; + } + if (pr == 0) { + continue; + } + const ssize_t n = ::send( + fd, + reinterpret_cast(data.data()) + off, + data.size() - off, MSG_NOSIGNAL); + if (n < 0) { + if (errno == EINTR || errno == EAGAIN || + errno == EWOULDBLOCK) { + continue; + } + return std::unexpected{make_net_error( + NetErrorCode::io_error, + std::format("Net::HttpServer: send failed: {}", + std::strerror(errno)), + std::error_code{errno, std::generic_category()})}; + } + if (n == 0) { + return std::unexpected{make_net_error( + NetErrorCode::io_error, + "Net::HttpServer: peer closed socket on send")}; + } + off += static_cast(n); + } + return {}; + } + + [[nodiscard]] Void::Result::Result + send_str(int fd, std::string_view s, + std::chrono::milliseconds timeout) + { + return send_all(fd, + std::as_bytes(std::span{s.data(), s.size()}), + timeout); + } + } // namespace + + struct BodyReader::State { + int fd{-1}; + const std::atomic* stopping{nullptr}; + std::chrono::milliseconds read_timeout{}; + std::uint64_t default_max_bytes{0}; + std::string* rx_buf{nullptr}; + std::size_t* rx_off{nullptr}; + + bool chunked{false}; + std::optional declared_length{}; + std::uint64_t total_read{0}; + std::uint64_t remaining_fixed{0}; + bool eof{false}; + + enum class ChunkPhase { + Header, + Data, + AfterDataCrlf, + Trailers, + Done + }; + ChunkPhase chunk_phase{ChunkPhase::Header}; + std::uint64_t chunk_remaining{0}; + + void consume_rx(std::size_t n) noexcept + { + *rx_off += n; + if (*rx_off >= rx_buf->size()) { + rx_buf->clear(); + *rx_off = 0; + } else if (*rx_off > 64ULL * 1024U) { + rx_buf->erase(0, *rx_off); + *rx_off = 0; + } + } + + [[nodiscard]] Void::Result::Result fill_rx() + { + if (*rx_off < rx_buf->size()) { + return true; + } + rx_buf->clear(); + *rx_off = 0; + std::array tmp{}; + auto n = recv_slice(fd, tmp, *stopping, read_timeout); + if (!n.has_value()) { + return std::unexpected{std::move(n.error())}; + } + if (*n == 0) { + return false; + } + rx_buf->append(tmp.data(), *n); + return true; + } + + [[nodiscard]] Void::Result::Result read_line_crlf( + std::size_t max_len = 8192) + { + for (;;) { + const std::size_t pos = rx_buf->find("\r\n", *rx_off); + if (pos != std::string::npos) { + const std::size_t line_len = pos - *rx_off; + if (line_len > max_len) { + return std::unexpected{make_net_error( + NetErrorCode::protocol_error, + "Net::HttpServer: chunk header line too long")}; + } + std::string line = rx_buf->substr(*rx_off, line_len); + consume_rx(line_len + 2U); + return line; + } + if (rx_buf->size() - *rx_off > max_len) { + return std::unexpected{make_net_error( + NetErrorCode::protocol_error, + "Net::HttpServer: chunk line exceeds limit")}; + } + rx_buf->erase(0, *rx_off); + *rx_off = 0; + std::array tmp{}; + auto n = recv_slice(fd, tmp, *stopping, read_timeout); + if (!n.has_value()) { + return std::unexpected{std::move(n.error())}; + } + if (*n == 0) { + return std::unexpected{make_net_error( + NetErrorCode::protocol_error, + "Net::HttpServer: unexpected EOF in chunked body")}; + } + rx_buf->append(tmp.data(), *n); + } + } + }; + + std::optional BodyReader::content_length() const noexcept + { + return m_state ? m_state->declared_length : std::nullopt; + } + + bool BodyReader::is_chunked() const noexcept + { + return m_state != nullptr && m_state->chunked; + } + + std::uint64_t BodyReader::bytes_read() const noexcept + { + return m_state ? m_state->total_read : 0; + } + + Void::Result::Result + BodyReader::read_some(std::span dst) + { + if (m_state == nullptr || m_state->eof) { + return std::size_t{0}; + } + if (dst.empty()) { + return std::size_t{0}; + } + + if (!m_state->chunked) { + if (m_state->remaining_fixed == 0) { + m_state->eof = true; + return std::size_t{0}; + } + const std::size_t avail = + m_state->rx_buf->size() - *m_state->rx_off; + if (avail > 0) { + const std::size_t take = static_cast( + std::min( + std::min(dst.size(), avail), m_state->remaining_fixed)); + std::memcpy(dst.data(), + m_state->rx_buf->data() + *m_state->rx_off, take); + m_state->consume_rx(take); + m_state->remaining_fixed -= take; + m_state->total_read += take; + if (m_state->remaining_fixed == 0) { + m_state->eof = true; + } + return take; + } + const std::size_t want = static_cast( + std::min(dst.size(), m_state->remaining_fixed)); + auto r = recv_slice( + m_state->fd, + std::span{reinterpret_cast(dst.data()), want}, + *m_state->stopping, m_state->read_timeout); + if (!r.has_value()) { + return std::unexpected{std::move(r.error())}; + } + if (*r == 0) { + return std::unexpected{make_net_error( + NetErrorCode::protocol_error, + "Net::HttpServer: unexpected EOF before Content-Length")}; + } + m_state->remaining_fixed -= *r; + m_state->total_read += *r; + if (m_state->remaining_fixed == 0) { + m_state->eof = true; + } + return *r; + } + + for (;;) { + switch (m_state->chunk_phase) { + case State::ChunkPhase::Header: { + auto line = m_state->read_line_crlf(); + if (!line.has_value()) { + return std::unexpected{std::move(line.error())}; + } + const std::size_t semi = line->find(';'); + std::string_view hex_part = + semi == std::string::npos + ? std::string_view{*line} + : std::string_view{*line}.substr(0, semi); + hex_part = trim_ows(hex_part); + if (hex_part.empty()) { + return std::unexpected{make_net_error( + NetErrorCode::protocol_error, + "Net::HttpServer: empty chunk size")}; + } + std::uint64_t csize = 0; + const auto res = std::from_chars( + hex_part.data(), hex_part.data() + hex_part.size(), + csize, 16); + if (res.ec != std::errc{} || + res.ptr != hex_part.data() + hex_part.size()) { + return std::unexpected{make_net_error( + NetErrorCode::protocol_error, + "Net::HttpServer: invalid chunk size")}; + } + m_state->chunk_remaining = csize; + if (csize == 0) { + m_state->chunk_phase = State::ChunkPhase::Trailers; + } else { + m_state->chunk_phase = State::ChunkPhase::Data; + } + break; + } + case State::ChunkPhase::Data: { + const std::size_t avail = + m_state->rx_buf->size() - *m_state->rx_off; + std::size_t got = 0; + if (avail > 0) { + got = static_cast(std::min( + std::min(dst.size(), avail), + m_state->chunk_remaining)); + std::memcpy(dst.data(), + m_state->rx_buf->data() + *m_state->rx_off, + got); + m_state->consume_rx(got); + } else { + const std::size_t want = static_cast( + std::min(dst.size(), + m_state->chunk_remaining)); + auto r = recv_slice( + m_state->fd, + std::span{ + reinterpret_cast(dst.data()), want}, + *m_state->stopping, m_state->read_timeout); + if (!r.has_value()) { + return std::unexpected{std::move(r.error())}; + } + if (*r == 0) { + return std::unexpected{make_net_error( + NetErrorCode::protocol_error, + "Net::HttpServer: unexpected EOF in chunk data")}; + } + got = *r; + } + m_state->chunk_remaining -= got; + m_state->total_read += got; + if (m_state->chunk_remaining == 0) { + m_state->chunk_phase = State::ChunkPhase::AfterDataCrlf; + } + return got; + } + case State::ChunkPhase::AfterDataCrlf: { + auto line = m_state->read_line_crlf(16); + if (!line.has_value()) { + return std::unexpected{std::move(line.error())}; + } + if (!line->empty()) { + return std::unexpected{make_net_error( + NetErrorCode::protocol_error, + "Net::HttpServer: expected CRLF after chunk")}; + } + m_state->chunk_phase = State::ChunkPhase::Header; + break; + } + case State::ChunkPhase::Trailers: { + for (;;) { + auto line = m_state->read_line_crlf(); + if (!line.has_value()) { + return std::unexpected{std::move(line.error())}; + } + if (line->empty()) { + m_state->chunk_phase = State::ChunkPhase::Done; + m_state->eof = true; + return std::size_t{0}; + } + } + } + case State::ChunkPhase::Done: + m_state->eof = true; + return std::size_t{0}; + } + } + } + + Void::Result::Result + BodyReader::read_to_file(const std::filesystem::path& destination, + std::uint64_t max_bytes) + { + if (m_state == nullptr) { + return std::unexpected{make_net_error( + NetErrorCode::invalid_argument, + "Net::BodyReader::read_to_file: invalid reader state")}; + } + + std::uint64_t effective_limit = max_bytes; + if (effective_limit == 0) { + effective_limit = m_state->default_max_bytes; + } else if (m_state->default_max_bytes > 0) { + effective_limit = + std::min(effective_limit, m_state->default_max_bytes); + } + + if (effective_limit > 0 && m_state->declared_length.has_value() && + *m_state->declared_length > effective_limit) { + return std::unexpected{make_net_error( + NetErrorCode::payload_too_large, + "Net::BodyReader::read_to_file: declared body exceeds limit")}; + } + + std::filesystem::path parent = destination.parent_path(); + if (parent.empty()) { + parent = "."; + } + std::error_code ec; + std::filesystem::create_directories(parent, ec); + if (ec) { + return std::unexpected{make_net_error( + NetErrorCode::io_error, + std::format("Net::BodyReader: create_directories failed: {}", + ec.message()), + ec)}; + } + + const std::filesystem::path tmp_path = + parent / std::format(".void-upload-{}-{}", + static_cast(::getpid()), + g_temp_upload_seq.fetch_add( + 1, std::memory_order_relaxed)); + OwnedFd out_fd{::open(tmp_path.c_str(), + O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC | + O_NOFOLLOW, + 0644)}; + if (!out_fd) { + return std::unexpected{make_net_error( + NetErrorCode::io_error, + std::format("Net::BodyReader: cannot create temp file: {}", + std::strerror(errno)), + std::error_code{errno, std::generic_category()})}; + } + + auto fail_cleanup = [&](Void::Result::Error err) + -> Void::Result::Result { + out_fd.reset(); + std::error_code rm_ec; + std::filesystem::remove(tmp_path, rm_ec); + return std::unexpected{std::move(err)}; + }; + + std::array buf{}; + std::uint64_t written_total = 0; + for (;;) { + auto n = read_some(buf); + if (!n.has_value()) { + return fail_cleanup(std::move(n.error())); + } + if (*n == 0) { + break; + } + const auto amt = static_cast(*n); + if (effective_limit > 0 && amt > effective_limit - written_total) { + return fail_cleanup(make_net_error( + NetErrorCode::payload_too_large, + "Net::BodyReader::read_to_file: streaming body exceeds " + "limit")); + } + std::size_t off = 0; + while (off < *n) { + const ssize_t w = ::write( + out_fd.get(), + reinterpret_cast(buf.data()) + off, + *n - off); + if (w < 0 && errno == EINTR) { + continue; + } + if (w <= 0) { + return fail_cleanup(make_net_error( + NetErrorCode::io_error, + std::format("Net::BodyReader: write temp file failed: " + "{}", + std::strerror(errno)), + std::error_code{errno, std::generic_category()})); + } + off += static_cast(w); + } + written_total += amt; + } + + if (::fsync(out_fd.get()) != 0) { + return fail_cleanup(make_net_error( + NetErrorCode::io_error, + std::format("Net::BodyReader: fsync failed: {}", + std::strerror(errno)), + std::error_code{errno, std::generic_category()})); + } + const int raw = out_fd.release(); + if (::close(raw) != 0) { + return fail_cleanup(make_net_error( + NetErrorCode::io_error, + std::format("Net::BodyReader: close failed: {}", + std::strerror(errno)), + std::error_code{errno, std::generic_category()})); + } + + std::filesystem::rename(tmp_path, destination, ec); + if (ec) { + std::error_code rm_ec; + std::filesystem::remove(tmp_path, rm_ec); + return std::unexpected{make_net_error( + NetErrorCode::io_error, + std::format("Net::BodyReader: rename failed: {}", ec.message()), + ec)}; + } + return written_total; + } + + namespace + { + struct StreamingRoute { + Method method; + std::string pattern; + std::vector segments; + StreamingRouteHandler handler; + }; + + struct WorkerEntry { + std::uint64_t id{0}; + std::atomic client_fd{-1}; + std::atomic finished{false}; + std::thread thread{}; + }; + } // namespace + + struct HttpServer::Impl { + HttpServerOptions options{}; + std::optional owned_router{}; + Router* router{nullptr}; + + mutable std::shared_mutex stream_mutex{}; + std::vector streaming_routes{}; + + std::atomic running{false}; + std::atomic stopping{false}; + int listen_fd{-1}; + int wake_fd{-1}; + std::uint16_t bound_port{0}; + std::string bind_addr_str{}; + std::thread accept_thread{}; + + std::mutex workers_mutex{}; + std::condition_variable workers_cv{}; + std::uint64_t next_worker_id{0}; + std::map> workers{}; + + ~Impl() noexcept { shutdown(std::chrono::seconds{5}); } + + void reap_finished_workers() + { + std::vector to_join; + { + std::lock_guard lock{workers_mutex}; + for (auto it = workers.begin(); it != workers.end();) { + if (it->second->finished.load( + std::memory_order_acquire)) { + if (it->second->thread.joinable()) { + to_join.push_back(std::move(it->second->thread)); + } + it = workers.erase(it); + } else { + ++it; + } + } + } + for (auto& t : to_join) { + t.join(); + } + } + + [[nodiscard]] std::optional< + std::pair> + match_streaming(Method m, std::string_view path_view) const + { + const auto segments = split_path(path_view); + std::shared_lock lock{stream_mutex}; + const StreamingRoute* best = nullptr; + RouteParameters best_params; + for (const auto& r : streaming_routes) { + if (r.method != m) { + continue; + } + auto matched = match_segments(r.segments, segments); + if (!matched.has_value()) { + continue; + } + if (best == nullptr || + more_specific_route(r.segments, best->segments)) { + best = &r; + best_params = std::move(*matched); + } + } + if (best == nullptr) { + return std::nullopt; + } + return std::pair{ + best->handler, std::move(best_params)}; + } + + [[nodiscard]] std::vector + collect_allowed_methods(std::string_view path_view) const + { + std::vector methods = router->allowed_methods(path_view); + const auto segments = split_path(path_view); + { + std::shared_lock lock{stream_mutex}; + for (const auto& r : streaming_routes) { + if (match_segments(r.segments, segments).has_value() && + std::ranges::find(methods, r.method) == + methods.end()) { + methods.push_back(r.method); + } + } + } + return methods; + } + + void send_response(int fd, Method req_method, ServerResponse resp, + bool keep_alive) + { + std::string file_path_err; + OwnedFd file_fd; + std::uint64_t body_len = resp.body.size(); + std::string content_type_default; + + if (resp.file_body.has_value()) { + OwnedFd f{::open(resp.file_body->c_str(), + O_RDONLY | O_CLOEXEC | O_NOFOLLOW)}; + if (!f) { + const std::uint16_t err_status = + errno == ENOENT ? 404 : 500; + resp.file_body.reset(); + resp.status = err_status; + resp.headers.clear(); + resp.body = err_status == 404 ? "Not Found" + : "Internal Server Error"; + body_len = resp.body.size(); + } else { + struct stat st{}; + if (::fstat(f.get(), &st) != 0 || + !S_ISREG(st.st_mode)) { + resp.file_body.reset(); + resp.status = 500; + resp.headers.clear(); + resp.body = "Internal Server Error"; + body_len = resp.body.size(); + } else { + file_fd = std::move(f); + body_len = static_cast(st.st_size); + content_type_default = + std::string{content_type_for(*resp.file_body)}; + } + } + } + + std::string head = std::format( + "HTTP/1.1 {} {}\r\nContent-Length: {}\r\nConnection: " + "{}\r\n", + resp.status, reason_phrase(resp.status), body_len, + keep_alive ? "keep-alive" : "close"); + bool has_ct = false; + for (const auto& h : resp.headers) { + if (has_crlf_or_nul(h.name) || has_crlf_or_nul(h.value) || + !is_valid_token(h.name)) { + continue; + } + if (equal_ascii_ci(h.name, "Content-Length") || + equal_ascii_ci(h.name, "Connection") || + equal_ascii_ci(h.name, "Transfer-Encoding")) { + continue; + } + if (equal_ascii_ci(h.name, "Content-Type")) { + has_ct = true; + } + head += h.name; + head += ": "; + head += h.value; + head += "\r\n"; + } + if (!has_ct && !content_type_default.empty()) { + head += "Content-Type: "; + head += content_type_default; + head += "\r\n"; + } + head += "\r\n"; + + if (!send_str(fd, head, options.write_timeout).has_value()) { + return; + } + if (req_method == Method::Head) { + return; + } + if (file_fd) { + std::array buf{}; + std::uint64_t remaining = body_len; + while (remaining > 0) { + const std::size_t want = static_cast( + std::min(remaining, buf.size())); + const ssize_t r = ::read(file_fd.get(), buf.data(), want); + if (r < 0 && errno == EINTR) { + continue; + } + if (r <= 0) { + return; + } + if (!send_all(fd, + std::span{ + buf.data(), + static_cast(r)}, + options.write_timeout) + .has_value()) { + return; + } + remaining -= static_cast(r); + } + return; + } + if (!resp.body.empty()) { + (void)send_str(fd, resp.body, options.write_timeout); + } + } + + void send_error_close(int fd, std::uint16_t status, + std::string_view msg, + std::vector
extra = {}) + { + ServerResponse r; + r.status = status; + r.headers = std::move(extra); + r.body = std::string{msg}; + send_response(fd, Method::Get, std::move(r), false); + (void)::shutdown(fd, SHUT_WR); + } + + void serve_connection(int raw_fd, WorkerEntry& entry) + { + OwnedFd fd_guard{raw_fd}; + std::string rx_buf; + std::size_t rx_off = 0; + + while (!stopping.load(std::memory_order_acquire)) { + // 1. Read request headers up to \r\n\r\n. + std::size_t hdr_end = std::string::npos; + bool peer_eof = false; + bool hdr_too_large = false; + while (true) { + const std::size_t found = rx_buf.find("\r\n\r\n", rx_off); + if (found != std::string::npos) { + if (found - rx_off > options.max_header_bytes) { + hdr_too_large = true; + } + hdr_end = found; + break; + } + if (rx_buf.size() - rx_off > options.max_header_bytes) { + hdr_too_large = true; + break; + } + if (rx_off > 0 && rx_buf.size() == rx_off) { + rx_buf.clear(); + rx_off = 0; + } + std::array chunk{}; + auto nr = recv_slice(fd_guard.get(), chunk, stopping, + options.read_timeout); + if (!nr.has_value()) { + peer_eof = true; + break; + } + if (*nr == 0) { + peer_eof = true; + break; + } + rx_buf.append(chunk.data(), *nr); + } + + if (hdr_too_large) { + send_error_close(fd_guard.get(), 431, + "Request Header Fields Too Large"); + break; + } + if (peer_eof || hdr_end == std::string::npos) { + break; + } + + const std::string_view header_block{ + rx_buf.data() + rx_off, hdr_end - rx_off}; + rx_off = hdr_end + 4U; + + // 2. Parse request line. + const std::size_t first_eol = header_block.find("\r\n"); + const std::string_view req_line = + first_eol == std::string_view::npos + ? header_block + : header_block.substr(0, first_eol); + const std::size_t sp1 = req_line.find(' '); + const std::size_t sp2 = + sp1 == std::string_view::npos + ? std::string_view::npos + : req_line.find(' ', sp1 + 1U); + if (sp1 == std::string_view::npos || + sp2 == std::string_view::npos || + req_line.find(' ', sp2 + 1U) != std::string_view::npos) { + send_error_close(fd_guard.get(), 400, "Bad Request"); + break; + } + const auto method_opt = + parse_method(req_line.substr(0, sp1)); + if (!method_opt.has_value()) { + send_error_close(fd_guard.get(), 501, + "Not Implemented"); + break; + } + const std::string_view target = + req_line.substr(sp1 + 1U, sp2 - sp1 - 1U); + const std::string_view version = req_line.substr(sp2 + 1U); + if ((version != "HTTP/1.1" && version != "HTTP/1.0") || + target.empty() || target.front() != '/' || + has_crlf_or_nul(target)) { + send_error_close(fd_guard.get(), 400, "Bad Request"); + break; + } + + std::string_view raw_path = target; + std::string_view raw_query{}; + if (const std::size_t qpos = target.find('?'); + qpos != std::string_view::npos) { + raw_path = target.substr(0, qpos); + raw_query = target.substr(qpos + 1U); + } + if (const std::size_t hpos = raw_query.find('#'); + hpos != std::string_view::npos) { + raw_query = raw_query.substr(0, hpos); + } + + // 3. Parse & validate headers (RFC 9112 smuggling rules). + std::vector
headers; + bool has_te = false; + bool chunked = false; + bool bad_headers = false; + bool too_many_headers = false; + bool expect_continue = false; + std::optional content_length; + std::optional conn_keep_alive; + + std::size_t hpos = + first_eol == std::string_view::npos + ? header_block.size() + : first_eol + 2U; + while (hpos < header_block.size()) { + const std::size_t eol = header_block.find("\r\n", hpos); + const std::string_view line = + eol == std::string_view::npos + ? header_block.substr(hpos) + : header_block.substr(hpos, eol - hpos); + hpos = (eol == std::string_view::npos) + ? header_block.size() + : (eol + 2U); + const std::size_t colon = line.find(':'); + if (colon == std::string_view::npos) { + bad_headers = true; + break; + } + const std::string_view hname = line.substr(0, colon); + const std::string_view hval = + trim_ows(line.substr(colon + 1U)); + if (!is_valid_token(hname) || has_crlf_or_nul(hval)) { + bad_headers = true; + break; + } + if (headers.size() >= options.max_headers) { + too_many_headers = true; + break; + } + + if (equal_ascii_ci(hname, "Content-Length")) { + std::uint64_t cl = 0; + if (!parse_u64_decimal(hval, cl)) { + bad_headers = true; + break; + } + if (content_length.has_value() && + *content_length != cl) { + bad_headers = true; + break; + } + content_length = cl; + } else if (equal_ascii_ci(hname, "Transfer-Encoding")) { + has_te = true; + if (contains_ascii_ci(hval, "chunked")) { + chunked = true; + } + } else if (equal_ascii_ci(hname, "Connection")) { + if (contains_ascii_ci(hval, "close")) { + conn_keep_alive = false; + } else if (contains_ascii_ci(hval, "keep-alive")) { + conn_keep_alive = true; + } + } else if (equal_ascii_ci(hname, "Expect")) { + if (equal_ascii_ci(hval, "100-continue")) { + expect_continue = true; + } + } + headers.push_back( + Header{std::string{hname}, std::string{hval}}); + } + + if (too_many_headers) { + send_error_close(fd_guard.get(), 431, + "Request Header Fields Too Large"); + break; + } + if (bad_headers || (has_te && content_length.has_value())) { + send_error_close(fd_guard.get(), 400, "Bad Request"); + break; + } + if (has_te && !chunked) { + send_error_close(fd_guard.get(), 501, + "Not Implemented"); + break; + } + + bool keep_alive = + conn_keep_alive.has_value() + ? *conn_keep_alive + : (version == "HTTP/1.1"); + if (stopping.load(std::memory_order_acquire)) { + keep_alive = false; + } + + // 4. Check streaming route vs buffered Router. + auto streaming_match = + match_streaming(*method_opt, raw_path); + if (!streaming_match.has_value()) { + // Enforce buffered max_body_bytes before reading body. + if (!chunked && content_length.has_value() && + *content_length > options.max_body_bytes) { + send_error_close(fd_guard.get(), 413, + "Payload Too Large"); + break; + } + } else { + if (!chunked && content_length.has_value() && + options.max_streaming_body_bytes > 0 && + *content_length > + options.max_streaming_body_bytes) { + send_error_close(fd_guard.get(), 413, + "Payload Too Large"); + break; + } + } + + BodyReader::State reader_state; + reader_state.fd = fd_guard.get(); + reader_state.stopping = &stopping; + reader_state.read_timeout = options.read_timeout; + reader_state.default_max_bytes = + streaming_match.has_value() + ? options.max_streaming_body_bytes + : options.max_body_bytes; + reader_state.rx_buf = &rx_buf; + reader_state.rx_off = &rx_off; + reader_state.chunked = chunked; + reader_state.declared_length = content_length; + reader_state.remaining_fixed = + content_length.value_or(0ULL); + reader_state.eof = + (!chunked && reader_state.remaining_fixed == 0); + BodyReader body_reader{reader_state}; + + if (expect_continue && + (chunked || reader_state.remaining_fixed > 0)) { + if (!send_str(fd_guard.get(), + "HTTP/1.1 100 Continue\r\n\r\n", + options.write_timeout) + .has_value()) { + break; + } + } + + if (streaming_match.has_value()) { + ServerRequest req; + req.method = *method_opt; + req.path = std::string{raw_path}; + req.headers = std::move(headers); + req.parameters = std::move(streaming_match->second); + req.query = std::string{raw_query}; + + auto route_res = + streaming_match->first(req, body_reader); + if (!route_res.has_value()) { + if (route_res.error().kind() == + Void::Result::ErrorKind::exhausted) { + send_error_close(fd_guard.get(), 413, + "Payload Too Large"); + } else { + send_error_close(fd_guard.get(), 500, + "Internal Server Error"); + } + break; + } + if (!reader_state.eof) { + keep_alive = false; + } + send_response(fd_guard.get(), *method_opt, + std::move(*route_res), keep_alive); + if (!keep_alive) { + break; + } + continue; + } + + // Buffered body read (respecting max_body_bytes on both + // Content-Length and chunked transfer encoding). + std::string body_str; + bool payload_too_large = false; + bool body_io_err = false; + if (chunked || reader_state.remaining_fixed > 0) { + if (!chunked) { + body_str.reserve(static_cast( + reader_state.remaining_fixed)); + } + std::array tmp{}; + for (;;) { + auto nr = body_reader.read_some(tmp); + if (!nr.has_value()) { + body_io_err = true; + break; + } + if (*nr == 0) { + break; + } + if (body_str.size() + *nr > + options.max_body_bytes) { + payload_too_large = true; + break; + } + body_str.append( + reinterpret_cast(tmp.data()), *nr); + } + } + if (payload_too_large) { + send_error_close(fd_guard.get(), 413, + "Payload Too Large"); + break; + } + if (body_io_err) { + break; + } + + Method dispatch_method = *method_opt; + ServerRequest req; + req.method = dispatch_method; + req.path = std::string{raw_path}; + req.headers = std::move(headers); + req.body = std::move(body_str); + req.query = std::string{raw_query}; + + auto dispatched = router->dispatch(req); + if (!dispatched.has_value()) { + send_error_close(fd_guard.get(), 500, + "Internal Server Error"); + break; + } + if (!dispatched->has_value() && + dispatch_method == Method::Head) { + req.method = Method::Get; + dispatched = router->dispatch(req); + if (!dispatched.has_value()) { + send_error_close(fd_guard.get(), 500, + "Internal Server Error"); + break; + } + } + if (!dispatched->has_value()) { + const auto allowed = collect_allowed_methods(raw_path); + if (!allowed.empty()) { + std::string allow_hdr; + for (std::size_t i = 0; i < allowed.size(); ++i) { + if (i > 0) allow_hdr += ", "; + allow_hdr += method_string(allowed[i]); + } + send_response( + fd_guard.get(), *method_opt, + ServerResponse{ + .status = 405, + .headers = {Header{"Allow", + std::move(allow_hdr)}}, + .body = "Method Not Allowed"}, + keep_alive); + } else { + send_response( + fd_guard.get(), *method_opt, + ServerResponse{.status = 404, + .body = "Not Found"}, + keep_alive); + } + if (!keep_alive) { + break; + } + continue; + } + + send_response(fd_guard.get(), *method_opt, + std::move(**dispatched), keep_alive); + if (!keep_alive) { + break; + } + } + + entry.client_fd.store(-1, std::memory_order_release); + fd_guard.reset(); + } + + void accept_loop() + { + while (!stopping.load(std::memory_order_acquire)) { + std::array pfds{{ + {.fd = listen_fd, .events = POLLIN, .revents = 0}, + {.fd = wake_fd, .events = POLLIN, .revents = 0}, + }}; + const int pr = ::poll(pfds.data(), pfds.size(), 100); + if (pr < 0) { + if (errno == EINTR) { + continue; + } + break; + } + if ((pfds[1].revents & POLLIN) != 0) { + std::uint64_t val = 0; + (void)::read(wake_fd, &val, sizeof(val)); + } + if (stopping.load(std::memory_order_acquire)) { + break; + } + if ((pfds[0].revents & POLLIN) == 0) { + reap_finished_workers(); + continue; + } + + for (;;) { +#ifdef SOCK_CLOEXEC + int client_fd = ::accept4(listen_fd, nullptr, nullptr, + SOCK_CLOEXEC); +#else + int client_fd = ::accept(listen_fd, nullptr, nullptr); + if (client_fd >= 0) { + (void)::fcntl(client_fd, F_SETFD, FD_CLOEXEC); + } +#endif + if (client_fd < 0) { + if (errno == EINTR) { + continue; + } + break; + } + + reap_finished_workers(); + std::lock_guard lock{workers_mutex}; + if (stopping.load(std::memory_order_acquire) || + workers.size() >= + options.max_concurrent_connections) { + // Unlock or immediately decline without unbounded + // thread creation. + const std::string_view busy = + "HTTP/1.1 503 Service Unavailable\r\n" + "Content-Length: 19\r\n" + "Connection: close\r\n\r\n" + "Service Unavailable"; + (void)::send(client_fd, busy.data(), busy.size(), + MSG_NOSIGNAL); + (void)::close(client_fd); + continue; + } + const std::uint64_t id = ++next_worker_id; + auto entry = std::make_unique(); + entry->id = id; + entry->client_fd.store(client_fd, + std::memory_order_release); + WorkerEntry* raw_entry = entry.get(); + entry->thread = + std::thread([this, raw_entry, client_fd]() { + serve_connection(client_fd, *raw_entry); + raw_entry->finished.store( + true, std::memory_order_release); + std::lock_guard lk{workers_mutex}; + workers_cv.notify_all(); + }); + workers.emplace(id, std::move(entry)); + } + } + } + + void shutdown(std::chrono::milliseconds drain_timeout) noexcept + { + const bool was_running = + running.load(std::memory_order_acquire); + if (!was_running && listen_fd < 0 && + !accept_thread.joinable()) { + return; + } + stopping.store(true, std::memory_order_release); + if (wake_fd >= 0) { + const std::uint64_t one = 1; + (void)::write(wake_fd, &one, sizeof(one)); + } + if (accept_thread.joinable()) { + accept_thread.join(); + } + if (listen_fd >= 0) { + (void)::close(listen_fd); + listen_fd = -1; + } + if (wake_fd >= 0) { + (void)::close(wake_fd); + wake_fd = -1; + } + + std::vector to_join; + { + std::unique_lock lock{workers_mutex}; + const auto all_finished = [this]() { + for (const auto& [id, w] : workers) { + (void)id; + if (!w->finished.load(std::memory_order_acquire)) { + return false; + } + } + return true; + }; + if (drain_timeout > std::chrono::milliseconds::zero()) { + (void)workers_cv.wait_for(lock, drain_timeout, + all_finished); + } + for (const auto& [id, w] : workers) { + (void)id; + const int cfd = w->client_fd.exchange( + -1, std::memory_order_acq_rel); + if (cfd >= 0) { + (void)::shutdown(cfd, SHUT_RDWR); + } + } + for (auto& [id, w] : workers) { + (void)id; + if (w->thread.joinable()) { + to_join.push_back(std::move(w->thread)); + } + } + } + for (auto& t : to_join) { + t.join(); + } + { + std::lock_guard lock{workers_mutex}; + workers.clear(); + } + bound_port = 0; + bind_addr_str.clear(); + running.store(false, std::memory_order_release); + stopping.store(false, std::memory_order_release); + } + }; + + HttpServer::HttpServer(HttpServerOptions options) + : m_impl(std::make_unique()) + { + m_impl->options = std::move(options); + m_impl->owned_router.emplace(); + m_impl->router = &(*m_impl->owned_router); + } + + HttpServer::HttpServer(Router& external_router, HttpServerOptions options) + : m_impl(std::make_unique()) + { + m_impl->options = std::move(options); + m_impl->router = &external_router; + } + + HttpServer::~HttpServer() noexcept = default; + HttpServer::HttpServer(HttpServer&&) noexcept = default; + HttpServer& HttpServer::operator=(HttpServer&&) noexcept = default; + + Router& HttpServer::router() noexcept { return *m_impl->router; } + + Void::Result::Result + HttpServer::add_route(Method method, std::string pattern, + RouteHandler handler) + { + return m_impl->router->add(method, std::move(pattern), + std::move(handler)); + } + + Void::Result::Result + HttpServer::add_streaming_route(Method method, std::string pattern, + StreamingRouteHandler handler) + { + if (!handler) { + return std::unexpected{make_net_error( + NetErrorCode::invalid_argument, + "Net::HttpServer: streaming route handler is empty")}; + } + 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->streaming_routes, [&](const StreamingRoute& r) { + return r.method == method && + same_route_shape(r.segments, *compiled); + }); + if (dup != m_impl->streaming_routes.end()) { + return std::unexpected{make_net_error( + NetErrorCode::invalid_argument, + "Net::HttpServer: duplicate streaming route")}; + } + m_impl->streaming_routes.push_back(StreamingRoute{ + method, std::move(pattern), std::move(*compiled), + std::move(handler)}); + return {}; + } + + Void::Result::Result HttpServer::start() + { + if (m_impl->running.load(std::memory_order_acquire)) { + return std::unexpected{make_net_error( + NetErrorCode::invalid_argument, + "Net::HttpServer::start: server is already running")}; + } + if (m_impl->options.max_concurrent_connections == 0 || + m_impl->options.max_header_bytes == 0 || + m_impl->options.max_headers == 0) { + return std::unexpected{make_net_error( + NetErrorCode::invalid_argument, + "Net::HttpServer::start: limits must be positive")}; + } + + const std::string host = m_impl->options.bind_host.empty() + ? std::string{"127.0.0.1"} + : m_impl->options.bind_host; + const std::string port_str = std::to_string(m_impl->options.port); + + struct addrinfo hints{}; + hints.ai_family = AF_UNSPEC; + hints.ai_socktype = SOCK_STREAM; + hints.ai_flags = AI_PASSIVE; + struct addrinfo* res = nullptr; + const int gai = ::getaddrinfo(host.c_str(), port_str.c_str(), &hints, &res); + if (gai != 0 || res == nullptr) { + return std::unexpected{make_net_error( + NetErrorCode::connect_failed, + std::format("Net::HttpServer::start: getaddrinfo '{}' failed: " + "{}", + host, ::gai_strerror(gai)))}; + } + + OwnedFd listen_guard; + int last_errno = 0; + for (struct addrinfo* p = res; p != nullptr; p = p->ai_next) { +#ifdef SOCK_CLOEXEC + int fd = ::socket(p->ai_family, p->ai_socktype | SOCK_CLOEXEC, + p->ai_protocol); +#else + int fd = ::socket(p->ai_family, p->ai_socktype, p->ai_protocol); + if (fd >= 0) { + (void)::fcntl(fd, F_SETFD, FD_CLOEXEC); + } +#endif + if (fd < 0) { + last_errno = errno; + continue; + } + OwnedFd cand{fd}; + int yes = 1; + (void)::setsockopt(cand.get(), SOL_SOCKET, SO_REUSEADDR, &yes, + sizeof(yes)); + if (::bind(cand.get(), p->ai_addr, p->ai_addrlen) == 0 && + ::listen(cand.get(), m_impl->options.listen_backlog) == 0) { + listen_guard = std::move(cand); + break; + } + last_errno = errno; + } + ::freeaddrinfo(res); + + if (!listen_guard) { + return std::unexpected{make_net_error( + NetErrorCode::connect_failed, + std::format("Net::HttpServer::start: bind/listen on {}:{} " + "failed: {}", + host, m_impl->options.port, + std::strerror(last_errno)), + std::error_code{last_errno, std::generic_category()})}; + } + + (void)::fcntl(listen_guard.get(), F_SETFL, + ::fcntl(listen_guard.get(), F_GETFL, 0) | O_NONBLOCK); + + struct sockaddr_storage ss{}; + socklen_t slen = sizeof(ss); + if (::getsockname(listen_guard.get(), reinterpret_cast(&ss), + &slen) != 0) { + return std::unexpected{make_net_error( + NetErrorCode::io_error, + std::format("Net::HttpServer::start: getsockname failed: {}", + std::strerror(errno)), + std::error_code{errno, std::generic_category()})}; + } + + std::array ip_buf{}; + std::uint16_t actual_port = 0; + if (ss.ss_family == AF_INET) { + const auto* s4 = reinterpret_cast(&ss); + actual_port = ntohs(s4->sin_port); + (void)::inet_ntop(AF_INET, &s4->sin_addr, ip_buf.data(), + ip_buf.size()); + m_impl->bind_addr_str = ip_buf.data(); + } else if (ss.ss_family == AF_INET6) { + const auto* s6 = reinterpret_cast(&ss); + actual_port = ntohs(s6->sin6_port); + (void)::inet_ntop(AF_INET6, &s6->sin6_addr, ip_buf.data(), + ip_buf.size()); + m_impl->bind_addr_str = std::format("[{}]", ip_buf.data()); + } + + int efd = ::eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC); + if (efd < 0) { + return std::unexpected{make_net_error( + NetErrorCode::io_error, + std::format("Net::HttpServer::start: eventfd failed: {}", + std::strerror(errno)), + std::error_code{errno, std::generic_category()})}; + } + + m_impl->listen_fd = listen_guard.release(); + m_impl->wake_fd = efd; + m_impl->bound_port = actual_port; + m_impl->stopping.store(false, std::memory_order_release); + m_impl->running.store(true, std::memory_order_release); + m_impl->accept_thread = + std::thread([impl = m_impl.get()]() { impl->accept_loop(); }); + return {}; + } + + void HttpServer::shutdown(std::chrono::milliseconds drain_timeout) noexcept + { + if (m_impl) { + m_impl->shutdown(drain_timeout); + } + } + + bool HttpServer::running() const noexcept + { + return m_impl && m_impl->running.load(std::memory_order_acquire); + } + + std::uint16_t HttpServer::bound_port() const noexcept + { + return m_impl ? m_impl->bound_port : 0; + } + + std::string HttpServer::bind_address() const + { + return m_impl ? m_impl->bind_addr_str : std::string{}; + } + + std::string HttpServer::base_url() const + { + if (!m_impl || m_impl->bound_port == 0) { + return {}; + } + return std::format("http://{}:{}", m_impl->bind_addr_str, + m_impl->bound_port); + } + +} // namespace Void::Net diff --git a/src/Net/Server.cpp b/src/Net/Server.cpp index 19460e6..1def1ab 100644 --- a/src/Net/Server.cpp +++ b/src/Net/Server.cpp @@ -260,6 +260,21 @@ namespace Void::Net return find_header(headers, name); } + ServerResponse ServerResponse::from_file(std::filesystem::path path, + std::string content_type, + std::uint16_t status) + { + if (content_type.empty()) { + content_type = std::string{content_type_for(path)}; + } + return ServerResponse{ + .status = status, + .headers = {Header{"Content-Type", std::move(content_type)}}, + .body = {}, + .file_body = std::move(path), + }; + } + std::optional ServerResponse::header(std::string_view name) const noexcept { @@ -334,6 +349,25 @@ namespace Void::Net return std::optional{std::move(*response)}; } + std::vector Router::allowed_methods(std::string_view path) const + { + if (path.empty() || !path.starts_with('/')) { + return {}; + } + const auto segments = split_path(path_only(path)); + std::vector methods; + { + std::shared_lock lock{mutex_}; + for (const auto& route : routes_) { + if (match_route(route.segments, segments).has_value() && + std::ranges::find(methods, route.method) == methods.end()) { + methods.push_back(route.method); + } + } + } + return methods; + } + std::size_t Router::size() const { std::shared_lock lock{mutex_}; diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 48c2ecb..2759bda 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -133,6 +133,9 @@ if(_all_generated) if(TARGET OpenSSL::Crypto) target_link_libraries(VoidTests PRIVATE OpenSSL::Crypto) endif() + if(TARGET OpenSSL::SSL) + target_link_libraries(VoidTests PRIVATE OpenSSL::SSL) + endif() if(TARGET SQLite3::SQLite3) target_link_libraries(VoidTests PRIVATE SQLite3::SQLite3) endif() diff --git a/tests/package/InstalledComponents.cmake b/tests/package/InstalledComponents.cmake index e23d018..6bbc122 100644 --- a/tests/package/InstalledComponents.cmake +++ b/tests/package/InstalledComponents.cmake @@ -292,6 +292,14 @@ if(_has_fsm) -DCMAKE_DISABLE_FIND_PACKAGE_SQLite3=TRUE) endif() +has_modules(_has_net Net Functional Text) +if(_has_net) + run_consumer(NetOnly "${install_prefix}" "NetOnly" + -DCMAKE_DISABLE_FIND_PACKAGE_LibArchive=TRUE + -DCMAKE_DISABLE_FIND_PACKAGE_PkgConfig=TRUE + -DCMAKE_DISABLE_FIND_PACKAGE_SQLite3=TRUE) +endif() + # Foundation consumer with Core-formatting bridge and zero external packages. has_modules(_has_foundation Math Text Time Functional Binary FunctionalCoreFormatting Memory Core) if(_has_foundation) diff --git a/tests/package/NetOnly/CMakeLists.txt b/tests/package/NetOnly/CMakeLists.txt new file mode 100644 index 0000000..30910ce --- /dev/null +++ b/tests/package/NetOnly/CMakeLists.txt @@ -0,0 +1,11 @@ +cmake_minimum_required(VERSION 4.0) +project(VoidNetOnlyConsumer LANGUAGES CXX) + +find_package(Void CONFIG REQUIRED COMPONENTS Net) + +add_executable(void_net_only_consumer main.cpp) +target_link_libraries(void_net_only_consumer PRIVATE Void::Net) +target_compile_features(void_net_only_consumer PRIVATE cxx_std_26) + +enable_testing() +add_test(NAME NetOnlyConsumer COMMAND void_net_only_consumer) diff --git a/tests/package/NetOnly/main.cpp b/tests/package/NetOnly/main.cpp new file mode 100644 index 0000000..0390d70 --- /dev/null +++ b/tests/package/NetOnly/main.cpp @@ -0,0 +1,31 @@ +#include +#include + +#include + +int main() +{ + Void::Net::HttpServer server; + if (!server + .add_route(Void::Net::Method::Get, "/ping", + [](const Void::Net::ServerRequest&) { + return Void::Result::ok(Void::Net::ServerResponse{ + .status = 200, .body = "pong"}); + }) + .has_value()) { + return 1; + } + if (!server.start().has_value() || server.bound_port() == 0) { + return 2; + } + auto client = Void::Net::HttpClient::secure(); + if (!client.verify_tls()) { + return 3; + } + auto resp = client.get(server.base_url() + "/ping"); + server.shutdown(); + if (!resp.has_value() || resp->status != 200 || resp->body != "pong") { + return 4; + } + return 0; +} diff --git a/tests/standalone/Net/HttpClient.cpp b/tests/standalone/Net/HttpClient.cpp index 007e003..453ba3f 100644 --- a/tests/standalone/Net/HttpClient.cpp +++ b/tests/standalone/Net/HttpClient.cpp @@ -1,19 +1,34 @@ +#include #include +#include +#include #include #include +#include +#include +#include +#include +#include +#include + +#include #include +#include +#include #include +#include #include #include #include #include +#include namespace { // Minimal one-shot HTTP/1.1 server on a chosen loopback port. Accepts one // connection, reads the request (ignored beyond headers), and replies with - // a fixed 200 body. Runs on a detached helper thread; the test joins it. + // a fixed 200 body. struct OneShotServer { int fd = -1; std::uint16_t port = 0; @@ -29,7 +44,7 @@ namespace sockaddr_in addr{}; addr.sin_family = AF_INET; addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK); - addr.sin_port = 0; // ephemeral + addr.sin_port = 0; ::bind(fd, reinterpret_cast(&addr), sizeof(addr)); socklen_t len = sizeof(addr); ::getsockname(fd, reinterpret_cast(&addr), &len); @@ -59,6 +74,126 @@ namespace if (fd >= 0) ::close(fd); } }; + + struct GeneratedCert { + std::filesystem::path cert_file; + std::filesystem::path key_file; + }; + + GeneratedCert generate_self_signed_cert(const std::filesystem::path& dir, + const char* san_value, + const char* tag) + { + using PkeyPtr = std::unique_ptr; + using X509Ptr = std::unique_ptr; + using ExtPtr = + std::unique_ptr; + + PkeyPtr pkey{EVP_RSA_gen(2048), &EVP_PKEY_free}; + Void::Testing::require(static_cast(pkey)); + + X509Ptr cert{X509_new(), &X509_free}; + Void::Testing::require(static_cast(cert)); + X509_set_version(cert.get(), 2); + ASN1_INTEGER_set(X509_get_serialNumber(cert.get()), 1); + X509_gmtime_adj(X509_get_notBefore(cert.get()), -60); + X509_gmtime_adj(X509_get_notAfter(cert.get()), 3600); + X509_set_pubkey(cert.get(), pkey.get()); + + X509_NAME* name = X509_get_subject_name(cert.get()); + X509_NAME_add_entry_by_txt( + name, "CN", MBSTRING_ASC, + reinterpret_cast("127.0.0.1"), -1, -1, 0); + X509_set_issuer_name(cert.get(), name); + + X509V3_CTX ctx{}; + X509V3_set_ctx_nodb(&ctx); + X509V3_set_ctx(&ctx, cert.get(), cert.get(), nullptr, nullptr, 0); + ExtPtr ext{X509V3_EXT_conf_nid(nullptr, &ctx, NID_subject_alt_name, + const_cast(san_value)), + &X509_EXTENSION_free}; + Void::Testing::require(static_cast(ext)); + Void::Testing::require(X509_add_ext(cert.get(), ext.get(), -1) == 1); + + Void::Testing::require( + X509_sign(cert.get(), pkey.get(), EVP_sha256()) > 0); + + const auto cert_path = dir / (std::string{"cert_"} + tag + ".pem"); + const auto key_path = dir / (std::string{"key_"} + tag + ".pem"); + FILE* cf = std::fopen(cert_path.c_str(), "wb"); + Void::Testing::require(cf != nullptr); + Void::Testing::require(PEM_write_X509(cf, cert.get()) == 1); + std::fclose(cf); + + FILE* kf = std::fopen(key_path.c_str(), "wb"); + Void::Testing::require(kf != nullptr); + Void::Testing::require(PEM_write_PrivateKey(kf, pkey.get(), nullptr, + nullptr, 0, nullptr, + nullptr) == 1); + std::fclose(kf); + return GeneratedCert{cert_path, key_path}; + } + + struct OneShotTlsServer { + int fd = -1; + std::uint16_t port = 0; + SSL_CTX* ctx = nullptr; + std::thread worker; + + OneShotTlsServer(const GeneratedCert& creds, std::string body) + { + ctx = SSL_CTX_new(TLS_server_method()); + Void::Testing::require(ctx != nullptr); + Void::Testing::require( + SSL_CTX_use_certificate_file(ctx, creds.cert_file.c_str(), + SSL_FILETYPE_PEM) == 1); + Void::Testing::require( + SSL_CTX_use_PrivateKey_file(ctx, creds.key_file.c_str(), + SSL_FILETYPE_PEM) == 1); + + fd = ::socket(AF_INET, SOCK_STREAM, 0); + int yes = 1; + ::setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes)); + sockaddr_in addr{}; + addr.sin_family = AF_INET; + addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK); + addr.sin_port = 0; + Void::Testing::require( + ::bind(fd, reinterpret_cast(&addr), + sizeof(addr)) == 0); + socklen_t len = sizeof(addr); + ::getsockname(fd, reinterpret_cast(&addr), &len); + port = ntohs(addr.sin_port); + Void::Testing::require(::listen(fd, 1) == 0); + + worker = std::thread([this, body = std::move(body)]() { + const int conn = ::accept(fd, nullptr, nullptr); + if (conn < 0) return; + SSL* ssl = SSL_new(ctx); + SSL_set_fd(ssl, conn); + if (SSL_accept(ssl) == 1) { + char buf[2048]; + (void)SSL_read(ssl, buf, sizeof(buf)); + const std::string resp = + "HTTP/1.1 200 OK\r\nContent-Length: " + + std::to_string(body.size()) + + "\r\nConnection: close\r\n\r\n" + body; + (void)SSL_write(ssl, resp.data(), + static_cast(resp.size())); + SSL_shutdown(ssl); + } + SSL_free(ssl); + ::close(conn); + }); + } + + ~OneShotTlsServer() + { + if (worker.joinable()) worker.join(); + if (fd >= 0) ::close(fd); + if (ctx != nullptr) SSL_CTX_free(ctx); + } + }; } // namespace Void::Testing::Test http_client_get_localhost_round_trip() @@ -74,7 +209,6 @@ Void::Testing::Test http_client_get_localhost_round_trip() Void::Testing::expect_eq(resp->status, static_cast(200)); Void::Testing::expect_eq(resp->body, std::string{"hello from void"}); Void::Testing::expect(resp->ok()); - // Request line reached the server with the right target. Void::Testing::expect(server.last_request.find("GET /ping HTTP/1.1") != std::string::npos); } @@ -106,16 +240,12 @@ Void::Testing::Test http_client_invalid_url_is_error() Void::Testing::Test http_client_connection_refused_is_error() { Void::Net::HttpClient client; - // Port 1 on loopback: nothing listening. const auto resp = client.get("http://127.0.0.1:1/"); Void::Testing::expect(!resp.has_value()); } Void::Testing::Test http_client_timeout_bounds_a_stalled_server() { - // A server that accepts and then never responds. Without an enforced - // Request::timeout the sync read blocks forever (Asio's sync emulation - // poll()s on would-block with no deadline). struct StallServer { int fd = -1; std::uint16_t port = 0; @@ -138,7 +268,6 @@ Void::Testing::Test http_client_timeout_bounds_a_stalled_server() ::listen(fd, 1); worker = std::thread([this] { conn = ::accept(fd, nullptr, nullptr); - // Never write a byte; hold the connection open. }); } @@ -161,6 +290,226 @@ Void::Testing::Test http_client_timeout_bounds_a_stalled_server() const auto elapsed = std::chrono::steady_clock::now() - start; Void::Testing::expect(!resp.has_value()); - // Well under the old "forever": the deadline tripped around 1s. Void::Testing::expect(elapsed < std::chrono::seconds{5}); } + +Void::Testing::Test http_client_streaming_upload_download_quota_and_cancel() +{ + Void::FileSystem::TempDir tmp{"void_http_stream_"}; + const auto upload_src = tmp / "upload_4mib.bin"; + const auto server_stored = tmp / "server_copy.bin"; + const auto dl_dst = tmp / "downloaded.bin"; + const auto dl_quota_fail = tmp / "should_not_exist.bin"; + + // Generate deterministic 4 MiB test file. + constexpr std::size_t kSize = 4ULL * 1024ULL * 1024ULL; + std::string expected_data(kSize, '\0'); + for (std::size_t i = 0; i < kSize; ++i) { + expected_data[i] = static_cast((i * 131U) & 0xFFU); + } + { + std::ofstream out{upload_src, std::ios::binary | std::ios::trunc}; + Void::Testing::require(out.is_open()); + out.write(expected_data.data(), + static_cast(expected_data.size())); + out.close(); + } + auto expected_digest = Void::Crypto::sha256_file(upload_src); + Void::Testing::require(expected_digest.has_value()); + + Void::Net::HttpServer server; + Void::Testing::require( + server + .add_streaming_route( + Void::Net::Method::Put, "/blob", + [&](const Void::Net::ServerRequest&, + Void::Net::BodyReader& reader) -> Void::Net::RouteResult { + auto n = reader.read_to_file(server_stored); + if (!n.has_value()) { + return std::unexpected{std::move(n.error())}; + } + return Void::Net::ServerResponse{ + .status = 201, .body = std::to_string(*n)}; + }) + .has_value()); + Void::Testing::require( + server + .add_route(Void::Net::Method::Get, "/blob", + [&](const Void::Net::ServerRequest&) { + return Void::Result::ok( + Void::Net::ServerResponse::from_file( + server_stored)); + }) + .has_value()); + std::atomic slow_entered{false}; + std::atomic release_hang{false}; + Void::Testing::require( + server + .add_route(Void::Net::Method::Get, "/hang", + [&](const Void::Net::ServerRequest&) { + slow_entered.store(true, std::memory_order_release); + for (int i = 0; + i < 600 && + !release_hang.load(std::memory_order_acquire); + ++i) { + std::this_thread::sleep_for( + std::chrono::milliseconds{5}); + } + return Void::Result::ok( + Void::Net::ServerResponse{.status = 200, + .body = "late"}); + }) + .has_value()); + Void::Testing::require(server.start().has_value()); + + const std::string base = server.base_url(); + auto client = Void::Net::HttpClient::secure(); + Void::Testing::expect(client.verify_tls()); + + // 1. Streaming 4 MiB upload with progress callback. + std::uint64_t last_up = 0; + std::size_t up_callbacks = 0; + Void::Net::UploadOptions up_opts; + up_opts.on_progress = [&](const Void::Net::TransferProgress& p) { + Void::Testing::expect(p.bytes_transferred >= last_up); + last_up = p.bytes_transferred; + ++up_callbacks; + }; + auto up_res = client.upload_file(base + "/blob", upload_src, up_opts); + Void::Testing::require(up_res.has_value()); + Void::Testing::expect_eq(up_res->status, std::uint16_t{201}); + Void::Testing::expect_eq(last_up, static_cast(kSize)); + Void::Testing::expect(up_callbacks > 1U); + + // 2. Streaming 4 MiB download with on_chunk incremental SHA-256 verification. + auto chunk_hasher = + Void::Crypto::Hasher::create(Void::Crypto::HashAlgorithm::Sha256); + Void::Testing::require(chunk_hasher.has_value()); + std::uint64_t last_dn = 0; + Void::Net::DownloadOptions dl_opts; + dl_opts.max_bytes = kSize; + dl_opts.on_chunk = [&](std::span data) { + Void::Testing::require(chunk_hasher->update(data).has_value()); + }; + dl_opts.on_progress = [&](const Void::Net::TransferProgress& p) { + Void::Testing::expect(p.bytes_transferred >= last_dn); + last_dn = p.bytes_transferred; + }; + auto dl_res = client.download_to_file(base + "/blob", dl_dst, dl_opts); + Void::Testing::require(dl_res.has_value()); + Void::Testing::expect_eq(dl_res->status, std::uint16_t{200}); + Void::Testing::expect_eq(dl_res->bytes_written, + static_cast(kSize)); + auto streamed_digest = chunk_hasher->finalize(); + Void::Testing::require(streamed_digest.has_value()); + Void::Testing::expect_eq(*streamed_digest, *expected_digest); + auto file_digest = Void::Crypto::sha256_file(dl_dst); + Void::Testing::require(file_digest.has_value()); + Void::Testing::expect_eq(*file_digest, *expected_digest); + + // 3. Quota overflow aborts cleanly with quota_exceeded and leaves no file. + Void::Net::DownloadOptions tight_opts; + tight_opts.max_bytes = 1024U * 1024U; // < 4 MiB + auto quota_err = + client.download_to_file(base + "/blob", dl_quota_fail, tight_opts); + Void::Testing::require(!quota_err.has_value()); + Void::Testing::expect_eq( + quota_err.error().code().value, + static_cast(Void::Net::NetErrorCode::quota_exceeded)); + Void::Testing::expect(!std::filesystem::exists(dl_quota_fail)); + + // 4. std::stop_token cancels an in-flight stalled download promptly. + { + std::stop_source stop_src; + Void::Net::DownloadOptions cancel_opts; + cancel_opts.stop = stop_src.get_token(); + std::jthread killer([&]() { + while (!slow_entered.load(std::memory_order_acquire)) { + std::this_thread::sleep_for(std::chrono::milliseconds{2}); + } + std::this_thread::sleep_for(std::chrono::milliseconds{30}); + stop_src.request_stop(); + }); + const auto t0 = std::chrono::steady_clock::now(); + auto c_res = client.download_to_file( + base + "/hang", tmp / "cancelled.bin", cancel_opts); + const auto elapsed = std::chrono::steady_clock::now() - t0; + killer.join(); + Void::Testing::require(!c_res.has_value()); + Void::Testing::expect_eq( + c_res.error().code().value, + static_cast(Void::Net::NetErrorCode::cancelled)); + Void::Testing::expect(elapsed < std::chrono::seconds{2}); + Void::Testing::expect(!std::filesystem::exists(tmp / "cancelled.bin")); + release_hang.store(true, std::memory_order_release); + } + + server.shutdown(); +} + +Void::Testing::Test http_client_secure_tls_verification_and_redaction() +{ + // 1. Authorization & secret header redaction in diagnostics. + Void::Net::Request req; + req.method = Void::Net::Method::Get; + req.url = "https://user:superpass@registry.example/v1/pkg"; + req.headers = { + {"Authorization", "Bearer top-secret-token-value"}, + {"Proxy-Authorization", "Basic dXNlcjpwYXNz"}, + {"Cookie", "session=secret-cookie"}, + {"Accept", "application/json"}, + }; + const std::string diag = + Void::Net::HttpClient::format_request_diagnostics(req); + Void::Testing::expect(diag.find("top-secret-token-value") == + std::string::npos); + Void::Testing::expect(diag.find("dXNlcjpwYXNz") == std::string::npos); + Void::Testing::expect(diag.find("secret-cookie") == std::string::npos); + Void::Testing::expect(diag.find("superpass") == std::string::npos); + Void::Testing::expect(diag.find("") != std::string::npos); + Void::Testing::expect(diag.find("application/json") != std::string::npos); + + // 2. Local TLS server verification checks. + Void::FileSystem::TempDir tmp{"void_http_tls_"}; + const auto good_cert = + generate_self_signed_cert(tmp.path(), "IP:127.0.0.1", "good"); + const auto bad_san_cert = + generate_self_signed_cert(tmp.path(), "DNS:wrong.invalid", "badsan"); + + // a) Untrusted self-signed cert is rejected by default on secure(). + { + OneShotTlsServer tls_srv{good_cert, "tls-secret"}; + auto client = Void::Net::HttpClient::secure(); + auto r = client.get( + "https://127.0.0.1:" + std::to_string(tls_srv.port) + "/ok"); + Void::Testing::require(!r.has_value()); + Void::Testing::expect_eq( + r.error().code().value, + static_cast(Void::Net::NetErrorCode::tls_error)); + } + + // b) Trusted CA + matching IP:127.0.0.1 SAN succeeds. + { + OneShotTlsServer tls_srv{good_cert, "tls-verified-ok"}; + auto client = Void::Net::HttpClient::secure(); + client.set_ca_file(good_cert.cert_file.string()); + auto r = client.get( + "https://127.0.0.1:" + std::to_string(tls_srv.port) + "/ok"); + Void::Testing::require(r.has_value()); + Void::Testing::expect_eq(r->status, std::uint16_t{200}); + Void::Testing::expect_eq(r->body, std::string{"tls-verified-ok"}); + } + + // c) Trusted CA + mismatched SAN (DNS:wrong.invalid != 127.0.0.1) fails. + { + OneShotTlsServer tls_srv{bad_san_cert, "should-fail"}; + auto client = Void::Net::HttpClient::secure(); + client.set_ca_file(bad_san_cert.cert_file.string()); + auto r = client.get( + "https://127.0.0.1:" + std::to_string(tls_srv.port) + "/bad"); + Void::Testing::require(!r.has_value()); + Void::Testing::expect_eq( + r.error().code().value, + static_cast(Void::Net::NetErrorCode::tls_error)); + } +} diff --git a/tests/standalone/Net/HttpServer.cpp b/tests/standalone/Net/HttpServer.cpp new file mode 100644 index 0000000..75b9d6a --- /dev/null +++ b/tests/standalone/Net/HttpServer.cpp @@ -0,0 +1,393 @@ +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace +{ + using Void::Net::BodyReader; + using Void::Net::Header; + using Void::Net::HttpClient; + using Void::Net::HttpServer; + using Void::Net::HttpServerOptions; + using Void::Net::Method; + using Void::Net::Request; + using Void::Net::ServerRequest; + using Void::Net::ServerResponse; + + std::string raw_http_exchange(std::uint16_t port, std::string_view raw_req) + { + const int fd = ::socket(AF_INET, SOCK_STREAM, 0); + Void::Testing::require(fd >= 0); + + sockaddr_in addr{}; + addr.sin_family = AF_INET; + addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK); + addr.sin_port = htons(port); + Void::Testing::require( + ::connect(fd, reinterpret_cast(&addr), sizeof(addr)) == + 0); + + std::size_t off = 0; + while (off < raw_req.size()) { + const ssize_t w = + ::send(fd, raw_req.data() + off, raw_req.size() - off, 0); + Void::Testing::require(w > 0); + off += static_cast(w); + } + (void)::shutdown(fd, SHUT_WR); + + std::string out; + std::array buf{}; + for (;;) { + const ssize_t r = ::recv(fd, buf.data(), buf.size(), 0); + if (r <= 0) { + break; + } + out.append(buf.data(), static_cast(r)); + } + (void)::close(fd); + return out; + } + + std::string read_file_bytes(const std::filesystem::path& p) + { + std::ifstream in{p, std::ios::binary}; + Void::Testing::require(in.is_open()); + return std::string{std::istreambuf_iterator{in}, + std::istreambuf_iterator{}}; + } +} // namespace + +Void::Testing::Test http_server_ephemeral_methods_and_concurrent_dispatch() +{ + HttpServerOptions opts; + opts.bind_host = "127.0.0.1"; + opts.port = 0; + + HttpServer server{opts}; + Void::Testing::require( + server + .add_route(Method::Get, "/items/:id", + [](const ServerRequest& req) { + return Void::Result::ok(ServerResponse{ + .status = 200, + .headers = {Header{"X-Item", + req.parameters.at("id")}}, + .body = "get:" + req.parameters.at("id") + "?" + + req.query}); + }) + .has_value()); + Void::Testing::require( + server + .add_route(Method::Post, "/items", + [](const ServerRequest& req) { + return Void::Result::ok(ServerResponse{ + .status = 201, .body = "post:" + req.body}); + }) + .has_value()); + Void::Testing::require( + server + .add_route(Method::Put, "/items/:id", + [](const ServerRequest& req) { + return Void::Result::ok(ServerResponse{ + .status = 200, + .body = "put:" + req.parameters.at("id") + ":" + + req.body}); + }) + .has_value()); + Void::Testing::require( + server + .add_route(Method::Delete, "/items/:id", + [](const ServerRequest& req) { + return Void::Result::ok(ServerResponse{ + .status = 200, + .body = "del:" + req.parameters.at("id")}); + }) + .has_value()); + Void::Testing::require( + server + .add_route(Method::Get, "/boom", + [](const ServerRequest&) -> Void::Net::RouteResult { + return Void::Result::fail( + "internal secret db credentials leaked here"); + }) + .has_value()); + + Void::Testing::require(server.start().has_value()); + const std::uint16_t port = server.bound_port(); + Void::Testing::expect(port > 0); + Void::Testing::expect(server.running()); + + const std::string base = server.base_url(); + HttpClient client; + + // GET + query + path param + { + auto r = client.get(base + "/items/alpha?full=1"); + Void::Testing::require(r.has_value()); + Void::Testing::expect_eq(r->status, std::uint16_t{200}); + Void::Testing::expect_eq(r->body, std::string{"get:alpha?full=1"}); + Void::Testing::expect_eq(*r->header("x-item"), std::string_view{"alpha"}); + } + + // HEAD falls back to GET route without response body + { + auto r = client.send(Request{.method = Method::Head, + .url = base + "/items/alpha?full=1"}); + Void::Testing::require(r.has_value()); + Void::Testing::expect_eq(r->status, std::uint16_t{200}); + Void::Testing::expect(r->body.empty()); + Void::Testing::expect_eq(*r->header("X-Item"), std::string_view{"alpha"}); + } + + // POST, PUT, DELETE + { + auto post_r = client.post(base + "/items", "new-payload"); + Void::Testing::require(post_r.has_value()); + Void::Testing::expect_eq(post_r->status, std::uint16_t{201}); + Void::Testing::expect_eq(post_r->body, std::string{"post:new-payload"}); + + auto put_r = client.send(Request{.method = Method::Put, + .url = base + "/items/beta", + .body = "updated"}); + Void::Testing::require(put_r.has_value()); + Void::Testing::expect_eq(put_r->status, std::uint16_t{200}); + Void::Testing::expect_eq(put_r->body, std::string{"put:beta:updated"}); + + auto del_r = client.send(Request{.method = Method::Delete, + .url = base + "/items/beta"}); + Void::Testing::require(del_r.has_value()); + Void::Testing::expect_eq(del_r->status, std::uint16_t{200}); + Void::Testing::expect_eq(del_r->body, std::string{"del:beta"}); + } + + // 404, 405 + Allow, sanitized 500 + { + auto r404 = client.get(base + "/missing"); + Void::Testing::require(r404.has_value()); + Void::Testing::expect_eq(r404->status, std::uint16_t{404}); + + auto r405 = client.post(base + "/boom", "ignored"); + Void::Testing::require(r405.has_value()); + Void::Testing::expect_eq(r405->status, std::uint16_t{405}); + auto allow = r405->header("Allow"); + Void::Testing::require(allow.has_value()); + Void::Testing::expect(allow->find("GET") != std::string_view::npos); + + auto r500 = client.get(base + "/boom"); + Void::Testing::require(r500.has_value()); + Void::Testing::expect_eq(r500->status, std::uint16_t{500}); + Void::Testing::expect(r500->body.find("secret db credentials") == + std::string::npos); + } + + // Concurrent client burst + { + constexpr int kThreads = 8; + constexpr int kPerThread = 10; + std::atomic ok_count{0}; + std::vector threads; + threads.reserve(kThreads); + for (int t = 0; t < kThreads; ++t) { + threads.emplace_back([&, t]() { + HttpClient c; + for (int i = 0; i < kPerThread; ++i) { + const std::string tag = + std::to_string(t) + "-" + std::to_string(i); + auto res = c.get(base + "/items/" + tag); + if (res.has_value() && res->status == 200 && + res->body == ("get:" + tag + "?")) { + ok_count.fetch_add(1, std::memory_order_relaxed); + } + } + }); + } + for (auto& th : threads) { + th.join(); + } + Void::Testing::expect_eq(ok_count.load(), kThreads * kPerThread); + } + + server.shutdown(); + Void::Testing::expect(!server.running()); + Void::Testing::expect_eq(server.bound_port(), std::uint16_t{0}); + + // No dangling listening socket after shutdown(). + const int probe = ::socket(AF_INET, SOCK_STREAM, 0); + Void::Testing::require(probe >= 0); + sockaddr_in addr{}; + addr.sin_family = AF_INET; + addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK); + addr.sin_port = htons(port); + Void::Testing::expect( + ::connect(probe, reinterpret_cast(&addr), sizeof(addr)) != + 0); + (void)::close(probe); +} + +Void::Testing::Test http_server_limits_smuggling_streaming_and_graceful_drain() +{ + Void::FileSystem::TempDir tmp{"void_http_srv_"}; + const auto uploaded_path = tmp / "uploaded.bin"; + + HttpServerOptions opts; + opts.max_header_bytes = 512; + opts.max_body_bytes = 64; + opts.max_streaming_body_bytes = 2U * 1024U * 1024U; + + HttpServer server{opts}; + Void::Testing::require( + server + .add_route(Method::Post, "/small", + [](const ServerRequest& req) { + return Void::Result::ok(ServerResponse{ + .status = 200, .body = req.body}); + }) + .has_value()); + Void::Testing::require( + server + .add_streaming_route( + Method::Put, "/upload", + [&](const ServerRequest&, BodyReader& body) + -> Void::Net::RouteResult { + auto n = body.read_to_file(uploaded_path); + if (!n.has_value()) { + return std::unexpected{std::move(n.error())}; + } + return ServerResponse{ + .status = 201, + .body = std::to_string(*n)}; + }) + .has_value()); + Void::Testing::require( + server + .add_route(Method::Get, "/artifact", + [&](const ServerRequest&) { + return Void::Result::ok( + ServerResponse::from_file(uploaded_path)); + }) + .has_value()); + + std::atomic in_flight_entered{false}; + std::atomic allow_in_flight_exit{false}; + Void::Testing::require( + server + .add_route(Method::Get, "/slow", + [&](const ServerRequest&) { + in_flight_entered.store(true, + std::memory_order_release); + while (!allow_in_flight_exit.load( + std::memory_order_acquire)) { + std::this_thread::sleep_for( + std::chrono::milliseconds{5}); + } + return Void::Result::ok( + ServerResponse{.status = 200, .body = "drained"}); + }) + .has_value()); + + Void::Testing::require(server.start().has_value()); + const std::uint16_t port = server.bound_port(); + const std::string base = server.base_url(); + HttpClient client; + + // 1. Oversized buffered body (Content-Length and chunked) rejected with 413. + { + const std::string big(128, 'A'); + auto r413 = client.post(base + "/small", big); + Void::Testing::require(r413.has_value()); + Void::Testing::expect_eq(r413->status, std::uint16_t{413}); + + const std::string chunked_big = + "POST /small HTTP/1.1\r\n" + "Host: 127.0.0.1\r\n" + "Transfer-Encoding: chunked\r\n" + "Connection: close\r\n\r\n" + "50\r\n" + + std::string(80, 'B') + "\r\n0\r\n\r\n"; + const std::string raw_resp = raw_http_exchange(port, chunked_big); + Void::Testing::expect(raw_resp.starts_with("HTTP/1.1 413")); + } + + // 2. Oversized header rejected with 431; TE+CL smuggling rejected with 400. + { + const std::string huge_hdr = + "GET /small HTTP/1.1\r\n" + "Host: 127.0.0.1\r\n" + "X-Huge: " + + std::string(700, 'H') + "\r\n\r\n"; + const std::string raw_431 = raw_http_exchange(port, huge_hdr); + Void::Testing::expect(raw_431.starts_with("HTTP/1.1 431")); + + const std::string smuggle = + "POST /small HTTP/1.1\r\n" + "Host: 127.0.0.1\r\n" + "Content-Length: 4\r\n" + "Transfer-Encoding: chunked\r\n\r\n" + "0\r\n\r\n"; + const std::string raw_400 = raw_http_exchange(port, smuggle); + Void::Testing::expect(raw_400.starts_with("HTTP/1.1 400")); + } + + // 3. Streaming PUT to file + streaming file_body GET (larger than buffered + // max_body_bytes = 64B!). + { + std::string payload(256U * 1024U, '\0'); + for (std::size_t i = 0; i < payload.size(); ++i) { + payload[i] = static_cast('a' + (i % 26U)); + } + auto put_r = client.send(Request{.method = Method::Put, + .url = base + "/upload", + .body = payload}); + Void::Testing::require(put_r.has_value()); + Void::Testing::expect_eq(put_r->status, std::uint16_t{201}); + Void::Testing::expect_eq(put_r->body, + std::to_string(payload.size())); + Void::Testing::expect_eq(read_file_bytes(uploaded_path), payload); + + auto get_r = client.get(base + "/artifact"); + Void::Testing::require(get_r.has_value()); + Void::Testing::expect_eq(get_r->status, std::uint16_t{200}); + Void::Testing::expect_eq(get_r->body, payload); + } + + // 4. Graceful shutdown drains active in-flight request cleanly. + { + Void::Result::Result + slow_result = Void::Result::fail("uninitialized"); + std::thread slow_client([&]() { + HttpClient c; + slow_result = c.get(base + "/slow"); + }); + while (!in_flight_entered.load(std::memory_order_acquire)) { + std::this_thread::sleep_for(std::chrono::milliseconds{2}); + } + std::thread releaser([&]() { + std::this_thread::sleep_for(std::chrono::milliseconds{40}); + allow_in_flight_exit.store(true, std::memory_order_release); + }); + server.shutdown(std::chrono::seconds{2}); + releaser.join(); + slow_client.join(); + Void::Testing::require(slow_result.has_value()); + Void::Testing::expect_eq(slow_result->status, std::uint16_t{200}); + Void::Testing::expect_eq(slow_result->body, std::string{"drained"}); + } +}