From b23278d216dfedf1cc8a7c489b98a5ca24f87381 Mon Sep 17 00:00:00 2001
From: Andreas Traczyk <andreas.traczyk@savoirfairelinux.com>
Date: Mon, 11 Dec 2023 16:14:00 -0500
Subject: [PATCH] connectionmngr: prevent deadlock/crash

It seems there are scenarios in which the ConnectionInfo is disposed during the on-ready callback, resulting in the TlsSocketEndpoint's callback mutex being locked twice on the same thread.

Change-Id: I401b3c70ba81708e4a3d4ecf3f099f0292c2ff04
---
 src/connectionmanager.cpp | 10 ++++++++--
 1 file changed, 8 insertions(+), 2 deletions(-)

diff --git a/src/connectionmanager.cpp b/src/connectionmanager.cpp
index 2e0e99b..f425ef2 100644
--- a/src/connectionmanager.cpp
+++ b/src/connectionmanager.cpp
@@ -749,8 +749,14 @@ 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())
-                shared->onTlsNegotiationDone(dinfo.lock(), winfo.lock(), ok, deviceId, vid, name);
+            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_).
+                    dht::ThreadPool::io().run([info = std::move(info)] {});
+                }
+            }
         });
     return true;
 }
-- 
GitLab