mirror of
https://github.com/yhirose/cpp-httplib.git
synced 2026-11-27 20:58:28 +00:00
Expose the WebSocket close status and reason (#2695)
* Expose the WebSocket close status and reason When the peer closed a WebSocket, read() returned Fail and the code and reason of its Close frame were dropped after the reply, so a handler or a WebSocketClient user could not tell a normal close from going away, an application code, or a connection that ended without a Close at all. Add close_status() and close_reason() to ws::WebSocket and WebSocketClient. Once read() has returned Fail they report the code and reason of the peer's Close (RFC 6455 7.1.5 and 7.1.6), NoStatus (1005) when it carried no code, ProtocolError when it was malformed, and Abnormal (1006) when none came. After a close() of our own they report the peer's reply. Application codes (3000-4999) come back as a CloseStatus too, as close() already takes them. The status is set once, under the read mutex, with the reason written before it, so the accessors may be called from any thread. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Return close_reason() by value and fold the handler-side close tests WebSocketClient::close_reason() returned a reference into the connection that connect() replaces, so a reference kept across a reconnect dangled. Both close_reason() accessors now return a copy of the reason, which is at most 123 bytes. The six handler-side tests become one table-driven test on one server, and the client test checks the reason still reads after a reconnect. * Decode the close code in one place and fold the client close tests is_valid_close_payload() and set_close_status() each decoded the code by hand; they now share impl::close_code(). The client-side checks move into the existing CloseHandshake, CloseWithStatus and ClientCloseWithStatus tests, which already reach those states, and the reconnect check becomes a static_assert on close_reason()'s type. --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: yhirose <yuji.hirose.bug@gmail.com>
This commit is contained in:
5 files changed
+166
-5
No files matched your search
@@ -144,6 +144,14 @@ const Request &request() const;
|
|||||||
// Check if the connection is still open
|
// Check if the connection is still open
|
||||||
bool is_open() const;
|
bool is_open() const;
|
||||||
|
|
||||||
|
// Why the connection ended, once read() has returned Fail: the code and reason
|
||||||
|
// of the peer's Close frame (any code, including 3000-4999, which are not
|
||||||
|
// named in CloseStatus), NoStatus (1005) for a Close without a code,
|
||||||
|
// ProtocolError (1002) for a malformed one, and Abnormal (1006) when the
|
||||||
|
// connection ended without one. After your own close(), the peer's reply.
|
||||||
|
CloseStatus close_status() const;
|
||||||
|
std::string close_reason() const;
|
||||||
|
|
||||||
// Bound how long read() waits before returning Timeout (0 waits forever).
|
// Bound how long read() waits before returning Timeout (0 waits forever).
|
||||||
// Safe to call while another thread is in read().
|
// Safe to call while another thread is in read().
|
||||||
void set_read_timeout(time_t sec, time_t usec = 0);
|
void set_read_timeout(time_t sec, time_t usec = 0);
|
||||||
@@ -200,6 +208,8 @@ bool send(const char *data, size_t len);
|
|||||||
void close(CloseStatus status = CloseStatus::Normal,
|
void close(CloseStatus status = CloseStatus::Normal,
|
||||||
const std::string &reason = "");
|
const std::string &reason = "");
|
||||||
bool is_open() const;
|
bool is_open() const;
|
||||||
|
CloseStatus close_status() const;
|
||||||
|
std::string close_reason() const;
|
||||||
|
|
||||||
// Authentication - the same setters Client has (Basic wins over Bearer).
|
// Authentication - the same setters Client has (Basic wins over Bearer).
|
||||||
void set_basic_auth(const std::string &username, const std::string &password);
|
void set_basic_auth(const std::string &username, const std::string &password);
|
||||||
@@ -378,6 +388,12 @@ ws.close(httplib::ws::CloseStatus::GoingAway, "shutting down");
|
|||||||
|
|
||||||
// Server-side: close with a policy violation status
|
// Server-side: close with a policy violation status
|
||||||
ws.close(httplib::ws::CloseStatus::PolicyViolation, "forbidden");
|
ws.close(httplib::ws::CloseStatus::PolicyViolation, "forbidden");
|
||||||
|
|
||||||
|
// Either side: why the peer closed, once read() has returned Fail
|
||||||
|
std::string msg;
|
||||||
|
while (ws.read(msg)) {}
|
||||||
|
auto code = static_cast<uint16_t>(ws.close_status()); // e.g. 1000, 1001, 4001
|
||||||
|
auto reason = ws.close_reason();
|
||||||
```
|
```
|
||||||
|
|
||||||
### Accessing the Upgrade Request
|
### Accessing the Upgrade Request
|
||||||
|
|||||||
@@ -67,7 +67,15 @@ To notify in-flight clients that the server is going down, use `GoingAway`.
|
|||||||
ws.close(httplib::ws::CloseStatus::GoingAway, "server restarting");
|
ws.close(httplib::ws::CloseStatus::GoingAway, "server restarting");
|
||||||
```
|
```
|
||||||
|
|
||||||
On the client, `read()` just returns `Fail`; the status and reason it received aren't exposed. If the client needs to tell a restart from other closures, send it a message first (say, `ws.send("restarting")`), then call `close()`.
|
Once `read()` has returned `Fail`, `close_status()` and `close_reason()` tell you why: the status and reason of the peer's Close, `NoStatus` (1005) if it sent no status, or `Abnormal` (1006) if the connection ended without a Close. This works the same on the server and the client.
|
||||||
|
|
||||||
|
```cpp
|
||||||
|
std::string msg;
|
||||||
|
while (cli.read(msg)) {}
|
||||||
|
if (cli.close_status() == httplib::ws::CloseStatus::GoingAway) {
|
||||||
|
// the server is restarting: reconnect later
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
## Example: a tiny chat with quit
|
## Example: a tiny chat with quit
|
||||||
|
|
||||||
|
|||||||
@@ -67,7 +67,15 @@ cli.close(httplib::ws::CloseStatus::Normal);
|
|||||||
ws.close(httplib::ws::CloseStatus::GoingAway, "server restarting");
|
ws.close(httplib::ws::CloseStatus::GoingAway, "server restarting");
|
||||||
```
|
```
|
||||||
|
|
||||||
クライアント側の`read()`は`Fail`を返すだけで、受け取ったステータスや理由は取り出せません。再起動による切断をほかの切断と見分けたい場合は、先にメッセージ(`ws.send("restarting")`など)を送ってから`close()`を呼びましょう。
|
`read()`が`Fail`を返したあとは、`close_status()`と`close_reason()`で切断の理由を取り出せます。相手のCloseフレームのステータスと理由、ステータスがなければ`NoStatus` (1005)、Closeフレームなしで切れた場合は`Abnormal` (1006)です。サーバー側でもクライアント側でも同じです。
|
||||||
|
|
||||||
|
```cpp
|
||||||
|
std::string msg;
|
||||||
|
while (cli.read(msg)) {}
|
||||||
|
if (cli.close_status() == httplib::ws::CloseStatus::GoingAway) {
|
||||||
|
// サーバーが再起動中: あとで再接続する
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
## サンプル: 簡単なチャット終了
|
## サンプル: 簡単なチャット終了
|
||||||
|
|
||||||
|
|||||||
@@ -4919,6 +4919,13 @@ public:
|
|||||||
const Request &request() const;
|
const Request &request() const;
|
||||||
bool is_open() const;
|
bool is_open() const;
|
||||||
|
|
||||||
|
// Why the connection ended, once read() has returned Fail (RFC 6455 7.1.5,
|
||||||
|
// 7.1.6): the code and reason of the peer's Close, NoStatus when it had no
|
||||||
|
// code, ProtocolError when it was malformed, and Abnormal when none came.
|
||||||
|
// After a close() of our own, the peer's reply is what is reported.
|
||||||
|
CloseStatus close_status() const;
|
||||||
|
std::string close_reason() const;
|
||||||
|
|
||||||
// Bound how long read() waits before returning Timeout. 0 waits forever.
|
// Bound how long read() waits before returning Timeout. 0 waits forever.
|
||||||
// A server handler owns its connection's timeout this way; a client sets it
|
// A server handler owns its connection's timeout this way; a client sets it
|
||||||
// through WebSocketClient. Safe to call while another thread is in read().
|
// through WebSocketClient. Safe to call while another thread is in read().
|
||||||
@@ -4970,6 +4977,7 @@ private:
|
|||||||
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);
|
||||||
bool send_close(const std::string &payload);
|
bool send_close(const std::string &payload);
|
||||||
|
void set_close_status(const std::string &payload);
|
||||||
|
|
||||||
Stream &strm_;
|
Stream &strm_;
|
||||||
std::unique_ptr<Stream> owned_strm_;
|
std::unique_ptr<Stream> owned_strm_;
|
||||||
@@ -4999,6 +5007,10 @@ private:
|
|||||||
impl::FrameReader frames_;
|
impl::FrameReader frames_;
|
||||||
std::string message_;
|
std::string message_;
|
||||||
ReadResult message_kind_ = Fail; // Text or Binary while one is assembled
|
ReadResult message_kind_ = Fail; // Text or Binary while one is assembled
|
||||||
|
// The peer's Close, set once under read_mutex_. close_reason_ is written
|
||||||
|
// before close_status_ leaves Abnormal and is not changed after.
|
||||||
|
std::atomic<CloseStatus> close_status_{CloseStatus::Abnormal};
|
||||||
|
std::string close_reason_;
|
||||||
std::thread ping_thread_;
|
std::thread ping_thread_;
|
||||||
std::mutex ping_mutex_;
|
std::mutex ping_mutex_;
|
||||||
std::condition_variable ping_cv_;
|
std::condition_variable ping_cv_;
|
||||||
@@ -5022,6 +5034,8 @@ public:
|
|||||||
void close(CloseStatus status = CloseStatus::Normal,
|
void close(CloseStatus status = CloseStatus::Normal,
|
||||||
const std::string &reason = "");
|
const std::string &reason = "");
|
||||||
bool is_open() const;
|
bool is_open() const;
|
||||||
|
CloseStatus close_status() const;
|
||||||
|
std::string close_reason() const;
|
||||||
const std::string &subprotocol() const;
|
const std::string &subprotocol() const;
|
||||||
void set_read_timeout(time_t sec, time_t usec = 0);
|
void set_read_timeout(time_t sec, time_t usec = 0);
|
||||||
template <class Rep, class Period>
|
template <class Rep, class Period>
|
||||||
@@ -6294,11 +6308,16 @@ inline FrameRead read_websocket_frame(Stream &strm, Opcode &opcode,
|
|||||||
|
|
||||||
// RFC 6455 §5.5.1, §7.4: a Close payload is empty, or a status code that may
|
// RFC 6455 §5.5.1, §7.4: a Close payload is empty, or a status code that may
|
||||||
// be sent followed by a UTF-8 reason.
|
// be sent followed by a UTF-8 reason.
|
||||||
|
// The status code a Close payload of at least 2 bytes starts with
|
||||||
|
inline uint16_t close_code(const std::string &payload) {
|
||||||
|
return static_cast<uint16_t>((static_cast<uint8_t>(payload[0]) << 8) |
|
||||||
|
static_cast<uint8_t>(payload[1]));
|
||||||
|
}
|
||||||
|
|
||||||
inline bool is_valid_close_payload(const std::string &payload) {
|
inline bool is_valid_close_payload(const std::string &payload) {
|
||||||
if (payload.empty()) { return true; }
|
if (payload.empty()) { return true; }
|
||||||
if (payload.size() < 2) { return false; }
|
if (payload.size() < 2) { return false; }
|
||||||
auto code = (static_cast<uint8_t>(payload[0]) << 8) |
|
auto code = close_code(payload);
|
||||||
static_cast<uint8_t>(payload[1]);
|
|
||||||
auto may_be_sent = (1000 <= code && code <= 1003) ||
|
auto may_be_sent = (1000 <= code && code <= 1003) ||
|
||||||
(1007 <= code && code <= 1014) ||
|
(1007 <= code && code <= 1014) ||
|
||||||
(3000 <= code && code <= 4999);
|
(3000 <= code && code <= 4999);
|
||||||
@@ -24912,6 +24931,8 @@ inline ReadResult WebSocket::read(std::string &msg) {
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
case Opcode::Close:
|
case Opcode::Close:
|
||||||
|
// The reply to a close() of our own, too
|
||||||
|
set_close_status(payload);
|
||||||
// RFC 6455 §5.5.1: a Close is echoed back, unless its payload is
|
// RFC 6455 §5.5.1: a Close is echoed back, unless its payload is
|
||||||
// malformed, which is answered with a protocol error instead.
|
// malformed, which is answered with a protocol error instead.
|
||||||
send_close(impl::is_valid_close_payload(payload)
|
send_close(impl::is_valid_close_payload(payload)
|
||||||
@@ -25040,7 +25061,10 @@ inline void WebSocket::close(CloseStatus status, const std::string &reason) {
|
|||||||
while (std::chrono::steady_clock::now() < deadline &&
|
while (std::chrono::steady_clock::now() < deadline &&
|
||||||
frames_.read(strm_, op, resp, fin, is_server_, 125) ==
|
frames_.read(strm_, op, resp, fin, is_server_, 125) ==
|
||||||
impl::FrameRead::Ok) {
|
impl::FrameRead::Ok) {
|
||||||
if (op == Opcode::Close) { break; }
|
if (op == Opcode::Close) {
|
||||||
|
set_close_status(resp);
|
||||||
|
break;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -25092,6 +25116,25 @@ inline const Request &WebSocket::request() const { return req_; }
|
|||||||
|
|
||||||
inline bool WebSocket::is_open() const { return !closed_; }
|
inline bool WebSocket::is_open() const { return !closed_; }
|
||||||
|
|
||||||
|
inline CloseStatus WebSocket::close_status() const { return close_status_; }
|
||||||
|
|
||||||
|
inline std::string WebSocket::close_reason() const {
|
||||||
|
return close_status_ == CloseStatus::Abnormal ? std::string() : close_reason_;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Called with read_mutex_ held. Only the first Close counts.
|
||||||
|
inline void WebSocket::set_close_status(const std::string &payload) {
|
||||||
|
if (close_status_ != CloseStatus::Abnormal) { return; }
|
||||||
|
if (payload.empty()) {
|
||||||
|
close_status_ = CloseStatus::NoStatus;
|
||||||
|
} else if (impl::is_valid_close_payload(payload)) {
|
||||||
|
close_reason_ = payload.substr(2);
|
||||||
|
close_status_ = static_cast<CloseStatus>(impl::close_code(payload));
|
||||||
|
} else {
|
||||||
|
close_status_ = CloseStatus::ProtocolError;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
inline void WebSocket::set_read_timeout(time_t sec, time_t usec) {
|
inline void WebSocket::set_read_timeout(time_t sec, time_t usec) {
|
||||||
// 0 waits forever here, as it does for SO_RCVTIMEO. The stream waits with
|
// 0 waits forever here, as it does for SO_RCVTIMEO. The stream waits with
|
||||||
// poll(), where 0 would instead mean "return immediately", so hand it the
|
// poll(), where 0 would instead mean "return immediately", so hand it the
|
||||||
@@ -25365,6 +25408,14 @@ inline void WebSocketClient::close(CloseStatus status,
|
|||||||
|
|
||||||
inline bool WebSocketClient::is_open() const { return ws_ && ws_->is_open(); }
|
inline bool WebSocketClient::is_open() const { return ws_ && ws_->is_open(); }
|
||||||
|
|
||||||
|
inline CloseStatus WebSocketClient::close_status() const {
|
||||||
|
return ws_ ? ws_->close_status() : CloseStatus::Abnormal;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline std::string WebSocketClient::close_reason() const {
|
||||||
|
return ws_ ? ws_->close_reason() : std::string();
|
||||||
|
}
|
||||||
|
|
||||||
inline const std::string &WebSocketClient::subprotocol() const {
|
inline const std::string &WebSocketClient::subprotocol() const {
|
||||||
return subprotocol_;
|
return subprotocol_;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -29265,6 +29265,8 @@ TEST_F(WebSocketIntegrationTest, CloseHandshake) {
|
|||||||
std::string msg;
|
std::string msg;
|
||||||
EXPECT_FALSE(client.read(msg));
|
EXPECT_FALSE(client.read(msg));
|
||||||
EXPECT_FALSE(client.is_open());
|
EXPECT_FALSE(client.is_open());
|
||||||
|
EXPECT_EQ(ws::CloseStatus::Normal, client.close_status());
|
||||||
|
EXPECT_EQ("", client.close_reason());
|
||||||
}
|
}
|
||||||
|
|
||||||
TEST_F(WebSocketIntegrationTest, LargeMessage) {
|
TEST_F(WebSocketIntegrationTest, LargeMessage) {
|
||||||
@@ -29488,15 +29490,24 @@ TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
|
|||||||
std::string msg;
|
std::string msg;
|
||||||
EXPECT_FALSE(client.read(msg));
|
EXPECT_FALSE(client.read(msg));
|
||||||
EXPECT_FALSE(client.is_open());
|
EXPECT_FALSE(client.is_open());
|
||||||
|
EXPECT_EQ(ws::CloseStatus::GoingAway, client.close_status());
|
||||||
|
EXPECT_EQ("shutting down", client.close_reason());
|
||||||
|
// A copy, so it outlives a reconnect that replaces the connection
|
||||||
|
static_assert(
|
||||||
|
std::is_same<decltype(client.close_reason()), std::string>::value, "");
|
||||||
}
|
}
|
||||||
|
|
||||||
TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
|
TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
|
||||||
ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
|
ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
|
||||||
"/ws-echo");
|
"/ws-echo");
|
||||||
|
EXPECT_EQ(ws::CloseStatus::Abnormal, client.close_status());
|
||||||
ASSERT_TRUE(client.connect());
|
ASSERT_TRUE(client.connect());
|
||||||
|
|
||||||
client.close(ws::CloseStatus::GoingAway, "client leaving");
|
client.close(ws::CloseStatus::GoingAway, "client leaving");
|
||||||
EXPECT_FALSE(client.is_open());
|
EXPECT_FALSE(client.is_open());
|
||||||
|
// The server echoes the Close it receives
|
||||||
|
EXPECT_EQ(ws::CloseStatus::GoingAway, client.close_status());
|
||||||
|
EXPECT_EQ("client leaving", client.close_reason());
|
||||||
}
|
}
|
||||||
|
|
||||||
TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
|
TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
|
||||||
@@ -31503,6 +31514,73 @@ TEST(WebSocketTest, ClientFailsAMaskedFrameWithProtocolError) {
|
|||||||
EXPECT_EQ(std::string("\x03\xea"), payload);
|
EXPECT_EQ(std::string("\x03\xea"), payload);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// What a handler sees of the peer's close once read() has failed
|
||||||
|
TEST(WebSocketTest, HandlerSeesThePeersClose) {
|
||||||
|
std::mutex m;
|
||||||
|
std::condition_variable cv;
|
||||||
|
size_t handled = 0;
|
||||||
|
uint16_t seen_status = 0;
|
||||||
|
std::string seen_reason;
|
||||||
|
|
||||||
|
Server svr;
|
||||||
|
svr.set_websocket_ping_interval(0);
|
||||||
|
svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
|
||||||
|
std::string msg;
|
||||||
|
while (ws.read(msg)) {}
|
||||||
|
std::lock_guard<std::mutex> lock(m);
|
||||||
|
seen_status = static_cast<uint16_t>(ws.close_status());
|
||||||
|
seen_reason = ws.close_reason();
|
||||||
|
handled++;
|
||||||
|
cv.notify_one();
|
||||||
|
});
|
||||||
|
|
||||||
|
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();
|
||||||
|
|
||||||
|
auto expect_seen = [&](size_t n, uint16_t status, const std::string &reason,
|
||||||
|
const char *label) {
|
||||||
|
std::unique_lock<std::mutex> lock(m);
|
||||||
|
ASSERT_TRUE(cv.wait_for(lock, std::chrono::seconds(5), [&] {
|
||||||
|
return handled == n;
|
||||||
|
})) << label;
|
||||||
|
EXPECT_EQ(status, seen_status) << label;
|
||||||
|
EXPECT_EQ(reason, seen_reason) << label;
|
||||||
|
};
|
||||||
|
|
||||||
|
// What a raw client sends before it drops the connection
|
||||||
|
struct Case {
|
||||||
|
const char *label;
|
||||||
|
std::string sent;
|
||||||
|
uint16_t status;
|
||||||
|
std::string reason;
|
||||||
|
};
|
||||||
|
std::vector<Case> cases = {
|
||||||
|
{"application code", masked_frame(0x88, "\x0f\xa1logout"), 4001,
|
||||||
|
"logout"},
|
||||||
|
{"normal", masked_frame(0x88, "\x03\xe8"), 1000, ""},
|
||||||
|
{"no status", masked_frame(0x88, ""), 1005, ""},
|
||||||
|
{"malformed", masked_frame(0x88, "\x03"), 1002, ""},
|
||||||
|
{"no Close", masked_frame(0x81, "hi"), 1006, ""},
|
||||||
|
};
|
||||||
|
for (size_t i = 0; i < cases.size(); i++) {
|
||||||
|
auto sock = connect_raw_websocket(port, "/ws");
|
||||||
|
ASSERT_NE(INVALID_SOCKET, sock);
|
||||||
|
detail::send_socket(sock, cases[i].sent.data(), cases[i].sent.size(), 0);
|
||||||
|
detail::close_socket(sock);
|
||||||
|
expect_seen(i + 1, cases[i].status, cases[i].reason, cases[i].label);
|
||||||
|
}
|
||||||
|
|
||||||
|
ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws");
|
||||||
|
ASSERT_TRUE(client.connect());
|
||||||
|
client.close(static_cast<ws::CloseStatus>(4001), "logout");
|
||||||
|
expect_seen(cases.size() + 1, 4001, "logout", "WebSocketClient");
|
||||||
|
}
|
||||||
|
|
||||||
#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
|
#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
|
||||||
class WebSocketSSLIntegrationTest : public ::testing::Test {
|
class WebSocketSSLIntegrationTest : public ::testing::Test {
|
||||||
protected:
|
protected:
|
||||||
|
|||||||
Reference in new issue
Block a user