From 1b40ce850bac721edb6d63fdab59e021797b7fbc Mon Sep 17 00:00:00 2001 From: yhirose Date: Mon, 16 Nov 2026 23:30:26 -0500 Subject: [PATCH] Close the tunnel when the TLS handshake through a proxy fails SSLClient::setup_proxy_connection() left the socket open when the TLS handshake inside the CONNECT tunnel failed, so the client kept a connection with no TLS session on it. Only the next request's reuse check closed it, because tls::is_peer_closed() reports a missing session as closed. Close it where the handshake fails, as ensure_socket_connection() does for a direct connection. --- httplib.h | 2 ++ test/test.cc | 34 ++++++++++++++++++++++++++++++++++ 2 files changed, 36 insertions(+) diff --git a/httplib.h b/httplib.h index c5a894b4..98d45f94 100644 --- a/httplib.h +++ b/httplib.h @@ -19327,6 +19327,8 @@ inline bool SSLClient::setup_proxy_connection( } if (!initialize_ssl(socket, error)) { + shutdown_socket(socket); + close_socket(socket); success = false; return false; } diff --git a/test/test.cc b/test/test.cc index 010e30e7..2ffeeb48 100644 --- a/test/test.cc +++ b/test/test.cc @@ -32485,6 +32485,40 @@ TEST(ProxyTunnelTest, RedirectKeepsTunnelHostnameAddrMap) { EXPECT_NE(std::string::npos, connect_req.find("\r\nHost: " + target + "\r\n")); } + +// A failed handshake inside the tunnel must not leave the tunnel for reuse +TEST(ProxyTunnelTest, FailedHandshakeClosesTunnel) { + std::atomic origin_hits{0}; + proxy_tunnel_test::ScopedSSLServer origin; + origin.svr().Get(".*", [&](const Request &, Response &res) { + origin_hits++; + res.set_content("ok", "text/plain"); + }); + origin.listen(); + + proxy_tunnel_test::ScopedConnectProxy proxy(origin.port()); + ASSERT_NE(0, proxy.port()); + + SSLClient cli("127.0.0.1", origin.port()); + cli.enable_server_certificate_verification(false); + cli.set_proxy("127.0.0.1", proxy.port()); + cli.set_keep_alive(true); + cli.set_session_verifier( + [](tls::session_t) { return SSLVerifierResponse::CertificateRejected; }); + + auto res = cli.Get("/x"); + EXPECT_FALSE(res); + ASSERT_FALSE(cli.is_socket_open()); + + res = cli.Get("/x"); + EXPECT_FALSE(res); + EXPECT_EQ(2, proxy.connect_hits()); + + auto handle = cli.open_stream("GET", "/x"); + EXPECT_FALSE(handle.is_valid()); + EXPECT_EQ(3, proxy.connect_hits()); + EXPECT_EQ(0, origin_hits.load()); +} #endif namespace proxy_tunnel_test {