diff --git a/Makefile b/Makefile index 34817430b..95dc36519 100644 --- a/Makefile +++ b/Makefile @@ -416,6 +416,13 @@ ifeq ($(WITH_EVPP), yes) endif ifeq ($(WITH_HTTP), yes) $(CXX) -g -Wall -O0 -std=c++11 -I. -Ibase -Ihttp -o bin/websocket_parser_test unittest/websocket_parser_test.cpp -Llib -lhv -pthread +ifeq ($(WITH_EVPP), yes) +ifeq ($(WITH_HTTP_CLIENT), yes) +ifeq ($(WITH_HTTP_SERVER), yes) + $(CXX) -g -Wall -O0 -std=c++11 -I. -Ibase -Issl -Ievent -Icpputil -Ievpp -Ihttp -Ihttp/client -Ihttp/server -o bin/websocket_client_close_test unittest/websocket_client_close_test.cpp -Llib -lhv -pthread +endif +endif +endif endif ifeq ($(WITH_EVPP), yes) ifeq ($(WITH_REDIS), yes) diff --git a/docs/cn/WebSocketClient.md b/docs/cn/WebSocketClient.md index e01577960..dd34e6a0b 100644 --- a/docs/cn/WebSocketClient.md +++ b/docs/cn/WebSocketClient.md @@ -8,6 +8,8 @@ class WebSocketClient { std::function onopen; // 关闭回调 std::function onclose; + // 在 onclose 中查询本次关闭状态 + int getCloseCode() const; // 消息回调 std::function onmessage; @@ -34,4 +36,13 @@ class WebSocketClient { ``` +在 `onclose()` 中调用 `getCloseCode()` 可区分以下情况。每次新连接的 `onopen()` 中,初始值都是 `NoCloseFrame`。 + +| 返回值 | 含义 | +| --- | --- | +| 非负整数 | 对端 CLOSE 帧携带的 16 位状态码,例如 `1000` 或应用自定义的 `4000` | +| `WebSocketClient::CloseCode::NoCloseStatus` | 已收到对端 CLOSE 帧,负载中没有完整的状态码 | +| `WebSocketClient::CloseCode::LocalClose` | 应用主动关闭客户端,关闭前未收到对端 CLOSE 帧 | +| `WebSocketClient::CloseCode::NoCloseFrame` | 连接中断或连接尝试失败,未收到对端 CLOSE 帧 | + 测试代码见 [examples/websocket_client_test.cpp](../../examples/websocket_client_test.cpp) diff --git a/http/WebSocketChannel.h b/http/WebSocketChannel.h index b0a8a9713..03d25c945 100644 --- a/http/WebSocketChannel.h +++ b/http/WebSocketChannel.h @@ -1,6 +1,7 @@ #ifndef HV_WEBSOCKET_CHANNEL_H_ #define HV_WEBSOCKET_CHANNEL_H_ +#include #include #include "Channel.h" @@ -12,6 +13,12 @@ namespace hv { class HV_EXPORT WebSocketChannel : public SocketChannel { public: + enum CloseCode { + NoCloseFrame = -1, // no peer CLOSE received + NoCloseStatus = -2, // peer CLOSE without a complete status code + LocalClose = -3, // application closed the client + }; + ws_session_type type; WebSocketChannel(hio_t* io, ws_session_type type = WS_CLIENT) : SocketChannel(io) @@ -35,6 +42,11 @@ class HV_EXPORT WebSocketChannel : public SocketChannel { int sendPong(); int close() { + if (type == WS_CLIENT && isOpened()) { + // A write callback can request a local close while echoing a peer CLOSE. + int expected = NoCloseFrame; + close_code_.compare_exchange_strong(expected, LocalClose); + } return SocketChannel::close(type == WS_SERVER); } @@ -44,6 +56,8 @@ class HV_EXPORT WebSocketChannel : public SocketChannel { public: enum ws_opcode opcode; private: + friend class WebSocketClient; + std::atomic close_code_{NoCloseFrame}; Buffer sendbuf_; std::mutex mutex_; }; diff --git a/http/client/WebSocketClient.cpp b/http/client/WebSocketClient.cpp index 375bbbfcf..3c33fdcb9 100644 --- a/http/client/WebSocketClient.cpp +++ b/http/client/WebSocketClient.cpp @@ -101,7 +101,11 @@ int WebSocketClient::open(const char* _url, const http_headers& headers) { http_parser_->InitResponse(http_resp_.get()); } else { state = WS_CLOSED; + // A later DNS failure can reuse this channel. Clear it after the + // notification even if the callback replaced the client's channel. + WebSocketChannelPtr closed = channel; if (onclose) onclose(); + closed->close_code_ = CloseCode::NoCloseFrame; } }; onMessage = [this](const WebSocketChannelPtr& channel, Buffer* buf) { @@ -111,7 +115,7 @@ int WebSocketClient::open(const char* _url, const http_headers& headers) { int nparse = http_parser_->FeedRecvData(data, size); if (nparse != size && http_parser_->GetError()) { hloge("http parse error!"); - channel->close(); + channel->SocketChannel::close(); return; } data += nparse; @@ -134,7 +138,7 @@ int WebSocketClient::open(const char* _url, const http_headers& headers) { } } hloge("server side could not upgrade to websocket: status_code=%d", http_resp_->status_code); - channel->close(); + channel->SocketChannel::close(); return; } std::string ws_key = http_req_->GetHeader(SEC_WEBSOCKET_KEY); @@ -143,18 +147,29 @@ int WebSocketClient::open(const char* _url, const http_headers& headers) { std::string ws_accept2 = http_resp_->GetHeader(SEC_WEBSOCKET_ACCEPT); if (strcmp(ws_accept, ws_accept2.c_str()) != 0) { hloge("Sec-WebSocket-Accept not match!"); - channel->close(); + channel->SocketChannel::close(); return; } ws_parser_ = std::make_shared(); // websocket_onmessage - ws_parser_->onMessage = [this, &channel](int opcode, const std::string& msg) { + ws_parser_->onMessage = [this, channel](int opcode, const std::string& msg) { channel->opcode = (enum ws_opcode)opcode; switch (opcode) { case WS_OPCODE_CLOSE: + { + // An earlier message in the same read may have closed the channel. + if (!channel->isConnected()) break; + uint16_t code; + if (msg.size() >= sizeof(code)) { + memcpy(&code, msg.data(), sizeof(code)); + channel->close_code_ = ntohs(code); + } else { + channel->close_code_ = CloseCode::NoCloseStatus; + } channel->send(msg, WS_OPCODE_CLOSE); - channel->close(); + channel->SocketChannel::close(); break; + } case WS_OPCODE_PING: { // printf("recv ping\n"); @@ -183,7 +198,7 @@ int WebSocketClient::open(const char* _url, const http_headers& headers) { if (channel == NULL) return; if (ping_cnt++ == 3) { hloge("websocket no pong!"); - channel->close(); + channel->SocketChannel::close(); return; } // printf("send ping\n"); @@ -197,7 +212,7 @@ int WebSocketClient::open(const char* _url, const http_headers& headers) { int nparse = ws_parser_->FeedRecvData(data, size); if (nparse != size) { hloge("websocket parse error!"); - channel->close(); + channel->SocketChannel::close(); return; } } diff --git a/http/client/WebSocketClient.h b/http/client/WebSocketClient.h index da0a4afa8..d51b9736e 100644 --- a/http/client/WebSocketClient.h +++ b/http/client/WebSocketClient.h @@ -24,6 +24,10 @@ class HV_EXPORT WebSocketClient : public TcpClientTmpl { // PATCH: onmessage not given opcode enum ws_opcode opcode() { return channel ? channel->opcode : WS_OPCODE_CLOSE; } + using CloseCode = WebSocketChannel::CloseCode; + // Read in onclose. A nonnegative value is the status code sent by the peer. + int getCloseCode() const { return channel ? channel->close_code_.load() : CloseCode::NoCloseFrame; } + WebSocketClient(EventLoopPtr loop = NULL); virtual ~WebSocketClient(); diff --git a/scripts/unittest.sh b/scripts/unittest.sh index ca1046e8d..262558cba 100755 --- a/scripts/unittest.sh +++ b/scripts/unittest.sh @@ -35,6 +35,9 @@ bin/http_router_test if [ -x bin/websocket_parser_test ]; then bin/websocket_parser_test || exit $? fi +if [ -x bin/websocket_client_close_test ]; then + bin/websocket_client_close_test || exit $? +fi if [ -x bin/tlv_test ]; then bin/tlv_test fi diff --git a/unittest/CMakeLists.txt b/unittest/CMakeLists.txt index 6e17408b3..ac80c69e5 100644 --- a/unittest/CMakeLists.txt +++ b/unittest/CMakeLists.txt @@ -95,6 +95,12 @@ add_executable(websocket_parser_test websocket_parser_test.cpp) target_include_directories(websocket_parser_test PRIVATE .. ../base ../http) target_link_libraries(websocket_parser_test ${HV_LIBRARIES}) set(HTTP_UNITTEST_TARGETS websocket_parser_test) +if(WITH_EVPP AND WITH_HTTP_CLIENT AND WITH_HTTP_SERVER) +add_executable(websocket_client_close_test websocket_client_close_test.cpp) +target_include_directories(websocket_client_close_test PRIVATE .. ../base ../ssl ../event ../cpputil ../evpp ../http ../http/client ../http/server) +target_link_libraries(websocket_client_close_test ${HV_LIBRARIES}) +list(APPEND HTTP_UNITTEST_TARGETS websocket_client_close_test) +endif() endif() if(WITH_LUA) diff --git a/unittest/websocket_client_close_test.cpp b/unittest/websocket_client_close_test.cpp new file mode 100644 index 000000000..584741bed --- /dev/null +++ b/unittest/websocket_client_close_test.cpp @@ -0,0 +1,108 @@ +#include +#include +#include + +#include "WebSocketClient.h" +#include "WebSocketServer.h" + +using namespace hv; + +#define CHECK(expr) do { if (!(expr)) { \ + std::fprintf(stderr, "line %d: %s failed\n", __LINE__, #expr); \ + std::exit(1); \ +} } while (0) + +int main() { + WebSocketService peer; + peer.onmessage = [](const WebSocketChannelPtr& ch, const std::string& msg) { + ch->send("ready"); + if (msg == "local") { + ch->send(std::string("\x03\xe8"), WS_OPCODE_CLOSE); + } else if (msg == "coded") { + // Application code 4000 in network byte order, followed by a reason. + ch->send(std::string("\x0f\xa0maintenance"), WS_OPCODE_CLOSE); + } else if (msg == "empty") { + ch->send(std::string(), WS_OPCODE_CLOSE); + } else { + CHECK(msg == "drop"); + ch->close(); + } + }; + WebSocketServer server(&peer); + server.setHost("127.0.0.1"); + server.setPort(0); + CHECK(server.start() == 0); + std::string url = "ws://127.0.0.1:" + std::to_string(server.port) + "/"; + + struct { + const char* command; + int code; + } cases[] = { + {"local", WebSocketClient::CloseCode::LocalClose}, + {"drop", WebSocketClient::CloseCode::NoCloseFrame}, + {"coded", 4000}, + {"empty", WebSocketClient::CloseCode::NoCloseStatus}, + {"coded", 4000}, + }; + const size_t count = sizeof(cases) / sizeof(cases[0]); + size_t closed = 0; + std::string events; + char readbuf[64]; // valid until the parser finishes, including after close() + EventLoopPtr loop = std::make_shared(); + WebSocketClient client(loop); + reconn_setting_t reconn; + reconn_setting_init(&reconn); + reconn.min_delay = reconn.max_delay = 10; + auto connect = [&]() { + client.setReconnect(&reconn); + CHECK(client.open(url.c_str()) == 0); + }; + client.onopen = [&]() { + CHECK(closed < count); + CHECK(client.getCloseCode() == WebSocketClient::CloseCode::NoCloseFrame); + events += "open "; + if (closed == 0) { + // Deliver TEXT and CLOSE in one parser call. The TEXT callback + // closes the client before the parser reaches the peer's CLOSE. + int bytes = ws_calc_frame_size(5) + ws_calc_frame_size(2); + client.channel->setReadBuf(readbuf, sizeof(readbuf)); + CHECK(client.channel->readBytes(bytes) >= 0); + } + client.send(cases[closed].command); + }; + client.onmessage = [&](const std::string& msg) { + CHECK(closed < count && msg == "ready"); + events += "message "; + if (closed == 0) client.close(); + }; + client.onclose = [&]() { + CHECK(!client.isConnected()); + if (closed == count) { + // The server stopped after the last coded CLOSE. The retry failed + // before onopen, so it must not report the previous peer's code. + CHECK(events.empty()); + CHECK(client.getCloseCode() == WebSocketClient::CloseCode::NoCloseFrame); + client.setReconnect(NULL); + loop->stop(); + return; + } + CHECK(events == "open message "); + CHECK(client.getCloseCode() == cases[closed].code); + events.clear(); + ++closed; + if (closed == 1) { + // Local close disables automatic reconnect. Reopen the same client. + loop->queueInLoop(connect); + } else if (closed == count) { + server.stop(); + } + }; + + loop->queueInLoop(connect); + loop->setTimeout(5000, [](TimerID) { + std::fprintf(stderr, "timed out waiting for WebSocket callbacks\n"); + std::exit(1); + }); + loop->run(); + return 0; +}