Compare commits

..
Author SHA1 Message Date
yhirose 36065c657c Bound the wait of WebSocket::close() as a whole
close() waited for the peer's Close reply with a read timeout that
applied to each read, so a peer that kept sending other frames, or sent
one frame a byte at a time, held close() for as long as it liked.

Bound the wait as a whole. close() sets the stream's max timeout, which
shortens each wait to what is left, and stops reading frames at the
deadline, which matters when the peer keeps the socket full and no wait
happens at all. WebSocketSSLStream gains set_max_timeout(), the one
stream a WebSocket uses that lacked it.

A read() running on another thread when close() is called still waits
for the reply up to its own read timeout, as documented. The docs now
say how to bound it.
2026-11-17 00:56:06 -05:00
Graeme Smecher d7b0d4bedb Drain the socket before closing a TLS connection (#2673)
Server::process_and_close_socket() half-closes the socket and drains what
the peer is still sending before the final close (#2534), so that a close
with unread data, or with bytes still in flight, is not answered with a
RST. A RST can make the peer's stack discard a response it has received
but not yet read, as Windows does.

SSLServer::process_and_close_socket() still closed outright. After a
completed handshake, shut down TLS as before (sending close_notify when
the exchange completed) and then drain the same way. A failed handshake
closes outright as before.

Fix #2672
2026-11-16 23:53:56 -05:00
yhirose 4af42e1907 Don't reuse a client connection with unread data on it
A kept-alive connection was reused while bytes that belong to no
request were waiting on it, and the next request read them as its
response. Such bytes are not a response (RFC 9112 9.2). A server may,
for one, send a 408 before it closes an idle connection.

Close the connection when they show up: after a response, if bytes
past it are already buffered in the stream or the TLS library, and
before reuse, if anything is readable on the socket. As in curl, the
reuse check no longer asks the TLS library whether the peer closed, so
it is the same for every TLS backend. A TLS message on an idle
connection, such as a late session ticket, now costs a new connection.
2026-11-16 23:41:25 -05:00
yhirose 1b40ce850b 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.
2026-11-16 23:41:25 -05:00
6 changed files with 180 additions and 16 deletions

No files matched your search

+1 -1
View File
@@ -568,7 +568,7 @@ Choose sizes that account for both your expected HTTP load and the maximum numbe
A single `WebSocket` (server-side) or `WebSocketClient` handle is shared by three potential callers: the thread running your handler (or holding the client), the heartbeat thread, and, if your code does its own thing, a separate thread calling `send()`/`close()` while another thread is blocked in `read()`.
**Supported**: calling `read()` from one thread while calling `send()`/`close()` from another. This is the common pattern for a client that reads incoming messages in a loop on one thread and sends from elsewhere (e.g. a UI thread). A message that is in flight when `close()` is called still arrives intact; `close()` sends the Close frame and returns, leaving the connection's read side to the thread that owns it, so it does not block waiting for the peer's Close reply in that case. The heartbeat thread's automatic pings use the same `send()` path internally, so they are safe to run concurrently with your `read()` loop too — for `wss://` this requires every TLS call on a connection to be serialized internally, which cpp-httplib does for you.
**Supported**: calling `read()` from one thread while calling `send()`/`close()` from another. This is the common pattern for a client that reads incoming messages in a loop on one thread and sends from elsewhere (e.g. a UI thread). A message that is in flight when `close()` is called still arrives intact; `close()` sends the Close frame and returns, leaving the connection's read side to the thread that owns it, so it does not block waiting for the peer's Close reply in that case. That thread's `read()` keeps waiting for the reply until its own read timeout (by default none on a client, 300 seconds on a server); to bound it, set one with `set_read_timeout()` before the read starts. The heartbeat thread's automatic pings use the same `send()` path internally, so they are safe to run concurrently with your `read()` loop too — for `wss://` this requires every TLS call on a connection to be serialized internally, which cpp-httplib does for you.
**Not supported**: calling `read()` from two threads at the same time on the same handle. The calls are serialized rather than left to corrupt each other, but which thread receives which message is unspecified, so there is nothing useful to build on it.
@@ -56,4 +56,4 @@ When you call `stop()`, new connections are refused, but handlers that are alrea
> **Warning:** There's a wait between calling `stop()` and `listen()` returning — it's the time in-flight requests take to finish. To enforce a timeout, you'll need to add your own shutdown timer in application code.
> **Note:** `stop()` doesn't interrupt WebSocket handlers. A handler looping on `read()` keeps running as long as its peer stays connected, and `listen()` doesn't return until it ends. Keep track of open WebSocket connections and `close()` them on shutdown, e.g. with `CloseStatus::GoingAway`.
> **Note:** `stop()` doesn't interrupt WebSocket handlers. A handler looping on `read()` keeps running as long as its peer stays connected, and `listen()` doesn't return until it ends. Keep track of open WebSocket connections and `close()` them on shutdown, e.g. with `CloseStatus::GoingAway`. The handler's `read()` then waits for the peer's Close reply up to its read timeout (300 seconds by default). To shorten that, call `set_read_timeout()` in the handler before the loop; `read()` then also returns `Timeout` whenever the peer stays idle that long, so the loop has to handle it.
@@ -56,4 +56,4 @@ int main() {
> **Warning:** `stop()`を呼んでから`listen()`が戻るまでには、処理中のリクエストが終わるのを待つ時間がかかります。タイムアウトを強制したい場合は、シャットダウン用のタイマーを別途用意するなど、アプリケーション側の工夫が必要です。
> **Note:** `stop()`はWebSocketハンドラを中断しません。`read()`をループで回しているハンドラは相手がつながっている限り動き続け、それが終わるまで`listen()`も戻りません。開いているWebSocket接続を記録しておき、シャットダウン時に`close()`(`CloseStatus::GoingAway`など)で閉じてください。
> **Note:** `stop()`はWebSocketハンドラを中断しません。`read()`をループで回しているハンドラは相手がつながっている限り動き続け、それが終わるまで`listen()`も戻りません。開いているWebSocket接続を記録しておき、シャットダウン時に`close()`(`CloseStatus::GoingAway`など)で閉じてください。そのあとハンドラの`read()`は、相手のClose応答を読み込みタイムアウト(既定は300秒)まで待ちます。短くしたい場合は、ループの前に`set_read_timeout()`を呼んでください。その場合、相手が黙っている間は`read()`が`Timeout`を返すので、ループ側で扱う必要があります。
+37 -9
View File
@@ -10936,6 +10936,7 @@ public:
socket_t socket() const override;
time_t duration() const override;
void set_read_timeout(time_t sec, time_t usec = 0) override;
void set_max_timeout(time_t msec) override;
void set_read_interrupt(std::function<bool()> interrupted) override;
private:
@@ -10943,14 +10944,13 @@ private:
socket_t sock_;
tls::session_t session_;
// WebSocket::close() shortens the read timeout from the closing thread
// while the receive thread is inside wait_readable(), so these two are read
// and written concurrently. The write timeouts are never mutated.
// May change while another thread is in wait_readable(); write timeouts don't
std::atomic<time_t> read_timeout_sec_;
std::atomic<time_t> read_timeout_usec_;
time_t write_timeout_sec_;
time_t write_timeout_usec_;
const std::chrono::time_point<std::chrono::steady_clock> start_time_;
std::atomic<time_t> max_timeout_msec_{0};
std::atomic<std::chrono::steady_clock::rep> start_time_;
std::function<bool()> read_interrupted_;
};
@@ -13580,7 +13580,7 @@ inline WebSocketSSLStream::WebSocketSSLStream(socket_t sock,
read_timeout_usec_(read_timeout_usec),
write_timeout_sec_(write_timeout_sec),
write_timeout_usec_(write_timeout_usec),
start_time_(std::chrono::steady_clock::now()) {
start_time_(std::chrono::steady_clock::now().time_since_epoch().count()) {
// The receive and send paths run on different threads, so each TLS call is
// driven in non-blocking mode and readiness is awaited with select()
// outside the session lock. Set the socket non-blocking once here; it is
@@ -13599,7 +13599,18 @@ inline bool WebSocketSSLStream::is_readable() const {
}
inline bool WebSocketSSLStream::wait_readable() const {
return select_read_interruptible(sock_, read_timeout_sec_, read_timeout_usec_,
auto max_timeout_msec = max_timeout_msec_.load();
if (max_timeout_msec <= 0) {
return select_read_interruptible(sock_, read_timeout_sec_,
read_timeout_usec_, read_interrupted_) > 0;
}
time_t read_timeout_sec;
time_t read_timeout_usec;
calc_actual_timeout(max_timeout_msec, duration(), read_timeout_sec_,
read_timeout_usec_, read_timeout_sec, read_timeout_usec);
return select_read_interruptible(sock_, read_timeout_sec, read_timeout_usec,
read_interrupted_) > 0;
}
@@ -13689,12 +13700,20 @@ inline void WebSocketSSLStream::get_local_ip_and_port(std::string &ip,
inline socket_t WebSocketSSLStream::socket() const { return sock_; }
inline time_t WebSocketSSLStream::duration() const {
auto start = std::chrono::steady_clock::time_point(
std::chrono::steady_clock::duration(start_time_.load()));
return static_cast<time_t>(
std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::steady_clock::now() - start_time_)
std::chrono::steady_clock::now() - start)
.count());
}
// Start time first: a reader that sees the new bound also sees its start
inline void WebSocketSSLStream::set_max_timeout(time_t msec) {
start_time_ = std::chrono::steady_clock::now().time_since_epoch().count();
max_timeout_msec_ = msec;
}
inline void WebSocketSSLStream::set_read_timeout(time_t sec, time_t usec) {
read_timeout_sec_ = sec;
read_timeout_usec_ = usec;
@@ -19160,8 +19179,12 @@ inline bool SSLServer::process_and_close_socket(socket_t sock) {
auto cleanup = detail::scope_exit([&] {
if (handshake_done) { shutdown(session, !websocket_upgraded && ret); }
free_session(session);
if (handshake_done) {
detail::drain_and_close_socket(sock);
} else {
detail::shutdown_socket(sock);
detail::close_socket(sock);
}
});
// Perform TLS accept handshake with timeout
@@ -23866,13 +23889,18 @@ inline void WebSocket::close(CloseStatus status, const std::string &reason) {
std::unique_lock<std::mutex> read_lock(read_mutex_, std::try_to_lock);
if (!read_lock.owns_lock()) { return; }
// Use a short timeout to avoid hanging if the peer doesn't respond.
// A max timeout turns a negative (unbounded) read timeout into 0
strm_.set_read_timeout(CPPHTTPLIB_WEBSOCKET_CLOSE_TIMEOUT_SECOND, 0);
strm_.set_max_timeout(CPPHTTPLIB_WEBSOCKET_CLOSE_TIMEOUT_SECOND * 1000);
// The max timeout cuts a trickled frame short, the deadline a frame flood
auto deadline =
detail::deadline_after(CPPHTTPLIB_WEBSOCKET_CLOSE_TIMEOUT_SECOND, 0);
Opcode op;
std::string resp;
bool fin;
while (impl::read_websocket_frame(strm_, op, resp, fin, is_server_, 125) ==
while (std::chrono::steady_clock::now() < deadline &&
impl::read_websocket_frame(strm_, op, resp, fin, is_server_, 125) ==
impl::FrameRead::Ok) {
if (op == Opcode::Close) { break; }
}
+1 -1
View File
@@ -260,7 +260,7 @@ endif
test_benchmark : test_benchmark.cc ../httplib.h Makefile
$(CXX) -o $@ -I.. $(CXXFLAGS) test_benchmark.cc gtest/src/gtest-all.cc gtest/src/gtest_main.cc -Igtest -Igtest/include $(BENCHMARK_LIBS)
test_websocket_heartbeat : test_websocket_heartbeat.cc ../httplib.h Makefile
test_websocket_heartbeat : test_websocket_heartbeat.cc ../httplib.h Makefile cert.pem
$(CXX) -o $@ -I.. $(CXXFLAGS) test_websocket_heartbeat.cc $(TEST_ARGS)
@file $@
+139 -3
View File
@@ -1,10 +1,10 @@
// Standalone test for WebSocket automatic heartbeat.
// Compiled with a 1-second ping interval so we can verify heartbeat behavior
// without waiting 30 seconds.
// Standalone test for WebSocket heartbeat and close() timing, compiled with
// short intervals and timeouts so the tests don't wait for the defaults.
#define CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND 1
#define CPPHTTPLIB_WEBSOCKET_CLIENT_READ_TIMEOUT_SECOND 3
#define CPPHTTPLIB_WEBSOCKET_SERVER_READ_TIMEOUT_SECOND 3
#define CPPHTTPLIB_WEBSOCKET_CLOSE_TIMEOUT_SECOND 1
#include <httplib.h>
#include "gtest/gtest.h"
@@ -289,3 +289,139 @@ TEST_F(WebSocketHeartbeatTest, MultipleHeartbeatCycles) {
client.close();
}
// A raw client never answers the server's close() and sends `bytes`, `chunk`
// bytes at a time `gap` apart; close() must still return at its 1 s timeout.
static void expect_close_bounded(bool use_tls, const std::string &bytes,
size_t chunk, std::chrono::milliseconds gap) {
std::unique_ptr<Server> svr;
#ifdef CPPHTTPLIB_SSL_ENABLED
if (use_tls) { svr.reset(new SSLServer("cert.pem", "key.pem")); }
#endif
if (!svr) { svr.reset(new Server); }
svr->set_websocket_ping_interval(0);
std::atomic<bool> upgraded{false};
std::atomic<bool> closed{false};
std::chrono::steady_clock::duration close_took{};
svr->WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
while (!upgraded) {
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
auto start = std::chrono::steady_clock::now();
ws.close();
close_took = std::chrono::steady_clock::now() - start;
closed = true;
});
auto port = svr->bind_to_any_port("127.0.0.1");
ASSERT_GT(port, 0);
std::thread t([&] { svr->listen_after_bind(); });
auto se = detail::scope_exit([&] {
upgraded = true; // Releases the handler when an assertion bails out early
svr->stop();
t.join();
});
svr->wait_until_ready();
auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
ASSERT_NE(INVALID_SOCKET, sock);
auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
sockaddr_in addr{};
addr.sin_family = AF_INET;
addr.sin_port = htons(static_cast<uint16_t>(port));
::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
ASSERT_EQ(0,
::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
std::unique_ptr<Stream> strm;
#ifdef CPPHTTPLIB_SSL_ENABLED
tls::ctx_t ctx = nullptr;
tls::session_t session = nullptr;
auto tls_se = detail::scope_exit([&] {
if (session) { tls::free_session(session); }
if (ctx) { tls::free_context(ctx); }
});
if (use_tls) {
ctx = tls::create_client_context();
tls::set_verify_client(ctx, false); // The test certificate is self-signed
session = tls::create_session(ctx, sock);
ASSERT_TRUE(tls::connect_nonblocking(session, sock, 5, 0, nullptr));
strm.reset(new detail::SSLSocketStream(sock, session, 5, 0, 5, 0));
}
#endif
if (!strm) { strm.reset(new detail::SocketStream(sock, 5, 0, 5, 0)); }
const std::string upgrade = "GET /ws HTTP/1.1\r\n"
"Host: 127.0.0.1\r\n"
"Upgrade: websocket\r\n"
"Connection: Upgrade\r\n"
"Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
"Sec-WebSocket-Version: 13\r\n"
"\r\n";
ASSERT_EQ(static_cast<ssize_t>(upgrade.size()),
strm->write(upgrade.data(), upgrade.size()));
std::string response;
char c;
while (response.find("\r\n\r\n") == std::string::npos &&
strm->read(&c, 1) == 1) {
response += c;
}
ASSERT_NE(std::string::npos, response.find(" 101 "));
upgraded = true;
// Without the bound, close() would wait as long as the client sends
auto give_up = std::chrono::steady_clock::now() + std::chrono::seconds(4);
while (!closed && std::chrono::steady_clock::now() < give_up) {
for (size_t off = 0; off < bytes.size() && !closed;) {
auto n = strm->write(bytes.data() + off,
(std::min)(chunk, bytes.size() - off));
if (n <= 0) { break; }
off += static_cast<size_t>(n);
auto next = std::chrono::steady_clock::now() + gap;
while (!closed && std::chrono::steady_clock::now() < next) {
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
}
}
while (!closed) {
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
EXPECT_LT(close_took, std::chrono::milliseconds(2500));
}
// Empty masked Ping frames, enough to keep the socket full
static std::string ping_flood() {
const std::string ping("\x89\x80\0\0\0\0", 6);
std::string bytes;
while (bytes.size() < 64 * 1024) {
bytes += ping;
}
return bytes;
}
// A masked 20-byte Ping; sent a byte at a time, it outlasts the close timeout
static std::string ping_with_payload() {
return std::string("\x89\x8e\0\0\0\0", 6) + std::string(14, 'x');
}
TEST(WebSocketCloseTest, BoundedAgainstPeerThatKeepsSending) {
expect_close_bounded(/*use_tls=*/false, ping_flood(), ping_flood().size(),
std::chrono::milliseconds(0));
}
TEST(WebSocketCloseTest, BoundedAgainstPeerThatTricklesAFrame) {
expect_close_bounded(/*use_tls=*/false, ping_with_payload(), 1,
std::chrono::milliseconds(300));
}
#ifdef CPPHTTPLIB_SSL_ENABLED
TEST(WebSocketCloseTest, SSLBoundedAgainstPeerThatKeepsSending) {
expect_close_bounded(/*use_tls=*/true, ping_flood(), ping_flood().size(),
std::chrono::milliseconds(0));
}
TEST(WebSocketCloseTest, SSLBoundedAgainstPeerThatTricklesAFrame) {
expect_close_bounded(/*use_tls=*/true, ping_with_payload(), 1,
std::chrono::milliseconds(300));
}
#endif