From 68f72955001da29cb5b7dd5a5f17e4df7357f7fb Mon Sep 17 00:00:00 2001 From: Vladimir Golovnev Date: Sun, 15 Dec 2024 17:50:19 +0300 Subject: [PATCH] Avoid race condition when update tracker entries PR #21995. --- src/base/bittorrent/sessionimpl.cpp | 12 +++++++++--- src/base/bittorrent/sessionimpl.h | 2 ++ 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/src/base/bittorrent/sessionimpl.cpp b/src/base/bittorrent/sessionimpl.cpp index 26ae301b4412..edd6cc69607b 100644 --- a/src/base/bittorrent/sessionimpl.cpp +++ b/src/base/bittorrent/sessionimpl.cpp @@ -66,6 +66,7 @@ #include #include #include +#include #include #include #include @@ -6201,6 +6202,8 @@ void SessionImpl::handleTrackerAlert(const lt::tracker_alert *alert) if (!torrent) return; + [[maybe_unused]] const QMutexLocker updatedTrackerStatusesLocker {&m_updatedTrackerStatusesMutex}; + const auto prevSize = m_updatedTrackerStatuses.size(); QMap &updateInfo = m_updatedTrackerStatuses[torrent->nativeHandle()][std::string(alert->tracker_url())][alert->local_endpoint]; if (prevSize < m_updatedTrackerStatuses.size()) @@ -6297,14 +6300,17 @@ void SessionImpl::updateTrackerEntryStatuses(lt::torrent_handle torrentHandle) try { std::vector nativeTrackers = torrentHandle.trackers(); - invoke([this, torrentHandle, nativeTrackers = std::move(nativeTrackers)] + + QMutexLocker updatedTrackerStatusesLocker {&m_updatedTrackerStatusesMutex}; + QHash>> updatedTrackers = m_updatedTrackerStatuses.take(torrentHandle); + updatedTrackerStatusesLocker.unlock(); + + invoke([this, torrentHandle, nativeTrackers = std::move(nativeTrackers), updatedTrackers = std::move(updatedTrackers)] { TorrentImpl *torrent = m_torrents.value(torrentHandle.info_hash()); if (!torrent || torrent->isStopped()) return; - QHash>> updatedTrackers = m_updatedTrackerStatuses.take(torrentHandle); - QHash trackers; trackers.reserve(updatedTrackers.size()); for (const lt::announce_entry &announceEntry : nativeTrackers) diff --git a/src/base/bittorrent/sessionimpl.h b/src/base/bittorrent/sessionimpl.h index 4f35c59c2918..20f6558f5b7f 100644 --- a/src/base/bittorrent/sessionimpl.h +++ b/src/base/bittorrent/sessionimpl.h @@ -41,6 +41,7 @@ #include #include #include +#include #include #include #include @@ -793,6 +794,7 @@ namespace BitTorrent // This field holds amounts of peers reported by trackers in their responses to announces // (torrent.tracker_name.tracker_local_endpoint.protocol_version.num_peers) QHash>>> m_updatedTrackerStatuses; + QMutex m_updatedTrackerStatusesMutex; // I/O errored torrents QSet m_recentErroredTorrents;