From 8b6e99fd34f150fde5f21f3a57e0e9f28174c70c Mon Sep 17 00:00:00 2001
From: Andreas Traczyk <andreas.traczyk@savoirfairelinux.com>
Date: Thu, 4 Jan 2024 17:12:55 -0500
Subject: [PATCH] connectionmngr: prevent deadlock/crash

https://review.jami.net/c/dhtnet/+/26809 revisited

Change-Id: Ib8e20e6322fd06ca0a2acb25823549e3271ca593
---
 src/connectionmanager.cpp | 12 +++++++-----
 1 file changed, 7 insertions(+), 5 deletions(-)

diff --git a/src/connectionmanager.cpp b/src/connectionmanager.cpp
index f425ef2..37becf7 100644
--- a/src/connectionmanager.cpp
+++ b/src/connectionmanager.cpp
@@ -749,14 +749,12 @@ ConnectionManager::Impl::connectDeviceOnNegoDone(
     info->tls_->setOnReady(
         [w = weak_from_this(), dinfo, winfo=std::weak_ptr(info), deviceId = std::move(deviceId), vid = std::move(vid), name = std::move(name)](
             bool ok) {
-            if (auto shared = w.lock()) {
+            if (auto shared = w.lock())
                 if (auto info = winfo.lock()) {
                     shared->onTlsNegotiationDone(dinfo.lock(), info, ok, deviceId, vid, name);
-                    // Make sure there's another reference to info to avoid destruction when
-                    // we leave this scope (would lead to a deadlock on cbMtx_).
+                    // Make another reference to info to avoid destruction (could lead to a deadlock/crash).
                     dht::ThreadPool::io().run([info = std::move(info)] {});
                 }
-            }
         });
     return true;
 }
@@ -1355,7 +1353,11 @@ ConnectionManager::Impl::onRequestOnNegoDone(const std::weak_ptr<DeviceInfo>& di
     info->tls_->setOnReady(
         [w = weak_from_this(), dinfo, winfo=std::weak_ptr(info), deviceId = std::move(deviceId), vid = std::move(req.id)](bool ok) {
             if (auto shared = w.lock())
-                shared->onTlsNegotiationDone(dinfo.lock(), winfo.lock(), ok, deviceId, vid);
+                if (auto info = winfo.lock()) {
+                    shared->onTlsNegotiationDone(dinfo.lock(), winfo.lock(), ok, deviceId, vid);
+                    // Make another reference to info to avoid destruction (could lead to a deadlock/crash).
+                    dht::ThreadPool::io().run([info = std::move(info)] {});
+                }
         });
     return true;
 }
-- 
GitLab