From a9b7ade53bd8fc00b785735165c6c28097790d1d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?S=C3=A9bastien=20Blin?= <sebastien.blin@savoirfairelinux.com> Date: Fri, 11 Sep 2020 15:39:28 -0400 Subject: [PATCH] p2p: fix heap-use-after-free error Because the callback is shared by multiple objects, parent MUST be passed as a weak pointer to avoid any use after free. Change-Id: Ia03b1aa7326922fe3d07a62f0ac73e9a15da40b0 Gitlab: #307 --- src/jamidht/p2p.cpp | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/src/jamidht/p2p.cpp b/src/jamidht/p2p.cpp index 30c57e540c..73c99971b3 100644 --- a/src/jamidht/p2p.cpp +++ b/src/jamidht/p2p.cpp @@ -470,10 +470,17 @@ private: connection_ = std::make_unique<PeerConnection>([this] { cancel(); }, peer_.toString(), std::move(tls_ep_)); - connection_->setOnStateChangedCb([this](const DRing::DataTransferId& id, - const DRing::DataTransferEventCode& code) { - parent_.stateChanged(peer_.toString(), id, code); - }); + connection_->setOnStateChangedCb( + [p = parent_.weak(), + peer = peer_.toString()](const DRing::DataTransferId& id, + const DRing::DataTransferEventCode& code) { + // NOTE: this callback is shared by all potential inputs/output, not + // only used by connection_, weak pointers MUST be used. + auto parent = p.lock(); + if (!parent) + return; + parent->stateChanged(peer, id, code); + }); for (auto& cb : listeners_) { cb(connection_.get()); } -- GitLab