ConnectionManager: use peer certificate from TLS in closeConnectionsWith

Change-Id: I55ea604cc2542fb0d38b465cfa6a090450fe9322
diff --git a/include/multiplexed_socket.h b/include/multiplexed_socket.h
index e265db9..2079df5 100644
--- a/include/multiplexed_socket.h
+++ b/include/multiplexed_socket.h
@@ -162,6 +162,8 @@
 
     void eraseChannel(uint16_t channel);
 
+    TlsSocketEndpoint* endpoint();
+
 #ifdef DHTNET_TESTABLE
     /**
      * Check if we can send beacon on the socket
diff --git a/src/connectionmanager.cpp b/src/connectionmanager.cpp
index 67623b2..751b798 100644
--- a/src/connectionmanager.cpp
+++ b/src/connectionmanager.cpp
@@ -1713,11 +1713,16 @@
         std::lock_guard<std::mutex> lk(pimpl_->infosMtx_);
         for (auto iter = pimpl_->infos_.begin(); iter != pimpl_->infos_.end();) {
             auto const& [key, value] = *iter;
+            std::unique_lock<std::mutex> lkv {value->mutex_};
             auto deviceId = key.first;
-            auto cert = pimpl_->certStore().getCertificate(deviceId.toString());
+            auto tls = value->tls_ ? value->tls_.get() : (value->socket_ ? value->socket_->endpoint() : nullptr);
+            auto cert = tls ? tls->peerCertificate() : nullptr;
+            if (not cert)
+                cert = pimpl_->certStore().getCertificate(deviceId.toString());
             if (cert && cert->issuer && peerUri == cert->issuer->getId().toString()) {
                 connInfos.emplace_back(value);
                 peersDevices.emplace(deviceId);
+                lkv.unlock();
                 iter = pimpl_->infos_.erase(iter);
             } else {
                 iter++;
diff --git a/src/multiplexed_socket.cpp b/src/multiplexed_socket.cpp
index 154741b..9c1f952 100644
--- a/src/multiplexed_socket.cpp
+++ b/src/multiplexed_socket.cpp
@@ -770,6 +770,12 @@
     return pimpl_->endpoint->getRemoteAddress();
 }
 
+TlsSocketEndpoint*
+MultiplexedSocket::endpoint()
+{
+    return pimpl_->endpoint.get();
+}
+
 void
 MultiplexedSocket::eraseChannel(uint16_t channel)
 {