mirror of
https://github.com/yhirose/cpp-httplib.git
synced 2026-11-18 19:40:57 +00:00
Let Server::stop() end a WebSocket handler's read() (#2682)
stop() takes the listening socket away, and listen() then waits for every handler to return. A WebSocket handler waiting in read() on a client that stays connected never learned of the stop: with no read timeout it waited for the 300 s backstop, and with one it got Timeout back on an open connection, so a `while (ws.read(msg) != Fail)` loop went on forever and listen() with it. The server now hands each WebSocket a predicate for its own stop, and the WebSocket's read interrupt answers to it as it does to a pong timeout. A read cut short while the server stops, between messages or in the middle of a fragmented one, sends a Close with 1001 Going Away and returns Fail. That close does not wait for the peer's reply, so a stop is not held up per connection. A server WebSocket's reads now wait in the interruptible slices whatever the heartbeat settings, as keep-alive connections already do for the same check.
This commit is contained in:
1 parent
5a956da084
commit
92435b31b3
2 files changed
+155
-13
No files matched your search
@@ -2443,6 +2443,8 @@ protected:
|
|||||||
}
|
}
|
||||||
|
|
||||||
std::atomic<socket_t> svr_sock_{INVALID_SOCKET};
|
std::atomic<socket_t> svr_sock_{INVALID_SOCKET};
|
||||||
|
// stop() takes the listening socket away; listen() then waits for handlers
|
||||||
|
bool is_stopping() const { return svr_sock_ == INVALID_SOCKET; }
|
||||||
|
|
||||||
std::vector<std::string> trusted_proxies_;
|
std::vector<std::string> trusted_proxies_;
|
||||||
|
|
||||||
@@ -4732,23 +4734,33 @@ private:
|
|||||||
WebSocket(
|
WebSocket(
|
||||||
Stream &strm, const Request &req, bool is_server,
|
Stream &strm, const Request &req, bool is_server,
|
||||||
time_t ping_interval_sec = CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND,
|
time_t ping_interval_sec = CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND,
|
||||||
int max_missed_pongs = CPPHTTPLIB_WEBSOCKET_MAX_MISSED_PONGS)
|
int max_missed_pongs = CPPHTTPLIB_WEBSOCKET_MAX_MISSED_PONGS,
|
||||||
|
std::function<bool()> server_stopping = nullptr)
|
||||||
: strm_(strm), req_(req), is_server_(is_server),
|
: strm_(strm), req_(req), is_server_(is_server),
|
||||||
ping_interval_sec_(ping_interval_sec),
|
ping_interval_sec_(ping_interval_sec),
|
||||||
max_missed_pongs_(max_missed_pongs) {
|
max_missed_pongs_(max_missed_pongs),
|
||||||
|
server_stopping_(std::move(server_stopping)) {
|
||||||
|
interrupt_reads();
|
||||||
start_heartbeat();
|
start_heartbeat();
|
||||||
}
|
}
|
||||||
|
|
||||||
WebSocket(
|
WebSocket(
|
||||||
std::unique_ptr<Stream> &&owned_strm, const Request &req, bool is_server,
|
std::unique_ptr<Stream> &&owned_strm, const Request &req, bool is_server,
|
||||||
time_t ping_interval_sec = CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND,
|
time_t ping_interval_sec = CPPHTTPLIB_WEBSOCKET_PING_INTERVAL_SECOND,
|
||||||
int max_missed_pongs = CPPHTTPLIB_WEBSOCKET_MAX_MISSED_PONGS)
|
int max_missed_pongs = CPPHTTPLIB_WEBSOCKET_MAX_MISSED_PONGS,
|
||||||
|
std::function<bool()> server_stopping = nullptr)
|
||||||
: strm_(*owned_strm), owned_strm_(std::move(owned_strm)), req_(req),
|
: strm_(*owned_strm), owned_strm_(std::move(owned_strm)), req_(req),
|
||||||
is_server_(is_server), ping_interval_sec_(ping_interval_sec),
|
is_server_(is_server), ping_interval_sec_(ping_interval_sec),
|
||||||
max_missed_pongs_(max_missed_pongs) {
|
max_missed_pongs_(max_missed_pongs),
|
||||||
|
server_stopping_(std::move(server_stopping)) {
|
||||||
|
interrupt_reads();
|
||||||
start_heartbeat();
|
start_heartbeat();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
void interrupt_reads();
|
||||||
|
bool server_stopping() const {
|
||||||
|
return server_stopping_ && server_stopping_();
|
||||||
|
}
|
||||||
void start_heartbeat();
|
void start_heartbeat();
|
||||||
bool send_frame(Opcode op, const char *data, size_t len, bool fin = true);
|
bool send_frame(Opcode op, const char *data, size_t len, bool fin = true);
|
||||||
|
|
||||||
@@ -4762,6 +4774,8 @@ private:
|
|||||||
std::atomic<bool> closed_{false};
|
std::atomic<bool> closed_{false};
|
||||||
// Set when the peer stopped answering pings, to end a read() waiting on it
|
// Set when the peer stopped answering pings, to end a read() waiting on it
|
||||||
std::atomic<bool> pong_timed_out_{false};
|
std::atomic<bool> pong_timed_out_{false};
|
||||||
|
// A server connection's view of Server::stop(), which ends its read() too
|
||||||
|
std::function<bool()> server_stopping_;
|
||||||
// Set once the caller has bounded read() through set_read_timeout(). Until
|
// Set once the caller has bounded read() through set_read_timeout(). Until
|
||||||
// then the timeout in effect is the compile-time default, and elapsing it
|
// then the timeout in effect is the compile-time default, and elapsing it
|
||||||
// is a failure that closes the connection, not a Timeout.
|
// is a failure that closes the connection, not a Timeout.
|
||||||
@@ -14383,9 +14397,7 @@ inline bool
|
|||||||
Server::write_content_with_provider(Stream &strm, const Request &req,
|
Server::write_content_with_provider(Stream &strm, const Request &req,
|
||||||
Response &res, const std::string &boundary,
|
Response &res, const std::string &boundary,
|
||||||
const std::string &content_type) {
|
const std::string &content_type) {
|
||||||
auto is_shutting_down = [this]() {
|
auto is_shutting_down = [this]() { return is_stopping(); };
|
||||||
return this->svr_sock_ == INVALID_SOCKET;
|
|
||||||
};
|
|
||||||
|
|
||||||
if (res.content_length_ > 0) {
|
if (res.content_length_ > 0) {
|
||||||
if (!detail::is_partial_content(req, res)) {
|
if (!detail::is_partial_content(req, res)) {
|
||||||
@@ -15555,6 +15567,7 @@ Server::process_request(Stream &strm, const std::string &remote_addr,
|
|||||||
|
|
||||||
connection_closed = true;
|
connection_closed = true;
|
||||||
if (websocket_upgraded) { *websocket_upgraded = true; }
|
if (websocket_upgraded) { *websocket_upgraded = true; }
|
||||||
|
auto stopping = [this] { return is_stopping(); };
|
||||||
|
|
||||||
#ifdef CPPHTTPLIB_SSL_ENABLED
|
#ifdef CPPHTTPLIB_SSL_ENABLED
|
||||||
if (req.ssl) {
|
if (req.ssl) {
|
||||||
@@ -15568,7 +15581,7 @@ Server::process_request(Stream &strm, const std::string &remote_addr,
|
|||||||
write_timeout_sec_, write_timeout_usec_));
|
write_timeout_sec_, write_timeout_usec_));
|
||||||
ws::WebSocket ws(std::move(ws_strm), req, true,
|
ws::WebSocket ws(std::move(ws_strm), req, true,
|
||||||
websocket_ping_interval_sec_,
|
websocket_ping_interval_sec_,
|
||||||
websocket_max_missed_pongs_);
|
websocket_max_missed_pongs_, stopping);
|
||||||
ws_route->handler(req, ws);
|
ws_route->handler(req, ws);
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
@@ -15576,7 +15589,7 @@ Server::process_request(Stream &strm, const std::string &remote_addr,
|
|||||||
// Use WebSocket-specific read timeout instead of HTTP timeout
|
// Use WebSocket-specific read timeout instead of HTTP timeout
|
||||||
strm.set_read_timeout(CPPHTTPLIB_WEBSOCKET_SERVER_READ_TIMEOUT_SECOND, 0);
|
strm.set_read_timeout(CPPHTTPLIB_WEBSOCKET_SERVER_READ_TIMEOUT_SECOND, 0);
|
||||||
ws::WebSocket ws(strm, req, true, websocket_ping_interval_sec_,
|
ws::WebSocket ws(strm, req, true, websocket_ping_interval_sec_,
|
||||||
websocket_max_missed_pongs_);
|
websocket_max_missed_pongs_, stopping);
|
||||||
ws_route->handler(req, ws);
|
ws_route->handler(req, ws);
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
@@ -23832,6 +23845,13 @@ inline ReadResult WebSocket::read(std::string &msg) {
|
|||||||
};
|
};
|
||||||
|
|
||||||
std::unique_lock<std::mutex> read_lock(read_mutex_);
|
std::unique_lock<std::mutex> read_lock(read_mutex_);
|
||||||
|
// A server going down closes the connection rather than wait on it: its
|
||||||
|
// listen() waits for this handler to return.
|
||||||
|
auto going_away = [&]() -> ReadResult {
|
||||||
|
read_lock.unlock();
|
||||||
|
close(CloseStatus::GoingAway, "server stopping");
|
||||||
|
return Fail;
|
||||||
|
};
|
||||||
while (!closed_) {
|
while (!closed_) {
|
||||||
Opcode opcode;
|
Opcode opcode;
|
||||||
std::string payload;
|
std::string payload;
|
||||||
@@ -23840,6 +23860,7 @@ inline ReadResult WebSocket::read(std::string &msg) {
|
|||||||
impl::FrameRead r =
|
impl::FrameRead r =
|
||||||
impl::read_websocket_frame(strm_, opcode, payload, fin, is_server_,
|
impl::read_websocket_frame(strm_, opcode, payload, fin, is_server_,
|
||||||
CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH);
|
CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH);
|
||||||
|
if (r != impl::FrameRead::Ok && server_stopping()) { return going_away(); }
|
||||||
// A timeout landed on a frame boundary of an open connection: it is
|
// A timeout landed on a frame boundary of an open connection: it is
|
||||||
// untouched and still usable, so hand control back without closing it.
|
// untouched and still usable, so hand control back without closing it.
|
||||||
// That is only useful to a caller who asked for the timeout; the
|
// That is only useful to a caller who asked for the timeout; the
|
||||||
@@ -23881,6 +23902,7 @@ inline ReadResult WebSocket::read(std::string &msg) {
|
|||||||
if (impl::read_websocket_frame(strm_, cont_opcode, cont_payload,
|
if (impl::read_websocket_frame(strm_, cont_opcode, cont_payload,
|
||||||
cont_fin, is_server_,
|
cont_fin, is_server_,
|
||||||
max_len) != impl::FrameRead::Ok) {
|
max_len) != impl::FrameRead::Ok) {
|
||||||
|
if (server_stopping()) { return going_away(); }
|
||||||
closed_ = true;
|
closed_ = true;
|
||||||
return Fail;
|
return Fail;
|
||||||
}
|
}
|
||||||
@@ -23986,12 +24008,17 @@ inline WebSocket::~WebSocket() {
|
|||||||
strm_.set_read_interrupt(nullptr);
|
strm_.set_read_interrupt(nullptr);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// A pong timeout ends a read() blocked on the silent peer, and so does the
|
||||||
|
// server stopping: its listen() waits for every handler to return.
|
||||||
|
inline void WebSocket::interrupt_reads() {
|
||||||
|
auto watches_pongs = ping_interval_sec_ > 0 && max_missed_pongs_ > 0;
|
||||||
|
if (!watches_pongs && !server_stopping_) { return; }
|
||||||
|
strm_.set_read_interrupt(
|
||||||
|
[this] { return pong_timed_out_.load() || server_stopping(); });
|
||||||
|
}
|
||||||
|
|
||||||
inline void WebSocket::start_heartbeat() {
|
inline void WebSocket::start_heartbeat() {
|
||||||
if (ping_interval_sec_ <= 0) { return; }
|
if (ping_interval_sec_ <= 0) { return; }
|
||||||
// A pong timeout ends a read() blocked on the silent peer
|
|
||||||
if (max_missed_pongs_ > 0) {
|
|
||||||
strm_.set_read_interrupt([this] { return pong_timed_out_.load(); });
|
|
||||||
}
|
|
||||||
ping_thread_ = std::thread([this]() {
|
ping_thread_ = std::thread([this]() {
|
||||||
std::unique_lock<std::mutex> lock(ping_mutex_);
|
std::unique_lock<std::mutex> lock(ping_mutex_);
|
||||||
// The predicate keeps a spurious wakeup from sending a ping early
|
// The predicate keeps a spurious wakeup from sending a ping early
|
||||||
|
|||||||
+115
@@ -30628,6 +30628,121 @@ TEST(WebSocketTest, PongTimeoutEndsABlockedReadOverTLS) {
|
|||||||
}
|
}
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
|
// listen() returns only after every handler has, so Server::stop() has to end
|
||||||
|
// a WebSocket handler's read() waiting on a client that stays connected and
|
||||||
|
// quiet, whether or not the handler bounded its reads, and the client's
|
||||||
|
// connection ends with it.
|
||||||
|
static void check_stop_ends_websocket_read(Server &svr, const char *scheme,
|
||||||
|
bool bounded) {
|
||||||
|
svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
|
||||||
|
if (bounded) { ws.set_read_timeout(0, 50000); }
|
||||||
|
std::string msg;
|
||||||
|
while (ws.read(msg) != ws::Fail) {}
|
||||||
|
});
|
||||||
|
|
||||||
|
auto port = svr.bind_to_any_port(HOST);
|
||||||
|
std::thread t([&]() { svr.listen_after_bind(); });
|
||||||
|
auto se = detail::scope_exit([&] {
|
||||||
|
if (t.joinable()) {
|
||||||
|
svr.stop();
|
||||||
|
t.join();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
svr.wait_until_ready();
|
||||||
|
|
||||||
|
ws::WebSocketClient client(std::string(scheme) +
|
||||||
|
"://localhost:" + std::to_string(port) + "/ws");
|
||||||
|
#ifdef CPPHTTPLIB_SSL_ENABLED
|
||||||
|
client.enable_server_certificate_verification(false);
|
||||||
|
#endif
|
||||||
|
client.set_read_timeout(2);
|
||||||
|
ASSERT_TRUE(client.connect());
|
||||||
|
|
||||||
|
auto stopped = std::async(std::launch::async, [&] {
|
||||||
|
svr.stop();
|
||||||
|
t.join();
|
||||||
|
});
|
||||||
|
std::string msg;
|
||||||
|
EXPECT_EQ(ws::Fail, client.read(msg));
|
||||||
|
EXPECT_FALSE(client.is_open());
|
||||||
|
auto in_time =
|
||||||
|
stopped.wait_for(std::chrono::seconds(5)) == std::future_status::ready;
|
||||||
|
// A handler the stop did not reach ends when the client leaves
|
||||||
|
if (!in_time) { client.close(); }
|
||||||
|
stopped.wait();
|
||||||
|
EXPECT_TRUE(in_time);
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(WebSocketTest, StopEndsAWaitingRead) {
|
||||||
|
Server svr;
|
||||||
|
check_stop_ends_websocket_read(svr, "ws", false);
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(WebSocketTest, StopEndsAWaitingBoundedRead) {
|
||||||
|
Server svr;
|
||||||
|
check_stop_ends_websocket_read(svr, "ws", true);
|
||||||
|
}
|
||||||
|
|
||||||
|
#ifdef CPPHTTPLIB_SSL_ENABLED
|
||||||
|
TEST(WebSocketTest, StopEndsAWaitingReadOverTLS) {
|
||||||
|
SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
|
||||||
|
ASSERT_TRUE(svr.is_valid());
|
||||||
|
check_stop_ends_websocket_read(svr, "wss", false);
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
|
||||||
|
// The stop reaches the client as a Close with 1001 Going Away, not as a
|
||||||
|
// dropped connection, whether the handler waits for a message or for the rest
|
||||||
|
// of one: `sent` is what the client sends first.
|
||||||
|
static void check_stop_closes_with_going_away(const std::string &sent) {
|
||||||
|
Server svr;
|
||||||
|
svr.set_websocket_ping_interval(0);
|
||||||
|
svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
|
||||||
|
std::string msg;
|
||||||
|
while (ws.read(msg)) {}
|
||||||
|
});
|
||||||
|
|
||||||
|
auto port = svr.bind_to_any_port("127.0.0.1");
|
||||||
|
std::thread t([&]() { svr.listen_after_bind(); });
|
||||||
|
auto se = detail::scope_exit([&] {
|
||||||
|
svr.stop();
|
||||||
|
t.join();
|
||||||
|
});
|
||||||
|
svr.wait_until_ready();
|
||||||
|
|
||||||
|
// Closed before the join above, which a handler the stop did not reach
|
||||||
|
// would otherwise hold up.
|
||||||
|
auto sock = connect_raw_websocket(port, "/ws");
|
||||||
|
ASSERT_NE(INVALID_SOCKET, sock);
|
||||||
|
auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
|
||||||
|
ASSERT_EQ(static_cast<ssize_t>(sent.size()),
|
||||||
|
detail::send_socket(sock, sent.data(), sent.size(), 0));
|
||||||
|
// Let the handler take what was sent and wait for more
|
||||||
|
std::this_thread::sleep_for(std::chrono::milliseconds(100));
|
||||||
|
|
||||||
|
svr.stop();
|
||||||
|
|
||||||
|
// FIN + Close, its length, then the code: unmasked, from a server
|
||||||
|
std::string head;
|
||||||
|
char c;
|
||||||
|
while (head.size() < 4 && ::recv(sock, &c, 1, 0) == 1) {
|
||||||
|
head += c;
|
||||||
|
}
|
||||||
|
const std::string reason = "server stopping";
|
||||||
|
EXPECT_EQ(std::string("\x88") + static_cast<char>(2 + reason.size()) +
|
||||||
|
"\x03\xe9",
|
||||||
|
head);
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(WebSocketTest, StopClosesWithGoingAway) {
|
||||||
|
check_stop_closes_with_going_away("");
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST(WebSocketTest, StopMidMessageClosesWithGoingAway) {
|
||||||
|
// A Text frame without FIN: the first fragment of a message
|
||||||
|
check_stop_closes_with_going_away(masked_frame(0x01, "half"));
|
||||||
|
}
|
||||||
|
|
||||||
TEST(WebSocketTest, AnswersAMalformedCloseWithProtocolError) {
|
TEST(WebSocketTest, AnswersAMalformedCloseWithProtocolError) {
|
||||||
Server svr;
|
Server svr;
|
||||||
svr.set_websocket_ping_interval(0);
|
svr.set_websocket_ping_interval(0);
|
||||||
|
|||||||
Reference in new issue
Block a user