From 5d96ddcb98669a54fd6949349d481a1ebf829387 Mon Sep 17 00:00:00 2001 From: Peter Johnson Date: Sun, 29 Oct 2023 15:43:12 -0700 Subject: [PATCH] [ntcore] Fix a use-after-free in client close --- ntcore/src/main/native/cpp/NetworkClient.cpp | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/ntcore/src/main/native/cpp/NetworkClient.cpp b/ntcore/src/main/native/cpp/NetworkClient.cpp index eda011f059e..7634be988b9 100644 --- a/ntcore/src/main/native/cpp/NetworkClient.cpp +++ b/ntcore/src/main/native/cpp/NetworkClient.cpp @@ -418,9 +418,13 @@ void NetworkClient::WsConnected(wpi::WebSocket& ws, uv::Tcp& tcp, ws.closed.connect([this, &ws](uint16_t, std::string_view reason) { if (!ws.GetStream().IsLoopClosing()) { // we could be in the middle of sending data, so defer disconnect + // capture a shared_ptr copy of ws to make sure it doesn't get destroyed + // until after DoDisconnect returns uv::Timer::SingleShot( m_loop, uv::Timer::Time{0}, - [this, reason = std::string{reason}] { DoDisconnect(reason); }); + [this, reason = std::string{reason}, keepws = ws.shared_from_this()] { + DoDisconnect(reason); + }); } }); ws.text.connect([this](std::string_view data, bool) {