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}); +}