Browse Source

mark a websocket closed when a frame write fails

WebSocket::send_frame returned false when write_websocket_frame failed
but left the connection open, and the Pong reply in read() ignored a
failed write. A write that fails partway (the write timeout expiring
while the peer is not reading) has already sent a frame header that
announces the whole payload, so anything written after it is read by
the peer as the rest of that frame, and a later payload's bytes as a
frame of their own. Mark the connection closed on a failed write, as
the heartbeat already does for its Ping, and send the Pong through
send_frame.
Sayed Kaif 1 month ago
parent
commit
77b035c892
3 changed files with 67 additions and 8 deletions
  1. 2 1
      README-websocket.md
  2. 9 7
      httplib.h
  3. 56 0
      test/test.cc

+ 2 - 1
README-websocket.md

@@ -129,7 +129,8 @@ Passed to the handler registered with `Server::WebSocket()`. The handler runs in
 // Read next message (blocks until received, returns Fail/Text/Binary/Timeout)
 ReadResult read(std::string &msg);
 
-// Send messages
+// Send messages. A send that fails (e.g. the write timeout elapsed) closes the
+// connection, since part of the frame may already have gone out.
 bool send(const std::string &data);              // Text
 bool send(const char *data, size_t len);          // Binary
 

+ 9 - 7
httplib.h

@@ -24838,7 +24838,13 @@ inline bool WebSocket::send_frame(Opcode op, const char *data, size_t len,
                                   bool fin) {
   std::lock_guard<std::mutex> lock(write_mutex_);
   if (closed_) { return false; }
-  return detail::write_websocket_frame(strm_, op, data, len, fin, !is_server_);
+  // A failed write may have sent part of the frame, whose header announces the
+  // whole length, so the peer would read the next frames as the rest of it.
+  if (!detail::write_websocket_frame(strm_, op, data, len, fin, !is_server_)) {
+    closed_ = true;
+    return false;
+  }
+  return true;
 }
 
 inline ReadResult WebSocket::read(std::string &msg) {
@@ -24846,12 +24852,8 @@ inline ReadResult WebSocket::read(std::string &msg) {
   // Returns false when the connection is done.
   auto handle_control = [&](Opcode op, const std::string &payload) -> bool {
     switch (op) {
-    case Opcode::Ping: {
-      std::lock_guard<std::mutex> lock(write_mutex_);
-      detail::write_websocket_frame(strm_, Opcode::Pong, payload.data(),
-                                    payload.size(), true, !is_server_);
-      return true;
-    }
+    case Opcode::Ping:
+      return send_frame(Opcode::Pong, payload.data(), payload.size());
     case Opcode::Pong: {
       std::lock_guard<std::mutex> lock(ping_mutex_);
       unacked_pings_ = 0;

+ 56 - 0
test/test.cc

@@ -29615,6 +29615,62 @@ TEST(WebSocketPartialWriteTest, FrameIsWrittenWhole) {
 
   client.close();
 }
+
+// A send() that fails partway leaves a frame on the wire whose header announces
+// more than was sent. Nothing may follow it, or the peer reads the next frames
+// as the rest of it and a later payload's bytes as a frame of their own.
+TEST(WebSocketPartialWriteTest, FailedWriteClosesConnection) {
+  signal(SIGPIPE, SIG_IGN);
+
+  const std::string large(4 * 1024 * 1024, 'A');
+  std::atomic<bool> large_sent{true};
+  std::atomic<bool> open_after_failure{true};
+  std::atomic<bool> small_sent{true};
+  std::atomic<bool> handler_done{false};
+
+  Server svr;
+  svr.set_write_timeout(0, 200000);
+  svr.set_socket_options([](socket_t sock) {
+    int size = 8192;
+    setsockopt(sock, SOL_SOCKET, SO_SNDBUF,
+               reinterpret_cast<const char *>(&size), sizeof(size));
+  });
+  svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
+    large_sent = ws.send(large.data(), large.size());
+    open_after_failure = ws.is_open();
+    small_sent = ws.send("after");
+    handler_done = true;
+  });
+
+  auto port = svr.bind_to_any_port(HOST);
+  std::thread t([&]() { svr.listen_after_bind(); });
+  auto se = detail::scope_exit([&] {
+    svr.stop();
+    t.join();
+  });
+  svr.wait_until_ready();
+
+  ws::WebSocketClient client("ws://" + std::string(HOST) + ":" +
+                             std::to_string(port) + "/ws");
+  client.set_socket_options([](socket_t sock) {
+    int size = 8192;
+    setsockopt(sock, SOL_SOCKET, SO_RCVBUF,
+               reinterpret_cast<const char *>(&size), sizeof(size));
+  });
+  ASSERT_TRUE(client.connect());
+
+  // Read nothing, so the server's write times out partway through the frame.
+  for (int i = 0; i < 100 && !handler_done; i++) {
+    std::this_thread::sleep_for(std::chrono::milliseconds(100));
+  }
+  ASSERT_TRUE(handler_done);
+
+  EXPECT_FALSE(large_sent);
+  EXPECT_FALSE(open_after_failure);
+  EXPECT_FALSE(small_sent);
+
+  client.close();
+}
 #endif
 
 TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {