mirror of
https://github.com/yhirose/cpp-httplib.git
synced 2026-11-17 19:30:54 +00:00
Compare commits
4
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
36065c657c | ||
|
|
d7b0d4bedb | ||
|
|
4af42e1907 | ||
|
|
1b40ce850b |
No files matched your search
+1
-1
@@ -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`を返すので、ループ側で扱う必要があります。
|
||||
@@ -3031,8 +3031,8 @@ protected:
|
||||
void disconnect(bool gracefully);
|
||||
|
||||
// Under socket_mutex_: whether the connection kept alive can take another
|
||||
// request. One the peer has closed, or one set up under TLS settings changed
|
||||
// since, is closed instead.
|
||||
// request. One with anything to read, or one set up under TLS settings
|
||||
// changed since, is closed instead.
|
||||
bool socket_reusable();
|
||||
|
||||
// TLS settings apply as a connection is set up, so a change makes the
|
||||
@@ -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;
|
||||
@@ -15801,14 +15820,8 @@ inline void ClientImpl::disconnect(bool gracefully) {
|
||||
inline bool ClientImpl::socket_reusable() {
|
||||
if (!socket_.is_open()) { return false; }
|
||||
|
||||
auto is_alive = detail::is_socket_alive(socket_.sock);
|
||||
#ifdef CPPHTTPLIB_SSL_ENABLED
|
||||
if (is_alive && is_ssl() && tls::is_peer_closed(socket_.ssl, socket_.sock)) {
|
||||
is_alive = false;
|
||||
}
|
||||
#endif
|
||||
if (!is_alive) {
|
||||
// Peer seems gone — non-graceful shutdown to avoid SIGPIPE.
|
||||
// RFC 9112 9.2: data with no request outstanding is not a response
|
||||
if (detail::select_read(socket_.sock, 0, 0) != 0) {
|
||||
disconnect(/*gracefully=*/false);
|
||||
return false;
|
||||
}
|
||||
@@ -16459,9 +16472,10 @@ inline bool ClientImpl::handle_request(Stream &strm, Request &req,
|
||||
// to do these things to the socket if another thread is using the socket.
|
||||
std::lock_guard<std::mutex> guard(socket_mutex_);
|
||||
// Also when the request asked for it (e.g. a body that was never sent,
|
||||
// or "Connection: close"), so that a redirect or an auth retry below does
|
||||
// not reuse the socket.
|
||||
// or "Connection: close") or bytes follow the response (RFC 9112 9.2), so
|
||||
// that a redirect or an auth retry below does not reuse the socket.
|
||||
if (socket_should_be_closed_when_request_is_done_ || close_connection ||
|
||||
strm.is_readable() ||
|
||||
detail::has_header_token(res.headers, "Connection", "close") ||
|
||||
(res.version == "HTTP/1.0" && res.reason != "Connection established")) {
|
||||
disconnect(/*gracefully=*/true);
|
||||
@@ -19165,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
|
||||
@@ -19327,6 +19345,8 @@ inline bool SSLClient::setup_proxy_connection(
|
||||
}
|
||||
|
||||
if (!initialize_ssl(socket, error)) {
|
||||
shutdown_socket(socket);
|
||||
close_socket(socket);
|
||||
success = false;
|
||||
return false;
|
||||
}
|
||||
@@ -23869,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
@@ -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 $@
|
||||
|
||||
|
||||
+203
@@ -13415,6 +13415,175 @@ TEST(KeepAliveTest, MaxCountZeroSetsNoLimit) {
|
||||
EXPECT_EQ(1u, remote_ports.size());
|
||||
}
|
||||
|
||||
// Forward declaration (see the base64_encode note).
|
||||
namespace httplib {
|
||||
namespace detail {
|
||||
ssize_t select_read(socket_t sock, time_t sec, time_t usec);
|
||||
} // namespace detail
|
||||
} // namespace httplib
|
||||
|
||||
// RFC 9112 9.2: an unsolicited 408 must not be read as the next response
|
||||
static void expect_no_reuse_with_unread_data(bool use_tls, bool same_write) {
|
||||
#ifndef _WIN32
|
||||
signal(SIGPIPE, SIG_IGN);
|
||||
#endif
|
||||
|
||||
auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
|
||||
ASSERT_NE(INVALID_SOCKET, srv);
|
||||
auto srv_se = detail::scope_exit([&] { detail::close_socket(srv); });
|
||||
default_socket_options(srv);
|
||||
|
||||
sockaddr_in addr{};
|
||||
addr.sin_family = AF_INET;
|
||||
addr.sin_port = 0;
|
||||
::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
|
||||
ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
|
||||
ASSERT_EQ(0, ::listen(srv, 2));
|
||||
socklen_t addr_len = sizeof(addr);
|
||||
ASSERT_EQ(0,
|
||||
::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len));
|
||||
auto port = ntohs(addr.sin_port);
|
||||
|
||||
struct Peer {
|
||||
socket_t sock = INVALID_SOCKET;
|
||||
#ifdef CPPHTTPLIB_SSL_ENABLED
|
||||
tls::session_t session = nullptr;
|
||||
#endif
|
||||
};
|
||||
|
||||
#ifdef CPPHTTPLIB_SSL_ENABLED
|
||||
tls::ctx_t ctx = nullptr;
|
||||
if (use_tls) {
|
||||
ctx = tls::create_server_context();
|
||||
tls::set_server_cert_file(ctx, SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
|
||||
nullptr);
|
||||
}
|
||||
auto ctx_se = detail::scope_exit([&] {
|
||||
if (ctx) { tls::free_context(ctx); }
|
||||
});
|
||||
#endif
|
||||
|
||||
auto close_peer = [](Peer &peer) {
|
||||
#ifdef CPPHTTPLIB_SSL_ENABLED
|
||||
if (peer.session) { tls::free_session(peer.session); }
|
||||
#endif
|
||||
if (peer.sock != INVALID_SOCKET) { detail::close_socket(peer.sock); }
|
||||
};
|
||||
auto accept_peer = [&]() {
|
||||
Peer peer;
|
||||
if (detail::select_read(srv, 5, 0) <= 0) { return peer; }
|
||||
peer.sock = ::accept(srv, nullptr, nullptr);
|
||||
if (peer.sock == INVALID_SOCKET) { return peer; }
|
||||
detail::set_socket_opt_time(peer.sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
|
||||
#ifdef CPPHTTPLIB_SSL_ENABLED
|
||||
if (use_tls) {
|
||||
peer.session = tls::create_session(ctx, peer.sock);
|
||||
tls::TlsError err;
|
||||
if (!tls::accept_nonblocking(peer.session, peer.sock, 5, 0, &err)) {
|
||||
close_peer(peer);
|
||||
return Peer();
|
||||
}
|
||||
}
|
||||
#endif
|
||||
return peer;
|
||||
};
|
||||
auto read_some = [](const Peer &peer, char *buf, size_t len) -> ssize_t {
|
||||
#ifdef CPPHTTPLIB_SSL_ENABLED
|
||||
tls::TlsError err;
|
||||
if (peer.session) { return tls::read(peer.session, buf, len, err); }
|
||||
#endif
|
||||
return detail::read_socket(peer.sock, buf, len, 0);
|
||||
};
|
||||
auto read_head = [&](const Peer &peer) {
|
||||
std::string head;
|
||||
char buf[1024];
|
||||
while (head.find("\r\n\r\n") == std::string::npos) {
|
||||
auto n = read_some(peer, buf, sizeof(buf));
|
||||
if (n <= 0) { break; }
|
||||
head.append(buf, static_cast<size_t>(n));
|
||||
}
|
||||
};
|
||||
auto send_text = [](const Peer &peer, const std::string &text) {
|
||||
#ifdef CPPHTTPLIB_SSL_ENABLED
|
||||
tls::TlsError err;
|
||||
if (peer.session) {
|
||||
tls::write(peer.session, text.data(), text.size(), err);
|
||||
return;
|
||||
}
|
||||
#endif
|
||||
detail::send_socket(peer.sock, text.data(), text.size(), 0);
|
||||
};
|
||||
|
||||
const std::string first = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nfirst";
|
||||
const std::string stray = "HTTP/1.1 408 Request Timeout\r\n"
|
||||
"Connection: close\r\nContent-Length: 0\r\n\r\n";
|
||||
|
||||
// Sent once the first response is read, so that it lands on an idle socket
|
||||
std::promise<void> first_response_read;
|
||||
auto first_response_read_future = first_response_read.get_future();
|
||||
auto server_thread = std::thread([&] {
|
||||
auto peer1 = accept_peer();
|
||||
if (peer1.sock == INVALID_SOCKET) { return; }
|
||||
read_head(peer1);
|
||||
if (same_write) {
|
||||
send_text(peer1, first + stray);
|
||||
} else {
|
||||
send_text(peer1, first);
|
||||
first_response_read_future.wait_for(std::chrono::seconds(5));
|
||||
send_text(peer1, stray);
|
||||
}
|
||||
|
||||
// peer1 stays open, so only the unread data can tell the client
|
||||
auto peer2 = accept_peer();
|
||||
if (peer2.sock != INVALID_SOCKET) {
|
||||
read_head(peer2);
|
||||
send_text(peer2, "HTTP/1.1 200 OK\r\nContent-Length: 6\r\n"
|
||||
"Connection: close\r\n\r\nsecond");
|
||||
close_peer(peer2);
|
||||
}
|
||||
close_peer(peer1);
|
||||
});
|
||||
auto server_se = detail::scope_exit([&] { server_thread.join(); });
|
||||
|
||||
Client cli((use_tls ? "https://127.0.0.1:" : "http://127.0.0.1:") +
|
||||
std::to_string(port));
|
||||
#ifdef CPPHTTPLIB_SSL_ENABLED
|
||||
cli.enable_server_certificate_verification(false);
|
||||
#endif
|
||||
cli.set_keep_alive(true);
|
||||
cli.set_read_timeout(5, 0);
|
||||
|
||||
auto res = cli.Get("/1");
|
||||
first_response_read.set_value();
|
||||
ASSERT_TRUE(res) << "Error: " << to_string(res.error());
|
||||
EXPECT_EQ("first", res->body);
|
||||
|
||||
if (!same_write) { ASSERT_GT(detail::select_read(cli.socket(), 5, 0), 0); }
|
||||
|
||||
res = cli.Get("/2");
|
||||
ASSERT_TRUE(res) << "Error: " << to_string(res.error());
|
||||
EXPECT_EQ(StatusCode::OK_200, res->status);
|
||||
EXPECT_EQ("second", res->body);
|
||||
}
|
||||
|
||||
TEST(KeepAliveTest, ClientDoesNotReuseConnectionWithUnreadData) {
|
||||
expect_no_reuse_with_unread_data(/*use_tls=*/false, /*same_write=*/false);
|
||||
}
|
||||
|
||||
TEST(KeepAliveTest, ClientDoesNotReuseConnectionWithDataPastResponse) {
|
||||
expect_no_reuse_with_unread_data(/*use_tls=*/false, /*same_write=*/true);
|
||||
}
|
||||
|
||||
#ifdef CPPHTTPLIB_SSL_ENABLED
|
||||
TEST(KeepAliveTest, SSLClientDoesNotReuseConnectionWithUnreadData) {
|
||||
expect_no_reuse_with_unread_data(/*use_tls=*/true, /*same_write=*/false);
|
||||
}
|
||||
|
||||
TEST(KeepAliveTest, SSLClientDoesNotReuseConnectionWithDataPastResponse) {
|
||||
expect_no_reuse_with_unread_data(/*use_tls=*/true, /*same_write=*/true);
|
||||
}
|
||||
#endif
|
||||
|
||||
TEST(KeepAliveTest, Issue1959) {
|
||||
Server svr;
|
||||
svr.set_keep_alive_timeout(5);
|
||||
@@ -32485,6 +32654,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<int> 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 {
|
||||
|
||||
@@ -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
|
||||
Reference in new issue
Block a user