WebUI: Provide 'Merge trackers to existing torrent' option
[qBittorrent.git] / src / base / bittorrent / sessionimpl.cpp
blobb8e77326c752720743f951e60ea592f85a088bb4
1 /*
2 * Bittorrent Client using Qt and libtorrent.
3 * Copyright (C) 2015-2024 Vladimir Golovnev <glassez@yandex.ru>
4 * Copyright (C) 2006 Christophe Dumez <chris@qbittorrent.org>
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License
8 * as published by the Free Software Foundation; either version 2
9 * of the License, or (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20 * In addition, as a special exception, the copyright holders give permission to
21 * link this program with the OpenSSL project's "OpenSSL" library (or with
22 * modified versions of it that use the same license as the "OpenSSL" library),
23 * and distribute the linked executables. You must obey the GNU General Public
24 * License in all respects for all of the code used other than "OpenSSL". If you
25 * modify file(s), you may extend this exception to your version of the file(s),
26 * but you are not obligated to do so. If you do not wish to do so, delete this
27 * exception statement from your version.
30 #include "sessionimpl.h"
32 #include <algorithm>
33 #include <chrono>
34 #include <cstdint>
35 #include <ctime>
36 #include <queue>
37 #include <string>
39 #ifdef Q_OS_WIN
40 #include <windows.h>
41 #include <wincrypt.h>
42 #include <iphlpapi.h>
43 #endif
45 #include <boost/asio/ip/tcp.hpp>
47 #include <libtorrent/add_torrent_params.hpp>
48 #include <libtorrent/address.hpp>
49 #include <libtorrent/alert_types.hpp>
50 #include <libtorrent/error_code.hpp>
51 #include <libtorrent/extensions/smart_ban.hpp>
52 #include <libtorrent/extensions/ut_metadata.hpp>
53 #include <libtorrent/extensions/ut_pex.hpp>
54 #include <libtorrent/ip_filter.hpp>
55 #include <libtorrent/magnet_uri.hpp>
56 #include <libtorrent/session.hpp>
57 #include <libtorrent/session_stats.hpp>
58 #include <libtorrent/session_status.hpp>
59 #include <libtorrent/torrent_info.hpp>
61 #include <QDeadlineTimer>
62 #include <QDebug>
63 #include <QDir>
64 #include <QHostAddress>
65 #include <QJsonArray>
66 #include <QJsonDocument>
67 #include <QJsonObject>
68 #include <QJsonValue>
69 #include <QNetworkAddressEntry>
70 #include <QNetworkInterface>
71 #include <QRegularExpression>
72 #include <QString>
73 #include <QThread>
74 #include <QThreadPool>
75 #include <QTimer>
76 #include <QUuid>
78 #include "base/algorithm.h"
79 #include "base/global.h"
80 #include "base/logger.h"
81 #include "base/net/proxyconfigurationmanager.h"
82 #include "base/preferences.h"
83 #include "base/profile.h"
84 #include "base/unicodestrings.h"
85 #include "base/utils/fs.h"
86 #include "base/utils/io.h"
87 #include "base/utils/net.h"
88 #include "base/utils/number.h"
89 #include "base/utils/random.h"
90 #include "base/version.h"
91 #include "bandwidthscheduler.h"
92 #include "bencoderesumedatastorage.h"
93 #include "customstorage.h"
94 #include "dbresumedatastorage.h"
95 #include "downloadpriority.h"
96 #include "extensiondata.h"
97 #include "filesearcher.h"
98 #include "filterparserthread.h"
99 #include "loadtorrentparams.h"
100 #include "lttypecast.h"
101 #include "nativesessionextension.h"
102 #include "portforwarderimpl.h"
103 #include "resumedatastorage.h"
104 #include "torrentcontentremover.h"
105 #include "torrentdescriptor.h"
106 #include "torrentimpl.h"
107 #include "tracker.h"
108 #include "trackerentry.h"
110 using namespace std::chrono_literals;
111 using namespace BitTorrent;
113 const Path CATEGORIES_FILE_NAME {u"categories.json"_s};
114 const int MAX_PROCESSING_RESUMEDATA_COUNT = 50;
115 const int STATISTICS_SAVE_INTERVAL = std::chrono::milliseconds(15min).count();
117 namespace
119 const char PEER_ID[] = "qB";
120 const auto USER_AGENT = QStringLiteral("qBittorrent/" QBT_VERSION_2);
121 const QString DEFAULT_DHT_BOOTSTRAP_NODES = u"dht.libtorrent.org:25401, dht.transmissionbt.com:6881, router.bittorrent.com:6881, router.utorrent.com:6881, dht.aelitis.com:6881"_s;
123 void torrentQueuePositionUp(const lt::torrent_handle &handle)
127 handle.queue_position_up();
129 catch (const std::exception &exc)
131 qDebug() << Q_FUNC_INFO << " fails: " << exc.what();
135 void torrentQueuePositionDown(const lt::torrent_handle &handle)
139 handle.queue_position_down();
141 catch (const std::exception &exc)
143 qDebug() << Q_FUNC_INFO << " fails: " << exc.what();
147 void torrentQueuePositionTop(const lt::torrent_handle &handle)
151 handle.queue_position_top();
153 catch (const std::exception &exc)
155 qDebug() << Q_FUNC_INFO << " fails: " << exc.what();
159 void torrentQueuePositionBottom(const lt::torrent_handle &handle)
163 handle.queue_position_bottom();
165 catch (const std::exception &exc)
167 qDebug() << Q_FUNC_INFO << " fails: " << exc.what();
171 QMap<QString, CategoryOptions> expandCategories(const QMap<QString, CategoryOptions> &categories)
173 QMap<QString, CategoryOptions> expanded = categories;
175 for (auto i = categories.cbegin(); i != categories.cend(); ++i)
177 const QString &category = i.key();
178 for (const QString &subcat : asConst(Session::expandCategory(category)))
180 if (!expanded.contains(subcat))
181 expanded[subcat] = {};
185 return expanded;
188 QString toString(const lt::socket_type_t socketType)
190 switch (socketType)
192 #ifdef QBT_USES_LIBTORRENT2
193 case lt::socket_type_t::http:
194 return u"HTTP"_s;
195 case lt::socket_type_t::http_ssl:
196 return u"HTTP_SSL"_s;
197 #endif
198 case lt::socket_type_t::i2p:
199 return u"I2P"_s;
200 case lt::socket_type_t::socks5:
201 return u"SOCKS5"_s;
202 #ifdef QBT_USES_LIBTORRENT2
203 case lt::socket_type_t::socks5_ssl:
204 return u"SOCKS5_SSL"_s;
205 #endif
206 case lt::socket_type_t::tcp:
207 return u"TCP"_s;
208 case lt::socket_type_t::tcp_ssl:
209 return u"TCP_SSL"_s;
210 #ifdef QBT_USES_LIBTORRENT2
211 case lt::socket_type_t::utp:
212 return u"UTP"_s;
213 #else
214 case lt::socket_type_t::udp:
215 return u"UDP"_s;
216 #endif
217 case lt::socket_type_t::utp_ssl:
218 return u"UTP_SSL"_s;
220 return u"INVALID"_s;
223 QString toString(const lt::address &address)
227 return QString::fromLatin1(address.to_string().c_str());
229 catch (const std::exception &)
231 // suppress conversion error
233 return {};
236 template <typename T>
237 struct LowerLimited
239 LowerLimited(T limit, T ret)
240 : m_limit(limit)
241 , m_ret(ret)
245 explicit LowerLimited(T limit)
246 : LowerLimited(limit, limit)
250 T operator()(T val) const
252 return val <= m_limit ? m_ret : val;
255 private:
256 const T m_limit;
257 const T m_ret;
260 template <typename T>
261 LowerLimited<T> lowerLimited(T limit) { return LowerLimited<T>(limit); }
263 template <typename T>
264 LowerLimited<T> lowerLimited(T limit, T ret) { return LowerLimited<T>(limit, ret); }
266 template <typename T>
267 auto clampValue(const T lower, const T upper)
269 return [lower, upper](const T value) -> T
271 return std::clamp(value, lower, upper);
275 #ifdef Q_OS_WIN
276 QString convertIfaceNameToGuid(const QString &name)
278 // Under Windows XP or on Qt version <= 5.5 'name' will be a GUID already.
279 const QUuid uuid(name);
280 if (!uuid.isNull())
281 return uuid.toString().toUpper(); // Libtorrent expects the GUID in uppercase
283 const std::wstring nameWStr = name.toStdWString();
284 NET_LUID luid {};
285 const LONG res = ::ConvertInterfaceNameToLuidW(nameWStr.c_str(), &luid);
286 if (res == 0)
288 GUID guid;
289 if (::ConvertInterfaceLuidToGuid(&luid, &guid) == 0)
290 return QUuid(guid).toString().toUpper();
293 return {};
295 #endif
297 constexpr lt::move_flags_t toNative(const MoveStorageMode mode)
299 switch (mode)
301 default:
302 Q_ASSERT(false);
303 case MoveStorageMode::FailIfExist:
304 return lt::move_flags_t::fail_if_exist;
305 case MoveStorageMode::KeepExistingFiles:
306 return lt::move_flags_t::dont_replace;
307 case MoveStorageMode::Overwrite:
308 return lt::move_flags_t::always_replace_files;
313 struct BitTorrent::SessionImpl::ResumeSessionContext final : public QObject
315 using QObject::QObject;
317 ResumeDataStorage *startupStorage = nullptr;
318 ResumeDataStorageType currentStorageType = ResumeDataStorageType::Legacy;
319 QList<LoadedResumeData> loadedResumeData;
320 int processingResumeDataCount = 0;
321 int64_t totalResumeDataCount = 0;
322 int64_t finishedResumeDataCount = 0;
323 bool isLoadFinished = false;
324 bool isLoadedResumeDataHandlingEnqueued = false;
325 QSet<QString> recoveredCategories;
326 #ifdef QBT_USES_LIBTORRENT2
327 QSet<TorrentID> indexedTorrents;
328 QSet<TorrentID> skippedIDs;
329 #endif
332 const int addTorrentParamsId = qRegisterMetaType<AddTorrentParams>();
334 Session *SessionImpl::m_instance = nullptr;
336 void Session::initInstance()
338 if (!SessionImpl::m_instance)
339 SessionImpl::m_instance = new SessionImpl;
342 void Session::freeInstance()
344 delete SessionImpl::m_instance;
345 SessionImpl::m_instance = nullptr;
348 Session *Session::instance()
350 return SessionImpl::m_instance;
353 bool Session::isValidCategoryName(const QString &name)
355 const QRegularExpression re {uR"(^([^\\\/]|[^\\\/]([^\\\/]|\/(?=[^\/]))*[^\\\/])$)"_s};
356 return (name.isEmpty() || (name.indexOf(re) == 0));
359 QString Session::subcategoryName(const QString &category)
361 const int sepIndex = category.lastIndexOf(u'/');
362 if (sepIndex >= 0)
363 return category.mid(sepIndex + 1);
365 return category;
368 QString Session::parentCategoryName(const QString &category)
370 const int sepIndex = category.lastIndexOf(u'/');
371 if (sepIndex >= 0)
372 return category.left(sepIndex);
374 return {};
377 QStringList Session::expandCategory(const QString &category)
379 QStringList result;
380 int index = 0;
381 while ((index = category.indexOf(u'/', index)) >= 0)
383 result << category.left(index);
384 ++index;
386 result << category;
388 return result;
391 #define BITTORRENT_KEY(name) u"BitTorrent/" name
392 #define BITTORRENT_SESSION_KEY(name) BITTORRENT_KEY(u"Session/") name
394 SessionImpl::SessionImpl(QObject *parent)
395 : Session(parent)
396 , m_DHTBootstrapNodes(BITTORRENT_SESSION_KEY(u"DHTBootstrapNodes"_s), DEFAULT_DHT_BOOTSTRAP_NODES)
397 , m_isDHTEnabled(BITTORRENT_SESSION_KEY(u"DHTEnabled"_s), true)
398 , m_isLSDEnabled(BITTORRENT_SESSION_KEY(u"LSDEnabled"_s), true)
399 , m_isPeXEnabled(BITTORRENT_SESSION_KEY(u"PeXEnabled"_s), true)
400 , m_isIPFilteringEnabled(BITTORRENT_SESSION_KEY(u"IPFilteringEnabled"_s), false)
401 , m_isTrackerFilteringEnabled(BITTORRENT_SESSION_KEY(u"TrackerFilteringEnabled"_s), false)
402 , m_IPFilterFile(BITTORRENT_SESSION_KEY(u"IPFilter"_s))
403 , m_announceToAllTrackers(BITTORRENT_SESSION_KEY(u"AnnounceToAllTrackers"_s), false)
404 , m_announceToAllTiers(BITTORRENT_SESSION_KEY(u"AnnounceToAllTiers"_s), true)
405 , m_asyncIOThreads(BITTORRENT_SESSION_KEY(u"AsyncIOThreadsCount"_s), 10)
406 , m_hashingThreads(BITTORRENT_SESSION_KEY(u"HashingThreadsCount"_s), 1)
407 , m_filePoolSize(BITTORRENT_SESSION_KEY(u"FilePoolSize"_s), 100)
408 , m_checkingMemUsage(BITTORRENT_SESSION_KEY(u"CheckingMemUsageSize"_s), 32)
409 , m_diskCacheSize(BITTORRENT_SESSION_KEY(u"DiskCacheSize"_s), -1)
410 , m_diskCacheTTL(BITTORRENT_SESSION_KEY(u"DiskCacheTTL"_s), 60)
411 , m_diskQueueSize(BITTORRENT_SESSION_KEY(u"DiskQueueSize"_s), (1024 * 1024))
412 , m_diskIOType(BITTORRENT_SESSION_KEY(u"DiskIOType"_s), DiskIOType::Default)
413 , m_diskIOReadMode(BITTORRENT_SESSION_KEY(u"DiskIOReadMode"_s), DiskIOReadMode::EnableOSCache)
414 , m_diskIOWriteMode(BITTORRENT_SESSION_KEY(u"DiskIOWriteMode"_s), DiskIOWriteMode::EnableOSCache)
415 #ifdef Q_OS_WIN
416 , m_coalesceReadWriteEnabled(BITTORRENT_SESSION_KEY(u"CoalesceReadWrite"_s), true)
417 #else
418 , m_coalesceReadWriteEnabled(BITTORRENT_SESSION_KEY(u"CoalesceReadWrite"_s), false)
419 #endif
420 , m_usePieceExtentAffinity(BITTORRENT_SESSION_KEY(u"PieceExtentAffinity"_s), false)
421 , m_isSuggestMode(BITTORRENT_SESSION_KEY(u"SuggestMode"_s), false)
422 , m_sendBufferWatermark(BITTORRENT_SESSION_KEY(u"SendBufferWatermark"_s), 500)
423 , m_sendBufferLowWatermark(BITTORRENT_SESSION_KEY(u"SendBufferLowWatermark"_s), 10)
424 , m_sendBufferWatermarkFactor(BITTORRENT_SESSION_KEY(u"SendBufferWatermarkFactor"_s), 50)
425 , m_connectionSpeed(BITTORRENT_SESSION_KEY(u"ConnectionSpeed"_s), 30)
426 , m_socketSendBufferSize(BITTORRENT_SESSION_KEY(u"SocketSendBufferSize"_s), 0)
427 , m_socketReceiveBufferSize(BITTORRENT_SESSION_KEY(u"SocketReceiveBufferSize"_s), 0)
428 , m_socketBacklogSize(BITTORRENT_SESSION_KEY(u"SocketBacklogSize"_s), 30)
429 , m_isAnonymousModeEnabled(BITTORRENT_SESSION_KEY(u"AnonymousModeEnabled"_s), false)
430 , m_isQueueingEnabled(BITTORRENT_SESSION_KEY(u"QueueingSystemEnabled"_s), false)
431 , m_maxActiveDownloads(BITTORRENT_SESSION_KEY(u"MaxActiveDownloads"_s), 3, lowerLimited(-1))
432 , m_maxActiveUploads(BITTORRENT_SESSION_KEY(u"MaxActiveUploads"_s), 3, lowerLimited(-1))
433 , m_maxActiveTorrents(BITTORRENT_SESSION_KEY(u"MaxActiveTorrents"_s), 5, lowerLimited(-1))
434 , m_ignoreSlowTorrentsForQueueing(BITTORRENT_SESSION_KEY(u"IgnoreSlowTorrentsForQueueing"_s), false)
435 , m_downloadRateForSlowTorrents(BITTORRENT_SESSION_KEY(u"SlowTorrentsDownloadRate"_s), 2)
436 , m_uploadRateForSlowTorrents(BITTORRENT_SESSION_KEY(u"SlowTorrentsUploadRate"_s), 2)
437 , m_slowTorrentsInactivityTimer(BITTORRENT_SESSION_KEY(u"SlowTorrentsInactivityTimer"_s), 60)
438 , m_outgoingPortsMin(BITTORRENT_SESSION_KEY(u"OutgoingPortsMin"_s), 0)
439 , m_outgoingPortsMax(BITTORRENT_SESSION_KEY(u"OutgoingPortsMax"_s), 0)
440 , m_UPnPLeaseDuration(BITTORRENT_SESSION_KEY(u"UPnPLeaseDuration"_s), 0)
441 , m_peerToS(BITTORRENT_SESSION_KEY(u"PeerToS"_s), 0x04)
442 , m_ignoreLimitsOnLAN(BITTORRENT_SESSION_KEY(u"IgnoreLimitsOnLAN"_s), false)
443 , m_includeOverheadInLimits(BITTORRENT_SESSION_KEY(u"IncludeOverheadInLimits"_s), false)
444 , m_announceIP(BITTORRENT_SESSION_KEY(u"AnnounceIP"_s))
445 , m_maxConcurrentHTTPAnnounces(BITTORRENT_SESSION_KEY(u"MaxConcurrentHTTPAnnounces"_s), 50)
446 , m_isReannounceWhenAddressChangedEnabled(BITTORRENT_SESSION_KEY(u"ReannounceWhenAddressChanged"_s), false)
447 , m_stopTrackerTimeout(BITTORRENT_SESSION_KEY(u"StopTrackerTimeout"_s), 2)
448 , m_maxConnections(BITTORRENT_SESSION_KEY(u"MaxConnections"_s), 500, lowerLimited(0, -1))
449 , m_maxUploads(BITTORRENT_SESSION_KEY(u"MaxUploads"_s), 20, lowerLimited(0, -1))
450 , m_maxConnectionsPerTorrent(BITTORRENT_SESSION_KEY(u"MaxConnectionsPerTorrent"_s), 100, lowerLimited(0, -1))
451 , m_maxUploadsPerTorrent(BITTORRENT_SESSION_KEY(u"MaxUploadsPerTorrent"_s), 4, lowerLimited(0, -1))
452 , m_btProtocol(BITTORRENT_SESSION_KEY(u"BTProtocol"_s), BTProtocol::Both
453 , clampValue(BTProtocol::Both, BTProtocol::UTP))
454 , m_isUTPRateLimited(BITTORRENT_SESSION_KEY(u"uTPRateLimited"_s), true)
455 , m_utpMixedMode(BITTORRENT_SESSION_KEY(u"uTPMixedMode"_s), MixedModeAlgorithm::TCP
456 , clampValue(MixedModeAlgorithm::TCP, MixedModeAlgorithm::Proportional))
457 , m_IDNSupportEnabled(BITTORRENT_SESSION_KEY(u"IDNSupportEnabled"_s), false)
458 , m_multiConnectionsPerIpEnabled(BITTORRENT_SESSION_KEY(u"MultiConnectionsPerIp"_s), false)
459 , m_validateHTTPSTrackerCertificate(BITTORRENT_SESSION_KEY(u"ValidateHTTPSTrackerCertificate"_s), true)
460 , m_SSRFMitigationEnabled(BITTORRENT_SESSION_KEY(u"SSRFMitigation"_s), true)
461 , m_blockPeersOnPrivilegedPorts(BITTORRENT_SESSION_KEY(u"BlockPeersOnPrivilegedPorts"_s), false)
462 , m_isAddTrackersEnabled(BITTORRENT_SESSION_KEY(u"AddTrackersEnabled"_s), false)
463 , m_additionalTrackers(BITTORRENT_SESSION_KEY(u"AdditionalTrackers"_s))
464 , m_globalMaxRatio(BITTORRENT_SESSION_KEY(u"GlobalMaxRatio"_s), -1, [](qreal r) { return r < 0 ? -1. : r;})
465 , m_globalMaxSeedingMinutes(BITTORRENT_SESSION_KEY(u"GlobalMaxSeedingMinutes"_s), -1, lowerLimited(-1))
466 , m_globalMaxInactiveSeedingMinutes(BITTORRENT_SESSION_KEY(u"GlobalMaxInactiveSeedingMinutes"_s), -1, lowerLimited(-1))
467 , m_isAddTorrentToQueueTop(BITTORRENT_SESSION_KEY(u"AddTorrentToTopOfQueue"_s), false)
468 , m_isAddTorrentStopped(BITTORRENT_SESSION_KEY(u"AddTorrentStopped"_s), false)
469 , m_torrentStopCondition(BITTORRENT_SESSION_KEY(u"TorrentStopCondition"_s), Torrent::StopCondition::None)
470 , m_torrentContentLayout(BITTORRENT_SESSION_KEY(u"TorrentContentLayout"_s), TorrentContentLayout::Original)
471 , m_isAppendExtensionEnabled(BITTORRENT_SESSION_KEY(u"AddExtensionToIncompleteFiles"_s), false)
472 , m_isUnwantedFolderEnabled(BITTORRENT_SESSION_KEY(u"UseUnwantedFolder"_s), false)
473 , m_refreshInterval(BITTORRENT_SESSION_KEY(u"RefreshInterval"_s), 1500)
474 , m_isPreallocationEnabled(BITTORRENT_SESSION_KEY(u"Preallocation"_s), false)
475 , m_torrentExportDirectory(BITTORRENT_SESSION_KEY(u"TorrentExportDirectory"_s))
476 , m_finishedTorrentExportDirectory(BITTORRENT_SESSION_KEY(u"FinishedTorrentExportDirectory"_s))
477 , m_globalDownloadSpeedLimit(BITTORRENT_SESSION_KEY(u"GlobalDLSpeedLimit"_s), 0, lowerLimited(0))
478 , m_globalUploadSpeedLimit(BITTORRENT_SESSION_KEY(u"GlobalUPSpeedLimit"_s), 0, lowerLimited(0))
479 , m_altGlobalDownloadSpeedLimit(BITTORRENT_SESSION_KEY(u"AlternativeGlobalDLSpeedLimit"_s), 10, lowerLimited(0))
480 , m_altGlobalUploadSpeedLimit(BITTORRENT_SESSION_KEY(u"AlternativeGlobalUPSpeedLimit"_s), 10, lowerLimited(0))
481 , m_isAltGlobalSpeedLimitEnabled(BITTORRENT_SESSION_KEY(u"UseAlternativeGlobalSpeedLimit"_s), false)
482 , m_isBandwidthSchedulerEnabled(BITTORRENT_SESSION_KEY(u"BandwidthSchedulerEnabled"_s), false)
483 , m_isPerformanceWarningEnabled(BITTORRENT_SESSION_KEY(u"PerformanceWarning"_s), false)
484 , m_saveResumeDataInterval(BITTORRENT_SESSION_KEY(u"SaveResumeDataInterval"_s), 60)
485 , m_shutdownTimeout(BITTORRENT_SESSION_KEY(u"ShutdownTimeout"_s), -1)
486 , m_port(BITTORRENT_SESSION_KEY(u"Port"_s), -1)
487 , m_sslEnabled(BITTORRENT_SESSION_KEY(u"SSL/Enabled"_s), false)
488 , m_sslPort(BITTORRENT_SESSION_KEY(u"SSL/Port"_s), -1)
489 , m_networkInterface(BITTORRENT_SESSION_KEY(u"Interface"_s))
490 , m_networkInterfaceName(BITTORRENT_SESSION_KEY(u"InterfaceName"_s))
491 , m_networkInterfaceAddress(BITTORRENT_SESSION_KEY(u"InterfaceAddress"_s))
492 , m_encryption(BITTORRENT_SESSION_KEY(u"Encryption"_s), 0)
493 , m_maxActiveCheckingTorrents(BITTORRENT_SESSION_KEY(u"MaxActiveCheckingTorrents"_s), 1)
494 , m_isProxyPeerConnectionsEnabled(BITTORRENT_SESSION_KEY(u"ProxyPeerConnections"_s), false)
495 , m_chokingAlgorithm(BITTORRENT_SESSION_KEY(u"ChokingAlgorithm"_s), ChokingAlgorithm::FixedSlots
496 , clampValue(ChokingAlgorithm::FixedSlots, ChokingAlgorithm::RateBased))
497 , m_seedChokingAlgorithm(BITTORRENT_SESSION_KEY(u"SeedChokingAlgorithm"_s), SeedChokingAlgorithm::FastestUpload
498 , clampValue(SeedChokingAlgorithm::RoundRobin, SeedChokingAlgorithm::AntiLeech))
499 , m_storedTags(BITTORRENT_SESSION_KEY(u"Tags"_s))
500 , m_shareLimitAction(BITTORRENT_SESSION_KEY(u"ShareLimitAction"_s), ShareLimitAction::Stop
501 , [](const ShareLimitAction action) { return (action == ShareLimitAction::Default) ? ShareLimitAction::Stop : action; })
502 , m_savePath(BITTORRENT_SESSION_KEY(u"DefaultSavePath"_s), specialFolderLocation(SpecialFolder::Downloads))
503 , m_downloadPath(BITTORRENT_SESSION_KEY(u"TempPath"_s), (savePath() / Path(u"temp"_s)))
504 , m_isDownloadPathEnabled(BITTORRENT_SESSION_KEY(u"TempPathEnabled"_s), false)
505 , m_isSubcategoriesEnabled(BITTORRENT_SESSION_KEY(u"SubcategoriesEnabled"_s), false)
506 , m_useCategoryPathsInManualMode(BITTORRENT_SESSION_KEY(u"UseCategoryPathsInManualMode"_s), false)
507 , m_isAutoTMMDisabledByDefault(BITTORRENT_SESSION_KEY(u"DisableAutoTMMByDefault"_s), true)
508 , m_isDisableAutoTMMWhenCategoryChanged(BITTORRENT_SESSION_KEY(u"DisableAutoTMMTriggers/CategoryChanged"_s), false)
509 , m_isDisableAutoTMMWhenDefaultSavePathChanged(BITTORRENT_SESSION_KEY(u"DisableAutoTMMTriggers/DefaultSavePathChanged"_s), true)
510 , m_isDisableAutoTMMWhenCategorySavePathChanged(BITTORRENT_SESSION_KEY(u"DisableAutoTMMTriggers/CategorySavePathChanged"_s), true)
511 , m_isTrackerEnabled(BITTORRENT_KEY(u"TrackerEnabled"_s), false)
512 , m_peerTurnover(BITTORRENT_SESSION_KEY(u"PeerTurnover"_s), 4)
513 , m_peerTurnoverCutoff(BITTORRENT_SESSION_KEY(u"PeerTurnoverCutOff"_s), 90)
514 , m_peerTurnoverInterval(BITTORRENT_SESSION_KEY(u"PeerTurnoverInterval"_s), 300)
515 , m_requestQueueSize(BITTORRENT_SESSION_KEY(u"RequestQueueSize"_s), 500)
516 , m_isExcludedFileNamesEnabled(BITTORRENT_KEY(u"ExcludedFileNamesEnabled"_s), false)
517 , m_excludedFileNames(BITTORRENT_SESSION_KEY(u"ExcludedFileNames"_s))
518 , m_bannedIPs(u"State/BannedIPs"_s, QStringList(), Algorithm::sorted<QStringList>)
519 , m_resumeDataStorageType(BITTORRENT_SESSION_KEY(u"ResumeDataStorageType"_s), ResumeDataStorageType::Legacy)
520 , m_isMergeTrackersEnabled(BITTORRENT_KEY(u"MergeTrackersEnabled"_s), false)
521 , m_isI2PEnabled {BITTORRENT_SESSION_KEY(u"I2P/Enabled"_s), false}
522 , m_I2PAddress {BITTORRENT_SESSION_KEY(u"I2P/Address"_s), u"127.0.0.1"_s}
523 , m_I2PPort {BITTORRENT_SESSION_KEY(u"I2P/Port"_s), 7656}
524 , m_I2PMixedMode {BITTORRENT_SESSION_KEY(u"I2P/MixedMode"_s), false}
525 , m_I2PInboundQuantity {BITTORRENT_SESSION_KEY(u"I2P/InboundQuantity"_s), 3}
526 , m_I2POutboundQuantity {BITTORRENT_SESSION_KEY(u"I2P/OutboundQuantity"_s), 3}
527 , m_I2PInboundLength {BITTORRENT_SESSION_KEY(u"I2P/InboundLength"_s), 3}
528 , m_I2POutboundLength {BITTORRENT_SESSION_KEY(u"I2P/OutboundLength"_s), 3}
529 , m_torrentContentRemoveOption {BITTORRENT_SESSION_KEY(u"TorrentContentRemoveOption"_s), TorrentContentRemoveOption::MoveToTrash}
530 , m_startPaused {BITTORRENT_SESSION_KEY(u"StartPaused"_s)}
531 , m_seedingLimitTimer {new QTimer(this)}
532 , m_resumeDataTimer {new QTimer(this)}
533 , m_ioThread {new QThread}
534 , m_asyncWorker {new QThreadPool(this)}
535 , m_recentErroredTorrentsTimer {new QTimer(this)}
537 // It is required to perform async access to libtorrent sequentially
538 m_asyncWorker->setMaxThreadCount(1);
540 if (port() < 0)
541 m_port = Utils::Random::rand(1024, 65535);
542 if (sslPort() < 0)
544 m_sslPort = Utils::Random::rand(1024, 65535);
545 while (m_sslPort == port())
546 m_sslPort = Utils::Random::rand(1024, 65535);
549 m_recentErroredTorrentsTimer->setSingleShot(true);
550 m_recentErroredTorrentsTimer->setInterval(1s);
551 connect(m_recentErroredTorrentsTimer, &QTimer::timeout
552 , this, [this]() { m_recentErroredTorrents.clear(); });
554 m_seedingLimitTimer->setInterval(10s);
555 connect(m_seedingLimitTimer, &QTimer::timeout, this, [this]
557 // We shouldn't iterate over `m_torrents` in the loop below
558 // since `deleteTorrent()` modifies it indirectly
559 const QHash<TorrentID, TorrentImpl *> torrents {m_torrents};
560 for (TorrentImpl *torrent : torrents)
561 processTorrentShareLimits(torrent);
564 initializeNativeSession();
565 configureComponents();
567 if (isBandwidthSchedulerEnabled())
568 enableBandwidthScheduler();
570 loadCategories();
571 if (isSubcategoriesEnabled())
573 // if subcategories support changed manually
574 m_categories = expandCategories(m_categories);
577 const QStringList storedTags = m_storedTags.get();
578 for (const QString &tagStr : storedTags)
580 if (const Tag tag {tagStr}; tag.isValid())
581 m_tags.insert(tag);
584 updateSeedingLimitTimer();
585 populateAdditionalTrackers();
586 if (isExcludedFileNamesEnabled())
587 populateExcludedFileNamesRegExpList();
589 connect(Net::ProxyConfigurationManager::instance()
590 , &Net::ProxyConfigurationManager::proxyConfigurationChanged
591 , this, &SessionImpl::configureDeferred);
593 m_fileSearcher = new FileSearcher;
594 m_fileSearcher->moveToThread(m_ioThread.get());
595 connect(m_ioThread.get(), &QThread::finished, m_fileSearcher, &QObject::deleteLater);
596 connect(m_fileSearcher, &FileSearcher::searchFinished, this, &SessionImpl::fileSearchFinished);
598 m_torrentContentRemover = new TorrentContentRemover;
599 m_torrentContentRemover->moveToThread(m_ioThread.get());
600 connect(m_ioThread.get(), &QThread::finished, m_torrentContentRemover, &QObject::deleteLater);
601 connect(m_torrentContentRemover, &TorrentContentRemover::jobFinished, this, &SessionImpl::torrentContentRemovingFinished);
603 m_ioThread->start();
605 initMetrics();
606 loadStatistics();
608 // initialize PortForwarder instance
609 new PortForwarderImpl(this);
611 // start embedded tracker
612 enableTracker(isTrackerEnabled());
614 prepareStartup();
617 SessionImpl::~SessionImpl()
619 m_nativeSession->pause();
621 const auto timeout = (m_shutdownTimeout >= 0) ? (static_cast<qint64>(m_shutdownTimeout) * 1000) : -1;
622 const QDeadlineTimer shutdownDeadlineTimer {timeout};
624 if (m_torrentsQueueChanged)
626 m_nativeSession->post_torrent_updates({});
627 m_torrentsQueueChanged = false;
628 m_needSaveTorrentsQueue = true;
631 // Do some bittorrent related saving
632 // After this, (ideally) no more important alerts will be generated/handled
633 saveResumeData();
635 saveStatistics();
637 // We must delete FilterParserThread
638 // before we delete lt::session
639 delete m_filterParser;
641 // We must delete PortForwarderImpl before
642 // we delete lt::session
643 delete Net::PortForwarder::instance();
645 // We must stop "async worker" only after deletion
646 // of all the components that could potentially use it
647 m_asyncWorker->clear();
648 m_asyncWorker->waitForDone();
650 auto *nativeSessionProxy = new lt::session_proxy(m_nativeSession->abort());
651 delete m_nativeSession;
653 qDebug("Deleting resume data storage...");
654 delete m_resumeDataStorage;
655 LogMsg(tr("Saving resume data completed."));
657 auto *sessionTerminateThread = QThread::create([nativeSessionProxy]()
659 qDebug("Deleting libtorrent session...");
660 delete nativeSessionProxy;
662 connect(sessionTerminateThread, &QThread::finished, sessionTerminateThread, &QObject::deleteLater);
663 sessionTerminateThread->start();
664 if (sessionTerminateThread->wait(shutdownDeadlineTimer))
665 LogMsg(tr("BitTorrent session successfully finished."));
666 else
667 LogMsg(tr("Session shutdown timed out."));
670 QString SessionImpl::getDHTBootstrapNodes() const
672 const QString nodes = m_DHTBootstrapNodes;
673 return !nodes.isEmpty() ? nodes : DEFAULT_DHT_BOOTSTRAP_NODES;
676 void SessionImpl::setDHTBootstrapNodes(const QString &nodes)
678 if (nodes == m_DHTBootstrapNodes)
679 return;
681 m_DHTBootstrapNodes = nodes;
682 configureDeferred();
685 bool SessionImpl::isDHTEnabled() const
687 return m_isDHTEnabled;
690 void SessionImpl::setDHTEnabled(bool enabled)
692 if (enabled != m_isDHTEnabled)
694 m_isDHTEnabled = enabled;
695 configureDeferred();
696 LogMsg(tr("Distributed Hash Table (DHT) support: %1").arg(enabled ? tr("ON") : tr("OFF")), Log::INFO);
700 bool SessionImpl::isLSDEnabled() const
702 return m_isLSDEnabled;
705 void SessionImpl::setLSDEnabled(const bool enabled)
707 if (enabled != m_isLSDEnabled)
709 m_isLSDEnabled = enabled;
710 configureDeferred();
711 LogMsg(tr("Local Peer Discovery support: %1").arg(enabled ? tr("ON") : tr("OFF"))
712 , Log::INFO);
716 bool SessionImpl::isPeXEnabled() const
718 return m_isPeXEnabled;
721 void SessionImpl::setPeXEnabled(const bool enabled)
723 m_isPeXEnabled = enabled;
724 if (m_wasPexEnabled != enabled)
725 LogMsg(tr("Restart is required to toggle Peer Exchange (PeX) support"), Log::WARNING);
728 bool SessionImpl::isDownloadPathEnabled() const
730 return m_isDownloadPathEnabled;
733 void SessionImpl::setDownloadPathEnabled(const bool enabled)
735 if (enabled != isDownloadPathEnabled())
737 m_isDownloadPathEnabled = enabled;
738 for (TorrentImpl *const torrent : asConst(m_torrents))
739 torrent->handleCategoryOptionsChanged();
743 bool SessionImpl::isAppendExtensionEnabled() const
745 return m_isAppendExtensionEnabled;
748 void SessionImpl::setAppendExtensionEnabled(const bool enabled)
750 if (isAppendExtensionEnabled() != enabled)
752 m_isAppendExtensionEnabled = enabled;
754 // append or remove .!qB extension for incomplete files
755 for (TorrentImpl *const torrent : asConst(m_torrents))
756 torrent->handleAppendExtensionToggled();
760 bool SessionImpl::isUnwantedFolderEnabled() const
762 return m_isUnwantedFolderEnabled;
765 void SessionImpl::setUnwantedFolderEnabled(const bool enabled)
767 if (isUnwantedFolderEnabled() != enabled)
769 m_isUnwantedFolderEnabled = enabled;
771 // append or remove .!qB extension for incomplete files
772 for (TorrentImpl *const torrent : asConst(m_torrents))
773 torrent->handleUnwantedFolderToggled();
777 int SessionImpl::refreshInterval() const
779 return m_refreshInterval;
782 void SessionImpl::setRefreshInterval(const int value)
784 if (value != refreshInterval())
786 m_refreshInterval = value;
790 bool SessionImpl::isPreallocationEnabled() const
792 return m_isPreallocationEnabled;
795 void SessionImpl::setPreallocationEnabled(const bool enabled)
797 m_isPreallocationEnabled = enabled;
800 Path SessionImpl::torrentExportDirectory() const
802 return m_torrentExportDirectory;
805 void SessionImpl::setTorrentExportDirectory(const Path &path)
807 if (path != torrentExportDirectory())
808 m_torrentExportDirectory = path;
811 Path SessionImpl::finishedTorrentExportDirectory() const
813 return m_finishedTorrentExportDirectory;
816 void SessionImpl::setFinishedTorrentExportDirectory(const Path &path)
818 if (path != finishedTorrentExportDirectory())
819 m_finishedTorrentExportDirectory = path;
822 Path SessionImpl::savePath() const
824 // TODO: Make sure it is always non-empty
825 return m_savePath;
828 Path SessionImpl::downloadPath() const
830 // TODO: Make sure it is always non-empty
831 return m_downloadPath;
834 QStringList SessionImpl::categories() const
836 return m_categories.keys();
839 CategoryOptions SessionImpl::categoryOptions(const QString &categoryName) const
841 return m_categories.value(categoryName);
844 Path SessionImpl::categorySavePath(const QString &categoryName) const
846 return categorySavePath(categoryName, categoryOptions(categoryName));
849 Path SessionImpl::categorySavePath(const QString &categoryName, const CategoryOptions &options) const
851 Path basePath = savePath();
852 if (categoryName.isEmpty())
853 return basePath;
855 Path path = options.savePath;
856 if (path.isEmpty())
858 // use implicit save path
859 if (isSubcategoriesEnabled())
861 path = Utils::Fs::toValidPath(subcategoryName(categoryName));
862 basePath = categorySavePath(parentCategoryName(categoryName));
864 else
866 path = Utils::Fs::toValidPath(categoryName);
870 return (path.isAbsolute() ? path : (basePath / path));
873 Path SessionImpl::categoryDownloadPath(const QString &categoryName) const
875 return categoryDownloadPath(categoryName, categoryOptions(categoryName));
878 Path SessionImpl::categoryDownloadPath(const QString &categoryName, const CategoryOptions &options) const
880 const DownloadPathOption downloadPathOption = resolveCategoryDownloadPathOption(categoryName, options.downloadPath);
881 if (!downloadPathOption.enabled)
882 return {};
884 if (categoryName.isEmpty())
885 return downloadPath();
887 const bool useSubcategories = isSubcategoriesEnabled();
888 const QString name = useSubcategories ? subcategoryName(categoryName) : categoryName;
889 const Path path = !downloadPathOption.path.isEmpty()
890 ? downloadPathOption.path
891 : Utils::Fs::toValidPath(name); // use implicit download path
893 if (path.isAbsolute())
894 return path;
896 const QString parentName = useSubcategories ? parentCategoryName(categoryName) : QString();
897 CategoryOptions parentOptions = categoryOptions(parentName);
898 // Even if download path of parent category is disabled (directly or by inheritance)
899 // we need to construct the one as if it would be enabled.
900 if (!parentOptions.downloadPath || !parentOptions.downloadPath->enabled)
901 parentOptions.downloadPath = {true, {}};
902 const Path parentDownloadPath = categoryDownloadPath(parentName, parentOptions);
903 const Path basePath = parentDownloadPath.isEmpty() ? downloadPath() : parentDownloadPath;
904 return (basePath / path);
907 DownloadPathOption SessionImpl::resolveCategoryDownloadPathOption(const QString &categoryName, const std::optional<DownloadPathOption> &option) const
909 if (categoryName.isEmpty())
910 return {isDownloadPathEnabled(), Path()};
912 if (option.has_value())
913 return *option;
915 const QString parentName = isSubcategoriesEnabled() ? parentCategoryName(categoryName) : QString();
916 return resolveCategoryDownloadPathOption(parentName, categoryOptions(parentName).downloadPath);
919 bool SessionImpl::addCategory(const QString &name, const CategoryOptions &options)
921 if (name.isEmpty())
922 return false;
924 if (!isValidCategoryName(name) || m_categories.contains(name))
925 return false;
927 if (isSubcategoriesEnabled())
929 for (const QString &parent : asConst(expandCategory(name)))
931 if ((parent != name) && !m_categories.contains(parent))
933 m_categories[parent] = {};
934 emit categoryAdded(parent);
939 m_categories[name] = options;
940 storeCategories();
941 emit categoryAdded(name);
943 return true;
946 bool SessionImpl::editCategory(const QString &name, const CategoryOptions &options)
948 const auto it = m_categories.find(name);
949 if (it == m_categories.end())
950 return false;
952 CategoryOptions &currentOptions = it.value();
953 if (options == currentOptions)
954 return false;
956 currentOptions = options;
957 storeCategories();
958 if (isDisableAutoTMMWhenCategorySavePathChanged())
960 for (TorrentImpl *const torrent : asConst(m_torrents))
962 if (torrent->category() == name)
963 torrent->setAutoTMMEnabled(false);
966 else
968 for (TorrentImpl *const torrent : asConst(m_torrents))
970 if (torrent->category() == name)
971 torrent->handleCategoryOptionsChanged();
975 emit categoryOptionsChanged(name);
976 return true;
979 bool SessionImpl::removeCategory(const QString &name)
981 for (TorrentImpl *const torrent : asConst(m_torrents))
983 if (torrent->belongsToCategory(name))
984 torrent->setCategory(u""_s);
987 // remove stored category and its subcategories if exist
988 bool result = false;
989 if (isSubcategoriesEnabled())
991 // remove subcategories
992 const QString test = name + u'/';
993 Algorithm::removeIf(m_categories, [this, &test, &result](const QString &category, const CategoryOptions &)
995 if (category.startsWith(test))
997 result = true;
998 emit categoryRemoved(category);
999 return true;
1001 return false;
1005 result = (m_categories.remove(name) > 0) || result;
1007 if (result)
1009 // update stored categories
1010 storeCategories();
1011 emit categoryRemoved(name);
1014 return result;
1017 bool SessionImpl::isSubcategoriesEnabled() const
1019 return m_isSubcategoriesEnabled;
1022 void SessionImpl::setSubcategoriesEnabled(const bool value)
1024 if (isSubcategoriesEnabled() == value) return;
1026 if (value)
1028 // expand categories to include all parent categories
1029 m_categories = expandCategories(m_categories);
1030 // update stored categories
1031 storeCategories();
1033 else
1035 // reload categories
1036 loadCategories();
1039 m_isSubcategoriesEnabled = value;
1040 emit subcategoriesSupportChanged();
1043 bool SessionImpl::useCategoryPathsInManualMode() const
1045 return m_useCategoryPathsInManualMode;
1048 void SessionImpl::setUseCategoryPathsInManualMode(const bool value)
1050 m_useCategoryPathsInManualMode = value;
1053 Path SessionImpl::suggestedSavePath(const QString &categoryName, std::optional<bool> useAutoTMM) const
1055 const bool useCategoryPaths = useAutoTMM.value_or(!isAutoTMMDisabledByDefault()) || useCategoryPathsInManualMode();
1056 const auto path = (useCategoryPaths ? categorySavePath(categoryName) : savePath());
1057 return path;
1060 Path SessionImpl::suggestedDownloadPath(const QString &categoryName, std::optional<bool> useAutoTMM) const
1062 const bool useCategoryPaths = useAutoTMM.value_or(!isAutoTMMDisabledByDefault()) || useCategoryPathsInManualMode();
1063 const auto categoryDownloadPath = this->categoryDownloadPath(categoryName);
1064 const auto path = ((useCategoryPaths && !categoryDownloadPath.isEmpty()) ? categoryDownloadPath : downloadPath());
1065 return path;
1068 TagSet SessionImpl::tags() const
1070 return m_tags;
1073 bool SessionImpl::hasTag(const Tag &tag) const
1075 return m_tags.contains(tag);
1078 bool SessionImpl::addTag(const Tag &tag)
1080 if (!tag.isValid() || hasTag(tag))
1081 return false;
1083 m_tags.insert(tag);
1084 m_storedTags = QStringList(m_tags.cbegin(), m_tags.cend());
1086 emit tagAdded(tag);
1087 return true;
1090 bool SessionImpl::removeTag(const Tag &tag)
1092 if (m_tags.remove(tag))
1094 for (TorrentImpl *const torrent : asConst(m_torrents))
1095 torrent->removeTag(tag);
1097 m_storedTags = QStringList(m_tags.cbegin(), m_tags.cend());
1099 emit tagRemoved(tag);
1100 return true;
1102 return false;
1105 bool SessionImpl::isAutoTMMDisabledByDefault() const
1107 return m_isAutoTMMDisabledByDefault;
1110 void SessionImpl::setAutoTMMDisabledByDefault(const bool value)
1112 m_isAutoTMMDisabledByDefault = value;
1115 bool SessionImpl::isDisableAutoTMMWhenCategoryChanged() const
1117 return m_isDisableAutoTMMWhenCategoryChanged;
1120 void SessionImpl::setDisableAutoTMMWhenCategoryChanged(const bool value)
1122 m_isDisableAutoTMMWhenCategoryChanged = value;
1125 bool SessionImpl::isDisableAutoTMMWhenDefaultSavePathChanged() const
1127 return m_isDisableAutoTMMWhenDefaultSavePathChanged;
1130 void SessionImpl::setDisableAutoTMMWhenDefaultSavePathChanged(const bool value)
1132 m_isDisableAutoTMMWhenDefaultSavePathChanged = value;
1135 bool SessionImpl::isDisableAutoTMMWhenCategorySavePathChanged() const
1137 return m_isDisableAutoTMMWhenCategorySavePathChanged;
1140 void SessionImpl::setDisableAutoTMMWhenCategorySavePathChanged(const bool value)
1142 m_isDisableAutoTMMWhenCategorySavePathChanged = value;
1145 bool SessionImpl::isAddTorrentToQueueTop() const
1147 return m_isAddTorrentToQueueTop;
1150 void SessionImpl::setAddTorrentToQueueTop(bool value)
1152 m_isAddTorrentToQueueTop = value;
1155 bool SessionImpl::isAddTorrentStopped() const
1157 return m_isAddTorrentStopped;
1160 void SessionImpl::setAddTorrentStopped(const bool value)
1162 m_isAddTorrentStopped = value;
1165 Torrent::StopCondition SessionImpl::torrentStopCondition() const
1167 return m_torrentStopCondition;
1170 void SessionImpl::setTorrentStopCondition(const Torrent::StopCondition stopCondition)
1172 m_torrentStopCondition = stopCondition;
1175 bool SessionImpl::isTrackerEnabled() const
1177 return m_isTrackerEnabled;
1180 void SessionImpl::setTrackerEnabled(const bool enabled)
1182 if (m_isTrackerEnabled != enabled)
1183 m_isTrackerEnabled = enabled;
1185 // call enableTracker() unconditionally, otherwise port change won't trigger
1186 // tracker restart
1187 enableTracker(enabled);
1190 qreal SessionImpl::globalMaxRatio() const
1192 return m_globalMaxRatio;
1195 // Torrents with a ratio superior to the given value will
1196 // be automatically deleted
1197 void SessionImpl::setGlobalMaxRatio(qreal ratio)
1199 if (ratio < 0)
1200 ratio = -1.;
1202 if (ratio != globalMaxRatio())
1204 m_globalMaxRatio = ratio;
1205 updateSeedingLimitTimer();
1209 int SessionImpl::globalMaxSeedingMinutes() const
1211 return m_globalMaxSeedingMinutes;
1214 void SessionImpl::setGlobalMaxSeedingMinutes(int minutes)
1216 if (minutes < 0)
1217 minutes = -1;
1219 if (minutes != globalMaxSeedingMinutes())
1221 m_globalMaxSeedingMinutes = minutes;
1222 updateSeedingLimitTimer();
1226 int SessionImpl::globalMaxInactiveSeedingMinutes() const
1228 return m_globalMaxInactiveSeedingMinutes;
1231 void SessionImpl::setGlobalMaxInactiveSeedingMinutes(int minutes)
1233 minutes = std::max(minutes, -1);
1235 if (minutes != globalMaxInactiveSeedingMinutes())
1237 m_globalMaxInactiveSeedingMinutes = minutes;
1238 updateSeedingLimitTimer();
1242 void SessionImpl::applyBandwidthLimits()
1244 lt::settings_pack settingsPack;
1245 settingsPack.set_int(lt::settings_pack::download_rate_limit, downloadSpeedLimit());
1246 settingsPack.set_int(lt::settings_pack::upload_rate_limit, uploadSpeedLimit());
1247 m_nativeSession->apply_settings(std::move(settingsPack));
1250 void SessionImpl::configure()
1252 m_nativeSession->apply_settings(loadLTSettings());
1253 configureComponents();
1255 m_deferredConfigureScheduled = false;
1258 void SessionImpl::configureComponents()
1260 // This function contains components/actions that:
1261 // 1. Need to be setup at start up
1262 // 2. When deferred configure is called
1264 configurePeerClasses();
1266 if (!m_IPFilteringConfigured)
1268 if (isIPFilteringEnabled())
1269 enableIPFilter();
1270 else
1271 disableIPFilter();
1272 m_IPFilteringConfigured = true;
1276 void SessionImpl::prepareStartup()
1278 qDebug("Initializing torrents resume data storage...");
1280 const Path dbPath = specialFolderLocation(SpecialFolder::Data) / Path(u"torrents.db"_s);
1281 const bool dbStorageExists = dbPath.exists();
1283 auto *context = new ResumeSessionContext(this);
1284 context->currentStorageType = resumeDataStorageType();
1286 if (context->currentStorageType == ResumeDataStorageType::SQLite)
1288 m_resumeDataStorage = new DBResumeDataStorage(dbPath, this);
1290 if (!dbStorageExists)
1292 const Path dataPath = specialFolderLocation(SpecialFolder::Data) / Path(u"BT_backup"_s);
1293 context->startupStorage = new BencodeResumeDataStorage(dataPath, this);
1296 else
1298 const Path dataPath = specialFolderLocation(SpecialFolder::Data) / Path(u"BT_backup"_s);
1299 m_resumeDataStorage = new BencodeResumeDataStorage(dataPath, this);
1301 if (dbStorageExists)
1302 context->startupStorage = new DBResumeDataStorage(dbPath, this);
1305 if (!context->startupStorage)
1306 context->startupStorage = m_resumeDataStorage;
1308 connect(context->startupStorage, &ResumeDataStorage::loadStarted, context
1309 , [this, context](const QList<TorrentID> &torrents)
1311 context->totalResumeDataCount = torrents.size();
1312 #ifdef QBT_USES_LIBTORRENT2
1313 context->indexedTorrents = QSet<TorrentID>(torrents.cbegin(), torrents.cend());
1314 #endif
1316 handleLoadedResumeData(context);
1319 connect(context->startupStorage, &ResumeDataStorage::loadFinished, context, [context]()
1321 context->isLoadFinished = true;
1324 connect(this, &SessionImpl::addTorrentAlertsReceived, context, [this, context](const qsizetype alertsCount)
1326 context->processingResumeDataCount -= alertsCount;
1327 context->finishedResumeDataCount += alertsCount;
1328 if (!context->isLoadedResumeDataHandlingEnqueued)
1330 QMetaObject::invokeMethod(this, [this, context] { handleLoadedResumeData(context); }, Qt::QueuedConnection);
1331 context->isLoadedResumeDataHandlingEnqueued = true;
1334 if (!m_refreshEnqueued)
1336 m_nativeSession->post_torrent_updates();
1337 m_refreshEnqueued = true;
1340 emit startupProgressUpdated((context->finishedResumeDataCount * 100.) / context->totalResumeDataCount);
1343 context->startupStorage->loadAll();
1346 void SessionImpl::handleLoadedResumeData(ResumeSessionContext *context)
1348 context->isLoadedResumeDataHandlingEnqueued = false;
1350 int count = context->processingResumeDataCount;
1351 while (context->processingResumeDataCount < MAX_PROCESSING_RESUMEDATA_COUNT)
1353 if (context->loadedResumeData.isEmpty())
1354 context->loadedResumeData = context->startupStorage->fetchLoadedResumeData();
1356 if (context->loadedResumeData.isEmpty())
1358 if (context->processingResumeDataCount == 0)
1360 if (context->isLoadFinished)
1362 endStartup(context);
1364 else if (!context->isLoadedResumeDataHandlingEnqueued)
1366 QMetaObject::invokeMethod(this, [this, context]() { handleLoadedResumeData(context); }, Qt::QueuedConnection);
1367 context->isLoadedResumeDataHandlingEnqueued = true;
1371 break;
1374 processNextResumeData(context);
1375 ++count;
1378 context->finishedResumeDataCount += (count - context->processingResumeDataCount);
1381 void SessionImpl::processNextResumeData(ResumeSessionContext *context)
1383 const LoadedResumeData loadedResumeDataItem = context->loadedResumeData.takeFirst();
1385 TorrentID torrentID = loadedResumeDataItem.torrentID;
1386 #ifdef QBT_USES_LIBTORRENT2
1387 if (context->skippedIDs.contains(torrentID))
1388 return;
1389 #endif
1391 const nonstd::expected<LoadTorrentParams, QString> &loadResumeDataResult = loadedResumeDataItem.result;
1392 if (!loadResumeDataResult)
1394 LogMsg(tr("Failed to resume torrent. Torrent: \"%1\". Reason: \"%2\"")
1395 .arg(torrentID.toString(), loadResumeDataResult.error()), Log::CRITICAL);
1396 return;
1399 LoadTorrentParams resumeData = *loadResumeDataResult;
1400 bool needStore = false;
1402 #ifdef QBT_USES_LIBTORRENT2
1403 const InfoHash infoHash {(resumeData.ltAddTorrentParams.ti
1404 ? resumeData.ltAddTorrentParams.ti->info_hashes()
1405 : resumeData.ltAddTorrentParams.info_hashes)};
1406 const bool isHybrid = infoHash.isHybrid();
1407 const auto torrentIDv2 = TorrentID::fromInfoHash(infoHash);
1408 const auto torrentIDv1 = TorrentID::fromSHA1Hash(infoHash.v1());
1409 if (torrentID == torrentIDv2)
1411 if (isHybrid && context->indexedTorrents.contains(torrentIDv1))
1413 // if we don't have metadata, try to find it in alternative "resume data"
1414 if (!resumeData.ltAddTorrentParams.ti)
1416 const nonstd::expected<LoadTorrentParams, QString> loadAltResumeDataResult = context->startupStorage->load(torrentIDv1);
1417 if (loadAltResumeDataResult)
1418 resumeData.ltAddTorrentParams.ti = loadAltResumeDataResult->ltAddTorrentParams.ti;
1421 // remove alternative "resume data" and skip the attempt to load it
1422 m_resumeDataStorage->remove(torrentIDv1);
1423 context->skippedIDs.insert(torrentIDv1);
1426 else if (torrentID == torrentIDv1)
1428 torrentID = torrentIDv2;
1429 needStore = true;
1430 m_resumeDataStorage->remove(torrentIDv1);
1432 if (context->indexedTorrents.contains(torrentID))
1434 context->skippedIDs.insert(torrentID);
1436 const nonstd::expected<LoadTorrentParams, QString> loadPreferredResumeDataResult = context->startupStorage->load(torrentID);
1437 if (loadPreferredResumeDataResult)
1439 std::shared_ptr<lt::torrent_info> ti = resumeData.ltAddTorrentParams.ti;
1440 resumeData = *loadPreferredResumeDataResult;
1441 if (!resumeData.ltAddTorrentParams.ti)
1442 resumeData.ltAddTorrentParams.ti = std::move(ti);
1446 else
1448 LogMsg(tr("Failed to resume torrent: inconsistent torrent ID is detected. Torrent: \"%1\"")
1449 .arg(torrentID.toString()), Log::WARNING);
1450 return;
1452 #else
1453 const lt::sha1_hash infoHash = (resumeData.ltAddTorrentParams.ti
1454 ? resumeData.ltAddTorrentParams.ti->info_hash()
1455 : resumeData.ltAddTorrentParams.info_hash);
1456 if (torrentID != TorrentID::fromInfoHash(infoHash))
1458 LogMsg(tr("Failed to resume torrent: inconsistent torrent ID is detected. Torrent: \"%1\"")
1459 .arg(torrentID.toString()), Log::WARNING);
1460 return;
1462 #endif
1464 if (m_resumeDataStorage != context->startupStorage)
1465 needStore = true;
1467 // TODO: Remove the following upgrade code in v4.6
1468 // == BEGIN UPGRADE CODE ==
1469 if (!needStore)
1471 if (m_needUpgradeDownloadPath && isDownloadPathEnabled() && !resumeData.useAutoTMM)
1473 resumeData.downloadPath = downloadPath();
1474 needStore = true;
1477 // == END UPGRADE CODE ==
1479 if (needStore)
1480 m_resumeDataStorage->store(torrentID, resumeData);
1482 const QString category = resumeData.category;
1483 bool isCategoryRecovered = context->recoveredCategories.contains(category);
1484 if (!category.isEmpty() && (isCategoryRecovered || !m_categories.contains(category)))
1486 if (!isCategoryRecovered)
1488 if (addCategory(category))
1490 context->recoveredCategories.insert(category);
1491 isCategoryRecovered = true;
1492 LogMsg(tr("Detected inconsistent data: category is missing from the configuration file."
1493 " Category will be recovered but its settings will be reset to default."
1494 " Torrent: \"%1\". Category: \"%2\"").arg(torrentID.toString(), category), Log::WARNING);
1496 else
1498 resumeData.category.clear();
1499 LogMsg(tr("Detected inconsistent data: invalid category. Torrent: \"%1\". Category: \"%2\"")
1500 .arg(torrentID.toString(), category), Log::WARNING);
1504 // We should check isCategoryRecovered again since the category
1505 // can be just recovered by the code above
1506 if (isCategoryRecovered && resumeData.useAutoTMM)
1508 const Path storageLocation {resumeData.ltAddTorrentParams.save_path};
1509 if ((storageLocation != categorySavePath(resumeData.category)) && (storageLocation != categoryDownloadPath(resumeData.category)))
1511 resumeData.useAutoTMM = false;
1512 resumeData.savePath = storageLocation;
1513 resumeData.downloadPath = {};
1514 LogMsg(tr("Detected mismatch between the save paths of the recovered category and the current save path of the torrent."
1515 " Torrent is now switched to Manual mode."
1516 " Torrent: \"%1\". Category: \"%2\"").arg(torrentID.toString(), category), Log::WARNING);
1521 std::erase_if(resumeData.tags, [this, &torrentID](const Tag &tag)
1523 if (hasTag(tag))
1524 return false;
1526 if (addTag(tag))
1528 LogMsg(tr("Detected inconsistent data: tag is missing from the configuration file."
1529 " Tag will be recovered."
1530 " Torrent: \"%1\". Tag: \"%2\"").arg(torrentID.toString(), tag.toString()), Log::WARNING);
1531 return false;
1534 LogMsg(tr("Detected inconsistent data: invalid tag. Torrent: \"%1\". Tag: \"%2\"")
1535 .arg(torrentID.toString(), tag.toString()), Log::WARNING);
1536 return true;
1539 resumeData.ltAddTorrentParams.userdata = LTClientData(new ExtensionData);
1540 #ifndef QBT_USES_LIBTORRENT2
1541 resumeData.ltAddTorrentParams.storage = customStorageConstructor;
1542 #endif
1544 qDebug() << "Starting up torrent" << torrentID.toString() << "...";
1545 m_loadingTorrents.insert(torrentID, resumeData);
1546 #ifdef QBT_USES_LIBTORRENT2
1547 if (infoHash.isHybrid())
1549 // this allows to know the being added hybrid torrent by its v1 info hash
1550 // without having yet another mapping table
1551 m_hybridTorrentsByAltID.insert(torrentIDv1, nullptr);
1553 #endif
1554 m_nativeSession->async_add_torrent(resumeData.ltAddTorrentParams);
1555 ++context->processingResumeDataCount;
1558 void SessionImpl::endStartup(ResumeSessionContext *context)
1560 if (m_resumeDataStorage != context->startupStorage)
1562 if (isQueueingSystemEnabled())
1563 saveTorrentsQueue();
1565 const Path dbPath = context->startupStorage->path();
1566 context->startupStorage->deleteLater();
1568 if (context->currentStorageType == ResumeDataStorageType::Legacy)
1570 connect(context->startupStorage, &QObject::destroyed, [dbPath]
1572 Utils::Fs::removeFile(dbPath);
1577 context->deleteLater();
1578 connect(context, &QObject::destroyed, this, [this]
1580 if (!m_isPaused)
1581 m_nativeSession->resume();
1583 if (m_refreshEnqueued)
1584 m_refreshEnqueued = false;
1585 else
1586 enqueueRefresh();
1588 m_statisticsLastUpdateTimer.start();
1590 // Regular saving of fastresume data
1591 connect(m_resumeDataTimer, &QTimer::timeout, this, &SessionImpl::generateResumeData);
1592 const int saveInterval = saveResumeDataInterval();
1593 if (saveInterval > 0)
1595 m_resumeDataTimer->setInterval(std::chrono::minutes(saveInterval));
1596 m_resumeDataTimer->start();
1599 m_wakeupCheckTimer = new QTimer(this);
1600 connect(m_wakeupCheckTimer, &QTimer::timeout, this, [this]
1602 const auto now = QDateTime::currentDateTime();
1603 if (m_wakeupCheckTimestamp.secsTo(now) > 100)
1605 LogMsg(tr("System wake-up event detected. Re-announcing to all the trackers..."));
1606 reannounceToAllTrackers();
1609 m_wakeupCheckTimestamp = QDateTime::currentDateTime();
1611 m_wakeupCheckTimestamp = QDateTime::currentDateTime();
1612 m_wakeupCheckTimer->start(30s);
1614 m_isRestored = true;
1615 emit startupProgressUpdated(100);
1616 emit restored();
1620 void SessionImpl::initializeNativeSession()
1622 lt::settings_pack pack = loadLTSettings();
1624 const std::string peerId = lt::generate_fingerprint(PEER_ID, QBT_VERSION_MAJOR, QBT_VERSION_MINOR, QBT_VERSION_BUGFIX, QBT_VERSION_BUILD);
1625 pack.set_str(lt::settings_pack::peer_fingerprint, peerId);
1627 pack.set_bool(lt::settings_pack::listen_system_port_fallback, false);
1628 pack.set_str(lt::settings_pack::user_agent, USER_AGENT.toStdString());
1629 pack.set_bool(lt::settings_pack::use_dht_as_fallback, false);
1630 // Speed up exit
1631 pack.set_int(lt::settings_pack::auto_scrape_interval, 1200); // 20 minutes
1632 pack.set_int(lt::settings_pack::auto_scrape_min_interval, 900); // 15 minutes
1633 // libtorrent 1.1 enables UPnP & NAT-PMP by default
1634 // turn them off before `lt::session` ctor to avoid split second effects
1635 pack.set_bool(lt::settings_pack::enable_upnp, false);
1636 pack.set_bool(lt::settings_pack::enable_natpmp, false);
1638 #ifdef QBT_USES_LIBTORRENT2
1639 // preserve the same behavior as in earlier libtorrent versions
1640 pack.set_bool(lt::settings_pack::enable_set_file_valid_data, true);
1641 #endif
1643 lt::session_params sessionParams {std::move(pack), {}};
1644 #ifdef QBT_USES_LIBTORRENT2
1645 switch (diskIOType())
1647 case DiskIOType::Posix:
1648 sessionParams.disk_io_constructor = customPosixDiskIOConstructor;
1649 break;
1650 case DiskIOType::MMap:
1651 sessionParams.disk_io_constructor = customMMapDiskIOConstructor;
1652 break;
1653 default:
1654 sessionParams.disk_io_constructor = customDiskIOConstructor;
1655 break;
1657 #endif
1659 #if LIBTORRENT_VERSION_NUM < 20100
1660 m_nativeSession = new lt::session(sessionParams, lt::session::paused);
1661 #else
1662 m_nativeSession = new lt::session(sessionParams);
1663 m_nativeSession->pause();
1664 #endif
1666 LogMsg(tr("Peer ID: \"%1\"").arg(QString::fromStdString(peerId)), Log::INFO);
1667 LogMsg(tr("HTTP User-Agent: \"%1\"").arg(USER_AGENT), Log::INFO);
1668 LogMsg(tr("Distributed Hash Table (DHT) support: %1").arg(isDHTEnabled() ? tr("ON") : tr("OFF")), Log::INFO);
1669 LogMsg(tr("Local Peer Discovery support: %1").arg(isLSDEnabled() ? tr("ON") : tr("OFF")), Log::INFO);
1670 LogMsg(tr("Peer Exchange (PeX) support: %1").arg(isPeXEnabled() ? tr("ON") : tr("OFF")), Log::INFO);
1671 LogMsg(tr("Anonymous mode: %1").arg(isAnonymousModeEnabled() ? tr("ON") : tr("OFF")), Log::INFO);
1672 LogMsg(tr("Encryption support: %1").arg((encryption() == 0) ? tr("ON") : ((encryption() == 1) ? tr("FORCED") : tr("OFF"))), Log::INFO);
1674 m_nativeSession->set_alert_notify([this]()
1676 QMetaObject::invokeMethod(this, &SessionImpl::readAlerts, Qt::QueuedConnection);
1679 // Enabling plugins
1680 m_nativeSession->add_extension(&lt::create_smart_ban_plugin);
1681 m_nativeSession->add_extension(&lt::create_ut_metadata_plugin);
1682 if (isPeXEnabled())
1683 m_nativeSession->add_extension(&lt::create_ut_pex_plugin);
1685 auto nativeSessionExtension = std::make_shared<NativeSessionExtension>();
1686 m_nativeSession->add_extension(nativeSessionExtension);
1687 m_nativeSessionExtension = nativeSessionExtension.get();
1690 void SessionImpl::processBannedIPs(lt::ip_filter &filter)
1692 // First, import current filter
1693 for (const QString &ip : asConst(m_bannedIPs.get()))
1695 lt::error_code ec;
1696 const lt::address addr = lt::make_address(ip.toLatin1().constData(), ec);
1697 Q_ASSERT(!ec);
1698 if (!ec)
1699 filter.add_rule(addr, addr, lt::ip_filter::blocked);
1703 void SessionImpl::initMetrics()
1705 const auto findMetricIndex = [](const char *name) -> int
1707 const int index = lt::find_metric_idx(name);
1708 Q_ASSERT(index >= 0);
1709 return index;
1712 m_metricIndices =
1714 .net =
1716 .hasIncomingConnections = findMetricIndex("net.has_incoming_connections"),
1717 .sentPayloadBytes = findMetricIndex("net.sent_payload_bytes"),
1718 .recvPayloadBytes = findMetricIndex("net.recv_payload_bytes"),
1719 .sentBytes = findMetricIndex("net.sent_bytes"),
1720 .recvBytes = findMetricIndex("net.recv_bytes"),
1721 .sentIPOverheadBytes = findMetricIndex("net.sent_ip_overhead_bytes"),
1722 .recvIPOverheadBytes = findMetricIndex("net.recv_ip_overhead_bytes"),
1723 .sentTrackerBytes = findMetricIndex("net.sent_tracker_bytes"),
1724 .recvTrackerBytes = findMetricIndex("net.recv_tracker_bytes"),
1725 .recvRedundantBytes = findMetricIndex("net.recv_redundant_bytes"),
1726 .recvFailedBytes = findMetricIndex("net.recv_failed_bytes")
1728 .peer =
1730 .numPeersConnected = findMetricIndex("peer.num_peers_connected"),
1731 .numPeersUpDisk = findMetricIndex("peer.num_peers_up_disk"),
1732 .numPeersDownDisk = findMetricIndex("peer.num_peers_down_disk")
1734 .dht =
1736 .dhtBytesIn = findMetricIndex("dht.dht_bytes_in"),
1737 .dhtBytesOut = findMetricIndex("dht.dht_bytes_out"),
1738 .dhtNodes = findMetricIndex("dht.dht_nodes")
1740 .disk =
1742 .diskBlocksInUse = findMetricIndex("disk.disk_blocks_in_use"),
1743 .numBlocksRead = findMetricIndex("disk.num_blocks_read"),
1744 #ifndef QBT_USES_LIBTORRENT2
1745 .numBlocksCacheHits = findMetricIndex("disk.num_blocks_cache_hits"),
1746 #endif
1747 .writeJobs = findMetricIndex("disk.num_write_ops"),
1748 .readJobs = findMetricIndex("disk.num_read_ops"),
1749 .hashJobs = findMetricIndex("disk.num_blocks_hashed"),
1750 .queuedDiskJobs = findMetricIndex("disk.queued_disk_jobs"),
1751 .diskJobTime = findMetricIndex("disk.disk_job_time")
1756 lt::settings_pack SessionImpl::loadLTSettings() const
1758 lt::settings_pack settingsPack;
1760 const lt::alert_category_t alertMask = lt::alert::error_notification
1761 | lt::alert::file_progress_notification
1762 | lt::alert::ip_block_notification
1763 | lt::alert::peer_notification
1764 | (isPerformanceWarningEnabled() ? lt::alert::performance_warning : lt::alert_category_t())
1765 | lt::alert::port_mapping_notification
1766 | lt::alert::status_notification
1767 | lt::alert::storage_notification
1768 | lt::alert::tracker_notification;
1769 settingsPack.set_int(lt::settings_pack::alert_mask, alertMask);
1771 settingsPack.set_int(lt::settings_pack::connection_speed, connectionSpeed());
1773 // from libtorrent doc:
1774 // It will not take affect until the listen_interfaces settings is updated
1775 settingsPack.set_int(lt::settings_pack::send_socket_buffer_size, socketSendBufferSize());
1776 settingsPack.set_int(lt::settings_pack::recv_socket_buffer_size, socketReceiveBufferSize());
1777 settingsPack.set_int(lt::settings_pack::listen_queue_size, socketBacklogSize());
1779 applyNetworkInterfacesSettings(settingsPack);
1781 settingsPack.set_int(lt::settings_pack::download_rate_limit, downloadSpeedLimit());
1782 settingsPack.set_int(lt::settings_pack::upload_rate_limit, uploadSpeedLimit());
1784 // The most secure, rc4 only so that all streams are encrypted
1785 settingsPack.set_int(lt::settings_pack::allowed_enc_level, lt::settings_pack::pe_rc4);
1786 settingsPack.set_bool(lt::settings_pack::prefer_rc4, true);
1787 switch (encryption())
1789 case 0: // Enabled
1790 settingsPack.set_int(lt::settings_pack::out_enc_policy, lt::settings_pack::pe_enabled);
1791 settingsPack.set_int(lt::settings_pack::in_enc_policy, lt::settings_pack::pe_enabled);
1792 break;
1793 case 1: // Forced
1794 settingsPack.set_int(lt::settings_pack::out_enc_policy, lt::settings_pack::pe_forced);
1795 settingsPack.set_int(lt::settings_pack::in_enc_policy, lt::settings_pack::pe_forced);
1796 break;
1797 default: // Disabled
1798 settingsPack.set_int(lt::settings_pack::out_enc_policy, lt::settings_pack::pe_disabled);
1799 settingsPack.set_int(lt::settings_pack::in_enc_policy, lt::settings_pack::pe_disabled);
1802 settingsPack.set_int(lt::settings_pack::active_checking, maxActiveCheckingTorrents());
1804 // I2P
1805 #if defined(QBT_USES_LIBTORRENT2) && TORRENT_USE_I2P
1806 if (isI2PEnabled())
1808 settingsPack.set_str(lt::settings_pack::i2p_hostname, I2PAddress().toStdString());
1809 settingsPack.set_int(lt::settings_pack::i2p_port, I2PPort());
1810 settingsPack.set_bool(lt::settings_pack::allow_i2p_mixed, I2PMixedMode());
1812 else
1814 settingsPack.set_str(lt::settings_pack::i2p_hostname, "");
1815 settingsPack.set_int(lt::settings_pack::i2p_port, 0);
1816 settingsPack.set_bool(lt::settings_pack::allow_i2p_mixed, false);
1819 // I2P session options
1820 settingsPack.set_int(lt::settings_pack::i2p_inbound_quantity, I2PInboundQuantity());
1821 settingsPack.set_int(lt::settings_pack::i2p_outbound_quantity, I2POutboundQuantity());
1822 settingsPack.set_int(lt::settings_pack::i2p_inbound_length, I2PInboundLength());
1823 settingsPack.set_int(lt::settings_pack::i2p_outbound_length, I2POutboundLength());
1824 #endif
1826 // proxy
1827 settingsPack.set_int(lt::settings_pack::proxy_type, lt::settings_pack::none);
1828 const auto *proxyManager = Net::ProxyConfigurationManager::instance();
1829 const Net::ProxyConfiguration proxyConfig = proxyManager->proxyConfiguration();
1830 if ((proxyConfig.type != Net::ProxyType::None) && Preferences::instance()->useProxyForBT())
1832 switch (proxyConfig.type)
1834 case Net::ProxyType::SOCKS4:
1835 settingsPack.set_int(lt::settings_pack::proxy_type, lt::settings_pack::socks4);
1836 break;
1838 case Net::ProxyType::HTTP:
1839 if (proxyConfig.authEnabled)
1840 settingsPack.set_int(lt::settings_pack::proxy_type, lt::settings_pack::http_pw);
1841 else
1842 settingsPack.set_int(lt::settings_pack::proxy_type, lt::settings_pack::http);
1843 break;
1845 case Net::ProxyType::SOCKS5:
1846 if (proxyConfig.authEnabled)
1847 settingsPack.set_int(lt::settings_pack::proxy_type, lt::settings_pack::socks5_pw);
1848 else
1849 settingsPack.set_int(lt::settings_pack::proxy_type, lt::settings_pack::socks5);
1850 break;
1852 default:
1853 break;
1856 settingsPack.set_str(lt::settings_pack::proxy_hostname, proxyConfig.ip.toStdString());
1857 settingsPack.set_int(lt::settings_pack::proxy_port, proxyConfig.port);
1859 if (proxyConfig.authEnabled)
1861 settingsPack.set_str(lt::settings_pack::proxy_username, proxyConfig.username.toStdString());
1862 settingsPack.set_str(lt::settings_pack::proxy_password, proxyConfig.password.toStdString());
1865 settingsPack.set_bool(lt::settings_pack::proxy_peer_connections, isProxyPeerConnectionsEnabled());
1866 settingsPack.set_bool(lt::settings_pack::proxy_hostnames, proxyConfig.hostnameLookupEnabled);
1869 settingsPack.set_bool(lt::settings_pack::announce_to_all_trackers, announceToAllTrackers());
1870 settingsPack.set_bool(lt::settings_pack::announce_to_all_tiers, announceToAllTiers());
1872 settingsPack.set_int(lt::settings_pack::peer_turnover, peerTurnover());
1873 settingsPack.set_int(lt::settings_pack::peer_turnover_cutoff, peerTurnoverCutoff());
1874 settingsPack.set_int(lt::settings_pack::peer_turnover_interval, peerTurnoverInterval());
1876 settingsPack.set_int(lt::settings_pack::max_out_request_queue, requestQueueSize());
1878 #ifdef QBT_USES_LIBTORRENT2
1879 settingsPack.set_int(lt::settings_pack::metadata_token_limit, Preferences::instance()->getBdecodeTokenLimit());
1880 #endif
1882 settingsPack.set_int(lt::settings_pack::aio_threads, asyncIOThreads());
1883 #ifdef QBT_USES_LIBTORRENT2
1884 settingsPack.set_int(lt::settings_pack::hashing_threads, hashingThreads());
1885 #endif
1886 settingsPack.set_int(lt::settings_pack::file_pool_size, filePoolSize());
1888 const int checkingMemUsageSize = checkingMemUsage() * 64;
1889 settingsPack.set_int(lt::settings_pack::checking_mem_usage, checkingMemUsageSize);
1891 #ifndef QBT_USES_LIBTORRENT2
1892 const int cacheSize = (diskCacheSize() > -1) ? (diskCacheSize() * 64) : -1;
1893 settingsPack.set_int(lt::settings_pack::cache_size, cacheSize);
1894 settingsPack.set_int(lt::settings_pack::cache_expiry, diskCacheTTL());
1895 #endif
1897 settingsPack.set_int(lt::settings_pack::max_queued_disk_bytes, diskQueueSize());
1899 switch (diskIOReadMode())
1901 case DiskIOReadMode::DisableOSCache:
1902 settingsPack.set_int(lt::settings_pack::disk_io_read_mode, lt::settings_pack::disable_os_cache);
1903 break;
1904 case DiskIOReadMode::EnableOSCache:
1905 default:
1906 settingsPack.set_int(lt::settings_pack::disk_io_read_mode, lt::settings_pack::enable_os_cache);
1907 break;
1910 switch (diskIOWriteMode())
1912 case DiskIOWriteMode::DisableOSCache:
1913 settingsPack.set_int(lt::settings_pack::disk_io_write_mode, lt::settings_pack::disable_os_cache);
1914 break;
1915 case DiskIOWriteMode::EnableOSCache:
1916 default:
1917 settingsPack.set_int(lt::settings_pack::disk_io_write_mode, lt::settings_pack::enable_os_cache);
1918 break;
1919 #ifdef QBT_USES_LIBTORRENT2
1920 case DiskIOWriteMode::WriteThrough:
1921 settingsPack.set_int(lt::settings_pack::disk_io_write_mode, lt::settings_pack::write_through);
1922 break;
1923 #endif
1926 #ifndef QBT_USES_LIBTORRENT2
1927 settingsPack.set_bool(lt::settings_pack::coalesce_reads, isCoalesceReadWriteEnabled());
1928 settingsPack.set_bool(lt::settings_pack::coalesce_writes, isCoalesceReadWriteEnabled());
1929 #endif
1931 settingsPack.set_bool(lt::settings_pack::piece_extent_affinity, usePieceExtentAffinity());
1933 settingsPack.set_int(lt::settings_pack::suggest_mode, isSuggestModeEnabled()
1934 ? lt::settings_pack::suggest_read_cache : lt::settings_pack::no_piece_suggestions);
1936 settingsPack.set_int(lt::settings_pack::send_buffer_watermark, sendBufferWatermark() * 1024);
1937 settingsPack.set_int(lt::settings_pack::send_buffer_low_watermark, sendBufferLowWatermark() * 1024);
1938 settingsPack.set_int(lt::settings_pack::send_buffer_watermark_factor, sendBufferWatermarkFactor());
1940 settingsPack.set_bool(lt::settings_pack::anonymous_mode, isAnonymousModeEnabled());
1942 // Queueing System
1943 if (isQueueingSystemEnabled())
1945 settingsPack.set_int(lt::settings_pack::active_downloads, maxActiveDownloads());
1946 settingsPack.set_int(lt::settings_pack::active_limit, maxActiveTorrents());
1947 settingsPack.set_int(lt::settings_pack::active_seeds, maxActiveUploads());
1948 settingsPack.set_bool(lt::settings_pack::dont_count_slow_torrents, ignoreSlowTorrentsForQueueing());
1949 settingsPack.set_int(lt::settings_pack::inactive_down_rate, downloadRateForSlowTorrents() * 1024); // KiB to Bytes
1950 settingsPack.set_int(lt::settings_pack::inactive_up_rate, uploadRateForSlowTorrents() * 1024); // KiB to Bytes
1951 settingsPack.set_int(lt::settings_pack::auto_manage_startup, slowTorrentsInactivityTimer());
1953 else
1955 settingsPack.set_int(lt::settings_pack::active_downloads, -1);
1956 settingsPack.set_int(lt::settings_pack::active_seeds, -1);
1957 settingsPack.set_int(lt::settings_pack::active_limit, -1);
1959 settingsPack.set_int(lt::settings_pack::active_tracker_limit, -1);
1960 settingsPack.set_int(lt::settings_pack::active_dht_limit, -1);
1961 settingsPack.set_int(lt::settings_pack::active_lsd_limit, -1);
1962 settingsPack.set_int(lt::settings_pack::alert_queue_size, std::numeric_limits<int>::max() / 2);
1964 // Outgoing ports
1965 settingsPack.set_int(lt::settings_pack::outgoing_port, outgoingPortsMin());
1966 settingsPack.set_int(lt::settings_pack::num_outgoing_ports, (outgoingPortsMax() - outgoingPortsMin()));
1967 // UPnP lease duration
1968 settingsPack.set_int(lt::settings_pack::upnp_lease_duration, UPnPLeaseDuration());
1969 // Type of service
1970 settingsPack.set_int(lt::settings_pack::peer_tos, peerToS());
1971 // Include overhead in transfer limits
1972 settingsPack.set_bool(lt::settings_pack::rate_limit_ip_overhead, includeOverheadInLimits());
1973 // IP address to announce to trackers
1974 settingsPack.set_str(lt::settings_pack::announce_ip, announceIP().toStdString());
1975 // Max concurrent HTTP announces
1976 settingsPack.set_int(lt::settings_pack::max_concurrent_http_announces, maxConcurrentHTTPAnnounces());
1977 // Stop tracker timeout
1978 settingsPack.set_int(lt::settings_pack::stop_tracker_timeout, stopTrackerTimeout());
1979 // * Max connections limit
1980 settingsPack.set_int(lt::settings_pack::connections_limit, maxConnections());
1981 // * Global max upload slots
1982 settingsPack.set_int(lt::settings_pack::unchoke_slots_limit, maxUploads());
1983 // uTP
1984 switch (btProtocol())
1986 case BTProtocol::Both:
1987 default:
1988 settingsPack.set_bool(lt::settings_pack::enable_incoming_tcp, true);
1989 settingsPack.set_bool(lt::settings_pack::enable_outgoing_tcp, true);
1990 settingsPack.set_bool(lt::settings_pack::enable_incoming_utp, true);
1991 settingsPack.set_bool(lt::settings_pack::enable_outgoing_utp, true);
1992 break;
1994 case BTProtocol::TCP:
1995 settingsPack.set_bool(lt::settings_pack::enable_incoming_tcp, true);
1996 settingsPack.set_bool(lt::settings_pack::enable_outgoing_tcp, true);
1997 settingsPack.set_bool(lt::settings_pack::enable_incoming_utp, false);
1998 settingsPack.set_bool(lt::settings_pack::enable_outgoing_utp, false);
1999 break;
2001 case BTProtocol::UTP:
2002 settingsPack.set_bool(lt::settings_pack::enable_incoming_tcp, false);
2003 settingsPack.set_bool(lt::settings_pack::enable_outgoing_tcp, false);
2004 settingsPack.set_bool(lt::settings_pack::enable_incoming_utp, true);
2005 settingsPack.set_bool(lt::settings_pack::enable_outgoing_utp, true);
2006 break;
2009 switch (utpMixedMode())
2011 case MixedModeAlgorithm::TCP:
2012 default:
2013 settingsPack.set_int(lt::settings_pack::mixed_mode_algorithm, lt::settings_pack::prefer_tcp);
2014 break;
2015 case MixedModeAlgorithm::Proportional:
2016 settingsPack.set_int(lt::settings_pack::mixed_mode_algorithm, lt::settings_pack::peer_proportional);
2017 break;
2020 settingsPack.set_bool(lt::settings_pack::allow_idna, isIDNSupportEnabled());
2022 settingsPack.set_bool(lt::settings_pack::allow_multiple_connections_per_ip, multiConnectionsPerIpEnabled());
2024 settingsPack.set_bool(lt::settings_pack::validate_https_trackers, validateHTTPSTrackerCertificate());
2026 settingsPack.set_bool(lt::settings_pack::ssrf_mitigation, isSSRFMitigationEnabled());
2028 settingsPack.set_bool(lt::settings_pack::no_connect_privileged_ports, blockPeersOnPrivilegedPorts());
2030 settingsPack.set_bool(lt::settings_pack::apply_ip_filter_to_trackers, isTrackerFilteringEnabled());
2032 settingsPack.set_str(lt::settings_pack::dht_bootstrap_nodes, getDHTBootstrapNodes().toStdString());
2033 settingsPack.set_bool(lt::settings_pack::enable_dht, isDHTEnabled());
2034 settingsPack.set_bool(lt::settings_pack::enable_lsd, isLSDEnabled());
2036 switch (chokingAlgorithm())
2038 case ChokingAlgorithm::FixedSlots:
2039 default:
2040 settingsPack.set_int(lt::settings_pack::choking_algorithm, lt::settings_pack::fixed_slots_choker);
2041 break;
2042 case ChokingAlgorithm::RateBased:
2043 settingsPack.set_int(lt::settings_pack::choking_algorithm, lt::settings_pack::rate_based_choker);
2044 break;
2047 switch (seedChokingAlgorithm())
2049 case SeedChokingAlgorithm::RoundRobin:
2050 settingsPack.set_int(lt::settings_pack::seed_choking_algorithm, lt::settings_pack::round_robin);
2051 break;
2052 case SeedChokingAlgorithm::FastestUpload:
2053 default:
2054 settingsPack.set_int(lt::settings_pack::seed_choking_algorithm, lt::settings_pack::fastest_upload);
2055 break;
2056 case SeedChokingAlgorithm::AntiLeech:
2057 settingsPack.set_int(lt::settings_pack::seed_choking_algorithm, lt::settings_pack::anti_leech);
2058 break;
2061 return settingsPack;
2064 void SessionImpl::applyNetworkInterfacesSettings(lt::settings_pack &settingsPack) const
2066 if (m_listenInterfaceConfigured)
2067 return;
2069 if (port() > 0) // user has specified port number
2070 settingsPack.set_int(lt::settings_pack::max_retry_port_bind, 0);
2072 QStringList endpoints;
2073 QStringList outgoingInterfaces;
2074 QStringList portStrings = {u':' + QString::number(port())};
2075 if (isSSLEnabled())
2076 portStrings.append(u':' + QString::number(sslPort()) + u's');
2078 for (const QString &ip : asConst(getListeningIPs()))
2080 const QHostAddress addr {ip};
2081 if (!addr.isNull())
2083 const bool isIPv6 = (addr.protocol() == QAbstractSocket::IPv6Protocol);
2084 const QString ip = isIPv6
2085 ? Utils::Net::canonicalIPv6Addr(addr).toString()
2086 : addr.toString();
2088 for (const QString &portString : asConst(portStrings))
2089 endpoints << ((isIPv6 ? (u'[' + ip + u']') : ip) + portString);
2091 if ((ip != u"0.0.0.0") && (ip != u"::"))
2092 outgoingInterfaces << ip;
2094 else
2096 // ip holds an interface name
2097 #ifdef Q_OS_WIN
2098 // On Vista+ versions and after Qt 5.5 QNetworkInterface::name() returns
2099 // the interface's LUID and not the GUID.
2100 // Libtorrent expects GUIDs for the 'listen_interfaces' setting.
2101 const QString guid = convertIfaceNameToGuid(ip);
2102 if (!guid.isEmpty())
2104 for (const QString &portString : asConst(portStrings))
2105 endpoints << (guid + portString);
2106 outgoingInterfaces << guid;
2108 else
2110 LogMsg(tr("Could not find GUID of network interface. Interface: \"%1\"").arg(ip), Log::WARNING);
2111 // Since we can't get the GUID, we'll pass the interface name instead.
2112 // Otherwise an empty string will be passed to outgoing_interface which will cause IP leak.
2113 for (const QString &portString : asConst(portStrings))
2114 endpoints << (ip + portString);
2115 outgoingInterfaces << ip;
2117 #else
2118 for (const QString &portString : asConst(portStrings))
2119 endpoints << (ip + portString);
2120 outgoingInterfaces << ip;
2121 #endif
2125 const QString finalEndpoints = endpoints.join(u',');
2126 settingsPack.set_str(lt::settings_pack::listen_interfaces, finalEndpoints.toStdString());
2127 LogMsg(tr("Trying to listen on the following list of IP addresses: \"%1\"").arg(finalEndpoints));
2129 settingsPack.set_str(lt::settings_pack::outgoing_interfaces, outgoingInterfaces.join(u',').toStdString());
2130 m_listenInterfaceConfigured = true;
2133 void SessionImpl::configurePeerClasses()
2135 lt::ip_filter f;
2136 // lt::make_address("255.255.255.255") crashes on some people's systems
2137 // so instead we use address_v4::broadcast()
2138 // Proactively do the same for 0.0.0.0 and address_v4::any()
2139 f.add_rule(lt::address_v4::any()
2140 , lt::address_v4::broadcast()
2141 , 1 << LT::toUnderlyingType(lt::session::global_peer_class_id));
2143 // IPv6 may not be available on OS and the parsing
2144 // would result in an exception -> abnormal program termination
2145 // Affects Windows XP
2148 f.add_rule(lt::address_v6::any()
2149 , lt::make_address("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff")
2150 , 1 << LT::toUnderlyingType(lt::session::global_peer_class_id));
2152 catch (const std::exception &) {}
2154 if (ignoreLimitsOnLAN())
2156 // local networks
2157 f.add_rule(lt::make_address("10.0.0.0")
2158 , lt::make_address("10.255.255.255")
2159 , 1 << LT::toUnderlyingType(lt::session::local_peer_class_id));
2160 f.add_rule(lt::make_address("172.16.0.0")
2161 , lt::make_address("172.31.255.255")
2162 , 1 << LT::toUnderlyingType(lt::session::local_peer_class_id));
2163 f.add_rule(lt::make_address("192.168.0.0")
2164 , lt::make_address("192.168.255.255")
2165 , 1 << LT::toUnderlyingType(lt::session::local_peer_class_id));
2166 // link local
2167 f.add_rule(lt::make_address("169.254.0.0")
2168 , lt::make_address("169.254.255.255")
2169 , 1 << LT::toUnderlyingType(lt::session::local_peer_class_id));
2170 // loopback
2171 f.add_rule(lt::make_address("127.0.0.0")
2172 , lt::make_address("127.255.255.255")
2173 , 1 << LT::toUnderlyingType(lt::session::local_peer_class_id));
2175 // IPv6 may not be available on OS and the parsing
2176 // would result in an exception -> abnormal program termination
2177 // Affects Windows XP
2180 // link local
2181 f.add_rule(lt::make_address("fe80::")
2182 , lt::make_address("febf:ffff:ffff:ffff:ffff:ffff:ffff:ffff")
2183 , 1 << LT::toUnderlyingType(lt::session::local_peer_class_id));
2184 // unique local addresses
2185 f.add_rule(lt::make_address("fc00::")
2186 , lt::make_address("fdff:ffff:ffff:ffff:ffff:ffff:ffff:ffff")
2187 , 1 << LT::toUnderlyingType(lt::session::local_peer_class_id));
2188 // loopback
2189 f.add_rule(lt::address_v6::loopback()
2190 , lt::address_v6::loopback()
2191 , 1 << LT::toUnderlyingType(lt::session::local_peer_class_id));
2193 catch (const std::exception &) {}
2195 m_nativeSession->set_peer_class_filter(f);
2197 lt::peer_class_type_filter peerClassTypeFilter;
2198 peerClassTypeFilter.add(lt::peer_class_type_filter::tcp_socket, lt::session::tcp_peer_class_id);
2199 peerClassTypeFilter.add(lt::peer_class_type_filter::ssl_tcp_socket, lt::session::tcp_peer_class_id);
2200 peerClassTypeFilter.add(lt::peer_class_type_filter::i2p_socket, lt::session::tcp_peer_class_id);
2201 if (!isUTPRateLimited())
2203 peerClassTypeFilter.disallow(lt::peer_class_type_filter::utp_socket
2204 , lt::session::global_peer_class_id);
2205 peerClassTypeFilter.disallow(lt::peer_class_type_filter::ssl_utp_socket
2206 , lt::session::global_peer_class_id);
2208 m_nativeSession->set_peer_class_type_filter(peerClassTypeFilter);
2211 void SessionImpl::enableTracker(const bool enable)
2213 const QString profile = u"embeddedTracker"_s;
2214 auto *portForwarder = Net::PortForwarder::instance();
2216 if (enable)
2218 if (!m_tracker)
2219 m_tracker = new Tracker(this);
2221 m_tracker->start();
2223 const auto *pref = Preferences::instance();
2224 if (pref->isTrackerPortForwardingEnabled())
2225 portForwarder->setPorts(profile, {static_cast<quint16>(pref->getTrackerPort())});
2226 else
2227 portForwarder->removePorts(profile);
2229 else
2231 delete m_tracker;
2233 portForwarder->removePorts(profile);
2237 void SessionImpl::enableBandwidthScheduler()
2239 if (!m_bwScheduler)
2241 m_bwScheduler = new BandwidthScheduler(this);
2242 connect(m_bwScheduler.data(), &BandwidthScheduler::bandwidthLimitRequested
2243 , this, &SessionImpl::setAltGlobalSpeedLimitEnabled);
2245 m_bwScheduler->start();
2248 void SessionImpl::populateAdditionalTrackers()
2250 m_additionalTrackerEntries = parseTrackerEntries(additionalTrackers());
2253 void SessionImpl::processTorrentShareLimits(TorrentImpl *torrent)
2255 if (!torrent->isFinished() || torrent->isForced())
2256 return;
2258 const auto effectiveLimit = []<typename T>(const T limit, const T useGlobalLimit, const T globalLimit) -> T
2260 return (limit == useGlobalLimit) ? globalLimit : limit;
2263 const qreal ratioLimit = effectiveLimit(torrent->ratioLimit(), Torrent::USE_GLOBAL_RATIO, globalMaxRatio());
2264 const int seedingTimeLimit = effectiveLimit(torrent->seedingTimeLimit(), Torrent::USE_GLOBAL_SEEDING_TIME, globalMaxSeedingMinutes());
2265 const int inactiveSeedingTimeLimit = effectiveLimit(torrent->inactiveSeedingTimeLimit(), Torrent::USE_GLOBAL_INACTIVE_SEEDING_TIME, globalMaxInactiveSeedingMinutes());
2267 bool reached = false;
2268 QString description;
2270 if (const qreal ratio = torrent->realRatio();
2271 (ratioLimit >= 0) && (ratio <= Torrent::MAX_RATIO) && (ratio >= ratioLimit))
2273 reached = true;
2274 description = tr("Torrent reached the share ratio limit.");
2276 else if (const qlonglong seedingTimeInMinutes = torrent->finishedTime() / 60;
2277 (seedingTimeLimit >= 0) && (seedingTimeInMinutes <= Torrent::MAX_SEEDING_TIME) && (seedingTimeInMinutes >= seedingTimeLimit))
2279 reached = true;
2280 description = tr("Torrent reached the seeding time limit.");
2282 else if (const qlonglong inactiveSeedingTimeInMinutes = torrent->timeSinceActivity() / 60;
2283 (inactiveSeedingTimeLimit >= 0) && (inactiveSeedingTimeInMinutes <= Torrent::MAX_INACTIVE_SEEDING_TIME) && (inactiveSeedingTimeInMinutes >= inactiveSeedingTimeLimit))
2285 reached = true;
2286 description = tr("Torrent reached the inactive seeding time limit.");
2289 if (reached)
2291 const QString torrentName = tr("Torrent: \"%1\".").arg(torrent->name());
2292 const ShareLimitAction shareLimitAction = (torrent->shareLimitAction() == ShareLimitAction::Default) ? m_shareLimitAction : torrent->shareLimitAction();
2294 if (shareLimitAction == ShareLimitAction::Remove)
2296 LogMsg(u"%1 %2 %3"_s.arg(description, tr("Removing torrent."), torrentName));
2297 removeTorrent(torrent->id(), TorrentRemoveOption::KeepContent);
2299 else if (shareLimitAction == ShareLimitAction::RemoveWithContent)
2301 LogMsg(u"%1 %2 %3"_s.arg(description, tr("Removing torrent and deleting its content."), torrentName));
2302 removeTorrent(torrent->id(), TorrentRemoveOption::RemoveContent);
2304 else if ((shareLimitAction == ShareLimitAction::Stop) && !torrent->isStopped())
2306 torrent->stop();
2307 LogMsg(u"%1 %2 %3"_s.arg(description, tr("Torrent stopped."), torrentName));
2309 else if ((shareLimitAction == ShareLimitAction::EnableSuperSeeding) && !torrent->isStopped() && !torrent->superSeeding())
2311 torrent->setSuperSeeding(true);
2312 LogMsg(u"%1 %2 %3"_s.arg(description, tr("Super seeding enabled."), torrentName));
2317 void SessionImpl::fileSearchFinished(const TorrentID &id, const Path &savePath, const PathList &fileNames)
2319 TorrentImpl *torrent = m_torrents.value(id);
2320 if (torrent)
2322 torrent->fileSearchFinished(savePath, fileNames);
2323 return;
2326 const auto loadingTorrentsIter = m_loadingTorrents.find(id);
2327 if (loadingTorrentsIter != m_loadingTorrents.end())
2329 LoadTorrentParams &params = loadingTorrentsIter.value();
2330 lt::add_torrent_params &p = params.ltAddTorrentParams;
2332 p.save_path = savePath.toString().toStdString();
2333 const TorrentInfo torrentInfo {*p.ti};
2334 const auto nativeIndexes = torrentInfo.nativeIndexes();
2335 for (int i = 0; i < fileNames.size(); ++i)
2336 p.renamed_files[nativeIndexes[i]] = fileNames[i].toString().toStdString();
2338 m_nativeSession->async_add_torrent(p);
2342 void SessionImpl::torrentContentRemovingFinished(const QString &torrentName, const QString &errorMessage)
2344 if (errorMessage.isEmpty())
2346 LogMsg(tr("Torrent content removed. Torrent: \"%1\"").arg(torrentName));
2348 else
2350 LogMsg(tr("Failed to remove torrent content. Torrent: \"%1\". Error: \"%2\"")
2351 .arg(torrentName, errorMessage), Log::WARNING);
2355 Torrent *SessionImpl::getTorrent(const TorrentID &id) const
2357 return m_torrents.value(id);
2360 Torrent *SessionImpl::findTorrent(const InfoHash &infoHash) const
2362 const auto id = TorrentID::fromInfoHash(infoHash);
2363 if (Torrent *torrent = m_torrents.value(id); torrent)
2364 return torrent;
2366 if (!infoHash.isHybrid())
2367 return m_hybridTorrentsByAltID.value(id);
2369 // alternative ID can be useful to find existing torrent
2370 // in case if hybrid torrent was added by v1 info hash
2371 const auto altID = TorrentID::fromSHA1Hash(infoHash.v1());
2372 return m_torrents.value(altID);
2375 void SessionImpl::banIP(const QString &ip)
2377 if (m_bannedIPs.get().contains(ip))
2378 return;
2380 lt::error_code ec;
2381 const lt::address addr = lt::make_address(ip.toLatin1().constData(), ec);
2382 Q_ASSERT(!ec);
2383 if (ec)
2384 return;
2386 invokeAsync([session = m_nativeSession, addr]
2388 lt::ip_filter filter = session->get_ip_filter();
2389 filter.add_rule(addr, addr, lt::ip_filter::blocked);
2390 session->set_ip_filter(std::move(filter));
2393 QStringList bannedIPs = m_bannedIPs;
2394 bannedIPs.append(ip);
2395 bannedIPs.sort();
2396 m_bannedIPs = bannedIPs;
2399 // Delete a torrent from the session, given its hash
2400 // and from the disk, if the corresponding deleteOption is chosen
2401 bool SessionImpl::removeTorrent(const TorrentID &id, const TorrentRemoveOption deleteOption)
2403 TorrentImpl *const torrent = m_torrents.take(id);
2404 if (!torrent)
2405 return false;
2407 const TorrentID torrentID = torrent->id();
2408 const QString torrentName = torrent->name();
2410 qDebug("Deleting torrent with ID: %s", qUtf8Printable(torrentID.toString()));
2411 emit torrentAboutToBeRemoved(torrent);
2413 if (const InfoHash infoHash = torrent->infoHash(); infoHash.isHybrid())
2414 m_hybridTorrentsByAltID.remove(TorrentID::fromSHA1Hash(infoHash.v1()));
2416 // Remove it from session
2417 if (deleteOption == TorrentRemoveOption::KeepContent)
2419 m_removingTorrents[torrentID] = {torrentName, torrent->actualStorageLocation(), {}, deleteOption};
2421 const lt::torrent_handle nativeHandle {torrent->nativeHandle()};
2422 const auto iter = std::find_if(m_moveStorageQueue.begin(), m_moveStorageQueue.end()
2423 , [&nativeHandle](const MoveStorageJob &job)
2425 return job.torrentHandle == nativeHandle;
2427 if (iter != m_moveStorageQueue.end())
2429 // We shouldn't actually remove torrent until existing "move storage jobs" are done
2430 torrentQueuePositionBottom(nativeHandle);
2431 nativeHandle.unset_flags(lt::torrent_flags::auto_managed);
2432 nativeHandle.pause();
2434 else
2436 m_nativeSession->remove_torrent(nativeHandle, lt::session::delete_partfile);
2439 else
2441 m_removingTorrents[torrentID] = {torrentName, torrent->actualStorageLocation(), torrent->actualFilePaths(), deleteOption};
2443 if (m_moveStorageQueue.size() > 1)
2445 // Delete "move storage job" for the deleted torrent
2446 // (note: we shouldn't delete active job)
2447 const auto iter = std::find_if((m_moveStorageQueue.begin() + 1), m_moveStorageQueue.end()
2448 , [torrent](const MoveStorageJob &job)
2450 return job.torrentHandle == torrent->nativeHandle();
2452 if (iter != m_moveStorageQueue.end())
2453 m_moveStorageQueue.erase(iter);
2456 m_nativeSession->remove_torrent(torrent->nativeHandle(), lt::session::delete_partfile);
2459 // Remove it from torrent resume directory
2460 m_resumeDataStorage->remove(torrentID);
2462 LogMsg(tr("Torrent removed. Torrent: \"%1\"").arg(torrentName));
2463 delete torrent;
2464 return true;
2467 bool SessionImpl::cancelDownloadMetadata(const TorrentID &id)
2469 const auto downloadedMetadataIter = m_downloadedMetadata.find(id);
2470 if (downloadedMetadataIter == m_downloadedMetadata.end())
2471 return false;
2473 const lt::torrent_handle nativeHandle = downloadedMetadataIter.value();
2474 m_downloadedMetadata.erase(downloadedMetadataIter);
2476 if (!nativeHandle.is_valid())
2477 return true;
2479 #ifdef QBT_USES_LIBTORRENT2
2480 const InfoHash infoHash {nativeHandle.info_hashes()};
2481 if (infoHash.isHybrid())
2483 // if magnet link was hybrid initially then it is indexed also by v1 info hash
2484 // so we need to remove both entries
2485 const auto altID = TorrentID::fromSHA1Hash(infoHash.v1());
2486 m_downloadedMetadata.remove(altID);
2488 #endif
2490 m_nativeSession->remove_torrent(nativeHandle);
2491 return true;
2494 void SessionImpl::increaseTorrentsQueuePos(const QList<TorrentID> &ids)
2496 using ElementType = std::pair<int, const TorrentImpl *>;
2497 std::priority_queue<ElementType
2498 , std::vector<ElementType>
2499 , std::greater<ElementType>> torrentQueue;
2501 // Sort torrents by queue position
2502 for (const TorrentID &id : ids)
2504 const TorrentImpl *torrent = m_torrents.value(id);
2505 if (!torrent) continue;
2506 if (const int position = torrent->queuePosition(); position >= 0)
2507 torrentQueue.emplace(position, torrent);
2510 // Increase torrents queue position (starting with the one in the highest queue position)
2511 while (!torrentQueue.empty())
2513 const TorrentImpl *torrent = torrentQueue.top().second;
2514 torrentQueuePositionUp(torrent->nativeHandle());
2515 torrentQueue.pop();
2518 m_torrentsQueueChanged = true;
2521 void SessionImpl::decreaseTorrentsQueuePos(const QList<TorrentID> &ids)
2523 using ElementType = std::pair<int, const TorrentImpl *>;
2524 std::priority_queue<ElementType> torrentQueue;
2526 // Sort torrents by queue position
2527 for (const TorrentID &id : ids)
2529 const TorrentImpl *torrent = m_torrents.value(id);
2530 if (!torrent) continue;
2531 if (const int position = torrent->queuePosition(); position >= 0)
2532 torrentQueue.emplace(position, torrent);
2535 // Decrease torrents queue position (starting with the one in the lowest queue position)
2536 while (!torrentQueue.empty())
2538 const TorrentImpl *torrent = torrentQueue.top().second;
2539 torrentQueuePositionDown(torrent->nativeHandle());
2540 torrentQueue.pop();
2543 for (const lt::torrent_handle &torrentHandle : asConst(m_downloadedMetadata))
2544 torrentQueuePositionBottom(torrentHandle);
2546 m_torrentsQueueChanged = true;
2549 void SessionImpl::topTorrentsQueuePos(const QList<TorrentID> &ids)
2551 using ElementType = std::pair<int, const TorrentImpl *>;
2552 std::priority_queue<ElementType> torrentQueue;
2554 // Sort torrents by queue position
2555 for (const TorrentID &id : ids)
2557 const TorrentImpl *torrent = m_torrents.value(id);
2558 if (!torrent) continue;
2559 if (const int position = torrent->queuePosition(); position >= 0)
2560 torrentQueue.emplace(position, torrent);
2563 // Top torrents queue position (starting with the one in the lowest queue position)
2564 while (!torrentQueue.empty())
2566 const TorrentImpl *torrent = torrentQueue.top().second;
2567 torrentQueuePositionTop(torrent->nativeHandle());
2568 torrentQueue.pop();
2571 m_torrentsQueueChanged = true;
2574 void SessionImpl::bottomTorrentsQueuePos(const QList<TorrentID> &ids)
2576 using ElementType = std::pair<int, const TorrentImpl *>;
2577 std::priority_queue<ElementType
2578 , std::vector<ElementType>
2579 , std::greater<ElementType>> torrentQueue;
2581 // Sort torrents by queue position
2582 for (const TorrentID &id : ids)
2584 const TorrentImpl *torrent = m_torrents.value(id);
2585 if (!torrent) continue;
2586 if (const int position = torrent->queuePosition(); position >= 0)
2587 torrentQueue.emplace(position, torrent);
2590 // Bottom torrents queue position (starting with the one in the highest queue position)
2591 while (!torrentQueue.empty())
2593 const TorrentImpl *torrent = torrentQueue.top().second;
2594 torrentQueuePositionBottom(torrent->nativeHandle());
2595 torrentQueue.pop();
2598 for (const lt::torrent_handle &torrentHandle : asConst(m_downloadedMetadata))
2599 torrentQueuePositionBottom(torrentHandle);
2601 m_torrentsQueueChanged = true;
2604 void SessionImpl::handleTorrentResumeDataRequested(const TorrentImpl *torrent)
2606 qDebug("Saving resume data is requested for torrent '%s'...", qUtf8Printable(torrent->name()));
2607 ++m_numResumeData;
2610 QList<Torrent *> SessionImpl::torrents() const
2612 QList<Torrent *> result;
2613 result.reserve(m_torrents.size());
2614 for (TorrentImpl *torrent : asConst(m_torrents))
2615 result << torrent;
2617 return result;
2620 qsizetype SessionImpl::torrentsCount() const
2622 return m_torrents.size();
2625 bool SessionImpl::addTorrent(const TorrentDescriptor &torrentDescr, const AddTorrentParams &params)
2627 if (!isRestored())
2628 return false;
2630 return addTorrent_impl(torrentDescr, params);
2633 LoadTorrentParams SessionImpl::initLoadTorrentParams(const AddTorrentParams &addTorrentParams)
2635 LoadTorrentParams loadTorrentParams;
2637 loadTorrentParams.name = addTorrentParams.name;
2638 loadTorrentParams.firstLastPiecePriority = addTorrentParams.firstLastPiecePriority;
2639 loadTorrentParams.hasFinishedStatus = addTorrentParams.skipChecking; // do not react on 'torrent_finished_alert' when skipping
2640 loadTorrentParams.contentLayout = addTorrentParams.contentLayout.value_or(torrentContentLayout());
2641 loadTorrentParams.operatingMode = (addTorrentParams.addForced ? TorrentOperatingMode::Forced : TorrentOperatingMode::AutoManaged);
2642 loadTorrentParams.stopped = addTorrentParams.addStopped.value_or(isAddTorrentStopped());
2643 loadTorrentParams.stopCondition = addTorrentParams.stopCondition.value_or(torrentStopCondition());
2644 loadTorrentParams.addToQueueTop = addTorrentParams.addToQueueTop.value_or(isAddTorrentToQueueTop());
2645 loadTorrentParams.ratioLimit = addTorrentParams.ratioLimit;
2646 loadTorrentParams.seedingTimeLimit = addTorrentParams.seedingTimeLimit;
2647 loadTorrentParams.inactiveSeedingTimeLimit = addTorrentParams.inactiveSeedingTimeLimit;
2648 loadTorrentParams.shareLimitAction = addTorrentParams.shareLimitAction;
2649 loadTorrentParams.sslParameters = addTorrentParams.sslParameters;
2651 const QString category = addTorrentParams.category;
2652 if (!category.isEmpty() && !m_categories.contains(category) && !addCategory(category))
2653 loadTorrentParams.category = u""_s;
2654 else
2655 loadTorrentParams.category = category;
2657 const auto defaultSavePath = suggestedSavePath(loadTorrentParams.category, addTorrentParams.useAutoTMM);
2658 const auto defaultDownloadPath = suggestedDownloadPath(loadTorrentParams.category, addTorrentParams.useAutoTMM);
2660 loadTorrentParams.useAutoTMM = addTorrentParams.useAutoTMM.value_or(
2661 addTorrentParams.savePath.isEmpty() && addTorrentParams.downloadPath.isEmpty() && !isAutoTMMDisabledByDefault());
2663 if (!loadTorrentParams.useAutoTMM)
2665 if (addTorrentParams.savePath.isAbsolute())
2666 loadTorrentParams.savePath = addTorrentParams.savePath;
2667 else
2668 loadTorrentParams.savePath = defaultSavePath / addTorrentParams.savePath;
2670 // if useDownloadPath isn't specified but downloadPath is explicitly set we prefer to use it
2671 const bool useDownloadPath = addTorrentParams.useDownloadPath.value_or(!addTorrentParams.downloadPath.isEmpty() || isDownloadPathEnabled());
2672 if (useDownloadPath)
2674 // Overridden "Download path" settings
2676 if (addTorrentParams.downloadPath.isAbsolute())
2678 loadTorrentParams.downloadPath = addTorrentParams.downloadPath;
2680 else
2682 const Path basePath = (!defaultDownloadPath.isEmpty() ? defaultDownloadPath : downloadPath());
2683 loadTorrentParams.downloadPath = basePath / addTorrentParams.downloadPath;
2688 for (const Tag &tag : addTorrentParams.tags)
2690 if (hasTag(tag) || addTag(tag))
2691 loadTorrentParams.tags.insert(tag);
2694 return loadTorrentParams;
2697 // Add a torrent to the BitTorrent session
2698 bool SessionImpl::addTorrent_impl(const TorrentDescriptor &source, const AddTorrentParams &addTorrentParams)
2700 Q_ASSERT(isRestored());
2702 const bool hasMetadata = (source.info().has_value());
2703 const auto infoHash = source.infoHash();
2704 const auto id = TorrentID::fromInfoHash(infoHash);
2706 // alternative ID can be useful to find existing torrent in case if hybrid torrent was added by v1 info hash
2707 const auto altID = (infoHash.isHybrid() ? TorrentID::fromSHA1Hash(infoHash.v1()) : TorrentID());
2709 // We should not add the torrent if it is already
2710 // processed or is pending to add to session
2711 if (m_loadingTorrents.contains(id) || (infoHash.isHybrid() && m_loadingTorrents.contains(altID)))
2712 return false;
2714 if (Torrent *torrent = findTorrent(infoHash))
2716 // a duplicate torrent is being added
2718 if (hasMetadata)
2720 // Trying to set metadata to existing torrent in case if it has none
2721 torrent->setMetadata(*source.info());
2724 if (!isMergeTrackersEnabled())
2726 LogMsg(tr("Detected an attempt to add a duplicate torrent. Existing torrent: %1. Result: %2")
2727 .arg(torrent->name(), tr("Merging of trackers is disabled")));
2728 return false;
2731 const bool isPrivate = torrent->isPrivate() || (hasMetadata && source.info()->isPrivate());
2732 if (isPrivate)
2734 LogMsg(tr("Detected an attempt to add a duplicate torrent. Existing torrent: %1. Result: %2")
2735 .arg(torrent->name(), tr("Trackers cannot be merged because it is a private torrent")));
2736 return false;
2739 // merge trackers and web seeds
2740 torrent->addTrackers(source.trackers());
2741 torrent->addUrlSeeds(source.urlSeeds());
2743 LogMsg(tr("Detected an attempt to add a duplicate torrent. Existing torrent: %1. Result: %2")
2744 .arg(torrent->name(), tr("Trackers are merged from new source")));
2745 return false;
2748 // It looks illogical that we don't just use an existing handle,
2749 // but as previous experience has shown, it actually creates unnecessary
2750 // problems and unwanted behavior due to the fact that it was originally
2751 // added with parameters other than those provided by the user.
2752 cancelDownloadMetadata(id);
2753 if (infoHash.isHybrid())
2754 cancelDownloadMetadata(altID);
2756 LoadTorrentParams loadTorrentParams = initLoadTorrentParams(addTorrentParams);
2757 lt::add_torrent_params &p = loadTorrentParams.ltAddTorrentParams;
2758 p = source.ltAddTorrentParams();
2760 bool isFindingIncompleteFiles = false;
2762 const bool useAutoTMM = loadTorrentParams.useAutoTMM;
2763 const Path actualSavePath = useAutoTMM ? categorySavePath(loadTorrentParams.category) : loadTorrentParams.savePath;
2765 if (hasMetadata)
2767 // Torrent that is being added with metadata is considered to be added as stopped
2768 // if "metadata received" stop condition is set for it.
2769 if (loadTorrentParams.stopCondition == Torrent::StopCondition::MetadataReceived)
2771 loadTorrentParams.stopped = true;
2772 loadTorrentParams.stopCondition = Torrent::StopCondition::None;
2775 const TorrentInfo &torrentInfo = *source.info();
2777 Q_ASSERT(addTorrentParams.filePaths.isEmpty() || (addTorrentParams.filePaths.size() == torrentInfo.filesCount()));
2779 PathList filePaths = addTorrentParams.filePaths;
2780 if (filePaths.isEmpty())
2782 filePaths = torrentInfo.filePaths();
2783 if (loadTorrentParams.contentLayout != TorrentContentLayout::Original)
2785 const Path originalRootFolder = Path::findRootFolder(filePaths);
2786 const auto originalContentLayout = (originalRootFolder.isEmpty()
2787 ? TorrentContentLayout::NoSubfolder : TorrentContentLayout::Subfolder);
2788 if (loadTorrentParams.contentLayout != originalContentLayout)
2790 if (loadTorrentParams.contentLayout == TorrentContentLayout::NoSubfolder)
2791 Path::stripRootFolder(filePaths);
2792 else
2793 Path::addRootFolder(filePaths, filePaths.at(0).removedExtension());
2798 // if torrent name wasn't explicitly set we handle the case of
2799 // initial renaming of torrent content and rename torrent accordingly
2800 if (loadTorrentParams.name.isEmpty())
2802 QString contentName = Path::findRootFolder(filePaths).toString();
2803 if (contentName.isEmpty() && (filePaths.size() == 1))
2804 contentName = filePaths.at(0).filename();
2806 if (!contentName.isEmpty() && (contentName != torrentInfo.name()))
2807 loadTorrentParams.name = contentName;
2810 if (!loadTorrentParams.hasFinishedStatus)
2812 const Path actualDownloadPath = useAutoTMM
2813 ? categoryDownloadPath(loadTorrentParams.category) : loadTorrentParams.downloadPath;
2814 findIncompleteFiles(torrentInfo, actualSavePath, actualDownloadPath, filePaths);
2815 isFindingIncompleteFiles = true;
2818 const auto nativeIndexes = torrentInfo.nativeIndexes();
2819 if (!isFindingIncompleteFiles)
2821 for (int index = 0; index < filePaths.size(); ++index)
2822 p.renamed_files[nativeIndexes[index]] = filePaths.at(index).toString().toStdString();
2825 Q_ASSERT(p.file_priorities.empty());
2826 Q_ASSERT(addTorrentParams.filePriorities.isEmpty() || (addTorrentParams.filePriorities.size() == nativeIndexes.size()));
2828 QList<DownloadPriority> filePriorities = addTorrentParams.filePriorities;
2830 if (filePriorities.isEmpty() && isExcludedFileNamesEnabled())
2832 // Check file name blacklist when priorities are not explicitly set
2833 applyFilenameFilter(filePaths, filePriorities);
2836 const int internalFilesCount = torrentInfo.nativeInfo()->files().num_files(); // including .pad files
2837 // Use qBittorrent default priority rather than libtorrent's (4)
2838 p.file_priorities = std::vector(internalFilesCount, LT::toNative(DownloadPriority::Normal));
2840 if (!filePriorities.isEmpty())
2842 for (int i = 0; i < filePriorities.size(); ++i)
2843 p.file_priorities[LT::toUnderlyingType(nativeIndexes[i])] = LT::toNative(filePriorities[i]);
2846 Q_ASSERT(p.ti);
2848 else
2850 if (loadTorrentParams.name.isEmpty() && !p.name.empty())
2851 loadTorrentParams.name = QString::fromStdString(p.name);
2854 p.save_path = actualSavePath.toString().toStdString();
2856 if (isAddTrackersEnabled() && !(hasMetadata && p.ti->priv()))
2858 const auto maxTierIter = std::max_element(p.tracker_tiers.cbegin(), p.tracker_tiers.cend());
2859 const int baseTier = (maxTierIter != p.tracker_tiers.cend()) ? (*maxTierIter + 1) : 0;
2861 p.trackers.reserve(p.trackers.size() + static_cast<std::size_t>(m_additionalTrackerEntries.size()));
2862 p.tracker_tiers.reserve(p.trackers.size() + static_cast<std::size_t>(m_additionalTrackerEntries.size()));
2863 p.tracker_tiers.resize(p.trackers.size(), 0);
2864 for (const TrackerEntry &trackerEntry : asConst(m_additionalTrackerEntries))
2866 p.trackers.emplace_back(trackerEntry.url.toStdString());
2867 p.tracker_tiers.emplace_back(Utils::Number::clampingAdd(trackerEntry.tier, baseTier));
2871 p.upload_limit = addTorrentParams.uploadLimit;
2872 p.download_limit = addTorrentParams.downloadLimit;
2874 // Preallocation mode
2875 p.storage_mode = isPreallocationEnabled() ? lt::storage_mode_allocate : lt::storage_mode_sparse;
2877 if (addTorrentParams.sequential)
2878 p.flags |= lt::torrent_flags::sequential_download;
2879 else
2880 p.flags &= ~lt::torrent_flags::sequential_download;
2882 // Seeding mode
2883 // Skip checking and directly start seeding
2884 if (addTorrentParams.skipChecking)
2885 p.flags |= lt::torrent_flags::seed_mode;
2886 else
2887 p.flags &= ~lt::torrent_flags::seed_mode;
2889 if (loadTorrentParams.stopped || (loadTorrentParams.operatingMode == TorrentOperatingMode::AutoManaged))
2890 p.flags |= lt::torrent_flags::paused;
2891 else
2892 p.flags &= ~lt::torrent_flags::paused;
2893 if (loadTorrentParams.stopped || (loadTorrentParams.operatingMode == TorrentOperatingMode::Forced))
2894 p.flags &= ~lt::torrent_flags::auto_managed;
2895 else
2896 p.flags |= lt::torrent_flags::auto_managed;
2898 p.flags |= lt::torrent_flags::duplicate_is_error;
2900 p.added_time = std::time(nullptr);
2902 // Limits
2903 p.max_connections = maxConnectionsPerTorrent();
2904 p.max_uploads = maxUploadsPerTorrent();
2906 p.userdata = LTClientData(new ExtensionData);
2907 #ifndef QBT_USES_LIBTORRENT2
2908 p.storage = customStorageConstructor;
2909 #endif
2911 m_loadingTorrents.insert(id, loadTorrentParams);
2912 if (infoHash.isHybrid())
2913 m_hybridTorrentsByAltID.insert(altID, nullptr);
2914 if (!isFindingIncompleteFiles)
2915 m_nativeSession->async_add_torrent(p);
2917 return true;
2920 void SessionImpl::findIncompleteFiles(const TorrentInfo &torrentInfo, const Path &savePath
2921 , const Path &downloadPath, const PathList &filePaths) const
2923 Q_ASSERT(filePaths.isEmpty() || (filePaths.size() == torrentInfo.filesCount()));
2925 const auto searchId = TorrentID::fromInfoHash(torrentInfo.infoHash());
2926 const PathList originalFileNames = (filePaths.isEmpty() ? torrentInfo.filePaths() : filePaths);
2927 QMetaObject::invokeMethod(m_fileSearcher, [=, this]
2929 m_fileSearcher->search(searchId, originalFileNames, savePath, downloadPath, isAppendExtensionEnabled());
2933 void SessionImpl::enablePortMapping()
2935 invokeAsync([this]
2937 if (m_isPortMappingEnabled)
2938 return;
2940 lt::settings_pack settingsPack;
2941 settingsPack.set_bool(lt::settings_pack::enable_upnp, true);
2942 settingsPack.set_bool(lt::settings_pack::enable_natpmp, true);
2943 m_nativeSession->apply_settings(std::move(settingsPack));
2945 m_isPortMappingEnabled = true;
2947 LogMsg(tr("UPnP/NAT-PMP support: ON"), Log::INFO);
2951 void SessionImpl::disablePortMapping()
2953 invokeAsync([this]
2955 if (!m_isPortMappingEnabled)
2956 return;
2958 lt::settings_pack settingsPack;
2959 settingsPack.set_bool(lt::settings_pack::enable_upnp, false);
2960 settingsPack.set_bool(lt::settings_pack::enable_natpmp, false);
2961 m_nativeSession->apply_settings(std::move(settingsPack));
2963 m_mappedPorts.clear();
2964 m_isPortMappingEnabled = false;
2966 LogMsg(tr("UPnP/NAT-PMP support: OFF"), Log::INFO);
2970 void SessionImpl::addMappedPorts(const QSet<quint16> &ports)
2972 invokeAsync([this, ports]
2974 if (!m_isPortMappingEnabled)
2975 return;
2977 for (const quint16 port : ports)
2979 if (!m_mappedPorts.contains(port))
2980 m_mappedPorts.insert(port, m_nativeSession->add_port_mapping(lt::session::tcp, port, port));
2985 void SessionImpl::removeMappedPorts(const QSet<quint16> &ports)
2987 invokeAsync([this, ports]
2989 if (!m_isPortMappingEnabled)
2990 return;
2992 Algorithm::removeIf(m_mappedPorts, [this, ports](const quint16 port, const std::vector<lt::port_mapping_t> &handles)
2994 if (!ports.contains(port))
2995 return false;
2997 for (const lt::port_mapping_t &handle : handles)
2998 m_nativeSession->delete_port_mapping(handle);
3000 return true;
3005 void SessionImpl::invokeAsync(std::function<void ()> func)
3007 m_asyncWorker->start(std::move(func));
3010 // Add a torrent to libtorrent session in hidden mode
3011 // and force it to download its metadata
3012 bool SessionImpl::downloadMetadata(const TorrentDescriptor &torrentDescr)
3014 Q_ASSERT(!torrentDescr.info().has_value());
3015 if (torrentDescr.info().has_value()) [[unlikely]]
3016 return false;
3018 const InfoHash infoHash = torrentDescr.infoHash();
3020 // We should not add torrent if it's already
3021 // processed or adding to session
3022 if (isKnownTorrent(infoHash))
3023 return false;
3025 lt::add_torrent_params p = torrentDescr.ltAddTorrentParams();
3027 if (isAddTrackersEnabled())
3029 // Use "additional trackers" when metadata retrieving (this can help when the DHT nodes are few)
3031 const auto maxTierIter = std::max_element(p.tracker_tiers.cbegin(), p.tracker_tiers.cend());
3032 const int baseTier = (maxTierIter != p.tracker_tiers.cend()) ? (*maxTierIter + 1) : 0;
3034 p.trackers.reserve(p.trackers.size() + static_cast<std::size_t>(m_additionalTrackerEntries.size()));
3035 p.tracker_tiers.reserve(p.trackers.size() + static_cast<std::size_t>(m_additionalTrackerEntries.size()));
3036 p.tracker_tiers.resize(p.trackers.size(), 0);
3037 for (const TrackerEntry &trackerEntry : asConst(m_additionalTrackerEntries))
3039 p.trackers.emplace_back(trackerEntry.url.toStdString());
3040 p.tracker_tiers.emplace_back(Utils::Number::clampingAdd(trackerEntry.tier, baseTier));
3044 // Flags
3045 // Preallocation mode
3046 if (isPreallocationEnabled())
3047 p.storage_mode = lt::storage_mode_allocate;
3048 else
3049 p.storage_mode = lt::storage_mode_sparse;
3051 // Limits
3052 p.max_connections = maxConnectionsPerTorrent();
3053 p.max_uploads = maxUploadsPerTorrent();
3055 const auto id = TorrentID::fromInfoHash(infoHash);
3056 const Path savePath = Utils::Fs::tempPath() / Path(id.toString());
3057 p.save_path = savePath.toString().toStdString();
3059 // Forced start
3060 p.flags &= ~lt::torrent_flags::paused;
3061 p.flags &= ~lt::torrent_flags::auto_managed;
3063 // Solution to avoid accidental file writes
3064 p.flags |= lt::torrent_flags::upload_mode;
3066 #ifndef QBT_USES_LIBTORRENT2
3067 p.storage = customStorageConstructor;
3068 #endif
3070 // Adding torrent to libtorrent session
3071 m_nativeSession->async_add_torrent(p);
3072 m_downloadedMetadata.insert(id, {});
3074 return true;
3077 void SessionImpl::exportTorrentFile(const Torrent *torrent, const Path &folderPath)
3079 if (!folderPath.exists() && !Utils::Fs::mkpath(folderPath))
3080 return;
3082 const QString validName = Utils::Fs::toValidFileName(torrent->name());
3083 QString torrentExportFilename = u"%1.torrent"_s.arg(validName);
3084 Path newTorrentPath = folderPath / Path(torrentExportFilename);
3085 int counter = 0;
3086 while (newTorrentPath.exists())
3088 // Append number to torrent name to make it unique
3089 torrentExportFilename = u"%1 %2.torrent"_s.arg(validName).arg(++counter);
3090 newTorrentPath = folderPath / Path(torrentExportFilename);
3093 const nonstd::expected<void, QString> result = torrent->exportToFile(newTorrentPath);
3094 if (!result)
3096 LogMsg(tr("Failed to export torrent. Torrent: \"%1\". Destination: \"%2\". Reason: \"%3\"")
3097 .arg(torrent->name(), newTorrentPath.toString(), result.error()), Log::WARNING);
3101 void SessionImpl::generateResumeData()
3103 for (TorrentImpl *const torrent : asConst(m_torrents))
3105 if (torrent->needSaveResumeData())
3106 torrent->requestResumeData();
3110 // Called on exit
3111 void SessionImpl::saveResumeData()
3113 for (TorrentImpl *torrent : asConst(m_torrents))
3115 // When the session is terminated due to unrecoverable error
3116 // some of the torrent handles can be corrupted
3119 torrent->requestResumeData(lt::torrent_handle::only_if_modified);
3121 catch (const std::exception &) {}
3124 // clear queued storage move jobs except the current ongoing one
3125 if (m_moveStorageQueue.size() > 1)
3126 m_moveStorageQueue.resize(1);
3128 QElapsedTimer timer;
3129 timer.start();
3131 while ((m_numResumeData > 0) || !m_moveStorageQueue.isEmpty() || m_needSaveTorrentsQueue)
3133 const lt::seconds waitTime {5};
3134 const lt::seconds expireTime {30};
3136 // only terminate when no storage is moving
3137 if (timer.hasExpired(lt::total_milliseconds(expireTime)) && m_moveStorageQueue.isEmpty())
3139 LogMsg(tr("Aborted saving resume data. Number of outstanding torrents: %1").arg(QString::number(m_numResumeData))
3140 , Log::CRITICAL);
3141 break;
3144 const std::vector<lt::alert *> alerts = getPendingAlerts(waitTime);
3146 bool hasWantedAlert = false;
3147 for (const lt::alert *alert : alerts)
3149 if (const int alertType = alert->type();
3150 (alertType == lt::save_resume_data_alert::alert_type) || (alertType == lt::save_resume_data_failed_alert::alert_type)
3151 || (alertType == lt::storage_moved_alert::alert_type) || (alertType == lt::storage_moved_failed_alert::alert_type)
3152 || (alertType == lt::state_update_alert::alert_type))
3154 hasWantedAlert = true;
3157 handleAlert(alert);
3160 if (hasWantedAlert)
3161 timer.start();
3165 void SessionImpl::saveTorrentsQueue()
3167 QList<TorrentID> queue;
3168 for (const TorrentImpl *torrent : asConst(m_torrents))
3170 if (const int queuePos = torrent->queuePosition(); queuePos >= 0)
3172 if (queuePos >= queue.size())
3173 queue.resize(queuePos + 1);
3174 queue[queuePos] = torrent->id();
3178 m_resumeDataStorage->storeQueue(queue);
3179 m_needSaveTorrentsQueue = false;
3182 void SessionImpl::removeTorrentsQueue()
3184 m_resumeDataStorage->storeQueue({});
3185 m_torrentsQueueChanged = false;
3186 m_needSaveTorrentsQueue = false;
3189 void SessionImpl::setSavePath(const Path &path)
3191 const auto newPath = (path.isAbsolute() ? path : (specialFolderLocation(SpecialFolder::Downloads) / path));
3192 if (newPath == m_savePath)
3193 return;
3195 if (isDisableAutoTMMWhenDefaultSavePathChanged())
3197 QSet<QString> affectedCatogories {{}}; // includes default (unnamed) category
3198 for (auto it = m_categories.cbegin(); it != m_categories.cend(); ++it)
3200 const QString &categoryName = it.key();
3201 const CategoryOptions &categoryOptions = it.value();
3202 if (categoryOptions.savePath.isRelative())
3203 affectedCatogories.insert(categoryName);
3206 for (TorrentImpl *const torrent : asConst(m_torrents))
3208 if (affectedCatogories.contains(torrent->category()))
3209 torrent->setAutoTMMEnabled(false);
3213 m_savePath = newPath;
3214 for (TorrentImpl *const torrent : asConst(m_torrents))
3215 torrent->handleCategoryOptionsChanged();
3218 void SessionImpl::setDownloadPath(const Path &path)
3220 const Path newPath = (path.isAbsolute() ? path : (savePath() / Path(u"temp"_s) / path));
3221 if (newPath == m_downloadPath)
3222 return;
3224 if (isDisableAutoTMMWhenDefaultSavePathChanged())
3226 QSet<QString> affectedCatogories {{}}; // includes default (unnamed) category
3227 for (auto it = m_categories.cbegin(); it != m_categories.cend(); ++it)
3229 const QString &categoryName = it.key();
3230 const CategoryOptions &categoryOptions = it.value();
3231 const DownloadPathOption downloadPathOption =
3232 categoryOptions.downloadPath.value_or(DownloadPathOption {isDownloadPathEnabled(), downloadPath()});
3233 if (downloadPathOption.enabled && downloadPathOption.path.isRelative())
3234 affectedCatogories.insert(categoryName);
3237 for (TorrentImpl *const torrent : asConst(m_torrents))
3239 if (affectedCatogories.contains(torrent->category()))
3240 torrent->setAutoTMMEnabled(false);
3244 m_downloadPath = newPath;
3245 for (TorrentImpl *const torrent : asConst(m_torrents))
3246 torrent->handleCategoryOptionsChanged();
3249 QStringList SessionImpl::getListeningIPs() const
3251 QStringList IPs;
3253 const QString ifaceName = networkInterface();
3254 const QString ifaceAddr = networkInterfaceAddress();
3255 const QHostAddress configuredAddr(ifaceAddr);
3256 const bool allIPv4 = (ifaceAddr == u"0.0.0.0"); // Means All IPv4 addresses
3257 const bool allIPv6 = (ifaceAddr == u"::"); // Means All IPv6 addresses
3259 if (!ifaceAddr.isEmpty() && !allIPv4 && !allIPv6 && configuredAddr.isNull())
3261 LogMsg(tr("The configured network address is invalid. Address: \"%1\"").arg(ifaceAddr), Log::CRITICAL);
3262 // Pass the invalid user configured interface name/address to libtorrent
3263 // in hopes that it will come online later.
3264 // This will not cause IP leak but allow user to reconnect the interface
3265 // and re-establish connection without restarting the client.
3266 IPs.append(ifaceAddr);
3267 return IPs;
3270 if (ifaceName.isEmpty())
3272 if (ifaceAddr.isEmpty())
3273 return {u"0.0.0.0"_s, u"::"_s}; // Indicates all interfaces + all addresses (aka default)
3275 if (allIPv4)
3276 return {u"0.0.0.0"_s};
3278 if (allIPv6)
3279 return {u"::"_s};
3282 const auto checkAndAddIP = [allIPv4, allIPv6, &IPs](const QHostAddress &addr, const QHostAddress &match)
3284 if ((allIPv4 && (addr.protocol() != QAbstractSocket::IPv4Protocol))
3285 || (allIPv6 && (addr.protocol() != QAbstractSocket::IPv6Protocol)))
3286 return;
3288 if ((match == addr) || allIPv4 || allIPv6)
3289 IPs.append(addr.toString());
3292 if (ifaceName.isEmpty())
3294 const QList<QHostAddress> addresses = QNetworkInterface::allAddresses();
3295 for (const auto &addr : addresses)
3296 checkAndAddIP(addr, configuredAddr);
3298 // At this point ifaceAddr was non-empty
3299 // If IPs.isEmpty() it means the configured Address was not found
3300 if (IPs.isEmpty())
3302 LogMsg(tr("Failed to find the configured network address to listen on. Address: \"%1\"")
3303 .arg(ifaceAddr), Log::CRITICAL);
3304 IPs.append(ifaceAddr);
3307 return IPs;
3310 // Attempt to listen on provided interface
3311 const QNetworkInterface networkIFace = QNetworkInterface::interfaceFromName(ifaceName);
3312 if (!networkIFace.isValid())
3314 qDebug("Invalid network interface: %s", qUtf8Printable(ifaceName));
3315 LogMsg(tr("The configured network interface is invalid. Interface: \"%1\"").arg(ifaceName), Log::CRITICAL);
3316 IPs.append(ifaceName);
3317 return IPs;
3320 if (ifaceAddr.isEmpty())
3322 IPs.append(ifaceName);
3323 return IPs; // On Windows calling code converts it to GUID
3326 const QList<QNetworkAddressEntry> addresses = networkIFace.addressEntries();
3327 qDebug() << "This network interface has " << addresses.size() << " IP addresses";
3328 for (const QNetworkAddressEntry &entry : addresses)
3329 checkAndAddIP(entry.ip(), configuredAddr);
3331 // Make sure there is at least one IP
3332 // At this point there was an explicit interface and an explicit address set
3333 // and the address should have been found
3334 if (IPs.isEmpty())
3336 LogMsg(tr("Failed to find the configured network address to listen on. Address: \"%1\"")
3337 .arg(ifaceAddr), Log::CRITICAL);
3338 IPs.append(ifaceAddr);
3341 return IPs;
3344 // Set the ports range in which is chosen the port
3345 // the BitTorrent session will listen to
3346 void SessionImpl::configureListeningInterface()
3348 m_listenInterfaceConfigured = false;
3349 configureDeferred();
3352 int SessionImpl::globalDownloadSpeedLimit() const
3354 // Unfortunately the value was saved as KiB instead of B.
3355 // But it is better to pass it around internally(+ webui) as Bytes.
3356 return m_globalDownloadSpeedLimit * 1024;
3359 void SessionImpl::setGlobalDownloadSpeedLimit(const int limit)
3361 // Unfortunately the value was saved as KiB instead of B.
3362 // But it is better to pass it around internally(+ webui) as Bytes.
3363 if (limit == globalDownloadSpeedLimit())
3364 return;
3366 if (limit <= 0)
3367 m_globalDownloadSpeedLimit = 0;
3368 else if (limit <= 1024)
3369 m_globalDownloadSpeedLimit = 1;
3370 else
3371 m_globalDownloadSpeedLimit = (limit / 1024);
3373 if (!isAltGlobalSpeedLimitEnabled())
3374 configureDeferred();
3377 int SessionImpl::globalUploadSpeedLimit() const
3379 // Unfortunately the value was saved as KiB instead of B.
3380 // But it is better to pass it around internally(+ webui) as Bytes.
3381 return m_globalUploadSpeedLimit * 1024;
3384 void SessionImpl::setGlobalUploadSpeedLimit(const int limit)
3386 // Unfortunately the value was saved as KiB instead of B.
3387 // But it is better to pass it around internally(+ webui) as Bytes.
3388 if (limit == globalUploadSpeedLimit())
3389 return;
3391 if (limit <= 0)
3392 m_globalUploadSpeedLimit = 0;
3393 else if (limit <= 1024)
3394 m_globalUploadSpeedLimit = 1;
3395 else
3396 m_globalUploadSpeedLimit = (limit / 1024);
3398 if (!isAltGlobalSpeedLimitEnabled())
3399 configureDeferred();
3402 int SessionImpl::altGlobalDownloadSpeedLimit() const
3404 // Unfortunately the value was saved as KiB instead of B.
3405 // But it is better to pass it around internally(+ webui) as Bytes.
3406 return m_altGlobalDownloadSpeedLimit * 1024;
3409 void SessionImpl::setAltGlobalDownloadSpeedLimit(const int limit)
3411 // Unfortunately the value was saved as KiB instead of B.
3412 // But it is better to pass it around internally(+ webui) as Bytes.
3413 if (limit == altGlobalDownloadSpeedLimit())
3414 return;
3416 if (limit <= 0)
3417 m_altGlobalDownloadSpeedLimit = 0;
3418 else if (limit <= 1024)
3419 m_altGlobalDownloadSpeedLimit = 1;
3420 else
3421 m_altGlobalDownloadSpeedLimit = (limit / 1024);
3423 if (isAltGlobalSpeedLimitEnabled())
3424 configureDeferred();
3427 int SessionImpl::altGlobalUploadSpeedLimit() const
3429 // Unfortunately the value was saved as KiB instead of B.
3430 // But it is better to pass it around internally(+ webui) as Bytes.
3431 return m_altGlobalUploadSpeedLimit * 1024;
3434 void SessionImpl::setAltGlobalUploadSpeedLimit(const int limit)
3436 // Unfortunately the value was saved as KiB instead of B.
3437 // But it is better to pass it around internally(+ webui) as Bytes.
3438 if (limit == altGlobalUploadSpeedLimit())
3439 return;
3441 if (limit <= 0)
3442 m_altGlobalUploadSpeedLimit = 0;
3443 else if (limit <= 1024)
3444 m_altGlobalUploadSpeedLimit = 1;
3445 else
3446 m_altGlobalUploadSpeedLimit = (limit / 1024);
3448 if (isAltGlobalSpeedLimitEnabled())
3449 configureDeferred();
3452 int SessionImpl::downloadSpeedLimit() const
3454 return isAltGlobalSpeedLimitEnabled()
3455 ? altGlobalDownloadSpeedLimit()
3456 : globalDownloadSpeedLimit();
3459 void SessionImpl::setDownloadSpeedLimit(const int limit)
3461 if (isAltGlobalSpeedLimitEnabled())
3462 setAltGlobalDownloadSpeedLimit(limit);
3463 else
3464 setGlobalDownloadSpeedLimit(limit);
3467 int SessionImpl::uploadSpeedLimit() const
3469 return isAltGlobalSpeedLimitEnabled()
3470 ? altGlobalUploadSpeedLimit()
3471 : globalUploadSpeedLimit();
3474 void SessionImpl::setUploadSpeedLimit(const int limit)
3476 if (isAltGlobalSpeedLimitEnabled())
3477 setAltGlobalUploadSpeedLimit(limit);
3478 else
3479 setGlobalUploadSpeedLimit(limit);
3482 bool SessionImpl::isAltGlobalSpeedLimitEnabled() const
3484 return m_isAltGlobalSpeedLimitEnabled;
3487 void SessionImpl::setAltGlobalSpeedLimitEnabled(const bool enabled)
3489 if (enabled == isAltGlobalSpeedLimitEnabled()) return;
3491 // Save new state to remember it on startup
3492 m_isAltGlobalSpeedLimitEnabled = enabled;
3493 applyBandwidthLimits();
3494 // Notify
3495 emit speedLimitModeChanged(m_isAltGlobalSpeedLimitEnabled);
3498 bool SessionImpl::isBandwidthSchedulerEnabled() const
3500 return m_isBandwidthSchedulerEnabled;
3503 void SessionImpl::setBandwidthSchedulerEnabled(const bool enabled)
3505 if (enabled != isBandwidthSchedulerEnabled())
3507 m_isBandwidthSchedulerEnabled = enabled;
3508 if (enabled)
3509 enableBandwidthScheduler();
3510 else
3511 delete m_bwScheduler;
3515 bool SessionImpl::isPerformanceWarningEnabled() const
3517 return m_isPerformanceWarningEnabled;
3520 void SessionImpl::setPerformanceWarningEnabled(const bool enable)
3522 if (enable == m_isPerformanceWarningEnabled)
3523 return;
3525 m_isPerformanceWarningEnabled = enable;
3526 configureDeferred();
3529 int SessionImpl::saveResumeDataInterval() const
3531 return m_saveResumeDataInterval;
3534 void SessionImpl::setSaveResumeDataInterval(const int value)
3536 if (value == m_saveResumeDataInterval)
3537 return;
3539 m_saveResumeDataInterval = value;
3541 if (value > 0)
3543 m_resumeDataTimer->setInterval(std::chrono::minutes(value));
3544 m_resumeDataTimer->start();
3546 else
3548 m_resumeDataTimer->stop();
3552 int SessionImpl::shutdownTimeout() const
3554 return m_shutdownTimeout;
3557 void SessionImpl::setShutdownTimeout(const int value)
3559 m_shutdownTimeout = value;
3562 int SessionImpl::port() const
3564 return m_port;
3567 void SessionImpl::setPort(const int port)
3569 if (port != m_port)
3571 m_port = port;
3572 configureListeningInterface();
3574 if (isReannounceWhenAddressChangedEnabled())
3575 reannounceToAllTrackers();
3579 bool SessionImpl::isSSLEnabled() const
3581 return m_sslEnabled;
3584 void SessionImpl::setSSLEnabled(const bool enabled)
3586 if (enabled == isSSLEnabled())
3587 return;
3589 m_sslEnabled = enabled;
3590 configureListeningInterface();
3592 if (isReannounceWhenAddressChangedEnabled())
3593 reannounceToAllTrackers();
3596 int SessionImpl::sslPort() const
3598 return m_sslPort;
3601 void SessionImpl::setSSLPort(const int port)
3603 if (port == sslPort())
3604 return;
3606 m_sslPort = port;
3607 configureListeningInterface();
3609 if (isReannounceWhenAddressChangedEnabled())
3610 reannounceToAllTrackers();
3613 QString SessionImpl::networkInterface() const
3615 return m_networkInterface;
3618 void SessionImpl::setNetworkInterface(const QString &iface)
3620 if (iface != networkInterface())
3622 m_networkInterface = iface;
3623 configureListeningInterface();
3627 QString SessionImpl::networkInterfaceName() const
3629 return m_networkInterfaceName;
3632 void SessionImpl::setNetworkInterfaceName(const QString &name)
3634 m_networkInterfaceName = name;
3637 QString SessionImpl::networkInterfaceAddress() const
3639 return m_networkInterfaceAddress;
3642 void SessionImpl::setNetworkInterfaceAddress(const QString &address)
3644 if (address != networkInterfaceAddress())
3646 m_networkInterfaceAddress = address;
3647 configureListeningInterface();
3651 int SessionImpl::encryption() const
3653 return m_encryption;
3656 void SessionImpl::setEncryption(const int state)
3658 if (state != encryption())
3660 m_encryption = state;
3661 configureDeferred();
3662 LogMsg(tr("Encryption support: %1").arg(
3663 state == 0 ? tr("ON") : ((state == 1) ? tr("FORCED") : tr("OFF")))
3664 , Log::INFO);
3668 int SessionImpl::maxActiveCheckingTorrents() const
3670 return m_maxActiveCheckingTorrents;
3673 void SessionImpl::setMaxActiveCheckingTorrents(const int val)
3675 if (val == m_maxActiveCheckingTorrents)
3676 return;
3678 m_maxActiveCheckingTorrents = val;
3679 configureDeferred();
3682 bool SessionImpl::isI2PEnabled() const
3684 return m_isI2PEnabled;
3687 void SessionImpl::setI2PEnabled(const bool enabled)
3689 if (m_isI2PEnabled != enabled)
3691 m_isI2PEnabled = enabled;
3692 configureDeferred();
3696 QString SessionImpl::I2PAddress() const
3698 return m_I2PAddress;
3701 void SessionImpl::setI2PAddress(const QString &address)
3703 if (m_I2PAddress != address)
3705 m_I2PAddress = address;
3706 configureDeferred();
3710 int SessionImpl::I2PPort() const
3712 return m_I2PPort;
3715 void SessionImpl::setI2PPort(int port)
3717 if (m_I2PPort != port)
3719 m_I2PPort = port;
3720 configureDeferred();
3724 bool SessionImpl::I2PMixedMode() const
3726 return m_I2PMixedMode;
3729 void SessionImpl::setI2PMixedMode(const bool enabled)
3731 if (m_I2PMixedMode != enabled)
3733 m_I2PMixedMode = enabled;
3734 configureDeferred();
3738 int SessionImpl::I2PInboundQuantity() const
3740 return m_I2PInboundQuantity;
3743 void SessionImpl::setI2PInboundQuantity(const int value)
3745 if (value == m_I2PInboundQuantity)
3746 return;
3748 m_I2PInboundQuantity = value;
3749 configureDeferred();
3752 int SessionImpl::I2POutboundQuantity() const
3754 return m_I2POutboundQuantity;
3757 void SessionImpl::setI2POutboundQuantity(const int value)
3759 if (value == m_I2POutboundQuantity)
3760 return;
3762 m_I2POutboundQuantity = value;
3763 configureDeferred();
3766 int SessionImpl::I2PInboundLength() const
3768 return m_I2PInboundLength;
3771 void SessionImpl::setI2PInboundLength(const int value)
3773 if (value == m_I2PInboundLength)
3774 return;
3776 m_I2PInboundLength = value;
3777 configureDeferred();
3780 int SessionImpl::I2POutboundLength() const
3782 return m_I2POutboundLength;
3785 void SessionImpl::setI2POutboundLength(const int value)
3787 if (value == m_I2POutboundLength)
3788 return;
3790 m_I2POutboundLength = value;
3791 configureDeferred();
3794 bool SessionImpl::isProxyPeerConnectionsEnabled() const
3796 return m_isProxyPeerConnectionsEnabled;
3799 void SessionImpl::setProxyPeerConnectionsEnabled(const bool enabled)
3801 if (enabled != isProxyPeerConnectionsEnabled())
3803 m_isProxyPeerConnectionsEnabled = enabled;
3804 configureDeferred();
3808 ChokingAlgorithm SessionImpl::chokingAlgorithm() const
3810 return m_chokingAlgorithm;
3813 void SessionImpl::setChokingAlgorithm(const ChokingAlgorithm mode)
3815 if (mode == m_chokingAlgorithm) return;
3817 m_chokingAlgorithm = mode;
3818 configureDeferred();
3821 SeedChokingAlgorithm SessionImpl::seedChokingAlgorithm() const
3823 return m_seedChokingAlgorithm;
3826 void SessionImpl::setSeedChokingAlgorithm(const SeedChokingAlgorithm mode)
3828 if (mode == m_seedChokingAlgorithm) return;
3830 m_seedChokingAlgorithm = mode;
3831 configureDeferred();
3834 bool SessionImpl::isAddTrackersEnabled() const
3836 return m_isAddTrackersEnabled;
3839 void SessionImpl::setAddTrackersEnabled(const bool enabled)
3841 m_isAddTrackersEnabled = enabled;
3844 QString SessionImpl::additionalTrackers() const
3846 return m_additionalTrackers;
3849 void SessionImpl::setAdditionalTrackers(const QString &trackers)
3851 if (trackers == additionalTrackers())
3852 return;
3854 m_additionalTrackers = trackers;
3855 populateAdditionalTrackers();
3858 bool SessionImpl::isIPFilteringEnabled() const
3860 return m_isIPFilteringEnabled;
3863 void SessionImpl::setIPFilteringEnabled(const bool enabled)
3865 if (enabled != m_isIPFilteringEnabled)
3867 m_isIPFilteringEnabled = enabled;
3868 m_IPFilteringConfigured = false;
3869 configureDeferred();
3873 Path SessionImpl::IPFilterFile() const
3875 return m_IPFilterFile;
3878 void SessionImpl::setIPFilterFile(const Path &path)
3880 if (path != IPFilterFile())
3882 m_IPFilterFile = path;
3883 m_IPFilteringConfigured = false;
3884 configureDeferred();
3888 bool SessionImpl::isExcludedFileNamesEnabled() const
3890 return m_isExcludedFileNamesEnabled;
3893 void SessionImpl::setExcludedFileNamesEnabled(const bool enabled)
3895 if (m_isExcludedFileNamesEnabled == enabled)
3896 return;
3898 m_isExcludedFileNamesEnabled = enabled;
3900 if (enabled)
3901 populateExcludedFileNamesRegExpList();
3902 else
3903 m_excludedFileNamesRegExpList.clear();
3906 QStringList SessionImpl::excludedFileNames() const
3908 return m_excludedFileNames;
3911 void SessionImpl::setExcludedFileNames(const QStringList &excludedFileNames)
3913 if (excludedFileNames != m_excludedFileNames)
3915 m_excludedFileNames = excludedFileNames;
3916 populateExcludedFileNamesRegExpList();
3920 void SessionImpl::populateExcludedFileNamesRegExpList()
3922 const QStringList excludedNames = excludedFileNames();
3924 m_excludedFileNamesRegExpList.clear();
3925 m_excludedFileNamesRegExpList.reserve(excludedNames.size());
3927 for (const QString &str : excludedNames)
3929 const QString pattern = QRegularExpression::wildcardToRegularExpression(str);
3930 const QRegularExpression re {pattern, QRegularExpression::CaseInsensitiveOption};
3931 m_excludedFileNamesRegExpList.append(re);
3935 void SessionImpl::applyFilenameFilter(const PathList &files, QList<DownloadPriority> &priorities)
3937 if (!isExcludedFileNamesEnabled())
3938 return;
3940 const auto isFilenameExcluded = [patterns = m_excludedFileNamesRegExpList](const Path &fileName)
3942 return std::any_of(patterns.begin(), patterns.end(), [&fileName](const QRegularExpression &re)
3944 Path path = fileName;
3945 while (!re.match(path.filename()).hasMatch())
3947 path = path.parentPath();
3948 if (path.isEmpty())
3949 return false;
3951 return true;
3955 priorities.resize(files.count(), DownloadPriority::Normal);
3956 for (int i = 0; i < priorities.size(); ++i)
3958 if (priorities[i] == BitTorrent::DownloadPriority::Ignored)
3959 continue;
3961 if (isFilenameExcluded(files.at(i)))
3962 priorities[i] = BitTorrent::DownloadPriority::Ignored;
3966 void SessionImpl::setBannedIPs(const QStringList &newList)
3968 if (newList == m_bannedIPs)
3969 return; // do nothing
3970 // here filter out incorrect IP
3971 QStringList filteredList;
3972 for (const QString &ip : newList)
3974 if (Utils::Net::isValidIP(ip))
3976 // the same IPv6 addresses could be written in different forms;
3977 // QHostAddress::toString() result format follows RFC5952;
3978 // thus we avoid duplicate entries pointing to the same address
3979 filteredList << QHostAddress(ip).toString();
3981 else
3983 LogMsg(tr("Rejected invalid IP address while applying the list of banned IP addresses. IP: \"%1\"")
3984 .arg(ip)
3985 , Log::WARNING);
3988 // now we have to sort IPs and make them unique
3989 filteredList.sort();
3990 filteredList.removeDuplicates();
3991 // Again ensure that the new list is different from the stored one.
3992 if (filteredList == m_bannedIPs)
3993 return; // do nothing
3994 // store to session settings
3995 // also here we have to recreate filter list including 3rd party ban file
3996 // and install it again into m_session
3997 m_bannedIPs = filteredList;
3998 m_IPFilteringConfigured = false;
3999 configureDeferred();
4002 ResumeDataStorageType SessionImpl::resumeDataStorageType() const
4004 return m_resumeDataStorageType;
4007 void SessionImpl::setResumeDataStorageType(const ResumeDataStorageType type)
4009 m_resumeDataStorageType = type;
4012 bool SessionImpl::isMergeTrackersEnabled() const
4014 return m_isMergeTrackersEnabled;
4017 void SessionImpl::setMergeTrackersEnabled(const bool enabled)
4019 m_isMergeTrackersEnabled = enabled;
4022 bool SessionImpl::isStartPaused() const
4024 return m_startPaused.get(false);
4027 void SessionImpl::setStartPaused(const bool value)
4029 m_startPaused = value;
4032 TorrentContentRemoveOption SessionImpl::torrentContentRemoveOption() const
4034 return m_torrentContentRemoveOption;
4037 void SessionImpl::setTorrentContentRemoveOption(const TorrentContentRemoveOption option)
4039 m_torrentContentRemoveOption = option;
4042 QStringList SessionImpl::bannedIPs() const
4044 return m_bannedIPs;
4047 bool SessionImpl::isRestored() const
4049 return m_isRestored;
4052 bool SessionImpl::isPaused() const
4054 return m_isPaused;
4057 void SessionImpl::pause()
4059 if (!m_isPaused)
4061 if (isRestored())
4062 m_nativeSession->pause();
4064 m_isPaused = true;
4065 emit paused();
4069 void SessionImpl::resume()
4071 if (m_isPaused)
4073 if (isRestored())
4074 m_nativeSession->resume();
4076 m_isPaused = false;
4077 emit resumed();
4081 int SessionImpl::maxConnectionsPerTorrent() const
4083 return m_maxConnectionsPerTorrent;
4086 void SessionImpl::setMaxConnectionsPerTorrent(int max)
4088 max = (max > 0) ? max : -1;
4089 if (max != maxConnectionsPerTorrent())
4091 m_maxConnectionsPerTorrent = max;
4093 for (const TorrentImpl *torrent : asConst(m_torrents))
4097 torrent->nativeHandle().set_max_connections(max);
4099 catch (const std::exception &) {}
4104 int SessionImpl::maxUploadsPerTorrent() const
4106 return m_maxUploadsPerTorrent;
4109 void SessionImpl::setMaxUploadsPerTorrent(int max)
4111 max = (max > 0) ? max : -1;
4112 if (max != maxUploadsPerTorrent())
4114 m_maxUploadsPerTorrent = max;
4116 for (const TorrentImpl *torrent : asConst(m_torrents))
4120 torrent->nativeHandle().set_max_uploads(max);
4122 catch (const std::exception &) {}
4127 bool SessionImpl::announceToAllTrackers() const
4129 return m_announceToAllTrackers;
4132 void SessionImpl::setAnnounceToAllTrackers(const bool val)
4134 if (val != m_announceToAllTrackers)
4136 m_announceToAllTrackers = val;
4137 configureDeferred();
4141 bool SessionImpl::announceToAllTiers() const
4143 return m_announceToAllTiers;
4146 void SessionImpl::setAnnounceToAllTiers(const bool val)
4148 if (val != m_announceToAllTiers)
4150 m_announceToAllTiers = val;
4151 configureDeferred();
4155 int SessionImpl::peerTurnover() const
4157 return m_peerTurnover;
4160 void SessionImpl::setPeerTurnover(const int val)
4162 if (val == m_peerTurnover)
4163 return;
4165 m_peerTurnover = val;
4166 configureDeferred();
4169 int SessionImpl::peerTurnoverCutoff() const
4171 return m_peerTurnoverCutoff;
4174 void SessionImpl::setPeerTurnoverCutoff(const int val)
4176 if (val == m_peerTurnoverCutoff)
4177 return;
4179 m_peerTurnoverCutoff = val;
4180 configureDeferred();
4183 int SessionImpl::peerTurnoverInterval() const
4185 return m_peerTurnoverInterval;
4188 void SessionImpl::setPeerTurnoverInterval(const int val)
4190 if (val == m_peerTurnoverInterval)
4191 return;
4193 m_peerTurnoverInterval = val;
4194 configureDeferred();
4197 DiskIOType SessionImpl::diskIOType() const
4199 return m_diskIOType;
4202 void SessionImpl::setDiskIOType(const DiskIOType type)
4204 if (type != m_diskIOType)
4206 m_diskIOType = type;
4210 int SessionImpl::requestQueueSize() const
4212 return m_requestQueueSize;
4215 void SessionImpl::setRequestQueueSize(const int val)
4217 if (val == m_requestQueueSize)
4218 return;
4220 m_requestQueueSize = val;
4221 configureDeferred();
4224 int SessionImpl::asyncIOThreads() const
4226 return std::clamp(m_asyncIOThreads.get(), 1, 1024);
4229 void SessionImpl::setAsyncIOThreads(const int num)
4231 if (num == m_asyncIOThreads)
4232 return;
4234 m_asyncIOThreads = num;
4235 configureDeferred();
4238 int SessionImpl::hashingThreads() const
4240 return std::clamp(m_hashingThreads.get(), 1, 1024);
4243 void SessionImpl::setHashingThreads(const int num)
4245 if (num == m_hashingThreads)
4246 return;
4248 m_hashingThreads = num;
4249 configureDeferred();
4252 int SessionImpl::filePoolSize() const
4254 return m_filePoolSize;
4257 void SessionImpl::setFilePoolSize(const int size)
4259 if (size == m_filePoolSize)
4260 return;
4262 m_filePoolSize = size;
4263 configureDeferred();
4266 int SessionImpl::checkingMemUsage() const
4268 return std::max(1, m_checkingMemUsage.get());
4271 void SessionImpl::setCheckingMemUsage(int size)
4273 size = std::max(size, 1);
4275 if (size == m_checkingMemUsage)
4276 return;
4278 m_checkingMemUsage = size;
4279 configureDeferred();
4282 int SessionImpl::diskCacheSize() const
4284 #ifdef QBT_APP_64BIT
4285 return std::min(m_diskCacheSize.get(), 33554431); // 32768GiB
4286 #else
4287 // When build as 32bit binary, set the maximum at less than 2GB to prevent crashes
4288 // allocate 1536MiB and leave 512MiB to the rest of program data in RAM
4289 return std::min(m_diskCacheSize.get(), 1536);
4290 #endif
4293 void SessionImpl::setDiskCacheSize(int size)
4295 #ifdef QBT_APP_64BIT
4296 size = std::min(size, 33554431); // 32768GiB
4297 #else
4298 // allocate 1536MiB and leave 512MiB to the rest of program data in RAM
4299 size = std::min(size, 1536);
4300 #endif
4301 if (size != m_diskCacheSize)
4303 m_diskCacheSize = size;
4304 configureDeferred();
4308 int SessionImpl::diskCacheTTL() const
4310 return m_diskCacheTTL;
4313 void SessionImpl::setDiskCacheTTL(const int ttl)
4315 if (ttl != m_diskCacheTTL)
4317 m_diskCacheTTL = ttl;
4318 configureDeferred();
4322 qint64 SessionImpl::diskQueueSize() const
4324 return m_diskQueueSize;
4327 void SessionImpl::setDiskQueueSize(const qint64 size)
4329 if (size == m_diskQueueSize)
4330 return;
4332 m_diskQueueSize = size;
4333 configureDeferred();
4336 DiskIOReadMode SessionImpl::diskIOReadMode() const
4338 return m_diskIOReadMode;
4341 void SessionImpl::setDiskIOReadMode(const DiskIOReadMode mode)
4343 if (mode == m_diskIOReadMode)
4344 return;
4346 m_diskIOReadMode = mode;
4347 configureDeferred();
4350 DiskIOWriteMode SessionImpl::diskIOWriteMode() const
4352 return m_diskIOWriteMode;
4355 void SessionImpl::setDiskIOWriteMode(const DiskIOWriteMode mode)
4357 if (mode == m_diskIOWriteMode)
4358 return;
4360 m_diskIOWriteMode = mode;
4361 configureDeferred();
4364 bool SessionImpl::isCoalesceReadWriteEnabled() const
4366 return m_coalesceReadWriteEnabled;
4369 void SessionImpl::setCoalesceReadWriteEnabled(const bool enabled)
4371 if (enabled == m_coalesceReadWriteEnabled) return;
4373 m_coalesceReadWriteEnabled = enabled;
4374 configureDeferred();
4377 bool SessionImpl::isSuggestModeEnabled() const
4379 return m_isSuggestMode;
4382 bool SessionImpl::usePieceExtentAffinity() const
4384 return m_usePieceExtentAffinity;
4387 void SessionImpl::setPieceExtentAffinity(const bool enabled)
4389 if (enabled == m_usePieceExtentAffinity) return;
4391 m_usePieceExtentAffinity = enabled;
4392 configureDeferred();
4395 void SessionImpl::setSuggestMode(const bool mode)
4397 if (mode == m_isSuggestMode) return;
4399 m_isSuggestMode = mode;
4400 configureDeferred();
4403 int SessionImpl::sendBufferWatermark() const
4405 return m_sendBufferWatermark;
4408 void SessionImpl::setSendBufferWatermark(const int value)
4410 if (value == m_sendBufferWatermark) return;
4412 m_sendBufferWatermark = value;
4413 configureDeferred();
4416 int SessionImpl::sendBufferLowWatermark() const
4418 return m_sendBufferLowWatermark;
4421 void SessionImpl::setSendBufferLowWatermark(const int value)
4423 if (value == m_sendBufferLowWatermark) return;
4425 m_sendBufferLowWatermark = value;
4426 configureDeferred();
4429 int SessionImpl::sendBufferWatermarkFactor() const
4431 return m_sendBufferWatermarkFactor;
4434 void SessionImpl::setSendBufferWatermarkFactor(const int value)
4436 if (value == m_sendBufferWatermarkFactor) return;
4438 m_sendBufferWatermarkFactor = value;
4439 configureDeferred();
4442 int SessionImpl::connectionSpeed() const
4444 return m_connectionSpeed;
4447 void SessionImpl::setConnectionSpeed(const int value)
4449 if (value == m_connectionSpeed) return;
4451 m_connectionSpeed = value;
4452 configureDeferred();
4455 int SessionImpl::socketSendBufferSize() const
4457 return m_socketSendBufferSize;
4460 void SessionImpl::setSocketSendBufferSize(const int value)
4462 if (value == m_socketSendBufferSize)
4463 return;
4465 m_socketSendBufferSize = value;
4466 configureDeferred();
4469 int SessionImpl::socketReceiveBufferSize() const
4471 return m_socketReceiveBufferSize;
4474 void SessionImpl::setSocketReceiveBufferSize(const int value)
4476 if (value == m_socketReceiveBufferSize)
4477 return;
4479 m_socketReceiveBufferSize = value;
4480 configureDeferred();
4483 int SessionImpl::socketBacklogSize() const
4485 return m_socketBacklogSize;
4488 void SessionImpl::setSocketBacklogSize(const int value)
4490 if (value == m_socketBacklogSize) return;
4492 m_socketBacklogSize = value;
4493 configureDeferred();
4496 bool SessionImpl::isAnonymousModeEnabled() const
4498 return m_isAnonymousModeEnabled;
4501 void SessionImpl::setAnonymousModeEnabled(const bool enabled)
4503 if (enabled != m_isAnonymousModeEnabled)
4505 m_isAnonymousModeEnabled = enabled;
4506 configureDeferred();
4507 LogMsg(tr("Anonymous mode: %1").arg(isAnonymousModeEnabled() ? tr("ON") : tr("OFF"))
4508 , Log::INFO);
4512 bool SessionImpl::isQueueingSystemEnabled() const
4514 return m_isQueueingEnabled;
4517 void SessionImpl::setQueueingSystemEnabled(const bool enabled)
4519 if (enabled != m_isQueueingEnabled)
4521 m_isQueueingEnabled = enabled;
4522 configureDeferred();
4524 if (enabled)
4525 m_torrentsQueueChanged = true;
4526 else
4527 removeTorrentsQueue();
4529 for (TorrentImpl *torrent : asConst(m_torrents))
4530 torrent->handleQueueingModeChanged();
4534 int SessionImpl::maxActiveDownloads() const
4536 return m_maxActiveDownloads;
4539 void SessionImpl::setMaxActiveDownloads(int max)
4541 max = std::max(max, -1);
4542 if (max != m_maxActiveDownloads)
4544 m_maxActiveDownloads = max;
4545 configureDeferred();
4549 int SessionImpl::maxActiveUploads() const
4551 return m_maxActiveUploads;
4554 void SessionImpl::setMaxActiveUploads(int max)
4556 max = std::max(max, -1);
4557 if (max != m_maxActiveUploads)
4559 m_maxActiveUploads = max;
4560 configureDeferred();
4564 int SessionImpl::maxActiveTorrents() const
4566 return m_maxActiveTorrents;
4569 void SessionImpl::setMaxActiveTorrents(int max)
4571 max = std::max(max, -1);
4572 if (max != m_maxActiveTorrents)
4574 m_maxActiveTorrents = max;
4575 configureDeferred();
4579 bool SessionImpl::ignoreSlowTorrentsForQueueing() const
4581 return m_ignoreSlowTorrentsForQueueing;
4584 void SessionImpl::setIgnoreSlowTorrentsForQueueing(const bool ignore)
4586 if (ignore != m_ignoreSlowTorrentsForQueueing)
4588 m_ignoreSlowTorrentsForQueueing = ignore;
4589 configureDeferred();
4593 int SessionImpl::downloadRateForSlowTorrents() const
4595 return m_downloadRateForSlowTorrents;
4598 void SessionImpl::setDownloadRateForSlowTorrents(const int rateInKibiBytes)
4600 if (rateInKibiBytes == m_downloadRateForSlowTorrents)
4601 return;
4603 m_downloadRateForSlowTorrents = rateInKibiBytes;
4604 configureDeferred();
4607 int SessionImpl::uploadRateForSlowTorrents() const
4609 return m_uploadRateForSlowTorrents;
4612 void SessionImpl::setUploadRateForSlowTorrents(const int rateInKibiBytes)
4614 if (rateInKibiBytes == m_uploadRateForSlowTorrents)
4615 return;
4617 m_uploadRateForSlowTorrents = rateInKibiBytes;
4618 configureDeferred();
4621 int SessionImpl::slowTorrentsInactivityTimer() const
4623 return m_slowTorrentsInactivityTimer;
4626 void SessionImpl::setSlowTorrentsInactivityTimer(const int timeInSeconds)
4628 if (timeInSeconds == m_slowTorrentsInactivityTimer)
4629 return;
4631 m_slowTorrentsInactivityTimer = timeInSeconds;
4632 configureDeferred();
4635 int SessionImpl::outgoingPortsMin() const
4637 return m_outgoingPortsMin;
4640 void SessionImpl::setOutgoingPortsMin(const int min)
4642 if (min != m_outgoingPortsMin)
4644 m_outgoingPortsMin = min;
4645 configureDeferred();
4649 int SessionImpl::outgoingPortsMax() const
4651 return m_outgoingPortsMax;
4654 void SessionImpl::setOutgoingPortsMax(const int max)
4656 if (max != m_outgoingPortsMax)
4658 m_outgoingPortsMax = max;
4659 configureDeferred();
4663 int SessionImpl::UPnPLeaseDuration() const
4665 return m_UPnPLeaseDuration;
4668 void SessionImpl::setUPnPLeaseDuration(const int duration)
4670 if (duration != m_UPnPLeaseDuration)
4672 m_UPnPLeaseDuration = duration;
4673 configureDeferred();
4677 int SessionImpl::peerToS() const
4679 return m_peerToS;
4682 void SessionImpl::setPeerToS(const int value)
4684 if (value == m_peerToS)
4685 return;
4687 m_peerToS = value;
4688 configureDeferred();
4691 bool SessionImpl::ignoreLimitsOnLAN() const
4693 return m_ignoreLimitsOnLAN;
4696 void SessionImpl::setIgnoreLimitsOnLAN(const bool ignore)
4698 if (ignore != m_ignoreLimitsOnLAN)
4700 m_ignoreLimitsOnLAN = ignore;
4701 configureDeferred();
4705 bool SessionImpl::includeOverheadInLimits() const
4707 return m_includeOverheadInLimits;
4710 void SessionImpl::setIncludeOverheadInLimits(const bool include)
4712 if (include != m_includeOverheadInLimits)
4714 m_includeOverheadInLimits = include;
4715 configureDeferred();
4719 QString SessionImpl::announceIP() const
4721 return m_announceIP;
4724 void SessionImpl::setAnnounceIP(const QString &ip)
4726 if (ip != m_announceIP)
4728 m_announceIP = ip;
4729 configureDeferred();
4733 int SessionImpl::maxConcurrentHTTPAnnounces() const
4735 return m_maxConcurrentHTTPAnnounces;
4738 void SessionImpl::setMaxConcurrentHTTPAnnounces(const int value)
4740 if (value == m_maxConcurrentHTTPAnnounces)
4741 return;
4743 m_maxConcurrentHTTPAnnounces = value;
4744 configureDeferred();
4747 bool SessionImpl::isReannounceWhenAddressChangedEnabled() const
4749 return m_isReannounceWhenAddressChangedEnabled;
4752 void SessionImpl::setReannounceWhenAddressChangedEnabled(const bool enabled)
4754 if (enabled == m_isReannounceWhenAddressChangedEnabled)
4755 return;
4757 m_isReannounceWhenAddressChangedEnabled = enabled;
4760 void SessionImpl::reannounceToAllTrackers() const
4762 for (const TorrentImpl *torrent : asConst(m_torrents))
4766 torrent->nativeHandle().force_reannounce(0, -1, lt::torrent_handle::ignore_min_interval);
4768 catch (const std::exception &) {}
4772 int SessionImpl::stopTrackerTimeout() const
4774 return m_stopTrackerTimeout;
4777 void SessionImpl::setStopTrackerTimeout(const int value)
4779 if (value == m_stopTrackerTimeout)
4780 return;
4782 m_stopTrackerTimeout = value;
4783 configureDeferred();
4786 int SessionImpl::maxConnections() const
4788 return m_maxConnections;
4791 void SessionImpl::setMaxConnections(int max)
4793 max = (max > 0) ? max : -1;
4794 if (max != m_maxConnections)
4796 m_maxConnections = max;
4797 configureDeferred();
4801 int SessionImpl::maxUploads() const
4803 return m_maxUploads;
4806 void SessionImpl::setMaxUploads(int max)
4808 max = (max > 0) ? max : -1;
4809 if (max != m_maxUploads)
4811 m_maxUploads = max;
4812 configureDeferred();
4816 BTProtocol SessionImpl::btProtocol() const
4818 return m_btProtocol;
4821 void SessionImpl::setBTProtocol(const BTProtocol protocol)
4823 if ((protocol < BTProtocol::Both) || (BTProtocol::UTP < protocol))
4824 return;
4826 if (protocol == m_btProtocol) return;
4828 m_btProtocol = protocol;
4829 configureDeferred();
4832 bool SessionImpl::isUTPRateLimited() const
4834 return m_isUTPRateLimited;
4837 void SessionImpl::setUTPRateLimited(const bool limited)
4839 if (limited != m_isUTPRateLimited)
4841 m_isUTPRateLimited = limited;
4842 configureDeferred();
4846 MixedModeAlgorithm SessionImpl::utpMixedMode() const
4848 return m_utpMixedMode;
4851 void SessionImpl::setUtpMixedMode(const MixedModeAlgorithm mode)
4853 if (mode == m_utpMixedMode) return;
4855 m_utpMixedMode = mode;
4856 configureDeferred();
4859 bool SessionImpl::isIDNSupportEnabled() const
4861 return m_IDNSupportEnabled;
4864 void SessionImpl::setIDNSupportEnabled(const bool enabled)
4866 if (enabled == m_IDNSupportEnabled) return;
4868 m_IDNSupportEnabled = enabled;
4869 configureDeferred();
4872 bool SessionImpl::multiConnectionsPerIpEnabled() const
4874 return m_multiConnectionsPerIpEnabled;
4877 void SessionImpl::setMultiConnectionsPerIpEnabled(const bool enabled)
4879 if (enabled == m_multiConnectionsPerIpEnabled) return;
4881 m_multiConnectionsPerIpEnabled = enabled;
4882 configureDeferred();
4885 bool SessionImpl::validateHTTPSTrackerCertificate() const
4887 return m_validateHTTPSTrackerCertificate;
4890 void SessionImpl::setValidateHTTPSTrackerCertificate(const bool enabled)
4892 if (enabled == m_validateHTTPSTrackerCertificate) return;
4894 m_validateHTTPSTrackerCertificate = enabled;
4895 configureDeferred();
4898 bool SessionImpl::isSSRFMitigationEnabled() const
4900 return m_SSRFMitigationEnabled;
4903 void SessionImpl::setSSRFMitigationEnabled(const bool enabled)
4905 if (enabled == m_SSRFMitigationEnabled) return;
4907 m_SSRFMitigationEnabled = enabled;
4908 configureDeferred();
4911 bool SessionImpl::blockPeersOnPrivilegedPorts() const
4913 return m_blockPeersOnPrivilegedPorts;
4916 void SessionImpl::setBlockPeersOnPrivilegedPorts(const bool enabled)
4918 if (enabled == m_blockPeersOnPrivilegedPorts) return;
4920 m_blockPeersOnPrivilegedPorts = enabled;
4921 configureDeferred();
4924 bool SessionImpl::isTrackerFilteringEnabled() const
4926 return m_isTrackerFilteringEnabled;
4929 void SessionImpl::setTrackerFilteringEnabled(const bool enabled)
4931 if (enabled != m_isTrackerFilteringEnabled)
4933 m_isTrackerFilteringEnabled = enabled;
4934 configureDeferred();
4938 bool SessionImpl::isListening() const
4940 return m_nativeSessionExtension->isSessionListening();
4943 ShareLimitAction SessionImpl::shareLimitAction() const
4945 return m_shareLimitAction;
4948 void SessionImpl::setShareLimitAction(const ShareLimitAction act)
4950 Q_ASSERT(act != ShareLimitAction::Default);
4952 m_shareLimitAction = act;
4955 bool SessionImpl::isKnownTorrent(const InfoHash &infoHash) const
4957 const bool isHybrid = infoHash.isHybrid();
4958 const auto id = TorrentID::fromInfoHash(infoHash);
4959 // alternative ID can be useful to find existing torrent
4960 // in case if hybrid torrent was added by v1 info hash
4961 const auto altID = (isHybrid ? TorrentID::fromSHA1Hash(infoHash.v1()) : TorrentID());
4963 if (m_loadingTorrents.contains(id) || (isHybrid && m_loadingTorrents.contains(altID)))
4964 return true;
4965 if (m_downloadedMetadata.contains(id) || (isHybrid && m_downloadedMetadata.contains(altID)))
4966 return true;
4967 return findTorrent(infoHash);
4970 void SessionImpl::updateSeedingLimitTimer()
4972 if ((globalMaxRatio() == Torrent::NO_RATIO_LIMIT) && !hasPerTorrentRatioLimit()
4973 && (globalMaxSeedingMinutes() == Torrent::NO_SEEDING_TIME_LIMIT) && !hasPerTorrentSeedingTimeLimit()
4974 && (globalMaxInactiveSeedingMinutes() == Torrent::NO_INACTIVE_SEEDING_TIME_LIMIT) && !hasPerTorrentInactiveSeedingTimeLimit())
4976 if (m_seedingLimitTimer->isActive())
4977 m_seedingLimitTimer->stop();
4979 else if (!m_seedingLimitTimer->isActive())
4981 m_seedingLimitTimer->start();
4985 void SessionImpl::handleTorrentShareLimitChanged(TorrentImpl *const)
4987 updateSeedingLimitTimer();
4990 void SessionImpl::handleTorrentNameChanged(TorrentImpl *const)
4994 void SessionImpl::handleTorrentSavePathChanged(TorrentImpl *const torrent)
4996 emit torrentSavePathChanged(torrent);
4999 void SessionImpl::handleTorrentCategoryChanged(TorrentImpl *const torrent, const QString &oldCategory)
5001 emit torrentCategoryChanged(torrent, oldCategory);
5004 void SessionImpl::handleTorrentTagAdded(TorrentImpl *const torrent, const Tag &tag)
5006 emit torrentTagAdded(torrent, tag);
5009 void SessionImpl::handleTorrentTagRemoved(TorrentImpl *const torrent, const Tag &tag)
5011 emit torrentTagRemoved(torrent, tag);
5014 void SessionImpl::handleTorrentSavingModeChanged(TorrentImpl *const torrent)
5016 emit torrentSavingModeChanged(torrent);
5019 void SessionImpl::handleTorrentTrackersAdded(TorrentImpl *const torrent, const QList<TrackerEntry> &newTrackers)
5021 for (const TrackerEntry &newTracker : newTrackers)
5022 LogMsg(tr("Added tracker to torrent. Torrent: \"%1\". Tracker: \"%2\"").arg(torrent->name(), newTracker.url));
5023 emit trackersAdded(torrent, newTrackers);
5026 void SessionImpl::handleTorrentTrackersRemoved(TorrentImpl *const torrent, const QStringList &deletedTrackers)
5028 for (const QString &deletedTracker : deletedTrackers)
5029 LogMsg(tr("Removed tracker from torrent. Torrent: \"%1\". Tracker: \"%2\"").arg(torrent->name(), deletedTracker));
5030 emit trackersRemoved(torrent, deletedTrackers);
5033 void SessionImpl::handleTorrentTrackersChanged(TorrentImpl *const torrent)
5035 emit trackersChanged(torrent);
5038 void SessionImpl::handleTorrentUrlSeedsAdded(TorrentImpl *const torrent, const QList<QUrl> &newUrlSeeds)
5040 for (const QUrl &newUrlSeed : newUrlSeeds)
5041 LogMsg(tr("Added URL seed to torrent. Torrent: \"%1\". URL: \"%2\"").arg(torrent->name(), newUrlSeed.toString()));
5044 void SessionImpl::handleTorrentUrlSeedsRemoved(TorrentImpl *const torrent, const QList<QUrl> &urlSeeds)
5046 for (const QUrl &urlSeed : urlSeeds)
5047 LogMsg(tr("Removed URL seed from torrent. Torrent: \"%1\". URL: \"%2\"").arg(torrent->name(), urlSeed.toString()));
5050 void SessionImpl::handleTorrentMetadataReceived(TorrentImpl *const torrent)
5052 if (!torrentExportDirectory().isEmpty())
5053 exportTorrentFile(torrent, torrentExportDirectory());
5055 emit torrentMetadataReceived(torrent);
5058 void SessionImpl::handleTorrentStopped(TorrentImpl *const torrent)
5060 torrent->resetTrackerEntryStatuses();
5062 const QList<TrackerEntryStatus> trackers = torrent->trackers();
5063 QHash<QString, TrackerEntryStatus> updatedTrackers;
5064 updatedTrackers.reserve(trackers.size());
5066 for (const TrackerEntryStatus &status : trackers)
5067 updatedTrackers.emplace(status.url, status);
5068 emit trackerEntryStatusesUpdated(torrent, updatedTrackers);
5070 LogMsg(tr("Torrent stopped. Torrent: \"%1\"").arg(torrent->name()));
5071 emit torrentStopped(torrent);
5074 void SessionImpl::handleTorrentStarted(TorrentImpl *const torrent)
5076 LogMsg(tr("Torrent resumed. Torrent: \"%1\"").arg(torrent->name()));
5077 emit torrentStarted(torrent);
5080 void SessionImpl::handleTorrentChecked(TorrentImpl *const torrent)
5082 emit torrentFinishedChecking(torrent);
5085 void SessionImpl::handleTorrentFinished(TorrentImpl *const torrent)
5087 m_pendingFinishedTorrents.append(torrent);
5090 void SessionImpl::handleTorrentResumeDataReady(TorrentImpl *const torrent, const LoadTorrentParams &data)
5092 m_resumeDataStorage->store(torrent->id(), data);
5093 const auto iter = m_changedTorrentIDs.find(torrent->id());
5094 if (iter != m_changedTorrentIDs.end())
5096 m_resumeDataStorage->remove(iter.value());
5097 m_changedTorrentIDs.erase(iter);
5101 void SessionImpl::handleTorrentInfoHashChanged(TorrentImpl *torrent, const InfoHash &prevInfoHash)
5103 Q_ASSERT(torrent->infoHash().isHybrid());
5105 m_hybridTorrentsByAltID.insert(TorrentID::fromSHA1Hash(torrent->infoHash().v1()), torrent);
5107 const auto prevID = TorrentID::fromInfoHash(prevInfoHash);
5108 const TorrentID currentID = torrent->id();
5109 if (currentID != prevID)
5111 m_torrents[torrent->id()] = m_torrents.take(prevID);
5112 m_changedTorrentIDs[torrent->id()] = prevID;
5116 void SessionImpl::handleTorrentStorageMovingStateChanged(TorrentImpl *torrent)
5118 emit torrentsUpdated({torrent});
5121 bool SessionImpl::addMoveTorrentStorageJob(TorrentImpl *torrent, const Path &newPath, const MoveStorageMode mode, const MoveStorageContext context)
5123 Q_ASSERT(torrent);
5125 const lt::torrent_handle torrentHandle = torrent->nativeHandle();
5126 const Path currentLocation = torrent->actualStorageLocation();
5127 const bool torrentHasActiveJob = !m_moveStorageQueue.isEmpty() && (m_moveStorageQueue.first().torrentHandle == torrentHandle);
5129 if (m_moveStorageQueue.size() > 1)
5131 auto iter = std::find_if((m_moveStorageQueue.begin() + 1), m_moveStorageQueue.end()
5132 , [&torrentHandle](const MoveStorageJob &job)
5134 return job.torrentHandle == torrentHandle;
5137 if (iter != m_moveStorageQueue.end())
5139 // remove existing inactive job
5140 torrent->handleMoveStorageJobFinished(currentLocation, iter->context, torrentHasActiveJob);
5141 LogMsg(tr("Torrent move canceled. Torrent: \"%1\". Source: \"%2\". Destination: \"%3\"").arg(torrent->name(), currentLocation.toString(), iter->path.toString()));
5142 m_moveStorageQueue.erase(iter);
5146 if (torrentHasActiveJob)
5148 // if there is active job for this torrent prevent creating meaningless
5149 // job that will move torrent to the same location as current one
5150 if (m_moveStorageQueue.first().path == newPath)
5152 LogMsg(tr("Failed to enqueue torrent move. Torrent: \"%1\". Source: \"%2\". Destination: \"%3\". Reason: torrent is currently moving to the destination")
5153 .arg(torrent->name(), currentLocation.toString(), newPath.toString()));
5154 return false;
5157 else
5159 if (currentLocation == newPath)
5161 LogMsg(tr("Failed to enqueue torrent move. Torrent: \"%1\". Source: \"%2\" Destination: \"%3\". Reason: both paths point to the same location")
5162 .arg(torrent->name(), currentLocation.toString(), newPath.toString()));
5163 return false;
5167 const MoveStorageJob moveStorageJob {torrentHandle, newPath, mode, context};
5168 m_moveStorageQueue << moveStorageJob;
5169 LogMsg(tr("Enqueued torrent move. Torrent: \"%1\". Source: \"%2\". Destination: \"%3\"").arg(torrent->name(), currentLocation.toString(), newPath.toString()));
5171 if (m_moveStorageQueue.size() == 1)
5172 moveTorrentStorage(moveStorageJob);
5174 return true;
5177 void SessionImpl::moveTorrentStorage(const MoveStorageJob &job) const
5179 #ifdef QBT_USES_LIBTORRENT2
5180 const auto id = TorrentID::fromInfoHash(job.torrentHandle.info_hashes());
5181 #else
5182 const auto id = TorrentID::fromInfoHash(job.torrentHandle.info_hash());
5183 #endif
5184 const TorrentImpl *torrent = m_torrents.value(id);
5185 const QString torrentName = (torrent ? torrent->name() : id.toString());
5186 LogMsg(tr("Start moving torrent. Torrent: \"%1\". Destination: \"%2\"").arg(torrentName, job.path.toString()));
5188 job.torrentHandle.move_storage(job.path.toString().toStdString(), toNative(job.mode));
5191 void SessionImpl::handleMoveTorrentStorageJobFinished(const Path &newPath)
5193 const MoveStorageJob finishedJob = m_moveStorageQueue.takeFirst();
5194 if (!m_moveStorageQueue.isEmpty())
5195 moveTorrentStorage(m_moveStorageQueue.first());
5197 const auto iter = std::find_if(m_moveStorageQueue.cbegin(), m_moveStorageQueue.cend()
5198 , [&finishedJob](const MoveStorageJob &job)
5200 return job.torrentHandle == finishedJob.torrentHandle;
5203 const bool torrentHasOutstandingJob = (iter != m_moveStorageQueue.cend());
5205 TorrentImpl *torrent = m_torrents.value(finishedJob.torrentHandle.info_hash());
5206 if (torrent)
5208 torrent->handleMoveStorageJobFinished(newPath, finishedJob.context, torrentHasOutstandingJob);
5210 else if (!torrentHasOutstandingJob)
5212 // Last job is completed for torrent that being removing, so actually remove it
5213 const lt::torrent_handle nativeHandle {finishedJob.torrentHandle};
5214 const RemovingTorrentData &removingTorrentData = m_removingTorrents[nativeHandle.info_hash()];
5215 if (removingTorrentData.removeOption == TorrentRemoveOption::KeepContent)
5216 m_nativeSession->remove_torrent(nativeHandle, lt::session::delete_partfile);
5220 void SessionImpl::storeCategories() const
5222 QJsonObject jsonObj;
5223 for (auto it = m_categories.cbegin(); it != m_categories.cend(); ++it)
5225 const QString &categoryName = it.key();
5226 const CategoryOptions &categoryOptions = it.value();
5227 jsonObj[categoryName] = categoryOptions.toJSON();
5230 const Path path = specialFolderLocation(SpecialFolder::Config) / CATEGORIES_FILE_NAME;
5231 const QByteArray data = QJsonDocument(jsonObj).toJson();
5232 const nonstd::expected<void, QString> result = Utils::IO::saveToFile(path, data);
5233 if (!result)
5235 LogMsg(tr("Failed to save Categories configuration. File: \"%1\". Error: \"%2\"")
5236 .arg(path.toString(), result.error()), Log::WARNING);
5240 void SessionImpl::upgradeCategories()
5242 const auto legacyCategories = SettingValue<QVariantMap>(u"BitTorrent/Session/Categories"_s).get();
5243 for (auto it = legacyCategories.cbegin(); it != legacyCategories.cend(); ++it)
5245 const QString &categoryName = it.key();
5246 CategoryOptions categoryOptions;
5247 categoryOptions.savePath = Path(it.value().toString());
5248 m_categories[categoryName] = categoryOptions;
5251 storeCategories();
5254 void SessionImpl::loadCategories()
5256 m_categories.clear();
5258 const Path path = specialFolderLocation(SpecialFolder::Config) / CATEGORIES_FILE_NAME;
5259 if (!path.exists())
5261 // TODO: Remove the following upgrade code in v4.5
5262 // == BEGIN UPGRADE CODE ==
5263 upgradeCategories();
5264 m_needUpgradeDownloadPath = true;
5265 // == END UPGRADE CODE ==
5267 // return;
5270 const int fileMaxSize = 1024 * 1024;
5271 const auto readResult = Utils::IO::readFile(path, fileMaxSize);
5272 if (!readResult)
5274 LogMsg(tr("Failed to load Categories. %1").arg(readResult.error().message), Log::WARNING);
5275 return;
5278 QJsonParseError jsonError;
5279 const QJsonDocument jsonDoc = QJsonDocument::fromJson(readResult.value(), &jsonError);
5280 if (jsonError.error != QJsonParseError::NoError)
5282 LogMsg(tr("Failed to parse Categories configuration. File: \"%1\". Error: \"%2\"")
5283 .arg(path.toString(), jsonError.errorString()), Log::WARNING);
5284 return;
5287 if (!jsonDoc.isObject())
5289 LogMsg(tr("Failed to load Categories configuration. File: \"%1\". Error: \"Invalid data format\"")
5290 .arg(path.toString()), Log::WARNING);
5291 return;
5294 const QJsonObject jsonObj = jsonDoc.object();
5295 for (auto it = jsonObj.constBegin(); it != jsonObj.constEnd(); ++it)
5297 const QString &categoryName = it.key();
5298 const auto categoryOptions = CategoryOptions::fromJSON(it.value().toObject());
5299 m_categories[categoryName] = categoryOptions;
5303 bool SessionImpl::hasPerTorrentRatioLimit() const
5305 return std::any_of(m_torrents.cbegin(), m_torrents.cend(), [](const TorrentImpl *torrent)
5307 return (torrent->ratioLimit() >= 0);
5311 bool SessionImpl::hasPerTorrentSeedingTimeLimit() const
5313 return std::any_of(m_torrents.cbegin(), m_torrents.cend(), [](const TorrentImpl *torrent)
5315 return (torrent->seedingTimeLimit() >= 0);
5319 bool SessionImpl::hasPerTorrentInactiveSeedingTimeLimit() const
5321 return std::any_of(m_torrents.cbegin(), m_torrents.cend(), [](const TorrentImpl *torrent)
5323 return (torrent->inactiveSeedingTimeLimit() >= 0);
5327 void SessionImpl::configureDeferred()
5329 if (m_deferredConfigureScheduled)
5330 return;
5332 m_deferredConfigureScheduled = true;
5333 QMetaObject::invokeMethod(this, qOverload<>(&SessionImpl::configure), Qt::QueuedConnection);
5336 // Enable IP Filtering
5337 // this method creates ban list from scratch combining user ban list and 3rd party ban list file
5338 void SessionImpl::enableIPFilter()
5340 qDebug("Enabling IPFilter");
5341 // 1. Parse the IP filter
5342 // 2. In the slot add the manually banned IPs to the provided lt::ip_filter
5343 // 3. Set the ip_filter in one go so there isn't a time window where there isn't an ip_filter
5344 // set between clearing the old one and setting the new one.
5345 if (!m_filterParser)
5347 m_filterParser = new FilterParserThread(this);
5348 connect(m_filterParser.data(), &FilterParserThread::IPFilterParsed, this, &SessionImpl::handleIPFilterParsed);
5349 connect(m_filterParser.data(), &FilterParserThread::IPFilterError, this, &SessionImpl::handleIPFilterError);
5351 m_filterParser->processFilterFile(IPFilterFile());
5354 // Disable IP Filtering
5355 void SessionImpl::disableIPFilter()
5357 qDebug("Disabling IPFilter");
5358 if (m_filterParser)
5360 disconnect(m_filterParser.data(), nullptr, this, nullptr);
5361 delete m_filterParser;
5364 // Add the banned IPs after the IPFilter disabling
5365 // which creates an empty filter and overrides all previously
5366 // applied bans.
5367 lt::ip_filter filter;
5368 processBannedIPs(filter);
5369 m_nativeSession->set_ip_filter(filter);
5372 const SessionStatus &SessionImpl::status() const
5374 return m_status;
5377 const CacheStatus &SessionImpl::cacheStatus() const
5379 return m_cacheStatus;
5382 void SessionImpl::enqueueRefresh()
5384 Q_ASSERT(!m_refreshEnqueued);
5386 QTimer::singleShot(refreshInterval(), Qt::CoarseTimer, this, [this]
5388 m_nativeSession->post_torrent_updates();
5389 m_nativeSession->post_session_stats();
5391 if (m_torrentsQueueChanged)
5393 m_torrentsQueueChanged = false;
5394 m_needSaveTorrentsQueue = true;
5398 m_refreshEnqueued = true;
5401 void SessionImpl::handleIPFilterParsed(const int ruleCount)
5403 if (m_filterParser)
5405 lt::ip_filter filter = m_filterParser->IPfilter();
5406 processBannedIPs(filter);
5407 m_nativeSession->set_ip_filter(filter);
5409 LogMsg(tr("Successfully parsed the IP filter file. Number of rules applied: %1").arg(ruleCount));
5410 emit IPFilterParsed(false, ruleCount);
5413 void SessionImpl::handleIPFilterError()
5415 lt::ip_filter filter;
5416 processBannedIPs(filter);
5417 m_nativeSession->set_ip_filter(filter);
5419 LogMsg(tr("Failed to parse the IP filter file"), Log::WARNING);
5420 emit IPFilterParsed(true, 0);
5423 std::vector<lt::alert *> SessionImpl::getPendingAlerts(const lt::time_duration time) const
5425 if (time > lt::time_duration::zero())
5426 m_nativeSession->wait_for_alert(time);
5428 std::vector<lt::alert *> alerts;
5429 m_nativeSession->pop_alerts(&alerts);
5430 return alerts;
5433 TorrentContentLayout SessionImpl::torrentContentLayout() const
5435 return m_torrentContentLayout;
5438 void SessionImpl::setTorrentContentLayout(const TorrentContentLayout value)
5440 m_torrentContentLayout = value;
5443 // Read alerts sent by libtorrent session
5444 void SessionImpl::readAlerts()
5446 const std::vector<lt::alert *> alerts = getPendingAlerts();
5448 Q_ASSERT(m_loadedTorrents.isEmpty());
5449 Q_ASSERT(m_receivedAddTorrentAlertsCount == 0);
5451 if (!isRestored())
5452 m_loadedTorrents.reserve(MAX_PROCESSING_RESUMEDATA_COUNT);
5454 for (const lt::alert *a : alerts)
5455 handleAlert(a);
5457 if (m_receivedAddTorrentAlertsCount > 0)
5459 emit addTorrentAlertsReceived(m_receivedAddTorrentAlertsCount);
5460 m_receivedAddTorrentAlertsCount = 0;
5462 if (!m_loadedTorrents.isEmpty())
5464 if (isRestored())
5465 m_torrentsQueueChanged = true;
5467 emit torrentsLoaded(m_loadedTorrents);
5468 m_loadedTorrents.clear();
5472 processTrackerStatuses();
5475 void SessionImpl::handleAddTorrentAlert(const lt::add_torrent_alert *alert)
5477 ++m_receivedAddTorrentAlertsCount;
5479 if (alert->error)
5481 const QString msg = QString::fromStdString(alert->message());
5482 LogMsg(tr("Failed to load torrent. Reason: \"%1\"").arg(msg), Log::WARNING);
5483 emit loadTorrentFailed(msg);
5485 const lt::add_torrent_params &params = alert->params;
5486 const bool hasMetadata = (params.ti && params.ti->is_valid());
5488 #ifdef QBT_USES_LIBTORRENT2
5489 const InfoHash infoHash {(hasMetadata ? params.ti->info_hashes() : params.info_hashes)};
5490 if (infoHash.isHybrid())
5491 m_hybridTorrentsByAltID.remove(TorrentID::fromSHA1Hash(infoHash.v1()));
5492 #else
5493 const InfoHash infoHash {(hasMetadata ? params.ti->info_hash() : params.info_hash)};
5494 #endif
5495 if (const auto loadingTorrentsIter = m_loadingTorrents.find(TorrentID::fromInfoHash(infoHash))
5496 ; loadingTorrentsIter != m_loadingTorrents.end())
5498 emit addTorrentFailed(infoHash, msg);
5499 m_loadingTorrents.erase(loadingTorrentsIter);
5501 else if (const auto downloadedMetadataIter = m_downloadedMetadata.find(TorrentID::fromInfoHash(infoHash))
5502 ; downloadedMetadataIter != m_downloadedMetadata.end())
5504 m_downloadedMetadata.erase(downloadedMetadataIter);
5505 if (infoHash.isHybrid())
5507 // index hybrid magnet links by both v1 and v2 info hashes
5508 const auto altID = TorrentID::fromSHA1Hash(infoHash.v1());
5509 m_downloadedMetadata.remove(altID);
5513 return;
5516 #ifdef QBT_USES_LIBTORRENT2
5517 const InfoHash infoHash {alert->handle.info_hashes()};
5518 #else
5519 const InfoHash infoHash {alert->handle.info_hash()};
5520 #endif
5521 const auto torrentID = TorrentID::fromInfoHash(infoHash);
5523 if (const auto loadingTorrentsIter = m_loadingTorrents.find(torrentID)
5524 ; loadingTorrentsIter != m_loadingTorrents.end())
5526 const LoadTorrentParams params = loadingTorrentsIter.value();
5527 m_loadingTorrents.erase(loadingTorrentsIter);
5529 Torrent *torrent = createTorrent(alert->handle, params);
5530 m_loadedTorrents.append(torrent);
5532 else if (const auto downloadedMetadataIter = m_downloadedMetadata.find(torrentID)
5533 ; downloadedMetadataIter != m_downloadedMetadata.end())
5535 downloadedMetadataIter.value() = alert->handle;
5536 if (infoHash.isHybrid())
5538 // index hybrid magnet links by both v1 and v2 info hashes
5539 const auto altID = TorrentID::fromSHA1Hash(infoHash.v1());
5540 m_downloadedMetadata[altID] = alert->handle;
5545 void SessionImpl::handleAlert(const lt::alert *alert)
5549 switch (alert->type())
5551 #ifdef QBT_USES_LIBTORRENT2
5552 case lt::file_prio_alert::alert_type:
5553 #endif
5554 case lt::file_renamed_alert::alert_type:
5555 case lt::file_rename_failed_alert::alert_type:
5556 case lt::file_completed_alert::alert_type:
5557 case lt::torrent_finished_alert::alert_type:
5558 case lt::save_resume_data_alert::alert_type:
5559 case lt::save_resume_data_failed_alert::alert_type:
5560 case lt::torrent_paused_alert::alert_type:
5561 case lt::torrent_resumed_alert::alert_type:
5562 case lt::fastresume_rejected_alert::alert_type:
5563 case lt::torrent_checked_alert::alert_type:
5564 case lt::metadata_received_alert::alert_type:
5565 case lt::performance_alert::alert_type:
5566 dispatchTorrentAlert(static_cast<const lt::torrent_alert *>(alert));
5567 break;
5568 case lt::state_update_alert::alert_type:
5569 handleStateUpdateAlert(static_cast<const lt::state_update_alert *>(alert));
5570 break;
5571 case lt::session_error_alert::alert_type:
5572 handleSessionErrorAlert(static_cast<const lt::session_error_alert *>(alert));
5573 break;
5574 case lt::session_stats_alert::alert_type:
5575 handleSessionStatsAlert(static_cast<const lt::session_stats_alert *>(alert));
5576 break;
5577 case lt::tracker_announce_alert::alert_type:
5578 case lt::tracker_error_alert::alert_type:
5579 case lt::tracker_reply_alert::alert_type:
5580 case lt::tracker_warning_alert::alert_type:
5581 handleTrackerAlert(static_cast<const lt::tracker_alert *>(alert));
5582 break;
5583 case lt::file_error_alert::alert_type:
5584 handleFileErrorAlert(static_cast<const lt::file_error_alert *>(alert));
5585 break;
5586 case lt::add_torrent_alert::alert_type:
5587 handleAddTorrentAlert(static_cast<const lt::add_torrent_alert *>(alert));
5588 break;
5589 case lt::torrent_removed_alert::alert_type:
5590 handleTorrentRemovedAlert(static_cast<const lt::torrent_removed_alert *>(alert));
5591 break;
5592 case lt::torrent_deleted_alert::alert_type:
5593 handleTorrentDeletedAlert(static_cast<const lt::torrent_deleted_alert *>(alert));
5594 break;
5595 case lt::torrent_delete_failed_alert::alert_type:
5596 handleTorrentDeleteFailedAlert(static_cast<const lt::torrent_delete_failed_alert *>(alert));
5597 break;
5598 case lt::torrent_need_cert_alert::alert_type:
5599 handleTorrentNeedCertAlert(static_cast<const lt::torrent_need_cert_alert *>(alert));
5600 break;
5601 case lt::portmap_error_alert::alert_type:
5602 handlePortmapWarningAlert(static_cast<const lt::portmap_error_alert *>(alert));
5603 break;
5604 case lt::portmap_alert::alert_type:
5605 handlePortmapAlert(static_cast<const lt::portmap_alert *>(alert));
5606 break;
5607 case lt::peer_blocked_alert::alert_type:
5608 handlePeerBlockedAlert(static_cast<const lt::peer_blocked_alert *>(alert));
5609 break;
5610 case lt::peer_ban_alert::alert_type:
5611 handlePeerBanAlert(static_cast<const lt::peer_ban_alert *>(alert));
5612 break;
5613 case lt::url_seed_alert::alert_type:
5614 handleUrlSeedAlert(static_cast<const lt::url_seed_alert *>(alert));
5615 break;
5616 case lt::listen_succeeded_alert::alert_type:
5617 handleListenSucceededAlert(static_cast<const lt::listen_succeeded_alert *>(alert));
5618 break;
5619 case lt::listen_failed_alert::alert_type:
5620 handleListenFailedAlert(static_cast<const lt::listen_failed_alert *>(alert));
5621 break;
5622 case lt::external_ip_alert::alert_type:
5623 handleExternalIPAlert(static_cast<const lt::external_ip_alert *>(alert));
5624 break;
5625 case lt::alerts_dropped_alert::alert_type:
5626 handleAlertsDroppedAlert(static_cast<const lt::alerts_dropped_alert *>(alert));
5627 break;
5628 case lt::storage_moved_alert::alert_type:
5629 handleStorageMovedAlert(static_cast<const lt::storage_moved_alert *>(alert));
5630 break;
5631 case lt::storage_moved_failed_alert::alert_type:
5632 handleStorageMovedFailedAlert(static_cast<const lt::storage_moved_failed_alert *>(alert));
5633 break;
5634 case lt::socks5_alert::alert_type:
5635 handleSocks5Alert(static_cast<const lt::socks5_alert *>(alert));
5636 break;
5637 case lt::i2p_alert::alert_type:
5638 handleI2PAlert(static_cast<const lt::i2p_alert *>(alert));
5639 break;
5640 #ifdef QBT_USES_LIBTORRENT2
5641 case lt::torrent_conflict_alert::alert_type:
5642 handleTorrentConflictAlert(static_cast<const lt::torrent_conflict_alert *>(alert));
5643 break;
5644 #endif
5647 catch (const std::exception &exc)
5649 qWarning() << "Caught exception in " << Q_FUNC_INFO << ": " << QString::fromStdString(exc.what());
5653 void SessionImpl::dispatchTorrentAlert(const lt::torrent_alert *alert)
5655 // The torrent can be deleted between the time the resume data was requested and
5656 // the time we received the appropriate alert. We have to decrease `m_numResumeData` anyway,
5657 // so we do this before checking for an existing torrent.
5658 if ((alert->type() == lt::save_resume_data_alert::alert_type)
5659 || (alert->type() == lt::save_resume_data_failed_alert::alert_type))
5661 --m_numResumeData;
5664 const TorrentID torrentID {alert->handle.info_hash()};
5665 TorrentImpl *torrent = m_torrents.value(torrentID);
5666 #ifdef QBT_USES_LIBTORRENT2
5667 if (!torrent && (alert->type() == lt::metadata_received_alert::alert_type))
5669 const InfoHash infoHash {alert->handle.info_hashes()};
5670 if (infoHash.isHybrid())
5671 torrent = m_torrents.value(TorrentID::fromSHA1Hash(infoHash.v1()));
5673 #endif
5675 if (torrent)
5677 torrent->handleAlert(alert);
5678 return;
5681 switch (alert->type())
5683 case lt::metadata_received_alert::alert_type:
5684 handleMetadataReceivedAlert(static_cast<const lt::metadata_received_alert *>(alert));
5685 break;
5689 TorrentImpl *SessionImpl::createTorrent(const lt::torrent_handle &nativeHandle, const LoadTorrentParams &params)
5691 auto *const torrent = new TorrentImpl(this, m_nativeSession, nativeHandle, params);
5692 m_torrents.insert(torrent->id(), torrent);
5693 if (const InfoHash infoHash = torrent->infoHash(); infoHash.isHybrid())
5694 m_hybridTorrentsByAltID.insert(TorrentID::fromSHA1Hash(infoHash.v1()), torrent);
5696 if (isRestored())
5698 if (params.addToQueueTop)
5699 nativeHandle.queue_position_top();
5701 torrent->requestResumeData(lt::torrent_handle::save_info_dict);
5703 // The following is useless for newly added magnet
5704 if (torrent->hasMetadata())
5706 if (!torrentExportDirectory().isEmpty())
5707 exportTorrentFile(torrent, torrentExportDirectory());
5711 if (((torrent->ratioLimit() >= 0) || (torrent->seedingTimeLimit() >= 0))
5712 && !m_seedingLimitTimer->isActive())
5714 m_seedingLimitTimer->start();
5717 if (!isRestored())
5719 LogMsg(tr("Restored torrent. Torrent: \"%1\"").arg(torrent->name()));
5721 else
5723 LogMsg(tr("Added new torrent. Torrent: \"%1\"").arg(torrent->name()));
5724 emit torrentAdded(torrent);
5727 // Torrent could have error just after adding to libtorrent
5728 if (torrent->hasError())
5729 LogMsg(tr("Torrent errored. Torrent: \"%1\". Error: \"%2\"").arg(torrent->name(), torrent->error()), Log::WARNING);
5731 return torrent;
5734 void SessionImpl::handleTorrentRemovedAlert(const lt::torrent_removed_alert */*alert*/)
5736 // We cannot consider `torrent_removed_alert` as a starting point for removing content,
5737 // because it has an inconsistent posting time between different versions of libtorrent,
5738 // so files may still be in use in some cases.
5741 void SessionImpl::handleTorrentDeletedAlert(const lt::torrent_deleted_alert *alert)
5743 #ifdef QBT_USES_LIBTORRENT2
5744 const auto torrentID = TorrentID::fromInfoHash(alert->info_hashes);
5745 #else
5746 const auto torrentID = TorrentID::fromInfoHash(alert->info_hash);
5747 #endif
5748 handleRemovedTorrent(torrentID);
5751 void SessionImpl::handleTorrentDeleteFailedAlert(const lt::torrent_delete_failed_alert *alert)
5753 #ifdef QBT_USES_LIBTORRENT2
5754 const auto torrentID = TorrentID::fromInfoHash(alert->info_hashes);
5755 #else
5756 const auto torrentID = TorrentID::fromInfoHash(alert->info_hash);
5757 #endif
5758 const auto errorMessage = alert->error ? QString::fromLocal8Bit(alert->error.message().c_str()) : QString();
5759 handleRemovedTorrent(torrentID, errorMessage);
5762 void SessionImpl::handleTorrentNeedCertAlert(const lt::torrent_need_cert_alert *alert)
5764 #ifdef QBT_USES_LIBTORRENT2
5765 const InfoHash infoHash {alert->handle.info_hashes()};
5766 #else
5767 const InfoHash infoHash {alert->handle.info_hash()};
5768 #endif
5769 const auto torrentID = TorrentID::fromInfoHash(infoHash);
5771 TorrentImpl *const torrent = m_torrents.value(torrentID);
5772 if (!torrent) [[unlikely]]
5773 return;
5775 if (!torrent->applySSLParameters())
5777 LogMsg(tr("Torrent is missing SSL parameters. Torrent: \"%1\". Message: \"%2\"").arg(torrent->name(), QString::fromStdString(alert->message()))
5778 , Log::WARNING);
5782 void SessionImpl::handleMetadataReceivedAlert(const lt::metadata_received_alert *alert)
5784 const TorrentID torrentID {alert->handle.info_hash()};
5786 bool found = false;
5787 if (const auto iter = m_downloadedMetadata.find(torrentID); iter != m_downloadedMetadata.end())
5789 found = true;
5790 m_downloadedMetadata.erase(iter);
5792 #ifdef QBT_USES_LIBTORRENT2
5793 const InfoHash infoHash {alert->handle.info_hashes()};
5794 if (infoHash.isHybrid())
5796 const auto altID = TorrentID::fromSHA1Hash(infoHash.v1());
5797 if (const auto iter = m_downloadedMetadata.find(altID); iter != m_downloadedMetadata.end())
5799 found = true;
5800 m_downloadedMetadata.erase(iter);
5803 #endif
5804 if (found)
5806 const TorrentInfo metadata {*alert->handle.torrent_file()};
5807 m_nativeSession->remove_torrent(alert->handle, lt::session::delete_files);
5809 emit metadataDownloaded(metadata);
5813 void SessionImpl::handleFileErrorAlert(const lt::file_error_alert *alert)
5815 TorrentImpl *const torrent = m_torrents.value(alert->handle.info_hash());
5816 if (!torrent)
5817 return;
5819 torrent->handleAlert(alert);
5821 const TorrentID id = torrent->id();
5822 if (!m_recentErroredTorrents.contains(id))
5824 m_recentErroredTorrents.insert(id);
5826 const QString msg = QString::fromStdString(alert->message());
5827 LogMsg(tr("File error alert. Torrent: \"%1\". File: \"%2\". Reason: \"%3\"")
5828 .arg(torrent->name(), QString::fromUtf8(alert->filename()), msg)
5829 , Log::WARNING);
5830 emit fullDiskError(torrent, msg);
5833 m_recentErroredTorrentsTimer->start();
5836 void SessionImpl::handlePortmapWarningAlert(const lt::portmap_error_alert *alert)
5838 LogMsg(tr("UPnP/NAT-PMP port mapping failed. Message: \"%1\"").arg(QString::fromStdString(alert->message())), Log::WARNING);
5841 void SessionImpl::handlePortmapAlert(const lt::portmap_alert *alert)
5843 qDebug("UPnP Success, msg: %s", alert->message().c_str());
5844 LogMsg(tr("UPnP/NAT-PMP port mapping succeeded. Message: \"%1\"").arg(QString::fromStdString(alert->message())), Log::INFO);
5847 void SessionImpl::handlePeerBlockedAlert(const lt::peer_blocked_alert *alert)
5849 QString reason;
5850 switch (alert->reason)
5852 case lt::peer_blocked_alert::ip_filter:
5853 reason = tr("IP filter", "this peer was blocked. Reason: IP filter.");
5854 break;
5855 case lt::peer_blocked_alert::port_filter:
5856 reason = tr("filtered port (%1)", "this peer was blocked. Reason: filtered port (8899).").arg(QString::number(alert->endpoint.port()));
5857 break;
5858 case lt::peer_blocked_alert::i2p_mixed:
5859 reason = tr("%1 mixed mode restrictions", "this peer was blocked. Reason: I2P mixed mode restrictions.").arg(u"I2P"_s); // don't translate I2P
5860 break;
5861 case lt::peer_blocked_alert::privileged_ports:
5862 reason = tr("privileged port (%1)", "this peer was blocked. Reason: privileged port (80).").arg(QString::number(alert->endpoint.port()));
5863 break;
5864 case lt::peer_blocked_alert::utp_disabled:
5865 reason = tr("%1 is disabled", "this peer was blocked. Reason: uTP is disabled.").arg(C_UTP); // don't translate μTP
5866 break;
5867 case lt::peer_blocked_alert::tcp_disabled:
5868 reason = tr("%1 is disabled", "this peer was blocked. Reason: TCP is disabled.").arg(u"TCP"_s); // don't translate TCP
5869 break;
5872 const QString ip {toString(alert->endpoint.address())};
5873 if (!ip.isEmpty())
5874 Logger::instance()->addPeer(ip, true, reason);
5877 void SessionImpl::handlePeerBanAlert(const lt::peer_ban_alert *alert)
5879 const QString ip {toString(alert->endpoint.address())};
5880 if (!ip.isEmpty())
5881 Logger::instance()->addPeer(ip, false);
5884 void SessionImpl::handleUrlSeedAlert(const lt::url_seed_alert *alert)
5886 const TorrentImpl *torrent = m_torrents.value(alert->handle.info_hash());
5887 if (!torrent)
5888 return;
5890 if (alert->error)
5892 LogMsg(tr("URL seed DNS lookup failed. Torrent: \"%1\". URL: \"%2\". Error: \"%3\"")
5893 .arg(torrent->name(), QString::fromUtf8(alert->server_url()), QString::fromStdString(alert->message()))
5894 , Log::WARNING);
5896 else
5898 LogMsg(tr("Received error message from URL seed. Torrent: \"%1\". URL: \"%2\". Message: \"%3\"")
5899 .arg(torrent->name(), QString::fromUtf8(alert->server_url()), QString::fromUtf8(alert->error_message()))
5900 , Log::WARNING);
5904 void SessionImpl::handleListenSucceededAlert(const lt::listen_succeeded_alert *alert)
5906 const QString proto {toString(alert->socket_type)};
5907 LogMsg(tr("Successfully listening on IP. IP: \"%1\". Port: \"%2/%3\"")
5908 .arg(toString(alert->address), proto, QString::number(alert->port)), Log::INFO);
5911 void SessionImpl::handleListenFailedAlert(const lt::listen_failed_alert *alert)
5913 const QString proto {toString(alert->socket_type)};
5914 LogMsg(tr("Failed to listen on IP. IP: \"%1\". Port: \"%2/%3\". Reason: \"%4\"")
5915 .arg(toString(alert->address), proto, QString::number(alert->port)
5916 , QString::fromLocal8Bit(alert->error.message().c_str())), Log::CRITICAL);
5919 void SessionImpl::handleExternalIPAlert(const lt::external_ip_alert *alert)
5921 const QString externalIP {toString(alert->external_address)};
5922 LogMsg(tr("Detected external IP. IP: \"%1\"")
5923 .arg(externalIP), Log::INFO);
5925 if (m_lastExternalIP != externalIP)
5927 if (isReannounceWhenAddressChangedEnabled() && !m_lastExternalIP.isEmpty())
5928 reannounceToAllTrackers();
5929 m_lastExternalIP = externalIP;
5933 void SessionImpl::handleSessionErrorAlert(const lt::session_error_alert *alert) const
5935 LogMsg(tr("BitTorrent session encountered a serious error. Reason: \"%1\"")
5936 .arg(QString::fromStdString(alert->message())), Log::CRITICAL);
5939 void SessionImpl::handleSessionStatsAlert(const lt::session_stats_alert *alert)
5941 if (m_refreshEnqueued)
5942 m_refreshEnqueued = false;
5943 else
5944 enqueueRefresh();
5946 const int64_t interval = lt::total_microseconds(alert->timestamp() - m_statsLastTimestamp);
5947 if (interval <= 0)
5948 return;
5950 m_statsLastTimestamp = alert->timestamp();
5952 const auto stats = alert->counters();
5954 m_status.hasIncomingConnections = static_cast<bool>(stats[m_metricIndices.net.hasIncomingConnections]);
5956 const int64_t ipOverheadDownload = stats[m_metricIndices.net.recvIPOverheadBytes];
5957 const int64_t ipOverheadUpload = stats[m_metricIndices.net.sentIPOverheadBytes];
5958 const int64_t totalDownload = stats[m_metricIndices.net.recvBytes] + ipOverheadDownload;
5959 const int64_t totalUpload = stats[m_metricIndices.net.sentBytes] + ipOverheadUpload;
5960 const int64_t totalPayloadDownload = stats[m_metricIndices.net.recvPayloadBytes];
5961 const int64_t totalPayloadUpload = stats[m_metricIndices.net.sentPayloadBytes];
5962 const int64_t trackerDownload = stats[m_metricIndices.net.recvTrackerBytes];
5963 const int64_t trackerUpload = stats[m_metricIndices.net.sentTrackerBytes];
5964 const int64_t dhtDownload = stats[m_metricIndices.dht.dhtBytesIn];
5965 const int64_t dhtUpload = stats[m_metricIndices.dht.dhtBytesOut];
5967 const auto calcRate = [interval](const qint64 previous, const qint64 current) -> qint64
5969 Q_ASSERT(current >= previous);
5970 Q_ASSERT(interval >= 0);
5971 return (((current - previous) * lt::microseconds(1s).count()) / interval);
5974 m_status.payloadDownloadRate = calcRate(m_status.totalPayloadDownload, totalPayloadDownload);
5975 m_status.payloadUploadRate = calcRate(m_status.totalPayloadUpload, totalPayloadUpload);
5976 m_status.downloadRate = calcRate(m_status.totalDownload, totalDownload);
5977 m_status.uploadRate = calcRate(m_status.totalUpload, totalUpload);
5978 m_status.ipOverheadDownloadRate = calcRate(m_status.ipOverheadDownload, ipOverheadDownload);
5979 m_status.ipOverheadUploadRate = calcRate(m_status.ipOverheadUpload, ipOverheadUpload);
5980 m_status.dhtDownloadRate = calcRate(m_status.dhtDownload, dhtDownload);
5981 m_status.dhtUploadRate = calcRate(m_status.dhtUpload, dhtUpload);
5982 m_status.trackerDownloadRate = calcRate(m_status.trackerDownload, trackerDownload);
5983 m_status.trackerUploadRate = calcRate(m_status.trackerUpload, trackerUpload);
5985 m_status.totalPayloadDownload = totalPayloadDownload;
5986 m_status.totalPayloadUpload = totalPayloadUpload;
5987 m_status.ipOverheadDownload = ipOverheadDownload;
5988 m_status.ipOverheadUpload = ipOverheadUpload;
5989 m_status.trackerDownload = trackerDownload;
5990 m_status.trackerUpload = trackerUpload;
5991 m_status.dhtDownload = dhtDownload;
5992 m_status.dhtUpload = dhtUpload;
5993 m_status.totalWasted = stats[m_metricIndices.net.recvRedundantBytes]
5994 + stats[m_metricIndices.net.recvFailedBytes];
5995 m_status.dhtNodes = stats[m_metricIndices.dht.dhtNodes];
5996 m_status.diskReadQueue = stats[m_metricIndices.peer.numPeersUpDisk];
5997 m_status.diskWriteQueue = stats[m_metricIndices.peer.numPeersDownDisk];
5998 m_status.peersCount = stats[m_metricIndices.peer.numPeersConnected];
6000 if (totalDownload > m_status.totalDownload)
6002 m_status.totalDownload = totalDownload;
6003 m_isStatisticsDirty = true;
6006 if (totalUpload > m_status.totalUpload)
6008 m_status.totalUpload = totalUpload;
6009 m_isStatisticsDirty = true;
6012 m_status.allTimeDownload = m_previouslyDownloaded + m_status.totalDownload;
6013 m_status.allTimeUpload = m_previouslyUploaded + m_status.totalUpload;
6015 if (m_statisticsLastUpdateTimer.hasExpired(STATISTICS_SAVE_INTERVAL))
6016 saveStatistics();
6018 m_cacheStatus.totalUsedBuffers = stats[m_metricIndices.disk.diskBlocksInUse];
6019 m_cacheStatus.jobQueueLength = stats[m_metricIndices.disk.queuedDiskJobs];
6021 #ifndef QBT_USES_LIBTORRENT2
6022 const int64_t numBlocksRead = stats[m_metricIndices.disk.numBlocksRead];
6023 const int64_t numBlocksCacheHits = stats[m_metricIndices.disk.numBlocksCacheHits];
6024 m_cacheStatus.readRatio = static_cast<qreal>(numBlocksCacheHits) / std::max<int64_t>((numBlocksCacheHits + numBlocksRead), 1);
6025 #endif
6027 const int64_t totalJobs = stats[m_metricIndices.disk.writeJobs] + stats[m_metricIndices.disk.readJobs]
6028 + stats[m_metricIndices.disk.hashJobs];
6029 m_cacheStatus.averageJobTime = (totalJobs > 0)
6030 ? (stats[m_metricIndices.disk.diskJobTime] / totalJobs) : 0;
6032 emit statsUpdated();
6035 void SessionImpl::handleAlertsDroppedAlert(const lt::alerts_dropped_alert *alert) const
6037 LogMsg(tr("Error: Internal alert queue is full and alerts are dropped, you might see degraded performance. Dropped alert type: \"%1\". Message: \"%2\"")
6038 .arg(QString::fromStdString(alert->dropped_alerts.to_string()), QString::fromStdString(alert->message())), Log::CRITICAL);
6041 void SessionImpl::handleStorageMovedAlert(const lt::storage_moved_alert *alert)
6043 Q_ASSERT(!m_moveStorageQueue.isEmpty());
6045 const MoveStorageJob &currentJob = m_moveStorageQueue.first();
6046 Q_ASSERT(currentJob.torrentHandle == alert->handle);
6048 const Path newPath {QString::fromUtf8(alert->storage_path())};
6049 Q_ASSERT(newPath == currentJob.path);
6051 #ifdef QBT_USES_LIBTORRENT2
6052 const auto id = TorrentID::fromInfoHash(currentJob.torrentHandle.info_hashes());
6053 #else
6054 const auto id = TorrentID::fromInfoHash(currentJob.torrentHandle.info_hash());
6055 #endif
6057 TorrentImpl *torrent = m_torrents.value(id);
6058 const QString torrentName = (torrent ? torrent->name() : id.toString());
6059 LogMsg(tr("Moved torrent successfully. Torrent: \"%1\". Destination: \"%2\"").arg(torrentName, newPath.toString()));
6061 handleMoveTorrentStorageJobFinished(newPath);
6064 void SessionImpl::handleStorageMovedFailedAlert(const lt::storage_moved_failed_alert *alert)
6066 Q_ASSERT(!m_moveStorageQueue.isEmpty());
6068 const MoveStorageJob &currentJob = m_moveStorageQueue.first();
6069 Q_ASSERT(currentJob.torrentHandle == alert->handle);
6071 #ifdef QBT_USES_LIBTORRENT2
6072 const auto id = TorrentID::fromInfoHash(currentJob.torrentHandle.info_hashes());
6073 #else
6074 const auto id = TorrentID::fromInfoHash(currentJob.torrentHandle.info_hash());
6075 #endif
6077 TorrentImpl *torrent = m_torrents.value(id);
6078 const QString torrentName = (torrent ? torrent->name() : id.toString());
6079 const Path currentLocation = (torrent ? torrent->actualStorageLocation()
6080 : Path(alert->handle.status(lt::torrent_handle::query_save_path).save_path));
6081 const QString errorMessage = QString::fromStdString(alert->message());
6082 LogMsg(tr("Failed to move torrent. Torrent: \"%1\". Source: \"%2\". Destination: \"%3\". Reason: \"%4\"")
6083 .arg(torrentName, currentLocation.toString(), currentJob.path.toString(), errorMessage), Log::WARNING);
6085 handleMoveTorrentStorageJobFinished(currentLocation);
6088 void SessionImpl::handleStateUpdateAlert(const lt::state_update_alert *alert)
6090 QList<Torrent *> updatedTorrents;
6091 updatedTorrents.reserve(static_cast<decltype(updatedTorrents)::size_type>(alert->status.size()));
6093 for (const lt::torrent_status &status : alert->status)
6095 #ifdef QBT_USES_LIBTORRENT2
6096 const auto id = TorrentID::fromInfoHash(status.info_hashes);
6097 #else
6098 const auto id = TorrentID::fromInfoHash(status.info_hash);
6099 #endif
6100 TorrentImpl *const torrent = m_torrents.value(id);
6101 if (!torrent)
6102 continue;
6104 torrent->handleStateUpdate(status);
6105 updatedTorrents.push_back(torrent);
6108 if (!updatedTorrents.isEmpty())
6109 emit torrentsUpdated(updatedTorrents);
6111 if (!m_pendingFinishedTorrents.isEmpty())
6113 for (TorrentImpl *torrent : m_pendingFinishedTorrents)
6115 LogMsg(tr("Torrent download finished. Torrent: \"%1\"").arg(torrent->name()));
6116 emit torrentFinished(torrent);
6118 if (const Path exportPath = finishedTorrentExportDirectory(); !exportPath.isEmpty())
6119 exportTorrentFile(torrent, exportPath);
6121 processTorrentShareLimits(torrent);
6124 m_pendingFinishedTorrents.clear();
6126 const bool hasUnfinishedTorrents = std::any_of(m_torrents.cbegin(), m_torrents.cend(), [](const TorrentImpl *torrent)
6128 return !(torrent->isFinished() || torrent->isStopped() || torrent->isErrored());
6130 if (!hasUnfinishedTorrents)
6131 emit allTorrentsFinished();
6134 if (m_needSaveTorrentsQueue)
6135 saveTorrentsQueue();
6137 if (m_refreshEnqueued)
6138 m_refreshEnqueued = false;
6139 else
6140 enqueueRefresh();
6143 void SessionImpl::handleSocks5Alert(const lt::socks5_alert *alert) const
6145 if (alert->error)
6147 const auto addr = alert->ip.address();
6148 const QString endpoint = (addr.is_v6() ? u"[%1]:%2"_s : u"%1:%2"_s)
6149 .arg(QString::fromStdString(addr.to_string()), QString::number(alert->ip.port()));
6150 LogMsg(tr("SOCKS5 proxy error. Address: %1. Message: \"%2\".")
6151 .arg(endpoint, QString::fromLocal8Bit(alert->error.message().c_str()))
6152 , Log::WARNING);
6156 void SessionImpl::handleI2PAlert(const lt::i2p_alert *alert) const
6158 if (alert->error)
6160 LogMsg(tr("I2P error. Message: \"%1\".")
6161 .arg(QString::fromStdString(alert->message())), Log::WARNING);
6165 void SessionImpl::handleTrackerAlert(const lt::tracker_alert *alert)
6167 TorrentImpl *torrent = m_torrents.value(alert->handle.info_hash());
6168 if (!torrent)
6169 return;
6171 QMap<int, int> &updateInfo = m_updatedTrackerStatuses[torrent->nativeHandle()][std::string(alert->tracker_url())][alert->local_endpoint];
6173 if (alert->type() == lt::tracker_reply_alert::alert_type)
6175 const int numPeers = static_cast<const lt::tracker_reply_alert *>(alert)->num_peers;
6176 #ifdef QBT_USES_LIBTORRENT2
6177 const int protocolVersionNum = (static_cast<const lt::tracker_reply_alert *>(alert)->version == lt::protocol_version::V1) ? 1 : 2;
6178 #else
6179 const int protocolVersionNum = 1;
6180 #endif
6181 updateInfo.insert(protocolVersionNum, numPeers);
6185 #ifdef QBT_USES_LIBTORRENT2
6186 void SessionImpl::handleTorrentConflictAlert(const lt::torrent_conflict_alert *alert)
6188 const auto torrentIDv1 = TorrentID::fromSHA1Hash(alert->metadata->info_hashes().v1);
6189 const auto torrentIDv2 = TorrentID::fromSHA256Hash(alert->metadata->info_hashes().v2);
6190 TorrentImpl *torrent1 = m_torrents.value(torrentIDv1);
6191 TorrentImpl *torrent2 = m_torrents.value(torrentIDv2);
6192 if (torrent2)
6194 if (torrent1)
6195 removeTorrent(torrentIDv1);
6196 else
6197 cancelDownloadMetadata(torrentIDv1);
6199 invokeAsync([torrentHandle = torrent2->nativeHandle(), metadata = alert->metadata]
6203 torrentHandle.set_metadata(metadata->info_section());
6205 catch (const std::exception &) {}
6208 else if (torrent1)
6210 if (!torrent2)
6211 cancelDownloadMetadata(torrentIDv2);
6213 invokeAsync([torrentHandle = torrent1->nativeHandle(), metadata = alert->metadata]
6217 torrentHandle.set_metadata(metadata->info_section());
6219 catch (const std::exception &) {}
6222 else
6224 cancelDownloadMetadata(torrentIDv1);
6225 cancelDownloadMetadata(torrentIDv2);
6228 if (!torrent1 || !torrent2)
6229 emit metadataDownloaded(TorrentInfo(*alert->metadata));
6231 #endif
6233 void SessionImpl::processTrackerStatuses()
6235 if (m_updatedTrackerStatuses.isEmpty())
6236 return;
6238 for (auto it = m_updatedTrackerStatuses.cbegin(); it != m_updatedTrackerStatuses.cend(); ++it)
6239 updateTrackerEntryStatuses(it.key(), it.value());
6241 m_updatedTrackerStatuses.clear();
6244 void SessionImpl::saveStatistics() const
6246 if (!m_isStatisticsDirty)
6247 return;
6249 const QVariantHash stats {
6250 {u"AlltimeDL"_s, m_status.allTimeDownload},
6251 {u"AlltimeUL"_s, m_status.allTimeUpload}};
6252 std::unique_ptr<QSettings> settings = Profile::instance()->applicationSettings(u"qBittorrent-data"_s);
6253 settings->setValue(u"Stats/AllStats"_s, stats);
6255 m_statisticsLastUpdateTimer.start();
6256 m_isStatisticsDirty = false;
6259 void SessionImpl::loadStatistics()
6261 const std::unique_ptr<QSettings> settings = Profile::instance()->applicationSettings(u"qBittorrent-data"_s);
6262 const QVariantHash value = settings->value(u"Stats/AllStats"_s).toHash();
6264 m_previouslyDownloaded = value[u"AlltimeDL"_s].toLongLong();
6265 m_previouslyUploaded = value[u"AlltimeUL"_s].toLongLong();
6268 void SessionImpl::updateTrackerEntryStatuses(lt::torrent_handle torrentHandle, QHash<std::string, QHash<lt::tcp::endpoint, QMap<int, int>>> updatedTrackers)
6270 invokeAsync([this, torrentHandle = std::move(torrentHandle), updatedTrackers = std::move(updatedTrackers)]() mutable
6274 std::vector<lt::announce_entry> nativeTrackers = torrentHandle.trackers();
6275 invoke([this, torrentHandle, nativeTrackers = std::move(nativeTrackers)
6276 , updatedTrackers = std::move(updatedTrackers)]
6278 TorrentImpl *torrent = m_torrents.value(torrentHandle.info_hash());
6279 if (!torrent || torrent->isStopped())
6280 return;
6282 QHash<QString, TrackerEntryStatus> trackers;
6283 trackers.reserve(updatedTrackers.size());
6284 for (const lt::announce_entry &announceEntry : nativeTrackers)
6286 const auto updatedTrackersIter = updatedTrackers.find(announceEntry.url);
6287 if (updatedTrackersIter == updatedTrackers.end())
6288 continue;
6290 const auto &updateInfo = updatedTrackersIter.value();
6291 TrackerEntryStatus status = torrent->updateTrackerEntryStatus(announceEntry, updateInfo);
6292 const QString url = status.url;
6293 trackers.emplace(url, std::move(status));
6296 emit trackerEntryStatusesUpdated(torrent, trackers);
6299 catch (const std::exception &)
6305 void SessionImpl::handleRemovedTorrent(const TorrentID &torrentID, const QString &partfileRemoveError)
6307 const auto removingTorrentDataIter = m_removingTorrents.find(torrentID);
6308 if (removingTorrentDataIter == m_removingTorrents.end())
6309 return;
6311 if (!partfileRemoveError.isEmpty())
6313 LogMsg(tr("Failed to remove partfile. Torrent: \"%1\". Reason: \"%2\".")
6314 .arg(removingTorrentDataIter->name, partfileRemoveError)
6315 , Log::WARNING);
6318 if ((removingTorrentDataIter->removeOption == TorrentRemoveOption::RemoveContent)
6319 && !removingTorrentDataIter->contentStoragePath.isEmpty())
6321 QMetaObject::invokeMethod(m_torrentContentRemover, [this, jobData = *removingTorrentDataIter]
6323 m_torrentContentRemover->performJob(jobData.name, jobData.contentStoragePath
6324 , jobData.fileNames, m_torrentContentRemoveOption);
6328 m_removingTorrents.erase(removingTorrentDataIter);