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
This commit is contained in:
Albert Vaca Cintora 2023-08-04 08:25:45 +00:00
parent d2d9c224ae
commit 21b245cd71
2 changed files with 14 additions and 1 deletions

View file

@ -39,6 +39,8 @@
static const int MAX_UNPAIRED_CONNECTIONS = 42; static const int MAX_UNPAIRED_CONNECTIONS = 42;
static const int MAX_REMEMBERED_IDENTITY_PACKETS = 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) LanLinkProvider::LanLinkProvider(bool testMode, quint16 udpBroadcastPort, quint16 udpListenPort)
: m_server(new Server(this)) : m_server(new Server(this))
, m_udpSocket(this) , m_udpSocket(this)
@ -277,12 +279,22 @@ void LanLinkProvider::udpBroadcastReceived()
continue; continue;
} }
if (receivedPacket->get<QString>(QStringLiteral("deviceId")) == KdeConnectConfig::instance().deviceId()) { QString deviceId = receivedPacket->get<QString>(QStringLiteral("deviceId"));
if (deviceId == KdeConnectConfig::instance().deviceId()) {
// qCDebug(KDECONNECT_CORE) << "Ignoring my own broadcast"; // qCDebug(KDECONNECT_CORE) << "Ignoring my own broadcast";
delete receivedPacket; delete receivedPacket;
continue; 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<int>(QStringLiteral("tcpPort")); int tcpPort = receivedPacket->get<int>(QStringLiteral("tcpPort"));
if (tcpPort < MIN_TCP_PORT || tcpPort > MAX_TCP_PORT) { if (tcpPort < MIN_TCP_PORT || tcpPort > MAX_TCP_PORT) {
qCDebug(KDECONNECT_CORE) << "TCP port outside of kdeconnect's range"; qCDebug(KDECONNECT_CORE) << "TCP port outside of kdeconnect's range";

View file

@ -93,6 +93,7 @@ private:
QHostAddress sender; QHostAddress sender;
}; };
QMap<QSslSocket *, PendingConnect> m_receivedIdentityPackets; QMap<QSslSocket *, PendingConnect> m_receivedIdentityPackets;
QMap<QString, qint64> m_lastConnectionTime;
const bool m_testMode; const bool m_testMode;
QTimer m_combineBroadcastsTimer; QTimer m_combineBroadcastsTimer;