From 21b245cd717873022b1e662b2b68c49b005cc6f4 Mon Sep 17 00:00:00 2001 From: Albert Vaca Cintora Date: Fri, 4 Aug 2023 08:25:45 +0000 Subject: [PATCH] Avoid starting more than 1 connection to the same device Since we close old connections when a new connection is received, due to race conditions we could end up without a valid connection in this case. Equivalent to https://invent.kde.org/network/kdeconnect-android/-/merge_requests/382 --- core/backends/lan/lanlinkprovider.cpp | 14 +++++++++++++- core/backends/lan/lanlinkprovider.h | 1 + 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/core/backends/lan/lanlinkprovider.cpp b/core/backends/lan/lanlinkprovider.cpp index d7c64465d..13c73af99 100644 --- a/core/backends/lan/lanlinkprovider.cpp +++ b/core/backends/lan/lanlinkprovider.cpp @@ -39,6 +39,8 @@ static const int MAX_UNPAIRED_CONNECTIONS = 42; static const int MAX_REMEMBERED_IDENTITY_PACKETS = 42; +static const long MILLIS_DELAY_BETWEEN_CONNECTIONS_TO_SAME_DEVICE = 500; + LanLinkProvider::LanLinkProvider(bool testMode, quint16 udpBroadcastPort, quint16 udpListenPort) : m_server(new Server(this)) , m_udpSocket(this) @@ -277,12 +279,22 @@ void LanLinkProvider::udpBroadcastReceived() continue; } - if (receivedPacket->get(QStringLiteral("deviceId")) == KdeConnectConfig::instance().deviceId()) { + QString deviceId = receivedPacket->get(QStringLiteral("deviceId")); + + if (deviceId == KdeConnectConfig::instance().deviceId()) { // qCDebug(KDECONNECT_CORE) << "Ignoring my own broadcast"; delete receivedPacket; continue; } + qint64 now = QDateTime::currentMSecsSinceEpoch(); + if (m_lastConnectionTime[deviceId] + MILLIS_DELAY_BETWEEN_CONNECTIONS_TO_SAME_DEVICE > now) { + qCDebug(KDECONNECT_CORE) << "Discarding second UPD packet from the same device" << deviceId << "received too quickly"; + delete receivedPacket; + return; + } + m_lastConnectionTime[deviceId] = now; + int tcpPort = receivedPacket->get(QStringLiteral("tcpPort")); if (tcpPort < MIN_TCP_PORT || tcpPort > MAX_TCP_PORT) { qCDebug(KDECONNECT_CORE) << "TCP port outside of kdeconnect's range"; diff --git a/core/backends/lan/lanlinkprovider.h b/core/backends/lan/lanlinkprovider.h index d60a14420..d984a0883 100644 --- a/core/backends/lan/lanlinkprovider.h +++ b/core/backends/lan/lanlinkprovider.h @@ -93,6 +93,7 @@ private: QHostAddress sender; }; QMap m_receivedIdentityPackets; + QMap m_lastConnectionTime; const bool m_testMode; QTimer m_combineBroadcastsTimer;