From abb3e7ace024f594ce93b832a01d7e642eb8600d Mon Sep 17 00:00:00 2001 From: Chocobo1 Date: Tue, 1 Oct 2019 15:05:26 +0800 Subject: [PATCH 1/6] Move libtorrent session initialization to its own function `m_IPFilteringChanged` default value has changed due to code unification. --- src/base/bittorrent/session.cpp | 189 ++++++++++++++++---------------- src/base/bittorrent/session.h | 4 +- 2 files changed, 97 insertions(+), 96 deletions(-) diff --git a/src/base/bittorrent/session.cpp b/src/base/bittorrent/session.cpp index 5b1c1f18d..fdf086534 100644 --- a/src/base/bittorrent/session.cpp +++ b/src/base/bittorrent/session.cpp @@ -244,7 +244,7 @@ Session *Session::m_instance = nullptr; Session::Session(QObject *parent) : QObject(parent) , m_deferredConfigureScheduled(false) - , m_IPFilteringChanged(false) + , m_IPFilteringChanged(true) , m_listenInterfaceChanged(true) , m_isDHTEnabled(BITTORRENT_SESSION_KEY("DHTEnabled"), true) , m_isLSDEnabled(BITTORRENT_SESSION_KEY("LSDEnabled"), true) @@ -364,91 +364,12 @@ Session::Session(QObject *parent) m_seedingLimitTimer->setInterval(10000); connect(m_seedingLimitTimer, &QTimer::timeout, this, &Session::processShareLimits); - // Set severity level of libtorrent session - const LTAlertCategory alertMask = lt::alert::error_notification - | lt::alert::peer_notification - | lt::alert::port_mapping_notification - | lt::alert::storage_notification - | lt::alert::tracker_notification - | lt::alert::status_notification - | lt::alert::ip_block_notification - | lt::alert::performance_warning - | lt::alert::file_progress_notification; - - const std::string peerId = lt::generate_fingerprint(PEER_ID, QBT_VERSION_MAJOR, QBT_VERSION_MINOR, QBT_VERSION_BUGFIX, QBT_VERSION_BUILD); - lt::settings_pack pack; - pack.set_int(lt::settings_pack::alert_mask, alertMask); - pack.set_str(lt::settings_pack::peer_fingerprint, peerId); - pack.set_bool(lt::settings_pack::listen_system_port_fallback, false); - pack.set_str(lt::settings_pack::user_agent, USER_AGENT); - pack.set_bool(lt::settings_pack::use_dht_as_fallback, false); - // Speed up exit - pack.set_int(lt::settings_pack::stop_tracker_timeout, 1); - pack.set_int(lt::settings_pack::auto_scrape_interval, 1200); // 20 minutes - pack.set_int(lt::settings_pack::auto_scrape_min_interval, 900); // 15 minutes - pack.set_int(lt::settings_pack::connection_speed, 20); // default is 10 - pack.set_bool(lt::settings_pack::no_connect_privileged_ports, false); - // libtorrent 1.1 enables UPnP & NAT-PMP by default - // turn them off before `lt::session` ctor to avoid split second effects - pack.set_bool(lt::settings_pack::enable_upnp, false); - pack.set_bool(lt::settings_pack::enable_natpmp, false); - pack.set_bool(lt::settings_pack::upnp_ignore_nonrouters, true); - -#if (LIBTORRENT_VERSION_NUM < 10200) - // Disable support for SSL torrents for now - pack.set_int(lt::settings_pack::ssl_listen, 0); - // To prevent ISPs from blocking seeding - pack.set_bool(lt::settings_pack::lazy_bitfields, true); - // Disk cache pool is rarely tested in libtorrent and doesn't free buffers - // Soon to be deprecated there - // More info: https://github.com/arvidn/libtorrent/issues/2251 - pack.set_bool(lt::settings_pack::use_disk_cache_pool, false); -#endif - - configure(pack); - - m_nativeSession = new lt::session {pack, LTSessionFlags {0}}; - m_nativeSession->set_alert_notify([this]() - { -#if (QT_VERSION >= QT_VERSION_CHECK(5, 10, 0)) - QMetaObject::invokeMethod(this, &Session::readAlerts, Qt::QueuedConnection); -#else - QMetaObject::invokeMethod(this, "readAlerts", Qt::QueuedConnection); -#endif - }); - - configurePeerClasses(); - - // Enabling plugins - //m_nativeSession->add_extension(<::create_metadata_plugin); - m_nativeSession->add_extension(<::create_ut_metadata_plugin); - if (isPeXEnabled()) - m_nativeSession->add_extension(<::create_ut_pex_plugin); - m_nativeSession->add_extension(<::create_smart_ban_plugin); - - LogMsg(tr("Peer ID: ") + QString::fromStdString(peerId)); - LogMsg(tr("HTTP User-Agent is '%1'").arg(USER_AGENT)); - LogMsg(tr("DHT support [%1]").arg(isDHTEnabled() ? tr("ON") : tr("OFF")), Log::INFO); - LogMsg(tr("Local Peer Discovery support [%1]").arg(isLSDEnabled() ? tr("ON") : tr("OFF")), Log::INFO); - LogMsg(tr("PeX support [%1]").arg(isPeXEnabled() ? tr("ON") : tr("OFF")), Log::INFO); - LogMsg(tr("Anonymous mode [%1]").arg(isAnonymousModeEnabled() ? tr("ON") : tr("OFF")), Log::INFO); - LogMsg(tr("Encryption support [%1]").arg((encryption() == 0) ? tr("ON") : - ((encryption() == 1) ? tr("FORCED") : tr("OFF"))), Log::INFO); + initializeNativeSession(); + configureComponents(); if (isBandwidthSchedulerEnabled()) enableBandwidthScheduler(); - if (isIPFilteringEnabled()) { - // Manually banned IPs are handled in that function too(in the slots) - enableIPFilter(); - } - else { - // Add the banned IPs - lt::ip_filter filter; - processBannedIPs(filter); - m_nativeSession->set_ip_filter(filter); - } - m_categories = map_cast(m_storedCategories); if (isSubcategoriesEnabled()) { // if subcategories support changed manually @@ -987,13 +908,23 @@ void Session::applyBandwidthLimits() m_nativeSession->apply_settings(settingsPack); } -// Set BitTorrent session configuration void Session::configure() { - qDebug("Configuring session"); lt::settings_pack settingsPack = m_nativeSession->get_settings(); - configure(settingsPack); + loadLTSettings(settingsPack); m_nativeSession->apply_settings(settingsPack); + + configureComponents(); + + m_deferredConfigureScheduled = false; +} + +void Session::configureComponents() +{ + // This function contains components/actions that: + // 1. Need to be setup at start up + // 2. When deferred configure is called + configurePeerClasses(); if (m_IPFilteringChanged) { @@ -1003,9 +934,76 @@ void Session::configure() disableIPFilter(); m_IPFilteringChanged = false; } +} - m_deferredConfigureScheduled = false; - qDebug("Session configured"); +void Session::initializeNativeSession() +{ + const LTAlertCategory alertMask = lt::alert::error_notification + | lt::alert::file_progress_notification + | lt::alert::ip_block_notification + | lt::alert::peer_notification + | lt::alert::performance_warning + | lt::alert::port_mapping_notification + | lt::alert::status_notification + | lt::alert::storage_notification + | lt::alert::tracker_notification; + const std::string peerId = lt::generate_fingerprint(PEER_ID, QBT_VERSION_MAJOR, QBT_VERSION_MINOR, QBT_VERSION_BUGFIX, QBT_VERSION_BUILD); + + lt::settings_pack pack; + pack.set_int(lt::settings_pack::alert_mask, alertMask); + pack.set_str(lt::settings_pack::peer_fingerprint, peerId); + pack.set_bool(lt::settings_pack::listen_system_port_fallback, false); + pack.set_str(lt::settings_pack::user_agent, USER_AGENT); + pack.set_bool(lt::settings_pack::use_dht_as_fallback, false); + // Speed up exit + pack.set_int(lt::settings_pack::stop_tracker_timeout, 1); + pack.set_int(lt::settings_pack::auto_scrape_interval, 1200); // 20 minutes + pack.set_int(lt::settings_pack::auto_scrape_min_interval, 900); // 15 minutes + pack.set_int(lt::settings_pack::connection_speed, 20); // default is 10 + pack.set_bool(lt::settings_pack::no_connect_privileged_ports, false); + // libtorrent 1.1 enables UPnP & NAT-PMP by default + // turn them off before `lt::session` ctor to avoid split second effects + pack.set_bool(lt::settings_pack::enable_upnp, false); + pack.set_bool(lt::settings_pack::enable_natpmp, false); + pack.set_bool(lt::settings_pack::upnp_ignore_nonrouters, true); + +#if (LIBTORRENT_VERSION_NUM < 10200) + // Disable support for SSL torrents for now + pack.set_int(lt::settings_pack::ssl_listen, 0); + // To prevent ISPs from blocking seeding + pack.set_bool(lt::settings_pack::lazy_bitfields, true); + // Disk cache pool is rarely tested in libtorrent and doesn't free buffers + // Soon to be deprecated there + // More info: https://github.com/arvidn/libtorrent/issues/2251 + pack.set_bool(lt::settings_pack::use_disk_cache_pool, false); +#endif + + loadLTSettings(pack); + m_nativeSession = new lt::session {pack, LTSessionFlags {0}}; + + LogMsg(tr("Peer ID: ") + QString::fromStdString(peerId)); + LogMsg(tr("HTTP User-Agent is '%1'").arg(USER_AGENT)); + LogMsg(tr("DHT support [%1]").arg(isDHTEnabled() ? tr("ON") : tr("OFF")), Log::INFO); + LogMsg(tr("Local Peer Discovery support [%1]").arg(isLSDEnabled() ? tr("ON") : tr("OFF")), Log::INFO); + LogMsg(tr("PeX support [%1]").arg(isPeXEnabled() ? tr("ON") : tr("OFF")), Log::INFO); + LogMsg(tr("Anonymous mode [%1]").arg(isAnonymousModeEnabled() ? tr("ON") : tr("OFF")), Log::INFO); + LogMsg(tr("Encryption support [%1]").arg((encryption() == 0) ? tr("ON") : + ((encryption() == 1) ? tr("FORCED") : tr("OFF"))), Log::INFO); + + m_nativeSession->set_alert_notify([this]() + { +#if (QT_VERSION >= QT_VERSION_CHECK(5, 10, 0)) + QMetaObject::invokeMethod(this, &Session::readAlerts, Qt::QueuedConnection); +#else + QMetaObject::invokeMethod(this, "readAlerts", Qt::QueuedConnection); +#endif + }); + + // Enabling plugins + m_nativeSession->add_extension(<::create_smart_ban_plugin); + m_nativeSession->add_extension(<::create_ut_metadata_plugin); + if (isPeXEnabled()) + m_nativeSession->add_extension(<::create_ut_pex_plugin); } void Session::processBannedIPs(lt::ip_filter &filter) @@ -1117,7 +1115,7 @@ void Session::initMetrics() Q_ASSERT(m_metricIndices.disk.diskJobTime >= 0); } -void Session::configure(lt::settings_pack &settingsPack) +void Session::loadLTSettings(lt::settings_pack &settingsPack) { // from libtorrent doc: // It will not take affect until the listen_interfaces settings is updated @@ -3573,16 +3571,17 @@ void Session::initResumeFolder() void Session::configureDeferred() { - if (!m_deferredConfigureScheduled) { + if (m_deferredConfigureScheduled) + return; + m_deferredConfigureScheduled = true; + #if (QT_VERSION >= QT_VERSION_CHECK(5, 10, 0)) - QMetaObject::invokeMethod(this - , qOverload<>(&Session::configure) - , Qt::QueuedConnection); + QMetaObject::invokeMethod(this + , qOverload<>(&Session::configure) + , Qt::QueuedConnection); #else - QMetaObject::invokeMethod(this, "configure", Qt::QueuedConnection); + QMetaObject::invokeMethod(this, "configure", Qt::QueuedConnection); #endif - m_deferredConfigureScheduled = true; - } } // Enable IP Filtering diff --git a/src/base/bittorrent/session.h b/src/base/bittorrent/session.h index 6f647d895..deddab567 100644 --- a/src/base/bittorrent/session.h +++ b/src/base/bittorrent/session.h @@ -512,7 +512,9 @@ namespace BitTorrent // Session configuration Q_INVOKABLE void configure(); - void configure(lt::settings_pack &settingsPack); + void configureComponents(); + void initializeNativeSession(); + void loadLTSettings(lt::settings_pack &settingsPack); void configurePeerClasses(); void adjustLimits(lt::settings_pack &settingsPack); void applyBandwidthLimits(lt::settings_pack &settingsPack) const; From 865394a59c095385a3dde34f93bf02791dea1227 Mon Sep 17 00:00:00 2001 From: Chocobo1 Date: Tue, 1 Oct 2019 15:33:11 +0800 Subject: [PATCH 2/6] Clean up Session class variable initialization --- src/base/bittorrent/session.cpp | 49 ++++++++++----------- src/base/bittorrent/session.h | 75 +++++++++++++++++---------------- 2 files changed, 61 insertions(+), 63 deletions(-) diff --git a/src/base/bittorrent/session.cpp b/src/base/bittorrent/session.cpp index fdf086534..7b3be3912 100644 --- a/src/base/bittorrent/session.cpp +++ b/src/base/bittorrent/session.cpp @@ -42,8 +42,10 @@ #include #include +#include #include #include +#include #include #include #include @@ -243,9 +245,6 @@ Session *Session::m_instance = nullptr; Session::Session(QObject *parent) : QObject(parent) - , m_deferredConfigureScheduled(false) - , m_IPFilteringChanged(true) - , m_listenInterfaceChanged(true) , m_isDHTEnabled(BITTORRENT_SESSION_KEY("DHTEnabled"), true) , m_isLSDEnabled(BITTORRENT_SESSION_KEY("LSDEnabled"), true) , m_isPeXEnabled(BITTORRENT_SESSION_KEY("PeXEnabled"), true) @@ -346,10 +345,14 @@ Session::Session(QObject *parent) return tmp; } ) - , m_wasPexEnabled(m_isPeXEnabled) - , m_numResumeData(0) - , m_extraLimit(0) - , m_recentErroredTorrentsTimer(new QTimer(this)) + , m_resumeFolderLock {new QFile {this}} + , m_refreshTimer {new QTimer {this}} + , m_seedingLimitTimer {new QTimer {this}} + , m_resumeDataTimer {new QTimer {this}} + , m_statistics {new Statistics {this}} + , m_ioThread {new QThread {this}} + , m_recentErroredTorrentsTimer {new QTimer {this}} + , m_networkManager {new QNetworkConfigurationManager {this}} { if (port() < 0) m_port = Utils::Random::rand(1024, 65535); @@ -358,9 +361,9 @@ Session::Session(QObject *parent) m_recentErroredTorrentsTimer->setSingleShot(true); m_recentErroredTorrentsTimer->setInterval(1000); - connect(m_recentErroredTorrentsTimer, &QTimer::timeout, this, [this]() { m_recentErroredTorrents.clear(); }); + connect(m_recentErroredTorrentsTimer, &QTimer::timeout + , this, [this]() { m_recentErroredTorrents.clear(); }); - m_seedingLimitTimer = new QTimer(this); m_seedingLimitTimer->setInterval(10000); connect(m_seedingLimitTimer, &QTimer::timeout, this, &Session::processShareLimits); @@ -379,35 +382,31 @@ Session::Session(QObject *parent) m_tags = QSet::fromList(m_storedTags.value()); - m_refreshTimer = new QTimer(this); m_refreshTimer->setInterval(refreshInterval()); connect(m_refreshTimer, &QTimer::timeout, this, &Session::refresh); m_refreshTimer->start(); - m_statistics = new Statistics(this); - updateSeedingLimitTimer(); populateAdditionalTrackers(); enableTracker(isTrackerEnabled()); - connect(Net::ProxyConfigurationManager::instance(), &Net::ProxyConfigurationManager::proxyConfigurationChanged - , this, &Session::configureDeferred); + connect(Net::ProxyConfigurationManager::instance() + , &Net::ProxyConfigurationManager::proxyConfigurationChanged + , this, &Session::configureDeferred); // Network configuration monitor - connect(&m_networkManager, &QNetworkConfigurationManager::onlineStateChanged, this, &Session::networkOnlineStateChanged); - connect(&m_networkManager, &QNetworkConfigurationManager::configurationAdded, this, &Session::networkConfigurationChange); - connect(&m_networkManager, &QNetworkConfigurationManager::configurationRemoved, this, &Session::networkConfigurationChange); - connect(&m_networkManager, &QNetworkConfigurationManager::configurationChanged, this, &Session::networkConfigurationChange); + connect(m_networkManager, &QNetworkConfigurationManager::onlineStateChanged, this, &Session::networkOnlineStateChanged); + connect(m_networkManager, &QNetworkConfigurationManager::configurationAdded, this, &Session::networkConfigurationChange); + connect(m_networkManager, &QNetworkConfigurationManager::configurationRemoved, this, &Session::networkConfigurationChange); + connect(m_networkManager, &QNetworkConfigurationManager::configurationChanged, this, &Session::networkConfigurationChange); - m_ioThread = new QThread(this); m_resumeDataSavingManager = new ResumeDataSavingManager {m_resumeFolderPath}; m_resumeDataSavingManager->moveToThread(m_ioThread); connect(m_ioThread, &QThread::finished, m_resumeDataSavingManager, &QObject::deleteLater); m_ioThread->start(); // Regular saving of fastresume data - m_resumeDataTimer = new QTimer(this); connect(m_resumeDataTimer, &QTimer::timeout, this, [this]() { generateResumeData(); }); const uint saveInterval = saveResumeDataInterval(); if (saveInterval > 0) { @@ -419,8 +418,6 @@ Session::Session(QObject *parent) new PortForwarderImpl {m_nativeSession}; initMetrics(); - - qDebug("* BitTorrent Session constructed"); } bool Session::isDHTEnabled() const @@ -869,8 +866,8 @@ Session::~Session() m_ioThread->quit(); m_ioThread->wait(); - m_resumeFolderLock.close(); - m_resumeFolderLock.remove(); + m_resumeFolderLock->close(); + m_resumeFolderLock->remove(); } void Session::initInstance() @@ -3559,8 +3556,8 @@ void Session::initResumeFolder() m_resumeFolderPath = Utils::Fs::expandPathAbs(specialFolderLocation(SpecialFolder::Data) + RESUME_FOLDER); const QDir resumeFolderDir(m_resumeFolderPath); if (resumeFolderDir.exists() || resumeFolderDir.mkpath(resumeFolderDir.absolutePath())) { - m_resumeFolderLock.setFileName(resumeFolderDir.absoluteFilePath("session.lock")); - if (!m_resumeFolderLock.open(QFile::WriteOnly)) { + m_resumeFolderLock->setFileName(resumeFolderDir.absoluteFilePath("session.lock")); + if (!m_resumeFolderLock->open(QFile::WriteOnly)) { throw RuntimeError {tr("Cannot write to torrent resume folder.")}; } } diff --git a/src/base/bittorrent/session.h b/src/base/bittorrent/session.h index deddab567..9c33e7dd9 100644 --- a/src/base/bittorrent/session.h +++ b/src/base/bittorrent/session.h @@ -34,9 +34,7 @@ #include -#include #include -#include #include #include #include @@ -48,16 +46,19 @@ #include "sessionstatus.h" #include "torrentinfo.h" -class QThread; -class QTimer; +class QFile; +class QNetworkConfiguration; +class QNetworkConfigurationManager; class QString; class QStringList; +class QThread; +class QTimer; class QUrl; -class FilterParserThread; class BandwidthScheduler; -class Statistics; +class FilterParserThread; class ResumeDataSavingManager; +class Statistics; // These values should remain unchanged when adding new items // so as not to break the existing user settings. @@ -89,9 +90,9 @@ namespace Net namespace BitTorrent { class InfoHash; + class MagnetUri; class TorrentHandle; class Tracker; - class MagnetUri; class TrackerEntry; struct CreateTorrentParams; @@ -102,6 +103,14 @@ namespace BitTorrent { Q_NAMESPACE + enum class BTProtocol : int + { + Both = 0, + TCP = 1, + UTP = 2 + }; + Q_ENUM_NS(BTProtocol) + enum class ChokingAlgorithm : int { FixedSlots = 0, @@ -109,14 +118,6 @@ namespace BitTorrent }; Q_ENUM_NS(ChokingAlgorithm) - enum class SeedChokingAlgorithm : int - { - RoundRobin = 0, - FastestUpload = 1, - AntiLeech = 2 - }; - Q_ENUM_NS(SeedChokingAlgorithm) - enum class MixedModeAlgorithm : int { TCP = 0, @@ -124,13 +125,13 @@ namespace BitTorrent }; Q_ENUM_NS(MixedModeAlgorithm) - enum class BTProtocol : int + enum class SeedChokingAlgorithm : int { - Both = 0, - TCP = 1, - UTP = 2 + RoundRobin = 0, + FastestUpload = 1, + AntiLeech = 2 }; - Q_ENUM_NS(BTProtocol) + Q_ENUM_NS(SeedChokingAlgorithm) } using namespace SessionSettingsEnums; @@ -492,7 +493,7 @@ namespace BitTorrent // Session reconfiguration triggers void networkOnlineStateChanged(bool online); - void networkConfigurationChange(const QNetworkConfiguration&); + void networkConfigurationChange(const QNetworkConfiguration &); private: struct RemovingTorrentData @@ -570,11 +571,11 @@ namespace BitTorrent void getPendingAlerts(std::vector &out, ulong time = 0); // BitTorrent - lt::session *m_nativeSession; + lt::session *m_nativeSession = nullptr; - bool m_deferredConfigureScheduled; - bool m_IPFilteringChanged; - bool m_listenInterfaceChanged; // optimization + bool m_deferredConfigureScheduled = false; + bool m_IPFilteringChanged = true; // initialization require this to be true + bool m_listenInterfaceChanged = true; // initialization require this to be true CachedSettingValue m_isDHTEnabled; CachedSettingValue m_isLSDEnabled; @@ -664,26 +665,26 @@ namespace BitTorrent // Order is important. This needs to be declared after its CachedSettingsValue // counterpart, because it uses it for initialization in the constructor // initialization list. - const bool m_wasPexEnabled; + const bool m_wasPexEnabled = m_isPeXEnabled; - int m_numResumeData; - int m_extraLimit; + int m_numResumeData = 0; + int m_extraLimit = 0; QVector m_additionalTrackerList; QString m_resumeFolderPath; - QFile m_resumeFolderLock; + QFile *m_resumeFolderLock = nullptr; - QTimer *m_refreshTimer; - QTimer *m_seedingLimitTimer; - QTimer *m_resumeDataTimer; - Statistics *m_statistics; + QTimer *m_refreshTimer = nullptr; + QTimer *m_seedingLimitTimer = nullptr; + QTimer *m_resumeDataTimer = nullptr; + Statistics *m_statistics = nullptr; // IP filtering QPointer m_filterParser; QPointer m_bwScheduler; // Tracker QPointer m_tracker; // fastresume data writing thread - QThread *m_ioThread; - ResumeDataSavingManager *m_resumeDataSavingManager; + QThread *m_ioThread = nullptr; + ResumeDataSavingManager *m_resumeDataSavingManager = nullptr; QHash m_loadedMetadata; QHash m_torrents; @@ -695,7 +696,7 @@ namespace BitTorrent // I/O errored torrents QSet m_recentErroredTorrents; - QTimer *m_recentErroredTorrentsTimer; + QTimer *m_recentErroredTorrentsTimer = nullptr; SessionMetricIndices m_metricIndices; lt::time_point m_statsLastTimestamp = lt::clock_type::now(); @@ -703,7 +704,7 @@ namespace BitTorrent SessionStatus m_status; CacheStatus m_cacheStatus; - QNetworkConfigurationManager m_networkManager; + QNetworkConfigurationManager *m_networkManager = nullptr; static Session *m_instance; }; From e32ef7f5c5a914734ac6ff22ba80a5df6d38b596 Mon Sep 17 00:00:00 2001 From: Chocobo1 Date: Tue, 1 Oct 2019 16:23:32 +0800 Subject: [PATCH 3/6] Use implicit sharing when getting categories from Session class --- src/base/bittorrent/session.cpp | 2 +- src/base/bittorrent/session.h | 2 +- src/webui/api/synccontroller.cpp | 2 +- src/webui/api/torrentscontroller.cpp | 4 ++-- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/base/bittorrent/session.cpp b/src/base/bittorrent/session.cpp index 7b3be3912..78f171a57 100644 --- a/src/base/bittorrent/session.cpp +++ b/src/base/bittorrent/session.cpp @@ -585,7 +585,7 @@ QStringList Session::expandCategory(const QString &category) return result; } -const QStringMap &Session::categories() const +QStringMap Session::categories() const { return m_categories; } diff --git a/src/base/bittorrent/session.h b/src/base/bittorrent/session.h index 9c33e7dd9..a065f1ed8 100644 --- a/src/base/bittorrent/session.h +++ b/src/base/bittorrent/session.h @@ -201,7 +201,7 @@ namespace BitTorrent // returns category itself and all top level categories static QStringList expandCategory(const QString &category); - const QStringMap &categories() const; + QStringMap categories() const; QString categorySavePath(const QString &categoryName) const; bool addCategory(const QString &name, const QString &savePath = ""); bool editCategory(const QString &name, const QString &savePath); diff --git a/src/webui/api/synccontroller.cpp b/src/webui/api/synccontroller.cpp index d11952eee..0531a70ee 100644 --- a/src/webui/api/synccontroller.cpp +++ b/src/webui/api/synccontroller.cpp @@ -446,7 +446,7 @@ void SyncController::maindataAction() data["torrents"] = torrents; QVariantHash categories; - const auto &categoriesList = session->categories(); + const QStringMap categoriesList = session->categories(); for (auto it = categoriesList.cbegin(); it != categoriesList.cend(); ++it) { const QString &key = it.key(); categories[key] = QVariantMap { diff --git a/src/webui/api/torrentscontroller.cpp b/src/webui/api/torrentscontroller.cpp index 22a722743..62c4196a2 100644 --- a/src/webui/api/torrentscontroller.cpp +++ b/src/webui/api/torrentscontroller.cpp @@ -1077,8 +1077,8 @@ void TorrentsController::removeCategoriesAction() void TorrentsController::categoriesAction() { QJsonObject categories; - const auto categoriesList = BitTorrent::Session::instance()->categories(); - for (auto it = categoriesList.cbegin(); it != categoriesList.cend(); ++it) { + const QStringMap categoriesMap = BitTorrent::Session::instance()->categories(); + for (auto it = categoriesMap.cbegin(); it != categoriesMap.cend(); ++it) { const auto &key = it.key(); categories[key] = QJsonObject { {"name", key}, From a3fd34018790e49f8878270bcae0219ec19c34b6 Mon Sep 17 00:00:00 2001 From: Chocobo1 Date: Sun, 27 Oct 2019 13:46:52 +0800 Subject: [PATCH 4/6] Revise Session::getPendingAlerts function signature --- src/base/bittorrent/session.cpp | 22 ++++++++++------------ src/base/bittorrent/session.h | 2 +- 2 files changed, 11 insertions(+), 13 deletions(-) diff --git a/src/base/bittorrent/session.cpp b/src/base/bittorrent/session.cpp index 78f171a57..3f0ba8738 100644 --- a/src/base/bittorrent/session.cpp +++ b/src/base/bittorrent/session.cpp @@ -2195,14 +2195,13 @@ void Session::saveResumeData() generateResumeData(true); while (m_numResumeData > 0) { - std::vector alerts; - getPendingAlerts(alerts, 30 * 1000); + const std::vector alerts = getPendingAlerts(lt::seconds(30)); if (alerts.empty()) { fprintf(stderr, " aborting with %d outstanding torrents to save resume data for\n", m_numResumeData); break; } - for (const auto a : alerts) { + for (const lt::alert *a : alerts) { switch (a->type()) { case lt::save_resume_data_failed_alert::alert_type: case lt::save_resume_data_alert::alert_type: @@ -3812,13 +3811,14 @@ void Session::handleIPFilterError() emit IPFilterParsed(true, 0); } -void Session::getPendingAlerts(std::vector &out, const ulong time) +std::vector Session::getPendingAlerts(const lt::time_duration time) const { - Q_ASSERT(out.empty()); + if (time > lt::time_duration::zero()) + m_nativeSession->wait_for_alert(time); - if (time > 0) - m_nativeSession->wait_for_alert(lt::milliseconds(time)); - m_nativeSession->pop_alerts(&out); + std::vector alerts; + m_nativeSession->pop_alerts(&alerts); + return alerts; } bool Session::isCreateTorrentSubfolder() const @@ -3834,10 +3834,8 @@ void Session::setCreateTorrentSubfolder(const bool value) // Read alerts sent by the BitTorrent session void Session::readAlerts() { - std::vector alerts; - getPendingAlerts(alerts); - - for (const auto a : alerts) + const std::vector alerts = getPendingAlerts(); + for (const lt::alert *a : alerts) handleAlert(a); } diff --git a/src/base/bittorrent/session.h b/src/base/bittorrent/session.h index a065f1ed8..a5f1ba95f 100644 --- a/src/base/bittorrent/session.h +++ b/src/base/bittorrent/session.h @@ -568,7 +568,7 @@ namespace BitTorrent void saveTorrentsQueue(); void removeTorrentsQueue(); - void getPendingAlerts(std::vector &out, ulong time = 0); + std::vector getPendingAlerts(lt::time_duration time = lt::time_duration::zero()) const; // BitTorrent lt::session *m_nativeSession = nullptr; From 89c58921de483810eaf495d0996be3a31a896a0b Mon Sep 17 00:00:00 2001 From: Chocobo1 Date: Sun, 27 Oct 2019 14:32:32 +0800 Subject: [PATCH 5/6] Log error properly --- src/base/bittorrent/session.cpp | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/src/base/bittorrent/session.cpp b/src/base/bittorrent/session.cpp index 3f0ba8738..718b4d29a 100644 --- a/src/base/bittorrent/session.cpp +++ b/src/base/bittorrent/session.cpp @@ -30,7 +30,6 @@ #include "session.h" #include -#include #include #include #include @@ -2185,8 +2184,6 @@ void Session::generateResumeData(const bool final) // Called on exit void Session::saveResumeData() { - qDebug("Saving resume data..."); - // Pause session m_nativeSession->pause(); @@ -2197,7 +2194,8 @@ void Session::saveResumeData() while (m_numResumeData > 0) { const std::vector alerts = getPendingAlerts(lt::seconds(30)); if (alerts.empty()) { - fprintf(stderr, " aborting with %d outstanding torrents to save resume data for\n", m_numResumeData); + LogMsg(tr("Error: Aborted saving resume data for %1 outstanding torrents.").arg(QString::number(m_numResumeData)) + , Log::CRITICAL); break; } From 29fe0029f004ce62535c9b9e1d47d51ce2059890 Mon Sep 17 00:00:00 2001 From: Chocobo1 Date: Tue, 29 Oct 2019 23:16:22 +0800 Subject: [PATCH 6/6] Rename variables in Session class --- src/base/bittorrent/session.cpp | 16 ++++++++-------- src/base/bittorrent/session.h | 4 ++-- 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/src/base/bittorrent/session.cpp b/src/base/bittorrent/session.cpp index 718b4d29a..c4fd93720 100644 --- a/src/base/bittorrent/session.cpp +++ b/src/base/bittorrent/session.cpp @@ -923,12 +923,12 @@ void Session::configureComponents() configurePeerClasses(); - if (m_IPFilteringChanged) { + if (!m_IPFilteringConfigured) { if (isIPFilteringEnabled()) enableIPFilter(); else disableIPFilter(); - m_IPFilteringChanged = false; + m_IPFilteringConfigured = true; } } @@ -1120,7 +1120,7 @@ void Session::loadLTSettings(lt::settings_pack &settingsPack) #ifdef Q_OS_WIN QString chosenIP; #endif - if (m_listenInterfaceChanged) { + if (!m_listenInterfaceConfigured) { const int port = useRandomPort() ? 0 : this->port(); if (port > 0) // user specified port settingsPack.set_int(lt::settings_pack::max_retry_port_bind, 0); @@ -1176,7 +1176,7 @@ void Session::loadLTSettings(lt::settings_pack &settingsPack) settingsPack.set_str(lt::settings_pack::outgoing_interfaces, networkInterface().toStdString()); #endif // Q_OS_WIN - m_listenInterfaceChanged = false; + m_listenInterfaceConfigured = true; } applyBandwidthLimits(settingsPack); @@ -2369,7 +2369,7 @@ QStringList Session::getListeningIPs() const // the BitTorrent session will listen to void Session::configureListeningInterface() { - m_listenInterfaceChanged = true; + m_listenInterfaceConfigured = false; configureDeferred(); } @@ -2695,7 +2695,7 @@ void Session::setIPFilteringEnabled(const bool enabled) { if (enabled != m_isIPFilteringEnabled) { m_isIPFilteringEnabled = enabled; - m_IPFilteringChanged = true; + m_IPFilteringConfigured = false; configureDeferred(); } } @@ -2710,7 +2710,7 @@ void Session::setIPFilterFile(QString path) path = Utils::Fs::toUniformPath(path); if (path != IPFilterFile()) { m_IPFilterFile = path; - m_IPFilteringChanged = true; + m_IPFilteringConfigured = false; configureDeferred(); } } @@ -2744,7 +2744,7 @@ void Session::setBannedIPs(const QStringList &newList) // also here we have to recreate filter list including 3rd party ban file // and install it again into m_session m_bannedIPs = filteredList; - m_IPFilteringChanged = true; + m_IPFilteringConfigured = false; configureDeferred(); } diff --git a/src/base/bittorrent/session.h b/src/base/bittorrent/session.h index a5f1ba95f..8b6571666 100644 --- a/src/base/bittorrent/session.h +++ b/src/base/bittorrent/session.h @@ -574,8 +574,8 @@ namespace BitTorrent lt::session *m_nativeSession = nullptr; bool m_deferredConfigureScheduled = false; - bool m_IPFilteringChanged = true; // initialization require this to be true - bool m_listenInterfaceChanged = true; // initialization require this to be true + bool m_IPFilteringConfigured = false; + bool m_listenInterfaceConfigured = false; CachedSettingValue m_isDHTEnabled; CachedSettingValue m_isLSDEnabled;