From 9a54f15e7e968de5510b6be9e91cf654cc9764c8 Mon Sep 17 00:00:00 2001 From: faumaray Date: Sun, 12 Jul 2026 00:14:01 +0300 Subject: [PATCH] Net: actually enforce Request::timeout on HTTP socket I/O MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Request::timeout was declared but never used — every sync Asio operation (TLS handshake, read, write) blocked without bound, so a stalled peer hung the calling thread indefinitely (observed: a stalled CDN download blocking a host's shutdown join forever). SO_RCVTIMEO cannot fix this: Asio's sync emulation treats the resulting EAGAIN as would-block and poll()s with no deadline. Instead a per-request DeadlineGuard watchdog ::shutdown()s the descriptor on expiry, which wakes any blocked sync op with EOF and fails the request. Declaration order in send() keeps the descriptor owners alive past the guard. Resolution and connect() remain on kernel defaults. Regression test: a stalled localhost server is bounded at ~1s. Co-Authored-By: Claude Fable 5 Claude-Session: https://claude.ai/code/session_018yj92cCihyaYtf4gKCT3nv --- src/Net/Http.cpp | 110 +++++++++++++++++++++++++--- tests/standalone/Net/HttpClient.cpp | 54 ++++++++++++++ 2 files changed, 152 insertions(+), 12 deletions(-) diff --git a/src/Net/Http.cpp b/src/Net/Http.cpp index 3ef6ec6..84134c7 100644 --- a/src/Net/Http.cpp +++ b/src/Net/Http.cpp @@ -14,12 +14,21 @@ #include +#if !defined(_WIN32) +#include +#include +#endif + #include #include +#include #include #include #include +#include +#include #include +#include #include namespace Void::Net @@ -227,17 +236,88 @@ namespace Void::Net 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) + { + if (timeout <= std::chrono::seconds::zero() || + !socket.is_open()) { + return; + } + const auto fd = socket.native_handle(); + m_worker = std::thread([this, fd, timeout] { + std::unique_lock lock{m_mutex}; + if (!m_cv.wait_for(lock, timeout, + [this] { return m_done; })) { +#if defined(_WIN32) + ::shutdown(fd, SD_BOTH); +#else + ::shutdown(fd, SHUT_RDWR); +#endif + m_timed_out = true; + } + }); + } + + DeadlineGuard(const DeadlineGuard&) = delete; + DeadlineGuard& operator=(const DeadlineGuard&) = delete; + + ~DeadlineGuard() + { + if (!m_worker.joinable()) { + return; + } + { + std::lock_guard lock{m_mutex}; + m_done = true; + } + m_cv.notify_all(); + m_worker.join(); + } + + [[nodiscard]] bool timed_out() const noexcept + { + return m_timed_out; + } + + private: + + std::thread m_worker; + std::mutex m_mutex; + std::condition_variable m_cv; + bool m_done{false}; + bool m_timed_out{false}; + }; + // Perform the request over an already-connected plain socket, doing a - // TLS upgrade in place when the target is https. - Response finish(tcp::socket socket, ssl::context& ctx, const Url& url, - const Request& req, std::string_view ua, - std::uint64_t max_body) + // 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) { if (url.is_tls) { - ssl::stream stream{std::move(socket), ctx}; - tls_handshake(stream, url); + tls.emplace(std::move(socket), ctx); + tls_handshake(*tls, url); auto rq = build_request(url, req, ua, url.target); - return write_read(stream, rq, max_body); + return write_read(*tls, rq, max_body); } auto rq = build_request(url, req, ua, url.target); return write_read(socket, rq, max_body); @@ -310,19 +390,25 @@ namespace Void::Net 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; + if (m_proxy.enabled()) { - tcp::socket socket{ioc}; asio::connect(socket, resolver.resolve( m_proxy.host, std::to_string(m_proxy.port))); + DeadlineGuard deadline{socket, req.timeout}; if (m_proxy.kind == ProxyConfig::Kind::Socks5) { socks5_connect(socket, *url, m_proxy); - response = finish(std::move(socket), ctx, *url, req, + response = finish(socket, tls, ctx, *url, req, m_user_agent, m_max_body); } else { // Http proxy if (url->is_tls) { http_connect_tunnel(socket, *url, m_proxy); - response = finish(std::move(socket), ctx, *url, req, + response = finish(socket, tls, ctx, *url, req, m_user_agent, m_max_body); } else { // Plain HTTP through proxy: absolute-form target. @@ -341,10 +427,10 @@ namespace Void::Net } } } else { - tcp::socket socket{ioc}; asio::connect(socket, resolver.resolve(url->host, url->port)); - response = finish(std::move(socket), ctx, *url, req, + DeadlineGuard deadline{socket, req.timeout}; + response = finish(socket, tls, ctx, *url, req, m_user_agent, m_max_body); } diff --git a/tests/standalone/Net/HttpClient.cpp b/tests/standalone/Net/HttpClient.cpp index 4d831fc..007e003 100644 --- a/tests/standalone/Net/HttpClient.cpp +++ b/tests/standalone/Net/HttpClient.cpp @@ -110,3 +110,57 @@ Void::Testing::Test http_client_connection_refused_is_error() 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; + int conn = -1; + std::thread worker; + + StallServer() + { + 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; + ::bind(fd, reinterpret_cast(&addr), sizeof(addr)); + socklen_t len = sizeof(addr); + ::getsockname(fd, reinterpret_cast(&addr), &len); + port = ntohs(addr.sin_port); + ::listen(fd, 1); + worker = std::thread([this] { + conn = ::accept(fd, nullptr, nullptr); + // Never write a byte; hold the connection open. + }); + } + + ~StallServer() + { + if (conn >= 0) ::close(conn); + if (worker.joinable()) worker.join(); + if (fd >= 0) ::close(fd); + } + }; + + StallServer server; + Void::Net::HttpClient client; + Void::Net::Request req; + req.url = "http://127.0.0.1:" + std::to_string(server.port) + "/stall"; + req.timeout = std::chrono::seconds{1}; + + const auto start = std::chrono::steady_clock::now(); + const auto resp = client.send(req); + 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}); +}