diff --git a/README-websocket.md b/README-websocket.md index 7640b4ed..f6b029f3 100644 --- a/README-websocket.md +++ b/README-websocket.md @@ -144,6 +144,14 @@ const Request &request() const; // Check if the connection is still open 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). // Safe to call while another thread is in read(). 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, const std::string &reason = ""); bool is_open() const; +CloseStatus close_status() const; +std::string close_reason() const; // Authentication - the same setters Client has (Basic wins over Bearer). 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 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(ws.close_status()); // e.g. 1000, 1001, 4001 +auto reason = ws.close_reason(); ``` ### Accessing the Upgrade Request diff --git a/docs-src/pages/en/cookbook/w03-websocket-close.md b/docs-src/pages/en/cookbook/w03-websocket-close.md index 961b71d7..36fb8a00 100644 --- a/docs-src/pages/en/cookbook/w03-websocket-close.md +++ b/docs-src/pages/en/cookbook/w03-websocket-close.md @@ -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"); ``` -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 diff --git a/docs-src/pages/ja/cookbook/w03-websocket-close.md b/docs-src/pages/ja/cookbook/w03-websocket-close.md index 2ba5fe35..3e7d0067 100644 --- a/docs-src/pages/ja/cookbook/w03-websocket-close.md +++ b/docs-src/pages/ja/cookbook/w03-websocket-close.md @@ -67,7 +67,15 @@ cli.close(httplib::ws::CloseStatus::Normal); 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) { + // サーバーが再起動中: あとで再接続する +} +``` ## サンプル: 簡単なチャット終了 diff --git a/httplib.h b/httplib.h index 4eb2b206..f25780ef 100644 --- a/httplib.h +++ b/httplib.h @@ -4919,6 +4919,13 @@ public: const Request &request() 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. // 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(). @@ -4970,6 +4977,7 @@ private: void start_heartbeat(); bool send_frame(Opcode op, const char *data, size_t len, bool fin = true); bool send_close(const std::string &payload); + void set_close_status(const std::string &payload); Stream &strm_; std::unique_ptr owned_strm_; @@ -4999,6 +5007,10 @@ private: impl::FrameReader frames_; std::string message_; 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 close_status_{CloseStatus::Abnormal}; + std::string close_reason_; std::thread ping_thread_; std::mutex ping_mutex_; std::condition_variable ping_cv_; @@ -5022,6 +5034,8 @@ public: void close(CloseStatus status = CloseStatus::Normal, const std::string &reason = ""); bool is_open() const; + CloseStatus close_status() const; + std::string close_reason() const; const std::string &subprotocol() const; void set_read_timeout(time_t sec, time_t usec = 0); template @@ -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 // 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((static_cast(payload[0]) << 8) | + static_cast(payload[1])); +} + inline bool is_valid_close_payload(const std::string &payload) { if (payload.empty()) { return true; } if (payload.size() < 2) { return false; } - auto code = (static_cast(payload[0]) << 8) | - static_cast(payload[1]); + auto code = close_code(payload); auto may_be_sent = (1000 <= code && code <= 1003) || (1007 <= code && code <= 1014) || (3000 <= code && code <= 4999); @@ -24912,6 +24931,8 @@ inline ReadResult WebSocket::read(std::string &msg) { return true; } 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 // malformed, which is answered with a protocol error instead. 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 && frames_.read(strm_, op, resp, fin, is_server_, 125) == 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 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(impl::close_code(payload)); + } else { + close_status_ = CloseStatus::ProtocolError; + } +} + 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 // 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 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 { return subprotocol_; } diff --git a/test/test.cc b/test/test.cc index 52224f39..a2145404 100644 --- a/test/test.cc +++ b/test/test.cc @@ -29265,6 +29265,8 @@ TEST_F(WebSocketIntegrationTest, CloseHandshake) { std::string msg; EXPECT_FALSE(client.read(msg)); EXPECT_FALSE(client.is_open()); + EXPECT_EQ(ws::CloseStatus::Normal, client.close_status()); + EXPECT_EQ("", client.close_reason()); } TEST_F(WebSocketIntegrationTest, LargeMessage) { @@ -29488,15 +29490,24 @@ TEST_F(WebSocketIntegrationTest, CloseWithStatus) { std::string msg; EXPECT_FALSE(client.read(msg)); 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::value, ""); } TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) { ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) + "/ws-echo"); + EXPECT_EQ(ws::CloseStatus::Abnormal, client.close_status()); ASSERT_TRUE(client.connect()); client.close(ws::CloseStatus::GoingAway, "client leaving"); 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) { @@ -31503,6 +31514,73 @@ TEST(WebSocketTest, ClientFailsAMaskedFrameWithProtocolError) { 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 lock(m); + seen_status = static_cast(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 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 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(4001), "logout"); + expect_seen(cases.size() + 1, 4001, "logout", "WebSocketClient"); +} + #ifdef CPPHTTPLIB_OPENSSL_SUPPORT class WebSocketSSLIntegrationTest : public ::testing::Test { protected: