From ce6adec5f855c08924944324d7daa57e786c4018 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Adrien=20B=C3=A9raud?= <adrien.beraud@savoirfairelinux.com>
Date: Mon, 4 Mar 2024 08:52:40 -0500
Subject: [PATCH] ConversationModule: avoid deadlock if callback is called
 synchronously

Change-Id: I7aedd81b133985210cf817d2c524ef3415a219c0
---
 src/jamidht/conversation_module.cpp | 20 +++++++++++---------
 1 file changed, 11 insertions(+), 9 deletions(-)

diff --git a/src/jamidht/conversation_module.cpp b/src/jamidht/conversation_module.cpp
index 4b6b164567..b70cc1ac2f 100644
--- a/src/jamidht/conversation_module.cpp
+++ b/src/jamidht/conversation_module.cpp
@@ -568,25 +568,27 @@ ConversationModule::Impl::fetchNewCommits(const std::string& peer,
         onNeedSocket_(
             conversationId,
             deviceId,
-            [this,
+            [w = weak(),
              conv,
              conversationId = std::move(conversationId),
              peer = std::move(peer),
              deviceId = std::move(deviceId),
              commitId = std::move(commitId)](const auto& channel) {
-                std::lock_guard lk(conv->mtx);
-                // auto conversation = conversations_.find(conversationId);
-                auto acc = account_.lock();
-                if (!channel || !acc || !conv->conversation) {
+                auto sthis = w.lock();
+                auto acc = sthis ? sthis->account_.lock() : nullptr;
+                std::unique_lock lk(conv->mtx);
+                auto conversation = conv->conversation;
+                if (!channel || !acc || !conversation) {
                     conv->stopFetch(deviceId);
-                    syncCnt.fetch_sub(1);
+                    if (sthis) sthis->syncCnt.fetch_sub(1);
                     return false;
                 }
-                conv->conversation->addGitSocket(channel->deviceId(), channel);
-                conv->conversation->sync(
+                conversation->addGitSocket(channel->deviceId(), channel);
+                lk.unlock();
+                conversation->sync(
                     peer,
                     deviceId,
-                    [w = weak(),
+                    [w,
                      conv,
                      conversationId = std::move(conversationId),
                      peer = std::move(peer),
-- 
GitLab