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"
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>
64 #include <QHostAddress>
66 #include <QJsonDocument>
67 #include <QJsonObject>
69 #include <QNetworkAddressEntry>
70 #include <QNetworkInterface>
71 #include <QRegularExpression>
74 #include <QThreadPool>
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"
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;
118 const char PEER_ID
[] = "qB";
119 const auto USER_AGENT
= QStringLiteral("qBittorrent/" QBT_VERSION_2
);
120 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
;
122 void torrentQueuePositionUp(const lt::torrent_handle
&handle
)
126 handle
.queue_position_up();
128 catch (const std::exception
&exc
)
130 qDebug() << Q_FUNC_INFO
<< " fails: " << exc
.what();
134 void torrentQueuePositionDown(const lt::torrent_handle
&handle
)
138 handle
.queue_position_down();
140 catch (const std::exception
&exc
)
142 qDebug() << Q_FUNC_INFO
<< " fails: " << exc
.what();
146 void torrentQueuePositionTop(const lt::torrent_handle
&handle
)
150 handle
.queue_position_top();
152 catch (const std::exception
&exc
)
154 qDebug() << Q_FUNC_INFO
<< " fails: " << exc
.what();
158 void torrentQueuePositionBottom(const lt::torrent_handle
&handle
)
162 handle
.queue_position_bottom();
164 catch (const std::exception
&exc
)
166 qDebug() << Q_FUNC_INFO
<< " fails: " << exc
.what();
170 QMap
<QString
, CategoryOptions
> expandCategories(const QMap
<QString
, CategoryOptions
> &categories
)
172 QMap
<QString
, CategoryOptions
> expanded
= categories
;
174 for (auto i
= categories
.cbegin(); i
!= categories
.cend(); ++i
)
176 const QString
&category
= i
.key();
177 for (const QString
&subcat
: asConst(Session::expandCategory(category
)))
179 if (!expanded
.contains(subcat
))
180 expanded
[subcat
] = {};
187 QString
toString(const lt::socket_type_t socketType
)
191 #ifdef QBT_USES_LIBTORRENT2
192 case lt::socket_type_t::http
:
194 case lt::socket_type_t::http_ssl
:
195 return u
"HTTP_SSL"_s
;
197 case lt::socket_type_t::i2p
:
199 case lt::socket_type_t::socks5
:
201 #ifdef QBT_USES_LIBTORRENT2
202 case lt::socket_type_t::socks5_ssl
:
203 return u
"SOCKS5_SSL"_s
;
205 case lt::socket_type_t::tcp
:
207 case lt::socket_type_t::tcp_ssl
:
209 #ifdef QBT_USES_LIBTORRENT2
210 case lt::socket_type_t::utp
:
213 case lt::socket_type_t::udp
:
216 case lt::socket_type_t::utp_ssl
:
222 QString
toString(const lt::address
&address
)
226 return QString::fromLatin1(address
.to_string().c_str());
228 catch (const std::exception
&)
230 // suppress conversion error
235 template <typename T
>
238 LowerLimited(T limit
, T ret
)
244 explicit LowerLimited(T limit
)
245 : LowerLimited(limit
, limit
)
249 T
operator()(T val
) const
251 return val
<= m_limit
? m_ret
: val
;
259 template <typename T
>
260 LowerLimited
<T
> lowerLimited(T limit
) { return LowerLimited
<T
>(limit
); }
262 template <typename T
>
263 LowerLimited
<T
> lowerLimited(T limit
, T ret
) { return LowerLimited
<T
>(limit
, ret
); }
265 template <typename T
>
266 auto clampValue(const T lower
, const T upper
)
268 return [lower
, upper
](const T value
) -> T
270 return std::clamp(value
, lower
, upper
);
275 QString
convertIfaceNameToGuid(const QString
&name
)
277 // Under Windows XP or on Qt version <= 5.5 'name' will be a GUID already.
278 const QUuid
uuid(name
);
280 return uuid
.toString().toUpper(); // Libtorrent expects the GUID in uppercase
282 const std::wstring nameWStr
= name
.toStdWString();
284 const LONG res
= ::ConvertInterfaceNameToLuidW(nameWStr
.c_str(), &luid
);
288 if (::ConvertInterfaceLuidToGuid(&luid
, &guid
) == 0)
289 return QUuid(guid
).toString().toUpper();
296 constexpr lt::move_flags_t
toNative(const MoveStorageMode mode
)
302 case MoveStorageMode::FailIfExist
:
303 return lt::move_flags_t::fail_if_exist
;
304 case MoveStorageMode::KeepExistingFiles
:
305 return lt::move_flags_t::dont_replace
;
306 case MoveStorageMode::Overwrite
:
307 return lt::move_flags_t::always_replace_files
;
312 struct BitTorrent::SessionImpl::ResumeSessionContext final
: public QObject
314 using QObject::QObject
;
316 ResumeDataStorage
*startupStorage
= nullptr;
317 ResumeDataStorageType currentStorageType
= ResumeDataStorageType::Legacy
;
318 QList
<LoadedResumeData
> loadedResumeData
;
319 int processingResumeDataCount
= 0;
320 int64_t totalResumeDataCount
= 0;
321 int64_t finishedResumeDataCount
= 0;
322 bool isLoadFinished
= false;
323 bool isLoadedResumeDataHandlingEnqueued
= false;
324 QSet
<QString
> recoveredCategories
;
325 #ifdef QBT_USES_LIBTORRENT2
326 QSet
<TorrentID
> indexedTorrents
;
327 QSet
<TorrentID
> skippedIDs
;
331 const int addTorrentParamsId
= qRegisterMetaType
<AddTorrentParams
>();
333 Session
*SessionImpl::m_instance
= nullptr;
335 void Session::initInstance()
337 if (!SessionImpl::m_instance
)
338 SessionImpl::m_instance
= new SessionImpl
;
341 void Session::freeInstance()
343 delete SessionImpl::m_instance
;
344 SessionImpl::m_instance
= nullptr;
347 Session
*Session::instance()
349 return SessionImpl::m_instance
;
352 bool Session::isValidCategoryName(const QString
&name
)
354 const QRegularExpression re
{uR
"(^([^\\\/]|[^\\\/]([^\\\/]|\/(?=[^\/]))*[^\\\/])$)"_s
};
355 return (name
.isEmpty() || (name
.indexOf(re
) == 0));
358 QString
Session::subcategoryName(const QString
&category
)
360 const int sepIndex
= category
.lastIndexOf(u
'/');
362 return category
.mid(sepIndex
+ 1);
367 QString
Session::parentCategoryName(const QString
&category
)
369 const int sepIndex
= category
.lastIndexOf(u
'/');
371 return category
.left(sepIndex
);
376 QStringList
Session::expandCategory(const QString
&category
)
380 while ((index
= category
.indexOf(u
'/', index
)) >= 0)
382 result
<< category
.left(index
);
390 #define BITTORRENT_KEY(name) u"BitTorrent/" name
391 #define BITTORRENT_SESSION_KEY(name) BITTORRENT_KEY(u"Session/") name
393 SessionImpl::SessionImpl(QObject
*parent
)
395 , m_DHTBootstrapNodes(BITTORRENT_SESSION_KEY(u
"DHTBootstrapNodes"_s
), DEFAULT_DHT_BOOTSTRAP_NODES
)
396 , m_isDHTEnabled(BITTORRENT_SESSION_KEY(u
"DHTEnabled"_s
), true)
397 , m_isLSDEnabled(BITTORRENT_SESSION_KEY(u
"LSDEnabled"_s
), true)
398 , m_isPeXEnabled(BITTORRENT_SESSION_KEY(u
"PeXEnabled"_s
), true)
399 , m_isIPFilteringEnabled(BITTORRENT_SESSION_KEY(u
"IPFilteringEnabled"_s
), false)
400 , m_isTrackerFilteringEnabled(BITTORRENT_SESSION_KEY(u
"TrackerFilteringEnabled"_s
), false)
401 , m_IPFilterFile(BITTORRENT_SESSION_KEY(u
"IPFilter"_s
))
402 , m_announceToAllTrackers(BITTORRENT_SESSION_KEY(u
"AnnounceToAllTrackers"_s
), false)
403 , m_announceToAllTiers(BITTORRENT_SESSION_KEY(u
"AnnounceToAllTiers"_s
), true)
404 , m_asyncIOThreads(BITTORRENT_SESSION_KEY(u
"AsyncIOThreadsCount"_s
), 10)
405 , m_hashingThreads(BITTORRENT_SESSION_KEY(u
"HashingThreadsCount"_s
), 1)
406 , m_filePoolSize(BITTORRENT_SESSION_KEY(u
"FilePoolSize"_s
), 100)
407 , m_checkingMemUsage(BITTORRENT_SESSION_KEY(u
"CheckingMemUsageSize"_s
), 32)
408 , m_diskCacheSize(BITTORRENT_SESSION_KEY(u
"DiskCacheSize"_s
), -1)
409 , m_diskCacheTTL(BITTORRENT_SESSION_KEY(u
"DiskCacheTTL"_s
), 60)
410 , m_diskQueueSize(BITTORRENT_SESSION_KEY(u
"DiskQueueSize"_s
), (1024 * 1024))
411 , m_diskIOType(BITTORRENT_SESSION_KEY(u
"DiskIOType"_s
), DiskIOType::Default
)
412 , m_diskIOReadMode(BITTORRENT_SESSION_KEY(u
"DiskIOReadMode"_s
), DiskIOReadMode::EnableOSCache
)
413 , m_diskIOWriteMode(BITTORRENT_SESSION_KEY(u
"DiskIOWriteMode"_s
), DiskIOWriteMode::EnableOSCache
)
415 , m_coalesceReadWriteEnabled(BITTORRENT_SESSION_KEY(u
"CoalesceReadWrite"_s
), true)
417 , m_coalesceReadWriteEnabled(BITTORRENT_SESSION_KEY(u
"CoalesceReadWrite"_s
), false)
419 , m_usePieceExtentAffinity(BITTORRENT_SESSION_KEY(u
"PieceExtentAffinity"_s
), false)
420 , m_isSuggestMode(BITTORRENT_SESSION_KEY(u
"SuggestMode"_s
), false)
421 , m_sendBufferWatermark(BITTORRENT_SESSION_KEY(u
"SendBufferWatermark"_s
), 500)
422 , m_sendBufferLowWatermark(BITTORRENT_SESSION_KEY(u
"SendBufferLowWatermark"_s
), 10)
423 , m_sendBufferWatermarkFactor(BITTORRENT_SESSION_KEY(u
"SendBufferWatermarkFactor"_s
), 50)
424 , m_connectionSpeed(BITTORRENT_SESSION_KEY(u
"ConnectionSpeed"_s
), 30)
425 , m_socketSendBufferSize(BITTORRENT_SESSION_KEY(u
"SocketSendBufferSize"_s
), 0)
426 , m_socketReceiveBufferSize(BITTORRENT_SESSION_KEY(u
"SocketReceiveBufferSize"_s
), 0)
427 , m_socketBacklogSize(BITTORRENT_SESSION_KEY(u
"SocketBacklogSize"_s
), 30)
428 , m_isAnonymousModeEnabled(BITTORRENT_SESSION_KEY(u
"AnonymousModeEnabled"_s
), false)
429 , m_isQueueingEnabled(BITTORRENT_SESSION_KEY(u
"QueueingSystemEnabled"_s
), false)
430 , m_maxActiveDownloads(BITTORRENT_SESSION_KEY(u
"MaxActiveDownloads"_s
), 3, lowerLimited(-1))
431 , m_maxActiveUploads(BITTORRENT_SESSION_KEY(u
"MaxActiveUploads"_s
), 3, lowerLimited(-1))
432 , m_maxActiveTorrents(BITTORRENT_SESSION_KEY(u
"MaxActiveTorrents"_s
), 5, lowerLimited(-1))
433 , m_ignoreSlowTorrentsForQueueing(BITTORRENT_SESSION_KEY(u
"IgnoreSlowTorrentsForQueueing"_s
), false)
434 , m_downloadRateForSlowTorrents(BITTORRENT_SESSION_KEY(u
"SlowTorrentsDownloadRate"_s
), 2)
435 , m_uploadRateForSlowTorrents(BITTORRENT_SESSION_KEY(u
"SlowTorrentsUploadRate"_s
), 2)
436 , m_slowTorrentsInactivityTimer(BITTORRENT_SESSION_KEY(u
"SlowTorrentsInactivityTimer"_s
), 60)
437 , m_outgoingPortsMin(BITTORRENT_SESSION_KEY(u
"OutgoingPortsMin"_s
), 0)
438 , m_outgoingPortsMax(BITTORRENT_SESSION_KEY(u
"OutgoingPortsMax"_s
), 0)
439 , m_UPnPLeaseDuration(BITTORRENT_SESSION_KEY(u
"UPnPLeaseDuration"_s
), 0)
440 , m_peerToS(BITTORRENT_SESSION_KEY(u
"PeerToS"_s
), 0x04)
441 , m_ignoreLimitsOnLAN(BITTORRENT_SESSION_KEY(u
"IgnoreLimitsOnLAN"_s
), false)
442 , m_includeOverheadInLimits(BITTORRENT_SESSION_KEY(u
"IncludeOverheadInLimits"_s
), false)
443 , m_announceIP(BITTORRENT_SESSION_KEY(u
"AnnounceIP"_s
))
444 , m_maxConcurrentHTTPAnnounces(BITTORRENT_SESSION_KEY(u
"MaxConcurrentHTTPAnnounces"_s
), 50)
445 , m_isReannounceWhenAddressChangedEnabled(BITTORRENT_SESSION_KEY(u
"ReannounceWhenAddressChanged"_s
), false)
446 , m_stopTrackerTimeout(BITTORRENT_SESSION_KEY(u
"StopTrackerTimeout"_s
), 2)
447 , m_maxConnections(BITTORRENT_SESSION_KEY(u
"MaxConnections"_s
), 500, lowerLimited(0, -1))
448 , m_maxUploads(BITTORRENT_SESSION_KEY(u
"MaxUploads"_s
), 20, lowerLimited(0, -1))
449 , m_maxConnectionsPerTorrent(BITTORRENT_SESSION_KEY(u
"MaxConnectionsPerTorrent"_s
), 100, lowerLimited(0, -1))
450 , m_maxUploadsPerTorrent(BITTORRENT_SESSION_KEY(u
"MaxUploadsPerTorrent"_s
), 4, lowerLimited(0, -1))
451 , m_btProtocol(BITTORRENT_SESSION_KEY(u
"BTProtocol"_s
), BTProtocol::Both
452 , clampValue(BTProtocol::Both
, BTProtocol::UTP
))
453 , m_isUTPRateLimited(BITTORRENT_SESSION_KEY(u
"uTPRateLimited"_s
), true)
454 , m_utpMixedMode(BITTORRENT_SESSION_KEY(u
"uTPMixedMode"_s
), MixedModeAlgorithm::TCP
455 , clampValue(MixedModeAlgorithm::TCP
, MixedModeAlgorithm::Proportional
))
456 , m_IDNSupportEnabled(BITTORRENT_SESSION_KEY(u
"IDNSupportEnabled"_s
), false)
457 , m_multiConnectionsPerIpEnabled(BITTORRENT_SESSION_KEY(u
"MultiConnectionsPerIp"_s
), false)
458 , m_validateHTTPSTrackerCertificate(BITTORRENT_SESSION_KEY(u
"ValidateHTTPSTrackerCertificate"_s
), true)
459 , m_SSRFMitigationEnabled(BITTORRENT_SESSION_KEY(u
"SSRFMitigation"_s
), true)
460 , m_blockPeersOnPrivilegedPorts(BITTORRENT_SESSION_KEY(u
"BlockPeersOnPrivilegedPorts"_s
), false)
461 , m_isAddTrackersEnabled(BITTORRENT_SESSION_KEY(u
"AddTrackersEnabled"_s
), false)
462 , m_additionalTrackers(BITTORRENT_SESSION_KEY(u
"AdditionalTrackers"_s
))
463 , m_globalMaxRatio(BITTORRENT_SESSION_KEY(u
"GlobalMaxRatio"_s
), -1, [](qreal r
) { return r
< 0 ? -1. : r
;})
464 , m_globalMaxSeedingMinutes(BITTORRENT_SESSION_KEY(u
"GlobalMaxSeedingMinutes"_s
), -1, lowerLimited(-1))
465 , m_globalMaxInactiveSeedingMinutes(BITTORRENT_SESSION_KEY(u
"GlobalMaxInactiveSeedingMinutes"_s
), -1, lowerLimited(-1))
466 , m_isAddTorrentToQueueTop(BITTORRENT_SESSION_KEY(u
"AddTorrentToTopOfQueue"_s
), false)
467 , m_isAddTorrentStopped(BITTORRENT_SESSION_KEY(u
"AddTorrentStopped"_s
), false)
468 , m_torrentStopCondition(BITTORRENT_SESSION_KEY(u
"TorrentStopCondition"_s
), Torrent::StopCondition::None
)
469 , m_torrentContentLayout(BITTORRENT_SESSION_KEY(u
"TorrentContentLayout"_s
), TorrentContentLayout::Original
)
470 , m_isAppendExtensionEnabled(BITTORRENT_SESSION_KEY(u
"AddExtensionToIncompleteFiles"_s
), false)
471 , m_isUnwantedFolderEnabled(BITTORRENT_SESSION_KEY(u
"UseUnwantedFolder"_s
), false)
472 , m_refreshInterval(BITTORRENT_SESSION_KEY(u
"RefreshInterval"_s
), 1500)
473 , m_isPreallocationEnabled(BITTORRENT_SESSION_KEY(u
"Preallocation"_s
), false)
474 , m_torrentExportDirectory(BITTORRENT_SESSION_KEY(u
"TorrentExportDirectory"_s
))
475 , m_finishedTorrentExportDirectory(BITTORRENT_SESSION_KEY(u
"FinishedTorrentExportDirectory"_s
))
476 , m_globalDownloadSpeedLimit(BITTORRENT_SESSION_KEY(u
"GlobalDLSpeedLimit"_s
), 0, lowerLimited(0))
477 , m_globalUploadSpeedLimit(BITTORRENT_SESSION_KEY(u
"GlobalUPSpeedLimit"_s
), 0, lowerLimited(0))
478 , m_altGlobalDownloadSpeedLimit(BITTORRENT_SESSION_KEY(u
"AlternativeGlobalDLSpeedLimit"_s
), 10, lowerLimited(0))
479 , m_altGlobalUploadSpeedLimit(BITTORRENT_SESSION_KEY(u
"AlternativeGlobalUPSpeedLimit"_s
), 10, lowerLimited(0))
480 , m_isAltGlobalSpeedLimitEnabled(BITTORRENT_SESSION_KEY(u
"UseAlternativeGlobalSpeedLimit"_s
), false)
481 , m_isBandwidthSchedulerEnabled(BITTORRENT_SESSION_KEY(u
"BandwidthSchedulerEnabled"_s
), false)
482 , m_isPerformanceWarningEnabled(BITTORRENT_SESSION_KEY(u
"PerformanceWarning"_s
), false)
483 , m_saveResumeDataInterval(BITTORRENT_SESSION_KEY(u
"SaveResumeDataInterval"_s
), 60)
484 , m_saveStatisticsInterval(BITTORRENT_SESSION_KEY(u
"SaveStatisticsInterval"_s
), 15)
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);
541 m_port
= Utils::Random::rand(1024, 65535);
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();
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())
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
);
608 // initialize PortForwarder instance
609 new PortForwarderImpl(this);
611 // start embedded tracker
612 enableTracker(isTrackerEnabled());
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
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."));
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
)
681 m_DHTBootstrapNodes
= nodes
;
685 bool SessionImpl::isDHTEnabled() const
687 return m_isDHTEnabled
;
690 void SessionImpl::setDHTEnabled(bool enabled
)
692 if (enabled
!= m_isDHTEnabled
)
694 m_isDHTEnabled
= enabled
;
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
;
711 LogMsg(tr("Local Peer Discovery support: %1").arg(enabled
? tr("ON") : tr("OFF"))
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
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())
855 Path path
= options
.savePath
;
858 // use implicit save path
859 if (isSubcategoriesEnabled())
861 path
= Utils::Fs::toValidPath(subcategoryName(categoryName
));
862 basePath
= categorySavePath(parentCategoryName(categoryName
));
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
)
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())
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())
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
)
924 if (!isValidCategoryName(name
) || m_categories
.contains(name
))
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
;
941 emit
categoryAdded(name
);
946 bool SessionImpl::editCategory(const QString
&name
, const CategoryOptions
&options
)
948 const auto it
= m_categories
.find(name
);
949 if (it
== m_categories
.end())
952 CategoryOptions
¤tOptions
= it
.value();
953 if (options
== currentOptions
)
956 currentOptions
= options
;
958 if (isDisableAutoTMMWhenCategorySavePathChanged())
960 for (TorrentImpl
*const torrent
: asConst(m_torrents
))
962 if (torrent
->category() == name
)
963 torrent
->setAutoTMMEnabled(false);
968 for (TorrentImpl
*const torrent
: asConst(m_torrents
))
970 if (torrent
->category() == name
)
971 torrent
->handleCategoryOptionsChanged();
975 emit
categoryOptionsChanged(name
);
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
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
))
998 emit
categoryRemoved(category
);
1005 result
= (m_categories
.remove(name
) > 0) || result
;
1009 // update stored categories
1011 emit
categoryRemoved(name
);
1017 bool SessionImpl::isSubcategoriesEnabled() const
1019 return m_isSubcategoriesEnabled
;
1022 void SessionImpl::setSubcategoriesEnabled(const bool value
)
1024 if (isSubcategoriesEnabled() == value
) return;
1028 // expand categories to include all parent categories
1029 m_categories
= expandCategories(m_categories
);
1030 // update stored categories
1035 // reload categories
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());
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());
1068 TagSet
SessionImpl::tags() const
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
))
1084 m_storedTags
= QStringList(m_tags
.cbegin(), m_tags
.cend());
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
);
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
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
)
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
)
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())
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);
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());
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;
1374 processNextResumeData(context
);
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
))
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
);
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
;
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
);
1448 LogMsg(tr("Failed to resume torrent: inconsistent torrent ID is detected. Torrent: \"%1\"")
1449 .arg(torrentID
.toString()), Log::WARNING
);
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
);
1464 if (m_resumeDataStorage
!= context
->startupStorage
)
1467 // TODO: Remove the following upgrade code in v4.6
1468 // == BEGIN UPGRADE CODE ==
1471 if (m_needUpgradeDownloadPath
&& isDownloadPathEnabled() && !resumeData
.useAutoTMM
)
1473 resumeData
.downloadPath
= downloadPath();
1477 // == END UPGRADE CODE ==
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
);
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
)
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
);
1534 LogMsg(tr("Detected inconsistent data: invalid tag. Torrent: \"%1\". Tag: \"%2\"")
1535 .arg(torrentID
.toString(), tag
.toString()), Log::WARNING
);
1539 resumeData
.ltAddTorrentParams
.userdata
= LTClientData(new ExtensionData
);
1540 #ifndef QBT_USES_LIBTORRENT2
1541 resumeData
.ltAddTorrentParams
.storage
= customStorageConstructor
;
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);
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]
1581 m_nativeSession
->resume();
1583 if (m_refreshEnqueued
)
1584 m_refreshEnqueued
= false;
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);
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);
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);
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
;
1650 case DiskIOType::MMap
:
1651 sessionParams
.disk_io_constructor
= customMMapDiskIOConstructor
;
1654 sessionParams
.disk_io_constructor
= customDiskIOConstructor
;
1659 #if LIBTORRENT_VERSION_NUM < 20100
1660 m_nativeSession
= new lt::session(sessionParams
, lt::session::paused
);
1662 m_nativeSession
= new lt::session(sessionParams
);
1663 m_nativeSession
->pause();
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
);
1680 m_nativeSession
->add_extension(<::create_smart_ban_plugin
);
1681 m_nativeSession
->add_extension(<::create_ut_metadata_plugin
);
1683 m_nativeSession
->add_extension(<::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()))
1696 const lt::address addr
= lt::make_address(ip
.toLatin1().constData(), 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);
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")
1730 .numPeersConnected
= findMetricIndex("peer.num_peers_connected"),
1731 .numPeersUpDisk
= findMetricIndex("peer.num_peers_up_disk"),
1732 .numPeersDownDisk
= findMetricIndex("peer.num_peers_down_disk")
1736 .dhtBytesIn
= findMetricIndex("dht.dht_bytes_in"),
1737 .dhtBytesOut
= findMetricIndex("dht.dht_bytes_out"),
1738 .dhtNodes
= findMetricIndex("dht.dht_nodes")
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"),
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())
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
);
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
);
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());
1805 #if defined(QBT_USES_LIBTORRENT2) && TORRENT_USE_I2P
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());
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());
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
);
1838 case Net::ProxyType::HTTP
:
1839 if (proxyConfig
.authEnabled
)
1840 settingsPack
.set_int(lt::settings_pack::proxy_type
, lt::settings_pack::http_pw
);
1842 settingsPack
.set_int(lt::settings_pack::proxy_type
, lt::settings_pack::http
);
1845 case Net::ProxyType::SOCKS5
:
1846 if (proxyConfig
.authEnabled
)
1847 settingsPack
.set_int(lt::settings_pack::proxy_type
, lt::settings_pack::socks5_pw
);
1849 settingsPack
.set_int(lt::settings_pack::proxy_type
, lt::settings_pack::socks5
);
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());
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());
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());
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
);
1904 case DiskIOReadMode::EnableOSCache
:
1906 settingsPack
.set_int(lt::settings_pack::disk_io_read_mode
, lt::settings_pack::enable_os_cache
);
1910 switch (diskIOWriteMode())
1912 case DiskIOWriteMode::DisableOSCache
:
1913 settingsPack
.set_int(lt::settings_pack::disk_io_write_mode
, lt::settings_pack::disable_os_cache
);
1915 case DiskIOWriteMode::EnableOSCache
:
1917 settingsPack
.set_int(lt::settings_pack::disk_io_write_mode
, lt::settings_pack::enable_os_cache
);
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
);
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());
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());
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());
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);
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());
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());
1984 switch (btProtocol())
1986 case BTProtocol::Both
:
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);
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);
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);
2009 switch (utpMixedMode())
2011 case MixedModeAlgorithm::TCP
:
2013 settingsPack
.set_int(lt::settings_pack::mixed_mode_algorithm
, lt::settings_pack::prefer_tcp
);
2015 case MixedModeAlgorithm::Proportional
:
2016 settingsPack
.set_int(lt::settings_pack::mixed_mode_algorithm
, lt::settings_pack::peer_proportional
);
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
:
2040 settingsPack
.set_int(lt::settings_pack::choking_algorithm
, lt::settings_pack::fixed_slots_choker
);
2042 case ChokingAlgorithm::RateBased
:
2043 settingsPack
.set_int(lt::settings_pack::choking_algorithm
, lt::settings_pack::rate_based_choker
);
2047 switch (seedChokingAlgorithm())
2049 case SeedChokingAlgorithm::RoundRobin
:
2050 settingsPack
.set_int(lt::settings_pack::seed_choking_algorithm
, lt::settings_pack::round_robin
);
2052 case SeedChokingAlgorithm::FastestUpload
:
2054 settingsPack
.set_int(lt::settings_pack::seed_choking_algorithm
, lt::settings_pack::fastest_upload
);
2056 case SeedChokingAlgorithm::AntiLeech
:
2057 settingsPack
.set_int(lt::settings_pack::seed_choking_algorithm
, lt::settings_pack::anti_leech
);
2061 return settingsPack
;
2064 void SessionImpl::applyNetworkInterfacesSettings(lt::settings_pack
&settingsPack
) const
2066 if (m_listenInterfaceConfigured
)
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())};
2076 portStrings
.append(u
':' + QString::number(sslPort()) + u
's');
2078 for (const QString
&ip
: asConst(getListeningIPs()))
2080 const QHostAddress addr
{ip
};
2083 const bool isIPv6
= (addr
.protocol() == QAbstractSocket::IPv6Protocol
);
2084 const QString ip
= isIPv6
2085 ? Utils::Net::canonicalIPv6Addr(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
;
2096 // ip holds an interface name
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
;
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
;
2118 for (const QString
&portString
: asConst(portStrings
))
2119 endpoints
<< (ip
+ portString
);
2120 outgoingInterfaces
<< ip
;
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()
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())
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
));
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
));
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
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
));
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();
2219 m_tracker
= new Tracker(this);
2223 const auto *pref
= Preferences::instance();
2224 if (pref
->isTrackerPortForwardingEnabled())
2225 portForwarder
->setPorts(profile
, {static_cast<quint16
>(pref
->getTrackerPort())});
2227 portForwarder
->removePorts(profile
);
2233 portForwarder
->removePorts(profile
);
2237 void SessionImpl::enableBandwidthScheduler()
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())
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
))
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
))
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
))
2286 description
= tr("Torrent reached the inactive seeding time limit.");
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())
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
);
2322 torrent
->fileSearchFinished(savePath
, fileNames
);
2326 const auto loadingTorrentsIter
= m_loadingTorrents
.find(id
);
2327 if (loadingTorrentsIter
!= m_loadingTorrents
.end())
2329 LoadTorrentParams
¶ms
= 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
));
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
)
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
))
2381 const lt::address addr
= lt::make_address(ip
.toLatin1().constData(), ec
);
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
);
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
);
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();
2436 m_nativeSession
->remove_torrent(nativeHandle
, lt::session::delete_partfile
);
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
));
2467 bool SessionImpl::cancelDownloadMetadata(const TorrentID
&id
)
2469 const auto downloadedMetadataIter
= m_downloadedMetadata
.find(id
);
2470 if (downloadedMetadataIter
== m_downloadedMetadata
.end())
2473 const lt::torrent_handle nativeHandle
= downloadedMetadataIter
.value();
2474 m_downloadedMetadata
.erase(downloadedMetadataIter
);
2476 if (!nativeHandle
.is_valid())
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
);
2490 m_nativeSession
->remove_torrent(nativeHandle
);
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());
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());
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());
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());
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()));
2610 QList
<Torrent
*> SessionImpl::torrents() const
2612 QList
<Torrent
*> result
;
2613 result
.reserve(m_torrents
.size());
2614 for (TorrentImpl
*torrent
: asConst(m_torrents
))
2620 qsizetype
SessionImpl::torrentsCount() const
2622 return m_torrents
.size();
2625 bool SessionImpl::addTorrent(const TorrentDescriptor
&torrentDescr
, const AddTorrentParams
¶ms
)
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
;
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
;
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
;
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
)))
2714 if (Torrent
*torrent
= findTorrent(infoHash
))
2716 // a duplicate torrent is being added
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")));
2731 const bool isPrivate
= torrent
->isPrivate() || (hasMetadata
&& source
.info()->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")));
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")));
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
;
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
);
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
]);
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
;
2880 p
.flags
&= ~lt::torrent_flags::sequential_download
;
2883 // Skip checking and directly start seeding
2884 if (addTorrentParams
.skipChecking
)
2885 p
.flags
|= lt::torrent_flags::seed_mode
;
2887 p
.flags
&= ~lt::torrent_flags::seed_mode
;
2889 if (loadTorrentParams
.stopped
|| (loadTorrentParams
.operatingMode
== TorrentOperatingMode::AutoManaged
))
2890 p
.flags
|= lt::torrent_flags::paused
;
2892 p
.flags
&= ~lt::torrent_flags::paused
;
2893 if (loadTorrentParams
.stopped
|| (loadTorrentParams
.operatingMode
== TorrentOperatingMode::Forced
))
2894 p
.flags
&= ~lt::torrent_flags::auto_managed
;
2896 p
.flags
|= lt::torrent_flags::auto_managed
;
2898 p
.flags
|= lt::torrent_flags::duplicate_is_error
;
2900 p
.added_time
= std::time(nullptr);
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
;
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
);
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()
2937 if (m_isPortMappingEnabled
)
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()
2955 if (!m_isPortMappingEnabled
)
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
)
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
)
2992 Algorithm::removeIf(m_mappedPorts
, [this, ports
](const quint16 port
, const std::vector
<lt::port_mapping_t
> &handles
)
2994 if (!ports
.contains(port
))
2997 for (const lt::port_mapping_t
&handle
: handles
)
2998 m_nativeSession
->delete_port_mapping(handle
);
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
]]
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
))
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
));
3045 // Preallocation mode
3046 if (isPreallocationEnabled())
3047 p
.storage_mode
= lt::storage_mode_allocate
;
3049 p
.storage_mode
= lt::storage_mode_sparse
;
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();
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
;
3070 // Adding torrent to libtorrent session
3071 m_nativeSession
->async_add_torrent(p
);
3072 m_downloadedMetadata
.insert(id
, {});
3077 void SessionImpl::exportTorrentFile(const Torrent
*torrent
, const Path
&folderPath
)
3079 if (!folderPath
.exists() && !Utils::Fs::mkpath(folderPath
))
3082 const QString validName
= Utils::Fs::toValidFileName(torrent
->name());
3083 QString torrentExportFilename
= u
"%1.torrent"_s
.arg(validName
);
3084 Path newTorrentPath
= folderPath
/ Path(torrentExportFilename
);
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
);
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();
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
;
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
))
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;
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
)
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
)
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
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
);
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)
3276 return {u
"0.0.0.0"_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
)))
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
3302 LogMsg(tr("Failed to find the configured network address to listen on. Address: \"%1\"")
3303 .arg(ifaceAddr
), Log::CRITICAL
);
3304 IPs
.append(ifaceAddr
);
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
);
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
3336 LogMsg(tr("Failed to find the configured network address to listen on. Address: \"%1\"")
3337 .arg(ifaceAddr
), Log::CRITICAL
);
3338 IPs
.append(ifaceAddr
);
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())
3367 m_globalDownloadSpeedLimit
= 0;
3368 else if (limit
<= 1024)
3369 m_globalDownloadSpeedLimit
= 1;
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())
3392 m_globalUploadSpeedLimit
= 0;
3393 else if (limit
<= 1024)
3394 m_globalUploadSpeedLimit
= 1;
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())
3417 m_altGlobalDownloadSpeedLimit
= 0;
3418 else if (limit
<= 1024)
3419 m_altGlobalDownloadSpeedLimit
= 1;
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())
3442 m_altGlobalUploadSpeedLimit
= 0;
3443 else if (limit
<= 1024)
3444 m_altGlobalUploadSpeedLimit
= 1;
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
);
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
);
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();
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
;
3509 enableBandwidthScheduler();
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
)
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
)
3539 m_saveResumeDataInterval
= value
;
3543 m_resumeDataTimer
->setInterval(std::chrono::minutes(value
));
3544 m_resumeDataTimer
->start();
3548 m_resumeDataTimer
->stop();
3552 std::chrono::minutes
SessionImpl::saveStatisticsInterval() const
3554 return std::chrono::minutes(m_saveStatisticsInterval
);
3557 void SessionImpl::setSaveStatisticsInterval(const std::chrono::minutes timeInMinutes
)
3559 m_saveStatisticsInterval
= timeInMinutes
.count();
3562 int SessionImpl::shutdownTimeout() const
3564 return m_shutdownTimeout
;
3567 void SessionImpl::setShutdownTimeout(const int value
)
3569 m_shutdownTimeout
= value
;
3572 int SessionImpl::port() const
3577 void SessionImpl::setPort(const int port
)
3582 configureListeningInterface();
3584 if (isReannounceWhenAddressChangedEnabled())
3585 reannounceToAllTrackers();
3589 bool SessionImpl::isSSLEnabled() const
3591 return m_sslEnabled
;
3594 void SessionImpl::setSSLEnabled(const bool enabled
)
3596 if (enabled
== isSSLEnabled())
3599 m_sslEnabled
= enabled
;
3600 configureListeningInterface();
3602 if (isReannounceWhenAddressChangedEnabled())
3603 reannounceToAllTrackers();
3606 int SessionImpl::sslPort() const
3611 void SessionImpl::setSSLPort(const int port
)
3613 if (port
== sslPort())
3617 configureListeningInterface();
3619 if (isReannounceWhenAddressChangedEnabled())
3620 reannounceToAllTrackers();
3623 QString
SessionImpl::networkInterface() const
3625 return m_networkInterface
;
3628 void SessionImpl::setNetworkInterface(const QString
&iface
)
3630 if (iface
!= networkInterface())
3632 m_networkInterface
= iface
;
3633 configureListeningInterface();
3637 QString
SessionImpl::networkInterfaceName() const
3639 return m_networkInterfaceName
;
3642 void SessionImpl::setNetworkInterfaceName(const QString
&name
)
3644 m_networkInterfaceName
= name
;
3647 QString
SessionImpl::networkInterfaceAddress() const
3649 return m_networkInterfaceAddress
;
3652 void SessionImpl::setNetworkInterfaceAddress(const QString
&address
)
3654 if (address
!= networkInterfaceAddress())
3656 m_networkInterfaceAddress
= address
;
3657 configureListeningInterface();
3661 int SessionImpl::encryption() const
3663 return m_encryption
;
3666 void SessionImpl::setEncryption(const int state
)
3668 if (state
!= encryption())
3670 m_encryption
= state
;
3671 configureDeferred();
3672 LogMsg(tr("Encryption support: %1").arg(
3673 state
== 0 ? tr("ON") : ((state
== 1) ? tr("FORCED") : tr("OFF")))
3678 int SessionImpl::maxActiveCheckingTorrents() const
3680 return m_maxActiveCheckingTorrents
;
3683 void SessionImpl::setMaxActiveCheckingTorrents(const int val
)
3685 if (val
== m_maxActiveCheckingTorrents
)
3688 m_maxActiveCheckingTorrents
= val
;
3689 configureDeferred();
3692 bool SessionImpl::isI2PEnabled() const
3694 return m_isI2PEnabled
;
3697 void SessionImpl::setI2PEnabled(const bool enabled
)
3699 if (m_isI2PEnabled
!= enabled
)
3701 m_isI2PEnabled
= enabled
;
3702 configureDeferred();
3706 QString
SessionImpl::I2PAddress() const
3708 return m_I2PAddress
;
3711 void SessionImpl::setI2PAddress(const QString
&address
)
3713 if (m_I2PAddress
!= address
)
3715 m_I2PAddress
= address
;
3716 configureDeferred();
3720 int SessionImpl::I2PPort() const
3725 void SessionImpl::setI2PPort(int port
)
3727 if (m_I2PPort
!= port
)
3730 configureDeferred();
3734 bool SessionImpl::I2PMixedMode() const
3736 return m_I2PMixedMode
;
3739 void SessionImpl::setI2PMixedMode(const bool enabled
)
3741 if (m_I2PMixedMode
!= enabled
)
3743 m_I2PMixedMode
= enabled
;
3744 configureDeferred();
3748 int SessionImpl::I2PInboundQuantity() const
3750 return m_I2PInboundQuantity
;
3753 void SessionImpl::setI2PInboundQuantity(const int value
)
3755 if (value
== m_I2PInboundQuantity
)
3758 m_I2PInboundQuantity
= value
;
3759 configureDeferred();
3762 int SessionImpl::I2POutboundQuantity() const
3764 return m_I2POutboundQuantity
;
3767 void SessionImpl::setI2POutboundQuantity(const int value
)
3769 if (value
== m_I2POutboundQuantity
)
3772 m_I2POutboundQuantity
= value
;
3773 configureDeferred();
3776 int SessionImpl::I2PInboundLength() const
3778 return m_I2PInboundLength
;
3781 void SessionImpl::setI2PInboundLength(const int value
)
3783 if (value
== m_I2PInboundLength
)
3786 m_I2PInboundLength
= value
;
3787 configureDeferred();
3790 int SessionImpl::I2POutboundLength() const
3792 return m_I2POutboundLength
;
3795 void SessionImpl::setI2POutboundLength(const int value
)
3797 if (value
== m_I2POutboundLength
)
3800 m_I2POutboundLength
= value
;
3801 configureDeferred();
3804 bool SessionImpl::isProxyPeerConnectionsEnabled() const
3806 return m_isProxyPeerConnectionsEnabled
;
3809 void SessionImpl::setProxyPeerConnectionsEnabled(const bool enabled
)
3811 if (enabled
!= isProxyPeerConnectionsEnabled())
3813 m_isProxyPeerConnectionsEnabled
= enabled
;
3814 configureDeferred();
3818 ChokingAlgorithm
SessionImpl::chokingAlgorithm() const
3820 return m_chokingAlgorithm
;
3823 void SessionImpl::setChokingAlgorithm(const ChokingAlgorithm mode
)
3825 if (mode
== m_chokingAlgorithm
) return;
3827 m_chokingAlgorithm
= mode
;
3828 configureDeferred();
3831 SeedChokingAlgorithm
SessionImpl::seedChokingAlgorithm() const
3833 return m_seedChokingAlgorithm
;
3836 void SessionImpl::setSeedChokingAlgorithm(const SeedChokingAlgorithm mode
)
3838 if (mode
== m_seedChokingAlgorithm
) return;
3840 m_seedChokingAlgorithm
= mode
;
3841 configureDeferred();
3844 bool SessionImpl::isAddTrackersEnabled() const
3846 return m_isAddTrackersEnabled
;
3849 void SessionImpl::setAddTrackersEnabled(const bool enabled
)
3851 m_isAddTrackersEnabled
= enabled
;
3854 QString
SessionImpl::additionalTrackers() const
3856 return m_additionalTrackers
;
3859 void SessionImpl::setAdditionalTrackers(const QString
&trackers
)
3861 if (trackers
== additionalTrackers())
3864 m_additionalTrackers
= trackers
;
3865 populateAdditionalTrackers();
3868 bool SessionImpl::isIPFilteringEnabled() const
3870 return m_isIPFilteringEnabled
;
3873 void SessionImpl::setIPFilteringEnabled(const bool enabled
)
3875 if (enabled
!= m_isIPFilteringEnabled
)
3877 m_isIPFilteringEnabled
= enabled
;
3878 m_IPFilteringConfigured
= false;
3879 configureDeferred();
3883 Path
SessionImpl::IPFilterFile() const
3885 return m_IPFilterFile
;
3888 void SessionImpl::setIPFilterFile(const Path
&path
)
3890 if (path
!= IPFilterFile())
3892 m_IPFilterFile
= path
;
3893 m_IPFilteringConfigured
= false;
3894 configureDeferred();
3898 bool SessionImpl::isExcludedFileNamesEnabled() const
3900 return m_isExcludedFileNamesEnabled
;
3903 void SessionImpl::setExcludedFileNamesEnabled(const bool enabled
)
3905 if (m_isExcludedFileNamesEnabled
== enabled
)
3908 m_isExcludedFileNamesEnabled
= enabled
;
3911 populateExcludedFileNamesRegExpList();
3913 m_excludedFileNamesRegExpList
.clear();
3916 QStringList
SessionImpl::excludedFileNames() const
3918 return m_excludedFileNames
;
3921 void SessionImpl::setExcludedFileNames(const QStringList
&excludedFileNames
)
3923 if (excludedFileNames
!= m_excludedFileNames
)
3925 m_excludedFileNames
= excludedFileNames
;
3926 populateExcludedFileNamesRegExpList();
3930 void SessionImpl::populateExcludedFileNamesRegExpList()
3932 const QStringList excludedNames
= excludedFileNames();
3934 m_excludedFileNamesRegExpList
.clear();
3935 m_excludedFileNamesRegExpList
.reserve(excludedNames
.size());
3937 for (const QString
&str
: excludedNames
)
3939 const QString pattern
= QRegularExpression::wildcardToRegularExpression(str
);
3940 const QRegularExpression re
{pattern
, QRegularExpression::CaseInsensitiveOption
};
3941 m_excludedFileNamesRegExpList
.append(re
);
3945 void SessionImpl::applyFilenameFilter(const PathList
&files
, QList
<DownloadPriority
> &priorities
)
3947 if (!isExcludedFileNamesEnabled())
3950 const auto isFilenameExcluded
= [patterns
= m_excludedFileNamesRegExpList
](const Path
&fileName
)
3952 return std::any_of(patterns
.begin(), patterns
.end(), [&fileName
](const QRegularExpression
&re
)
3954 Path path
= fileName
;
3955 while (!re
.match(path
.filename()).hasMatch())
3957 path
= path
.parentPath();
3965 priorities
.resize(files
.count(), DownloadPriority::Normal
);
3966 for (int i
= 0; i
< priorities
.size(); ++i
)
3968 if (priorities
[i
] == BitTorrent::DownloadPriority::Ignored
)
3971 if (isFilenameExcluded(files
.at(i
)))
3972 priorities
[i
] = BitTorrent::DownloadPriority::Ignored
;
3976 void SessionImpl::setBannedIPs(const QStringList
&newList
)
3978 if (newList
== m_bannedIPs
)
3979 return; // do nothing
3980 // here filter out incorrect IP
3981 QStringList filteredList
;
3982 for (const QString
&ip
: newList
)
3984 if (Utils::Net::isValidIP(ip
))
3986 // the same IPv6 addresses could be written in different forms;
3987 // QHostAddress::toString() result format follows RFC5952;
3988 // thus we avoid duplicate entries pointing to the same address
3989 filteredList
<< QHostAddress(ip
).toString();
3993 LogMsg(tr("Rejected invalid IP address while applying the list of banned IP addresses. IP: \"%1\"")
3998 // now we have to sort IPs and make them unique
3999 filteredList
.sort();
4000 filteredList
.removeDuplicates();
4001 // Again ensure that the new list is different from the stored one.
4002 if (filteredList
== m_bannedIPs
)
4003 return; // do nothing
4004 // store to session settings
4005 // also here we have to recreate filter list including 3rd party ban file
4006 // and install it again into m_session
4007 m_bannedIPs
= filteredList
;
4008 m_IPFilteringConfigured
= false;
4009 configureDeferred();
4012 ResumeDataStorageType
SessionImpl::resumeDataStorageType() const
4014 return m_resumeDataStorageType
;
4017 void SessionImpl::setResumeDataStorageType(const ResumeDataStorageType type
)
4019 m_resumeDataStorageType
= type
;
4022 bool SessionImpl::isMergeTrackersEnabled() const
4024 return m_isMergeTrackersEnabled
;
4027 void SessionImpl::setMergeTrackersEnabled(const bool enabled
)
4029 m_isMergeTrackersEnabled
= enabled
;
4032 bool SessionImpl::isStartPaused() const
4034 return m_startPaused
.get(false);
4037 void SessionImpl::setStartPaused(const bool value
)
4039 m_startPaused
= value
;
4042 TorrentContentRemoveOption
SessionImpl::torrentContentRemoveOption() const
4044 return m_torrentContentRemoveOption
;
4047 void SessionImpl::setTorrentContentRemoveOption(const TorrentContentRemoveOption option
)
4049 m_torrentContentRemoveOption
= option
;
4052 QStringList
SessionImpl::bannedIPs() const
4057 bool SessionImpl::isRestored() const
4059 return m_isRestored
;
4062 bool SessionImpl::isPaused() const
4067 void SessionImpl::pause()
4072 m_nativeSession
->pause();
4079 void SessionImpl::resume()
4084 m_nativeSession
->resume();
4091 int SessionImpl::maxConnectionsPerTorrent() const
4093 return m_maxConnectionsPerTorrent
;
4096 void SessionImpl::setMaxConnectionsPerTorrent(int max
)
4098 max
= (max
> 0) ? max
: -1;
4099 if (max
!= maxConnectionsPerTorrent())
4101 m_maxConnectionsPerTorrent
= max
;
4103 for (const TorrentImpl
*torrent
: asConst(m_torrents
))
4107 torrent
->nativeHandle().set_max_connections(max
);
4109 catch (const std::exception
&) {}
4114 int SessionImpl::maxUploadsPerTorrent() const
4116 return m_maxUploadsPerTorrent
;
4119 void SessionImpl::setMaxUploadsPerTorrent(int max
)
4121 max
= (max
> 0) ? max
: -1;
4122 if (max
!= maxUploadsPerTorrent())
4124 m_maxUploadsPerTorrent
= max
;
4126 for (const TorrentImpl
*torrent
: asConst(m_torrents
))
4130 torrent
->nativeHandle().set_max_uploads(max
);
4132 catch (const std::exception
&) {}
4137 bool SessionImpl::announceToAllTrackers() const
4139 return m_announceToAllTrackers
;
4142 void SessionImpl::setAnnounceToAllTrackers(const bool val
)
4144 if (val
!= m_announceToAllTrackers
)
4146 m_announceToAllTrackers
= val
;
4147 configureDeferred();
4151 bool SessionImpl::announceToAllTiers() const
4153 return m_announceToAllTiers
;
4156 void SessionImpl::setAnnounceToAllTiers(const bool val
)
4158 if (val
!= m_announceToAllTiers
)
4160 m_announceToAllTiers
= val
;
4161 configureDeferred();
4165 int SessionImpl::peerTurnover() const
4167 return m_peerTurnover
;
4170 void SessionImpl::setPeerTurnover(const int val
)
4172 if (val
== m_peerTurnover
)
4175 m_peerTurnover
= val
;
4176 configureDeferred();
4179 int SessionImpl::peerTurnoverCutoff() const
4181 return m_peerTurnoverCutoff
;
4184 void SessionImpl::setPeerTurnoverCutoff(const int val
)
4186 if (val
== m_peerTurnoverCutoff
)
4189 m_peerTurnoverCutoff
= val
;
4190 configureDeferred();
4193 int SessionImpl::peerTurnoverInterval() const
4195 return m_peerTurnoverInterval
;
4198 void SessionImpl::setPeerTurnoverInterval(const int val
)
4200 if (val
== m_peerTurnoverInterval
)
4203 m_peerTurnoverInterval
= val
;
4204 configureDeferred();
4207 DiskIOType
SessionImpl::diskIOType() const
4209 return m_diskIOType
;
4212 void SessionImpl::setDiskIOType(const DiskIOType type
)
4214 if (type
!= m_diskIOType
)
4216 m_diskIOType
= type
;
4220 int SessionImpl::requestQueueSize() const
4222 return m_requestQueueSize
;
4225 void SessionImpl::setRequestQueueSize(const int val
)
4227 if (val
== m_requestQueueSize
)
4230 m_requestQueueSize
= val
;
4231 configureDeferred();
4234 int SessionImpl::asyncIOThreads() const
4236 return std::clamp(m_asyncIOThreads
.get(), 1, 1024);
4239 void SessionImpl::setAsyncIOThreads(const int num
)
4241 if (num
== m_asyncIOThreads
)
4244 m_asyncIOThreads
= num
;
4245 configureDeferred();
4248 int SessionImpl::hashingThreads() const
4250 return std::clamp(m_hashingThreads
.get(), 1, 1024);
4253 void SessionImpl::setHashingThreads(const int num
)
4255 if (num
== m_hashingThreads
)
4258 m_hashingThreads
= num
;
4259 configureDeferred();
4262 int SessionImpl::filePoolSize() const
4264 return m_filePoolSize
;
4267 void SessionImpl::setFilePoolSize(const int size
)
4269 if (size
== m_filePoolSize
)
4272 m_filePoolSize
= size
;
4273 configureDeferred();
4276 int SessionImpl::checkingMemUsage() const
4278 return std::max(1, m_checkingMemUsage
.get());
4281 void SessionImpl::setCheckingMemUsage(int size
)
4283 size
= std::max(size
, 1);
4285 if (size
== m_checkingMemUsage
)
4288 m_checkingMemUsage
= size
;
4289 configureDeferred();
4292 int SessionImpl::diskCacheSize() const
4294 #ifdef QBT_APP_64BIT
4295 return std::min(m_diskCacheSize
.get(), 33554431); // 32768GiB
4297 // When build as 32bit binary, set the maximum at less than 2GB to prevent crashes
4298 // allocate 1536MiB and leave 512MiB to the rest of program data in RAM
4299 return std::min(m_diskCacheSize
.get(), 1536);
4303 void SessionImpl::setDiskCacheSize(int size
)
4305 #ifdef QBT_APP_64BIT
4306 size
= std::min(size
, 33554431); // 32768GiB
4308 // allocate 1536MiB and leave 512MiB to the rest of program data in RAM
4309 size
= std::min(size
, 1536);
4311 if (size
!= m_diskCacheSize
)
4313 m_diskCacheSize
= size
;
4314 configureDeferred();
4318 int SessionImpl::diskCacheTTL() const
4320 return m_diskCacheTTL
;
4323 void SessionImpl::setDiskCacheTTL(const int ttl
)
4325 if (ttl
!= m_diskCacheTTL
)
4327 m_diskCacheTTL
= ttl
;
4328 configureDeferred();
4332 qint64
SessionImpl::diskQueueSize() const
4334 return m_diskQueueSize
;
4337 void SessionImpl::setDiskQueueSize(const qint64 size
)
4339 if (size
== m_diskQueueSize
)
4342 m_diskQueueSize
= size
;
4343 configureDeferred();
4346 DiskIOReadMode
SessionImpl::diskIOReadMode() const
4348 return m_diskIOReadMode
;
4351 void SessionImpl::setDiskIOReadMode(const DiskIOReadMode mode
)
4353 if (mode
== m_diskIOReadMode
)
4356 m_diskIOReadMode
= mode
;
4357 configureDeferred();
4360 DiskIOWriteMode
SessionImpl::diskIOWriteMode() const
4362 return m_diskIOWriteMode
;
4365 void SessionImpl::setDiskIOWriteMode(const DiskIOWriteMode mode
)
4367 if (mode
== m_diskIOWriteMode
)
4370 m_diskIOWriteMode
= mode
;
4371 configureDeferred();
4374 bool SessionImpl::isCoalesceReadWriteEnabled() const
4376 return m_coalesceReadWriteEnabled
;
4379 void SessionImpl::setCoalesceReadWriteEnabled(const bool enabled
)
4381 if (enabled
== m_coalesceReadWriteEnabled
) return;
4383 m_coalesceReadWriteEnabled
= enabled
;
4384 configureDeferred();
4387 bool SessionImpl::isSuggestModeEnabled() const
4389 return m_isSuggestMode
;
4392 bool SessionImpl::usePieceExtentAffinity() const
4394 return m_usePieceExtentAffinity
;
4397 void SessionImpl::setPieceExtentAffinity(const bool enabled
)
4399 if (enabled
== m_usePieceExtentAffinity
) return;
4401 m_usePieceExtentAffinity
= enabled
;
4402 configureDeferred();
4405 void SessionImpl::setSuggestMode(const bool mode
)
4407 if (mode
== m_isSuggestMode
) return;
4409 m_isSuggestMode
= mode
;
4410 configureDeferred();
4413 int SessionImpl::sendBufferWatermark() const
4415 return m_sendBufferWatermark
;
4418 void SessionImpl::setSendBufferWatermark(const int value
)
4420 if (value
== m_sendBufferWatermark
) return;
4422 m_sendBufferWatermark
= value
;
4423 configureDeferred();
4426 int SessionImpl::sendBufferLowWatermark() const
4428 return m_sendBufferLowWatermark
;
4431 void SessionImpl::setSendBufferLowWatermark(const int value
)
4433 if (value
== m_sendBufferLowWatermark
) return;
4435 m_sendBufferLowWatermark
= value
;
4436 configureDeferred();
4439 int SessionImpl::sendBufferWatermarkFactor() const
4441 return m_sendBufferWatermarkFactor
;
4444 void SessionImpl::setSendBufferWatermarkFactor(const int value
)
4446 if (value
== m_sendBufferWatermarkFactor
) return;
4448 m_sendBufferWatermarkFactor
= value
;
4449 configureDeferred();
4452 int SessionImpl::connectionSpeed() const
4454 return m_connectionSpeed
;
4457 void SessionImpl::setConnectionSpeed(const int value
)
4459 if (value
== m_connectionSpeed
) return;
4461 m_connectionSpeed
= value
;
4462 configureDeferred();
4465 int SessionImpl::socketSendBufferSize() const
4467 return m_socketSendBufferSize
;
4470 void SessionImpl::setSocketSendBufferSize(const int value
)
4472 if (value
== m_socketSendBufferSize
)
4475 m_socketSendBufferSize
= value
;
4476 configureDeferred();
4479 int SessionImpl::socketReceiveBufferSize() const
4481 return m_socketReceiveBufferSize
;
4484 void SessionImpl::setSocketReceiveBufferSize(const int value
)
4486 if (value
== m_socketReceiveBufferSize
)
4489 m_socketReceiveBufferSize
= value
;
4490 configureDeferred();
4493 int SessionImpl::socketBacklogSize() const
4495 return m_socketBacklogSize
;
4498 void SessionImpl::setSocketBacklogSize(const int value
)
4500 if (value
== m_socketBacklogSize
) return;
4502 m_socketBacklogSize
= value
;
4503 configureDeferred();
4506 bool SessionImpl::isAnonymousModeEnabled() const
4508 return m_isAnonymousModeEnabled
;
4511 void SessionImpl::setAnonymousModeEnabled(const bool enabled
)
4513 if (enabled
!= m_isAnonymousModeEnabled
)
4515 m_isAnonymousModeEnabled
= enabled
;
4516 configureDeferred();
4517 LogMsg(tr("Anonymous mode: %1").arg(isAnonymousModeEnabled() ? tr("ON") : tr("OFF"))
4522 bool SessionImpl::isQueueingSystemEnabled() const
4524 return m_isQueueingEnabled
;
4527 void SessionImpl::setQueueingSystemEnabled(const bool enabled
)
4529 if (enabled
!= m_isQueueingEnabled
)
4531 m_isQueueingEnabled
= enabled
;
4532 configureDeferred();
4535 m_torrentsQueueChanged
= true;
4537 removeTorrentsQueue();
4539 for (TorrentImpl
*torrent
: asConst(m_torrents
))
4540 torrent
->handleQueueingModeChanged();
4544 int SessionImpl::maxActiveDownloads() const
4546 return m_maxActiveDownloads
;
4549 void SessionImpl::setMaxActiveDownloads(int max
)
4551 max
= std::max(max
, -1);
4552 if (max
!= m_maxActiveDownloads
)
4554 m_maxActiveDownloads
= max
;
4555 configureDeferred();
4559 int SessionImpl::maxActiveUploads() const
4561 return m_maxActiveUploads
;
4564 void SessionImpl::setMaxActiveUploads(int max
)
4566 max
= std::max(max
, -1);
4567 if (max
!= m_maxActiveUploads
)
4569 m_maxActiveUploads
= max
;
4570 configureDeferred();
4574 int SessionImpl::maxActiveTorrents() const
4576 return m_maxActiveTorrents
;
4579 void SessionImpl::setMaxActiveTorrents(int max
)
4581 max
= std::max(max
, -1);
4582 if (max
!= m_maxActiveTorrents
)
4584 m_maxActiveTorrents
= max
;
4585 configureDeferred();
4589 bool SessionImpl::ignoreSlowTorrentsForQueueing() const
4591 return m_ignoreSlowTorrentsForQueueing
;
4594 void SessionImpl::setIgnoreSlowTorrentsForQueueing(const bool ignore
)
4596 if (ignore
!= m_ignoreSlowTorrentsForQueueing
)
4598 m_ignoreSlowTorrentsForQueueing
= ignore
;
4599 configureDeferred();
4603 int SessionImpl::downloadRateForSlowTorrents() const
4605 return m_downloadRateForSlowTorrents
;
4608 void SessionImpl::setDownloadRateForSlowTorrents(const int rateInKibiBytes
)
4610 if (rateInKibiBytes
== m_downloadRateForSlowTorrents
)
4613 m_downloadRateForSlowTorrents
= rateInKibiBytes
;
4614 configureDeferred();
4617 int SessionImpl::uploadRateForSlowTorrents() const
4619 return m_uploadRateForSlowTorrents
;
4622 void SessionImpl::setUploadRateForSlowTorrents(const int rateInKibiBytes
)
4624 if (rateInKibiBytes
== m_uploadRateForSlowTorrents
)
4627 m_uploadRateForSlowTorrents
= rateInKibiBytes
;
4628 configureDeferred();
4631 int SessionImpl::slowTorrentsInactivityTimer() const
4633 return m_slowTorrentsInactivityTimer
;
4636 void SessionImpl::setSlowTorrentsInactivityTimer(const int timeInSeconds
)
4638 if (timeInSeconds
== m_slowTorrentsInactivityTimer
)
4641 m_slowTorrentsInactivityTimer
= timeInSeconds
;
4642 configureDeferred();
4645 int SessionImpl::outgoingPortsMin() const
4647 return m_outgoingPortsMin
;
4650 void SessionImpl::setOutgoingPortsMin(const int min
)
4652 if (min
!= m_outgoingPortsMin
)
4654 m_outgoingPortsMin
= min
;
4655 configureDeferred();
4659 int SessionImpl::outgoingPortsMax() const
4661 return m_outgoingPortsMax
;
4664 void SessionImpl::setOutgoingPortsMax(const int max
)
4666 if (max
!= m_outgoingPortsMax
)
4668 m_outgoingPortsMax
= max
;
4669 configureDeferred();
4673 int SessionImpl::UPnPLeaseDuration() const
4675 return m_UPnPLeaseDuration
;
4678 void SessionImpl::setUPnPLeaseDuration(const int duration
)
4680 if (duration
!= m_UPnPLeaseDuration
)
4682 m_UPnPLeaseDuration
= duration
;
4683 configureDeferred();
4687 int SessionImpl::peerToS() const
4692 void SessionImpl::setPeerToS(const int value
)
4694 if (value
== m_peerToS
)
4698 configureDeferred();
4701 bool SessionImpl::ignoreLimitsOnLAN() const
4703 return m_ignoreLimitsOnLAN
;
4706 void SessionImpl::setIgnoreLimitsOnLAN(const bool ignore
)
4708 if (ignore
!= m_ignoreLimitsOnLAN
)
4710 m_ignoreLimitsOnLAN
= ignore
;
4711 configureDeferred();
4715 bool SessionImpl::includeOverheadInLimits() const
4717 return m_includeOverheadInLimits
;
4720 void SessionImpl::setIncludeOverheadInLimits(const bool include
)
4722 if (include
!= m_includeOverheadInLimits
)
4724 m_includeOverheadInLimits
= include
;
4725 configureDeferred();
4729 QString
SessionImpl::announceIP() const
4731 return m_announceIP
;
4734 void SessionImpl::setAnnounceIP(const QString
&ip
)
4736 if (ip
!= m_announceIP
)
4739 configureDeferred();
4743 int SessionImpl::maxConcurrentHTTPAnnounces() const
4745 return m_maxConcurrentHTTPAnnounces
;
4748 void SessionImpl::setMaxConcurrentHTTPAnnounces(const int value
)
4750 if (value
== m_maxConcurrentHTTPAnnounces
)
4753 m_maxConcurrentHTTPAnnounces
= value
;
4754 configureDeferred();
4757 bool SessionImpl::isReannounceWhenAddressChangedEnabled() const
4759 return m_isReannounceWhenAddressChangedEnabled
;
4762 void SessionImpl::setReannounceWhenAddressChangedEnabled(const bool enabled
)
4764 if (enabled
== m_isReannounceWhenAddressChangedEnabled
)
4767 m_isReannounceWhenAddressChangedEnabled
= enabled
;
4770 void SessionImpl::reannounceToAllTrackers() const
4772 for (const TorrentImpl
*torrent
: asConst(m_torrents
))
4776 torrent
->nativeHandle().force_reannounce(0, -1, lt::torrent_handle::ignore_min_interval
);
4778 catch (const std::exception
&) {}
4782 int SessionImpl::stopTrackerTimeout() const
4784 return m_stopTrackerTimeout
;
4787 void SessionImpl::setStopTrackerTimeout(const int value
)
4789 if (value
== m_stopTrackerTimeout
)
4792 m_stopTrackerTimeout
= value
;
4793 configureDeferred();
4796 int SessionImpl::maxConnections() const
4798 return m_maxConnections
;
4801 void SessionImpl::setMaxConnections(int max
)
4803 max
= (max
> 0) ? max
: -1;
4804 if (max
!= m_maxConnections
)
4806 m_maxConnections
= max
;
4807 configureDeferred();
4811 int SessionImpl::maxUploads() const
4813 return m_maxUploads
;
4816 void SessionImpl::setMaxUploads(int max
)
4818 max
= (max
> 0) ? max
: -1;
4819 if (max
!= m_maxUploads
)
4822 configureDeferred();
4826 BTProtocol
SessionImpl::btProtocol() const
4828 return m_btProtocol
;
4831 void SessionImpl::setBTProtocol(const BTProtocol protocol
)
4833 if ((protocol
< BTProtocol::Both
) || (BTProtocol::UTP
< protocol
))
4836 if (protocol
== m_btProtocol
) return;
4838 m_btProtocol
= protocol
;
4839 configureDeferred();
4842 bool SessionImpl::isUTPRateLimited() const
4844 return m_isUTPRateLimited
;
4847 void SessionImpl::setUTPRateLimited(const bool limited
)
4849 if (limited
!= m_isUTPRateLimited
)
4851 m_isUTPRateLimited
= limited
;
4852 configureDeferred();
4856 MixedModeAlgorithm
SessionImpl::utpMixedMode() const
4858 return m_utpMixedMode
;
4861 void SessionImpl::setUtpMixedMode(const MixedModeAlgorithm mode
)
4863 if (mode
== m_utpMixedMode
) return;
4865 m_utpMixedMode
= mode
;
4866 configureDeferred();
4869 bool SessionImpl::isIDNSupportEnabled() const
4871 return m_IDNSupportEnabled
;
4874 void SessionImpl::setIDNSupportEnabled(const bool enabled
)
4876 if (enabled
== m_IDNSupportEnabled
) return;
4878 m_IDNSupportEnabled
= enabled
;
4879 configureDeferred();
4882 bool SessionImpl::multiConnectionsPerIpEnabled() const
4884 return m_multiConnectionsPerIpEnabled
;
4887 void SessionImpl::setMultiConnectionsPerIpEnabled(const bool enabled
)
4889 if (enabled
== m_multiConnectionsPerIpEnabled
) return;
4891 m_multiConnectionsPerIpEnabled
= enabled
;
4892 configureDeferred();
4895 bool SessionImpl::validateHTTPSTrackerCertificate() const
4897 return m_validateHTTPSTrackerCertificate
;
4900 void SessionImpl::setValidateHTTPSTrackerCertificate(const bool enabled
)
4902 if (enabled
== m_validateHTTPSTrackerCertificate
) return;
4904 m_validateHTTPSTrackerCertificate
= enabled
;
4905 configureDeferred();
4908 bool SessionImpl::isSSRFMitigationEnabled() const
4910 return m_SSRFMitigationEnabled
;
4913 void SessionImpl::setSSRFMitigationEnabled(const bool enabled
)
4915 if (enabled
== m_SSRFMitigationEnabled
) return;
4917 m_SSRFMitigationEnabled
= enabled
;
4918 configureDeferred();
4921 bool SessionImpl::blockPeersOnPrivilegedPorts() const
4923 return m_blockPeersOnPrivilegedPorts
;
4926 void SessionImpl::setBlockPeersOnPrivilegedPorts(const bool enabled
)
4928 if (enabled
== m_blockPeersOnPrivilegedPorts
) return;
4930 m_blockPeersOnPrivilegedPorts
= enabled
;
4931 configureDeferred();
4934 bool SessionImpl::isTrackerFilteringEnabled() const
4936 return m_isTrackerFilteringEnabled
;
4939 void SessionImpl::setTrackerFilteringEnabled(const bool enabled
)
4941 if (enabled
!= m_isTrackerFilteringEnabled
)
4943 m_isTrackerFilteringEnabled
= enabled
;
4944 configureDeferred();
4948 bool SessionImpl::isListening() const
4950 return m_nativeSessionExtension
->isSessionListening();
4953 ShareLimitAction
SessionImpl::shareLimitAction() const
4955 return m_shareLimitAction
;
4958 void SessionImpl::setShareLimitAction(const ShareLimitAction act
)
4960 Q_ASSERT(act
!= ShareLimitAction::Default
);
4962 m_shareLimitAction
= act
;
4965 bool SessionImpl::isKnownTorrent(const InfoHash
&infoHash
) const
4967 const bool isHybrid
= infoHash
.isHybrid();
4968 const auto id
= TorrentID::fromInfoHash(infoHash
);
4969 // alternative ID can be useful to find existing torrent
4970 // in case if hybrid torrent was added by v1 info hash
4971 const auto altID
= (isHybrid
? TorrentID::fromSHA1Hash(infoHash
.v1()) : TorrentID());
4973 if (m_loadingTorrents
.contains(id
) || (isHybrid
&& m_loadingTorrents
.contains(altID
)))
4975 if (m_downloadedMetadata
.contains(id
) || (isHybrid
&& m_downloadedMetadata
.contains(altID
)))
4977 return findTorrent(infoHash
);
4980 void SessionImpl::updateSeedingLimitTimer()
4982 if ((globalMaxRatio() == Torrent::NO_RATIO_LIMIT
) && !hasPerTorrentRatioLimit()
4983 && (globalMaxSeedingMinutes() == Torrent::NO_SEEDING_TIME_LIMIT
) && !hasPerTorrentSeedingTimeLimit()
4984 && (globalMaxInactiveSeedingMinutes() == Torrent::NO_INACTIVE_SEEDING_TIME_LIMIT
) && !hasPerTorrentInactiveSeedingTimeLimit())
4986 if (m_seedingLimitTimer
->isActive())
4987 m_seedingLimitTimer
->stop();
4989 else if (!m_seedingLimitTimer
->isActive())
4991 m_seedingLimitTimer
->start();
4995 void SessionImpl::handleTorrentShareLimitChanged(TorrentImpl
*const)
4997 updateSeedingLimitTimer();
5000 void SessionImpl::handleTorrentNameChanged(TorrentImpl
*const)
5004 void SessionImpl::handleTorrentSavePathChanged(TorrentImpl
*const torrent
)
5006 emit
torrentSavePathChanged(torrent
);
5009 void SessionImpl::handleTorrentCategoryChanged(TorrentImpl
*const torrent
, const QString
&oldCategory
)
5011 emit
torrentCategoryChanged(torrent
, oldCategory
);
5014 void SessionImpl::handleTorrentTagAdded(TorrentImpl
*const torrent
, const Tag
&tag
)
5016 emit
torrentTagAdded(torrent
, tag
);
5019 void SessionImpl::handleTorrentTagRemoved(TorrentImpl
*const torrent
, const Tag
&tag
)
5021 emit
torrentTagRemoved(torrent
, tag
);
5024 void SessionImpl::handleTorrentSavingModeChanged(TorrentImpl
*const torrent
)
5026 emit
torrentSavingModeChanged(torrent
);
5029 void SessionImpl::handleTorrentTrackersAdded(TorrentImpl
*const torrent
, const QList
<TrackerEntry
> &newTrackers
)
5031 for (const TrackerEntry
&newTracker
: newTrackers
)
5032 LogMsg(tr("Added tracker to torrent. Torrent: \"%1\". Tracker: \"%2\"").arg(torrent
->name(), newTracker
.url
));
5033 emit
trackersAdded(torrent
, newTrackers
);
5036 void SessionImpl::handleTorrentTrackersRemoved(TorrentImpl
*const torrent
, const QStringList
&deletedTrackers
)
5038 for (const QString
&deletedTracker
: deletedTrackers
)
5039 LogMsg(tr("Removed tracker from torrent. Torrent: \"%1\". Tracker: \"%2\"").arg(torrent
->name(), deletedTracker
));
5040 emit
trackersRemoved(torrent
, deletedTrackers
);
5043 void SessionImpl::handleTorrentTrackersChanged(TorrentImpl
*const torrent
)
5045 emit
trackersChanged(torrent
);
5048 void SessionImpl::handleTorrentUrlSeedsAdded(TorrentImpl
*const torrent
, const QList
<QUrl
> &newUrlSeeds
)
5050 for (const QUrl
&newUrlSeed
: newUrlSeeds
)
5051 LogMsg(tr("Added URL seed to torrent. Torrent: \"%1\". URL: \"%2\"").arg(torrent
->name(), newUrlSeed
.toString()));
5054 void SessionImpl::handleTorrentUrlSeedsRemoved(TorrentImpl
*const torrent
, const QList
<QUrl
> &urlSeeds
)
5056 for (const QUrl
&urlSeed
: urlSeeds
)
5057 LogMsg(tr("Removed URL seed from torrent. Torrent: \"%1\". URL: \"%2\"").arg(torrent
->name(), urlSeed
.toString()));
5060 void SessionImpl::handleTorrentMetadataReceived(TorrentImpl
*const torrent
)
5062 if (!torrentExportDirectory().isEmpty())
5063 exportTorrentFile(torrent
, torrentExportDirectory());
5065 emit
torrentMetadataReceived(torrent
);
5068 void SessionImpl::handleTorrentStopped(TorrentImpl
*const torrent
)
5070 torrent
->resetTrackerEntryStatuses();
5072 const QList
<TrackerEntryStatus
> trackers
= torrent
->trackers();
5073 QHash
<QString
, TrackerEntryStatus
> updatedTrackers
;
5074 updatedTrackers
.reserve(trackers
.size());
5076 for (const TrackerEntryStatus
&status
: trackers
)
5077 updatedTrackers
.emplace(status
.url
, status
);
5078 emit
trackerEntryStatusesUpdated(torrent
, updatedTrackers
);
5080 LogMsg(tr("Torrent stopped. Torrent: \"%1\"").arg(torrent
->name()));
5081 emit
torrentStopped(torrent
);
5084 void SessionImpl::handleTorrentStarted(TorrentImpl
*const torrent
)
5086 LogMsg(tr("Torrent resumed. Torrent: \"%1\"").arg(torrent
->name()));
5087 emit
torrentStarted(torrent
);
5090 void SessionImpl::handleTorrentChecked(TorrentImpl
*const torrent
)
5092 emit
torrentFinishedChecking(torrent
);
5095 void SessionImpl::handleTorrentFinished(TorrentImpl
*const torrent
)
5097 m_pendingFinishedTorrents
.append(torrent
);
5100 void SessionImpl::handleTorrentResumeDataReady(TorrentImpl
*const torrent
, const LoadTorrentParams
&data
)
5102 m_resumeDataStorage
->store(torrent
->id(), data
);
5103 const auto iter
= m_changedTorrentIDs
.find(torrent
->id());
5104 if (iter
!= m_changedTorrentIDs
.end())
5106 m_resumeDataStorage
->remove(iter
.value());
5107 m_changedTorrentIDs
.erase(iter
);
5111 void SessionImpl::handleTorrentInfoHashChanged(TorrentImpl
*torrent
, const InfoHash
&prevInfoHash
)
5113 Q_ASSERT(torrent
->infoHash().isHybrid());
5115 m_hybridTorrentsByAltID
.insert(TorrentID::fromSHA1Hash(torrent
->infoHash().v1()), torrent
);
5117 const auto prevID
= TorrentID::fromInfoHash(prevInfoHash
);
5118 const TorrentID currentID
= torrent
->id();
5119 if (currentID
!= prevID
)
5121 m_torrents
[torrent
->id()] = m_torrents
.take(prevID
);
5122 m_changedTorrentIDs
[torrent
->id()] = prevID
;
5126 void SessionImpl::handleTorrentStorageMovingStateChanged(TorrentImpl
*torrent
)
5128 emit
torrentsUpdated({torrent
});
5131 bool SessionImpl::addMoveTorrentStorageJob(TorrentImpl
*torrent
, const Path
&newPath
, const MoveStorageMode mode
, const MoveStorageContext context
)
5135 const lt::torrent_handle torrentHandle
= torrent
->nativeHandle();
5136 const Path currentLocation
= torrent
->actualStorageLocation();
5137 const bool torrentHasActiveJob
= !m_moveStorageQueue
.isEmpty() && (m_moveStorageQueue
.first().torrentHandle
== torrentHandle
);
5139 if (m_moveStorageQueue
.size() > 1)
5141 auto iter
= std::find_if((m_moveStorageQueue
.begin() + 1), m_moveStorageQueue
.end()
5142 , [&torrentHandle
](const MoveStorageJob
&job
)
5144 return job
.torrentHandle
== torrentHandle
;
5147 if (iter
!= m_moveStorageQueue
.end())
5149 // remove existing inactive job
5150 torrent
->handleMoveStorageJobFinished(currentLocation
, iter
->context
, torrentHasActiveJob
);
5151 LogMsg(tr("Torrent move canceled. Torrent: \"%1\". Source: \"%2\". Destination: \"%3\"").arg(torrent
->name(), currentLocation
.toString(), iter
->path
.toString()));
5152 m_moveStorageQueue
.erase(iter
);
5156 if (torrentHasActiveJob
)
5158 // if there is active job for this torrent prevent creating meaningless
5159 // job that will move torrent to the same location as current one
5160 if (m_moveStorageQueue
.first().path
== newPath
)
5162 LogMsg(tr("Failed to enqueue torrent move. Torrent: \"%1\". Source: \"%2\". Destination: \"%3\". Reason: torrent is currently moving to the destination")
5163 .arg(torrent
->name(), currentLocation
.toString(), newPath
.toString()));
5169 if (currentLocation
== newPath
)
5171 LogMsg(tr("Failed to enqueue torrent move. Torrent: \"%1\". Source: \"%2\" Destination: \"%3\". Reason: both paths point to the same location")
5172 .arg(torrent
->name(), currentLocation
.toString(), newPath
.toString()));
5177 const MoveStorageJob moveStorageJob
{torrentHandle
, newPath
, mode
, context
};
5178 m_moveStorageQueue
<< moveStorageJob
;
5179 LogMsg(tr("Enqueued torrent move. Torrent: \"%1\". Source: \"%2\". Destination: \"%3\"").arg(torrent
->name(), currentLocation
.toString(), newPath
.toString()));
5181 if (m_moveStorageQueue
.size() == 1)
5182 moveTorrentStorage(moveStorageJob
);
5187 void SessionImpl::moveTorrentStorage(const MoveStorageJob
&job
) const
5189 #ifdef QBT_USES_LIBTORRENT2
5190 const auto id
= TorrentID::fromInfoHash(job
.torrentHandle
.info_hashes());
5192 const auto id
= TorrentID::fromInfoHash(job
.torrentHandle
.info_hash());
5194 const TorrentImpl
*torrent
= m_torrents
.value(id
);
5195 const QString torrentName
= (torrent
? torrent
->name() : id
.toString());
5196 LogMsg(tr("Start moving torrent. Torrent: \"%1\". Destination: \"%2\"").arg(torrentName
, job
.path
.toString()));
5198 job
.torrentHandle
.move_storage(job
.path
.toString().toStdString(), toNative(job
.mode
));
5201 void SessionImpl::handleMoveTorrentStorageJobFinished(const Path
&newPath
)
5203 const MoveStorageJob finishedJob
= m_moveStorageQueue
.takeFirst();
5204 if (!m_moveStorageQueue
.isEmpty())
5205 moveTorrentStorage(m_moveStorageQueue
.first());
5207 const auto iter
= std::find_if(m_moveStorageQueue
.cbegin(), m_moveStorageQueue
.cend()
5208 , [&finishedJob
](const MoveStorageJob
&job
)
5210 return job
.torrentHandle
== finishedJob
.torrentHandle
;
5213 const bool torrentHasOutstandingJob
= (iter
!= m_moveStorageQueue
.cend());
5215 TorrentImpl
*torrent
= m_torrents
.value(finishedJob
.torrentHandle
.info_hash());
5218 torrent
->handleMoveStorageJobFinished(newPath
, finishedJob
.context
, torrentHasOutstandingJob
);
5220 else if (!torrentHasOutstandingJob
)
5222 // Last job is completed for torrent that being removing, so actually remove it
5223 const lt::torrent_handle nativeHandle
{finishedJob
.torrentHandle
};
5224 const RemovingTorrentData
&removingTorrentData
= m_removingTorrents
[nativeHandle
.info_hash()];
5225 if (removingTorrentData
.removeOption
== TorrentRemoveOption::KeepContent
)
5226 m_nativeSession
->remove_torrent(nativeHandle
, lt::session::delete_partfile
);
5230 void SessionImpl::storeCategories() const
5232 QJsonObject jsonObj
;
5233 for (auto it
= m_categories
.cbegin(); it
!= m_categories
.cend(); ++it
)
5235 const QString
&categoryName
= it
.key();
5236 const CategoryOptions
&categoryOptions
= it
.value();
5237 jsonObj
[categoryName
] = categoryOptions
.toJSON();
5240 const Path path
= specialFolderLocation(SpecialFolder::Config
) / CATEGORIES_FILE_NAME
;
5241 const QByteArray data
= QJsonDocument(jsonObj
).toJson();
5242 const nonstd::expected
<void, QString
> result
= Utils::IO::saveToFile(path
, data
);
5245 LogMsg(tr("Failed to save Categories configuration. File: \"%1\". Error: \"%2\"")
5246 .arg(path
.toString(), result
.error()), Log::WARNING
);
5250 void SessionImpl::upgradeCategories()
5252 const auto legacyCategories
= SettingValue
<QVariantMap
>(u
"BitTorrent/Session/Categories"_s
).get();
5253 for (auto it
= legacyCategories
.cbegin(); it
!= legacyCategories
.cend(); ++it
)
5255 const QString
&categoryName
= it
.key();
5256 CategoryOptions categoryOptions
;
5257 categoryOptions
.savePath
= Path(it
.value().toString());
5258 m_categories
[categoryName
] = categoryOptions
;
5264 void SessionImpl::loadCategories()
5266 m_categories
.clear();
5268 const Path path
= specialFolderLocation(SpecialFolder::Config
) / CATEGORIES_FILE_NAME
;
5271 // TODO: Remove the following upgrade code in v4.5
5272 // == BEGIN UPGRADE CODE ==
5273 upgradeCategories();
5274 m_needUpgradeDownloadPath
= true;
5275 // == END UPGRADE CODE ==
5280 const int fileMaxSize
= 1024 * 1024;
5281 const auto readResult
= Utils::IO::readFile(path
, fileMaxSize
);
5284 LogMsg(tr("Failed to load Categories. %1").arg(readResult
.error().message
), Log::WARNING
);
5288 QJsonParseError jsonError
;
5289 const QJsonDocument jsonDoc
= QJsonDocument::fromJson(readResult
.value(), &jsonError
);
5290 if (jsonError
.error
!= QJsonParseError::NoError
)
5292 LogMsg(tr("Failed to parse Categories configuration. File: \"%1\". Error: \"%2\"")
5293 .arg(path
.toString(), jsonError
.errorString()), Log::WARNING
);
5297 if (!jsonDoc
.isObject())
5299 LogMsg(tr("Failed to load Categories configuration. File: \"%1\". Error: \"Invalid data format\"")
5300 .arg(path
.toString()), Log::WARNING
);
5304 const QJsonObject jsonObj
= jsonDoc
.object();
5305 for (auto it
= jsonObj
.constBegin(); it
!= jsonObj
.constEnd(); ++it
)
5307 const QString
&categoryName
= it
.key();
5308 const auto categoryOptions
= CategoryOptions::fromJSON(it
.value().toObject());
5309 m_categories
[categoryName
] = categoryOptions
;
5313 bool SessionImpl::hasPerTorrentRatioLimit() const
5315 return std::any_of(m_torrents
.cbegin(), m_torrents
.cend(), [](const TorrentImpl
*torrent
)
5317 return (torrent
->ratioLimit() >= 0);
5321 bool SessionImpl::hasPerTorrentSeedingTimeLimit() const
5323 return std::any_of(m_torrents
.cbegin(), m_torrents
.cend(), [](const TorrentImpl
*torrent
)
5325 return (torrent
->seedingTimeLimit() >= 0);
5329 bool SessionImpl::hasPerTorrentInactiveSeedingTimeLimit() const
5331 return std::any_of(m_torrents
.cbegin(), m_torrents
.cend(), [](const TorrentImpl
*torrent
)
5333 return (torrent
->inactiveSeedingTimeLimit() >= 0);
5337 void SessionImpl::configureDeferred()
5339 if (m_deferredConfigureScheduled
)
5342 m_deferredConfigureScheduled
= true;
5343 QMetaObject::invokeMethod(this, qOverload
<>(&SessionImpl::configure
), Qt::QueuedConnection
);
5346 // Enable IP Filtering
5347 // this method creates ban list from scratch combining user ban list and 3rd party ban list file
5348 void SessionImpl::enableIPFilter()
5350 qDebug("Enabling IPFilter");
5351 // 1. Parse the IP filter
5352 // 2. In the slot add the manually banned IPs to the provided lt::ip_filter
5353 // 3. Set the ip_filter in one go so there isn't a time window where there isn't an ip_filter
5354 // set between clearing the old one and setting the new one.
5355 if (!m_filterParser
)
5357 m_filterParser
= new FilterParserThread(this);
5358 connect(m_filterParser
.data(), &FilterParserThread::IPFilterParsed
, this, &SessionImpl::handleIPFilterParsed
);
5359 connect(m_filterParser
.data(), &FilterParserThread::IPFilterError
, this, &SessionImpl::handleIPFilterError
);
5361 m_filterParser
->processFilterFile(IPFilterFile());
5364 // Disable IP Filtering
5365 void SessionImpl::disableIPFilter()
5367 qDebug("Disabling IPFilter");
5370 disconnect(m_filterParser
.data(), nullptr, this, nullptr);
5371 delete m_filterParser
;
5374 // Add the banned IPs after the IPFilter disabling
5375 // which creates an empty filter and overrides all previously
5377 lt::ip_filter filter
;
5378 processBannedIPs(filter
);
5379 m_nativeSession
->set_ip_filter(filter
);
5382 const SessionStatus
&SessionImpl::status() const
5387 const CacheStatus
&SessionImpl::cacheStatus() const
5389 return m_cacheStatus
;
5392 void SessionImpl::enqueueRefresh()
5394 Q_ASSERT(!m_refreshEnqueued
);
5396 QTimer::singleShot(refreshInterval(), Qt::CoarseTimer
, this, [this]
5398 m_nativeSession
->post_torrent_updates();
5399 m_nativeSession
->post_session_stats();
5401 if (m_torrentsQueueChanged
)
5403 m_torrentsQueueChanged
= false;
5404 m_needSaveTorrentsQueue
= true;
5408 m_refreshEnqueued
= true;
5411 void SessionImpl::handleIPFilterParsed(const int ruleCount
)
5415 lt::ip_filter filter
= m_filterParser
->IPfilter();
5416 processBannedIPs(filter
);
5417 m_nativeSession
->set_ip_filter(filter
);
5419 LogMsg(tr("Successfully parsed the IP filter file. Number of rules applied: %1").arg(ruleCount
));
5420 emit
IPFilterParsed(false, ruleCount
);
5423 void SessionImpl::handleIPFilterError()
5425 lt::ip_filter filter
;
5426 processBannedIPs(filter
);
5427 m_nativeSession
->set_ip_filter(filter
);
5429 LogMsg(tr("Failed to parse the IP filter file"), Log::WARNING
);
5430 emit
IPFilterParsed(true, 0);
5433 std::vector
<lt::alert
*> SessionImpl::getPendingAlerts(const lt::time_duration time
) const
5435 if (time
> lt::time_duration::zero())
5436 m_nativeSession
->wait_for_alert(time
);
5438 std::vector
<lt::alert
*> alerts
;
5439 m_nativeSession
->pop_alerts(&alerts
);
5443 TorrentContentLayout
SessionImpl::torrentContentLayout() const
5445 return m_torrentContentLayout
;
5448 void SessionImpl::setTorrentContentLayout(const TorrentContentLayout value
)
5450 m_torrentContentLayout
= value
;
5453 // Read alerts sent by libtorrent session
5454 void SessionImpl::readAlerts()
5456 const std::vector
<lt::alert
*> alerts
= getPendingAlerts();
5458 Q_ASSERT(m_loadedTorrents
.isEmpty());
5459 Q_ASSERT(m_receivedAddTorrentAlertsCount
== 0);
5462 m_loadedTorrents
.reserve(MAX_PROCESSING_RESUMEDATA_COUNT
);
5464 for (const lt::alert
*a
: alerts
)
5467 if (m_receivedAddTorrentAlertsCount
> 0)
5469 emit
addTorrentAlertsReceived(m_receivedAddTorrentAlertsCount
);
5470 m_receivedAddTorrentAlertsCount
= 0;
5472 if (!m_loadedTorrents
.isEmpty())
5475 m_torrentsQueueChanged
= true;
5477 emit
torrentsLoaded(m_loadedTorrents
);
5478 m_loadedTorrents
.clear();
5482 processTrackerStatuses();
5485 void SessionImpl::handleAddTorrentAlert(const lt::add_torrent_alert
*alert
)
5487 ++m_receivedAddTorrentAlertsCount
;
5491 const QString msg
= QString::fromStdString(alert
->message());
5492 LogMsg(tr("Failed to load torrent. Reason: \"%1\"").arg(msg
), Log::WARNING
);
5493 emit
loadTorrentFailed(msg
);
5495 const lt::add_torrent_params
¶ms
= alert
->params
;
5496 const bool hasMetadata
= (params
.ti
&& params
.ti
->is_valid());
5498 #ifdef QBT_USES_LIBTORRENT2
5499 const InfoHash infoHash
{(hasMetadata
? params
.ti
->info_hashes() : params
.info_hashes
)};
5500 if (infoHash
.isHybrid())
5501 m_hybridTorrentsByAltID
.remove(TorrentID::fromSHA1Hash(infoHash
.v1()));
5503 const InfoHash infoHash
{(hasMetadata
? params
.ti
->info_hash() : params
.info_hash
)};
5505 if (const auto loadingTorrentsIter
= m_loadingTorrents
.find(TorrentID::fromInfoHash(infoHash
))
5506 ; loadingTorrentsIter
!= m_loadingTorrents
.end())
5508 emit
addTorrentFailed(infoHash
, msg
);
5509 m_loadingTorrents
.erase(loadingTorrentsIter
);
5511 else if (const auto downloadedMetadataIter
= m_downloadedMetadata
.find(TorrentID::fromInfoHash(infoHash
))
5512 ; downloadedMetadataIter
!= m_downloadedMetadata
.end())
5514 m_downloadedMetadata
.erase(downloadedMetadataIter
);
5515 if (infoHash
.isHybrid())
5517 // index hybrid magnet links by both v1 and v2 info hashes
5518 const auto altID
= TorrentID::fromSHA1Hash(infoHash
.v1());
5519 m_downloadedMetadata
.remove(altID
);
5526 #ifdef QBT_USES_LIBTORRENT2
5527 const InfoHash infoHash
{alert
->handle
.info_hashes()};
5529 const InfoHash infoHash
{alert
->handle
.info_hash()};
5531 const auto torrentID
= TorrentID::fromInfoHash(infoHash
);
5533 if (const auto loadingTorrentsIter
= m_loadingTorrents
.find(torrentID
)
5534 ; loadingTorrentsIter
!= m_loadingTorrents
.end())
5536 const LoadTorrentParams params
= loadingTorrentsIter
.value();
5537 m_loadingTorrents
.erase(loadingTorrentsIter
);
5539 Torrent
*torrent
= createTorrent(alert
->handle
, params
);
5540 m_loadedTorrents
.append(torrent
);
5542 else if (const auto downloadedMetadataIter
= m_downloadedMetadata
.find(torrentID
)
5543 ; downloadedMetadataIter
!= m_downloadedMetadata
.end())
5545 downloadedMetadataIter
.value() = alert
->handle
;
5546 if (infoHash
.isHybrid())
5548 // index hybrid magnet links by both v1 and v2 info hashes
5549 const auto altID
= TorrentID::fromSHA1Hash(infoHash
.v1());
5550 m_downloadedMetadata
[altID
] = alert
->handle
;
5555 void SessionImpl::handleAlert(const lt::alert
*alert
)
5559 switch (alert
->type())
5561 #ifdef QBT_USES_LIBTORRENT2
5562 case lt::file_prio_alert::alert_type
:
5564 case lt::file_renamed_alert::alert_type
:
5565 case lt::file_rename_failed_alert::alert_type
:
5566 case lt::file_completed_alert::alert_type
:
5567 case lt::torrent_finished_alert::alert_type
:
5568 case lt::save_resume_data_alert::alert_type
:
5569 case lt::save_resume_data_failed_alert::alert_type
:
5570 case lt::torrent_paused_alert::alert_type
:
5571 case lt::torrent_resumed_alert::alert_type
:
5572 case lt::fastresume_rejected_alert::alert_type
:
5573 case lt::torrent_checked_alert::alert_type
:
5574 case lt::metadata_received_alert::alert_type
:
5575 case lt::performance_alert::alert_type
:
5576 dispatchTorrentAlert(static_cast<const lt::torrent_alert
*>(alert
));
5578 case lt::state_update_alert::alert_type
:
5579 handleStateUpdateAlert(static_cast<const lt::state_update_alert
*>(alert
));
5581 case lt::session_error_alert::alert_type
:
5582 handleSessionErrorAlert(static_cast<const lt::session_error_alert
*>(alert
));
5584 case lt::session_stats_alert::alert_type
:
5585 handleSessionStatsAlert(static_cast<const lt::session_stats_alert
*>(alert
));
5587 case lt::tracker_announce_alert::alert_type
:
5588 case lt::tracker_error_alert::alert_type
:
5589 case lt::tracker_reply_alert::alert_type
:
5590 case lt::tracker_warning_alert::alert_type
:
5591 handleTrackerAlert(static_cast<const lt::tracker_alert
*>(alert
));
5593 case lt::file_error_alert::alert_type
:
5594 handleFileErrorAlert(static_cast<const lt::file_error_alert
*>(alert
));
5596 case lt::add_torrent_alert::alert_type
:
5597 handleAddTorrentAlert(static_cast<const lt::add_torrent_alert
*>(alert
));
5599 case lt::torrent_removed_alert::alert_type
:
5600 handleTorrentRemovedAlert(static_cast<const lt::torrent_removed_alert
*>(alert
));
5602 case lt::torrent_deleted_alert::alert_type
:
5603 handleTorrentDeletedAlert(static_cast<const lt::torrent_deleted_alert
*>(alert
));
5605 case lt::torrent_delete_failed_alert::alert_type
:
5606 handleTorrentDeleteFailedAlert(static_cast<const lt::torrent_delete_failed_alert
*>(alert
));
5608 case lt::torrent_need_cert_alert::alert_type
:
5609 handleTorrentNeedCertAlert(static_cast<const lt::torrent_need_cert_alert
*>(alert
));
5611 case lt::portmap_error_alert::alert_type
:
5612 handlePortmapWarningAlert(static_cast<const lt::portmap_error_alert
*>(alert
));
5614 case lt::portmap_alert::alert_type
:
5615 handlePortmapAlert(static_cast<const lt::portmap_alert
*>(alert
));
5617 case lt::peer_blocked_alert::alert_type
:
5618 handlePeerBlockedAlert(static_cast<const lt::peer_blocked_alert
*>(alert
));
5620 case lt::peer_ban_alert::alert_type
:
5621 handlePeerBanAlert(static_cast<const lt::peer_ban_alert
*>(alert
));
5623 case lt::url_seed_alert::alert_type
:
5624 handleUrlSeedAlert(static_cast<const lt::url_seed_alert
*>(alert
));
5626 case lt::listen_succeeded_alert::alert_type
:
5627 handleListenSucceededAlert(static_cast<const lt::listen_succeeded_alert
*>(alert
));
5629 case lt::listen_failed_alert::alert_type
:
5630 handleListenFailedAlert(static_cast<const lt::listen_failed_alert
*>(alert
));
5632 case lt::external_ip_alert::alert_type
:
5633 handleExternalIPAlert(static_cast<const lt::external_ip_alert
*>(alert
));
5635 case lt::alerts_dropped_alert::alert_type
:
5636 handleAlertsDroppedAlert(static_cast<const lt::alerts_dropped_alert
*>(alert
));
5638 case lt::storage_moved_alert::alert_type
:
5639 handleStorageMovedAlert(static_cast<const lt::storage_moved_alert
*>(alert
));
5641 case lt::storage_moved_failed_alert::alert_type
:
5642 handleStorageMovedFailedAlert(static_cast<const lt::storage_moved_failed_alert
*>(alert
));
5644 case lt::socks5_alert::alert_type
:
5645 handleSocks5Alert(static_cast<const lt::socks5_alert
*>(alert
));
5647 case lt::i2p_alert::alert_type
:
5648 handleI2PAlert(static_cast<const lt::i2p_alert
*>(alert
));
5650 #ifdef QBT_USES_LIBTORRENT2
5651 case lt::torrent_conflict_alert::alert_type
:
5652 handleTorrentConflictAlert(static_cast<const lt::torrent_conflict_alert
*>(alert
));
5657 catch (const std::exception
&exc
)
5659 qWarning() << "Caught exception in " << Q_FUNC_INFO
<< ": " << QString::fromStdString(exc
.what());
5663 void SessionImpl::dispatchTorrentAlert(const lt::torrent_alert
*alert
)
5665 // The torrent can be deleted between the time the resume data was requested and
5666 // the time we received the appropriate alert. We have to decrease `m_numResumeData` anyway,
5667 // so we do this before checking for an existing torrent.
5668 if ((alert
->type() == lt::save_resume_data_alert::alert_type
)
5669 || (alert
->type() == lt::save_resume_data_failed_alert::alert_type
))
5674 const TorrentID torrentID
{alert
->handle
.info_hash()};
5675 TorrentImpl
*torrent
= m_torrents
.value(torrentID
);
5676 #ifdef QBT_USES_LIBTORRENT2
5677 if (!torrent
&& (alert
->type() == lt::metadata_received_alert::alert_type
))
5679 const InfoHash infoHash
{alert
->handle
.info_hashes()};
5680 if (infoHash
.isHybrid())
5681 torrent
= m_torrents
.value(TorrentID::fromSHA1Hash(infoHash
.v1()));
5687 torrent
->handleAlert(alert
);
5691 switch (alert
->type())
5693 case lt::metadata_received_alert::alert_type
:
5694 handleMetadataReceivedAlert(static_cast<const lt::metadata_received_alert
*>(alert
));
5699 TorrentImpl
*SessionImpl::createTorrent(const lt::torrent_handle
&nativeHandle
, const LoadTorrentParams
¶ms
)
5701 auto *const torrent
= new TorrentImpl(this, m_nativeSession
, nativeHandle
, params
);
5702 m_torrents
.insert(torrent
->id(), torrent
);
5703 if (const InfoHash infoHash
= torrent
->infoHash(); infoHash
.isHybrid())
5704 m_hybridTorrentsByAltID
.insert(TorrentID::fromSHA1Hash(infoHash
.v1()), torrent
);
5708 if (params
.addToQueueTop
)
5709 nativeHandle
.queue_position_top();
5711 torrent
->requestResumeData(lt::torrent_handle::save_info_dict
);
5713 // The following is useless for newly added magnet
5714 if (torrent
->hasMetadata())
5716 if (!torrentExportDirectory().isEmpty())
5717 exportTorrentFile(torrent
, torrentExportDirectory());
5721 if (((torrent
->ratioLimit() >= 0) || (torrent
->seedingTimeLimit() >= 0))
5722 && !m_seedingLimitTimer
->isActive())
5724 m_seedingLimitTimer
->start();
5729 LogMsg(tr("Restored torrent. Torrent: \"%1\"").arg(torrent
->name()));
5733 LogMsg(tr("Added new torrent. Torrent: \"%1\"").arg(torrent
->name()));
5734 emit
torrentAdded(torrent
);
5737 // Torrent could have error just after adding to libtorrent
5738 if (torrent
->hasError())
5739 LogMsg(tr("Torrent errored. Torrent: \"%1\". Error: \"%2\"").arg(torrent
->name(), torrent
->error()), Log::WARNING
);
5744 void SessionImpl::handleTorrentRemovedAlert(const lt::torrent_removed_alert */
*alert*/
)
5746 // We cannot consider `torrent_removed_alert` as a starting point for removing content,
5747 // because it has an inconsistent posting time between different versions of libtorrent,
5748 // so files may still be in use in some cases.
5751 void SessionImpl::handleTorrentDeletedAlert(const lt::torrent_deleted_alert
*alert
)
5753 #ifdef QBT_USES_LIBTORRENT2
5754 const auto torrentID
= TorrentID::fromInfoHash(alert
->info_hashes
);
5756 const auto torrentID
= TorrentID::fromInfoHash(alert
->info_hash
);
5758 handleRemovedTorrent(torrentID
);
5761 void SessionImpl::handleTorrentDeleteFailedAlert(const lt::torrent_delete_failed_alert
*alert
)
5763 #ifdef QBT_USES_LIBTORRENT2
5764 const auto torrentID
= TorrentID::fromInfoHash(alert
->info_hashes
);
5766 const auto torrentID
= TorrentID::fromInfoHash(alert
->info_hash
);
5768 const auto errorMessage
= alert
->error
? QString::fromLocal8Bit(alert
->error
.message().c_str()) : QString();
5769 handleRemovedTorrent(torrentID
, errorMessage
);
5772 void SessionImpl::handleTorrentNeedCertAlert(const lt::torrent_need_cert_alert
*alert
)
5774 #ifdef QBT_USES_LIBTORRENT2
5775 const InfoHash infoHash
{alert
->handle
.info_hashes()};
5777 const InfoHash infoHash
{alert
->handle
.info_hash()};
5779 const auto torrentID
= TorrentID::fromInfoHash(infoHash
);
5781 TorrentImpl
*const torrent
= m_torrents
.value(torrentID
);
5782 if (!torrent
) [[unlikely
]]
5785 if (!torrent
->applySSLParameters())
5787 LogMsg(tr("Torrent is missing SSL parameters. Torrent: \"%1\". Message: \"%2\"").arg(torrent
->name(), QString::fromStdString(alert
->message()))
5792 void SessionImpl::handleMetadataReceivedAlert(const lt::metadata_received_alert
*alert
)
5794 const TorrentID torrentID
{alert
->handle
.info_hash()};
5797 if (const auto iter
= m_downloadedMetadata
.find(torrentID
); iter
!= m_downloadedMetadata
.end())
5800 m_downloadedMetadata
.erase(iter
);
5802 #ifdef QBT_USES_LIBTORRENT2
5803 const InfoHash infoHash
{alert
->handle
.info_hashes()};
5804 if (infoHash
.isHybrid())
5806 const auto altID
= TorrentID::fromSHA1Hash(infoHash
.v1());
5807 if (const auto iter
= m_downloadedMetadata
.find(altID
); iter
!= m_downloadedMetadata
.end())
5810 m_downloadedMetadata
.erase(iter
);
5816 const TorrentInfo metadata
{*alert
->handle
.torrent_file()};
5817 m_nativeSession
->remove_torrent(alert
->handle
, lt::session::delete_files
);
5819 emit
metadataDownloaded(metadata
);
5823 void SessionImpl::handleFileErrorAlert(const lt::file_error_alert
*alert
)
5825 TorrentImpl
*const torrent
= m_torrents
.value(alert
->handle
.info_hash());
5829 torrent
->handleAlert(alert
);
5831 const TorrentID id
= torrent
->id();
5832 if (!m_recentErroredTorrents
.contains(id
))
5834 m_recentErroredTorrents
.insert(id
);
5836 const QString msg
= QString::fromStdString(alert
->message());
5837 LogMsg(tr("File error alert. Torrent: \"%1\". File: \"%2\". Reason: \"%3\"")
5838 .arg(torrent
->name(), QString::fromUtf8(alert
->filename()), msg
)
5840 emit
fullDiskError(torrent
, msg
);
5843 m_recentErroredTorrentsTimer
->start();
5846 void SessionImpl::handlePortmapWarningAlert(const lt::portmap_error_alert
*alert
)
5848 LogMsg(tr("UPnP/NAT-PMP port mapping failed. Message: \"%1\"").arg(QString::fromStdString(alert
->message())), Log::WARNING
);
5851 void SessionImpl::handlePortmapAlert(const lt::portmap_alert
*alert
)
5853 qDebug("UPnP Success, msg: %s", alert
->message().c_str());
5854 LogMsg(tr("UPnP/NAT-PMP port mapping succeeded. Message: \"%1\"").arg(QString::fromStdString(alert
->message())), Log::INFO
);
5857 void SessionImpl::handlePeerBlockedAlert(const lt::peer_blocked_alert
*alert
)
5860 switch (alert
->reason
)
5862 case lt::peer_blocked_alert::ip_filter
:
5863 reason
= tr("IP filter", "this peer was blocked. Reason: IP filter.");
5865 case lt::peer_blocked_alert::port_filter
:
5866 reason
= tr("filtered port (%1)", "this peer was blocked. Reason: filtered port (8899).").arg(QString::number(alert
->endpoint
.port()));
5868 case lt::peer_blocked_alert::i2p_mixed
:
5869 reason
= tr("%1 mixed mode restrictions", "this peer was blocked. Reason: I2P mixed mode restrictions.").arg(u
"I2P"_s
); // don't translate I2P
5871 case lt::peer_blocked_alert::privileged_ports
:
5872 reason
= tr("privileged port (%1)", "this peer was blocked. Reason: privileged port (80).").arg(QString::number(alert
->endpoint
.port()));
5874 case lt::peer_blocked_alert::utp_disabled
:
5875 reason
= tr("%1 is disabled", "this peer was blocked. Reason: uTP is disabled.").arg(C_UTP
); // don't translate μTP
5877 case lt::peer_blocked_alert::tcp_disabled
:
5878 reason
= tr("%1 is disabled", "this peer was blocked. Reason: TCP is disabled.").arg(u
"TCP"_s
); // don't translate TCP
5882 const QString ip
{toString(alert
->endpoint
.address())};
5884 Logger::instance()->addPeer(ip
, true, reason
);
5887 void SessionImpl::handlePeerBanAlert(const lt::peer_ban_alert
*alert
)
5889 const QString ip
{toString(alert
->endpoint
.address())};
5891 Logger::instance()->addPeer(ip
, false);
5894 void SessionImpl::handleUrlSeedAlert(const lt::url_seed_alert
*alert
)
5896 const TorrentImpl
*torrent
= m_torrents
.value(alert
->handle
.info_hash());
5902 LogMsg(tr("URL seed DNS lookup failed. Torrent: \"%1\". URL: \"%2\". Error: \"%3\"")
5903 .arg(torrent
->name(), QString::fromUtf8(alert
->server_url()), QString::fromStdString(alert
->message()))
5908 LogMsg(tr("Received error message from URL seed. Torrent: \"%1\". URL: \"%2\". Message: \"%3\"")
5909 .arg(torrent
->name(), QString::fromUtf8(alert
->server_url()), QString::fromUtf8(alert
->error_message()))
5914 void SessionImpl::handleListenSucceededAlert(const lt::listen_succeeded_alert
*alert
)
5916 const QString proto
{toString(alert
->socket_type
)};
5917 LogMsg(tr("Successfully listening on IP. IP: \"%1\". Port: \"%2/%3\"")
5918 .arg(toString(alert
->address
), proto
, QString::number(alert
->port
)), Log::INFO
);
5921 void SessionImpl::handleListenFailedAlert(const lt::listen_failed_alert
*alert
)
5923 const QString proto
{toString(alert
->socket_type
)};
5924 LogMsg(tr("Failed to listen on IP. IP: \"%1\". Port: \"%2/%3\". Reason: \"%4\"")
5925 .arg(toString(alert
->address
), proto
, QString::number(alert
->port
)
5926 , QString::fromLocal8Bit(alert
->error
.message().c_str())), Log::CRITICAL
);
5929 void SessionImpl::handleExternalIPAlert(const lt::external_ip_alert
*alert
)
5931 const QString externalIP
{toString(alert
->external_address
)};
5932 LogMsg(tr("Detected external IP. IP: \"%1\"")
5933 .arg(externalIP
), Log::INFO
);
5935 if (m_lastExternalIP
!= externalIP
)
5937 if (isReannounceWhenAddressChangedEnabled() && !m_lastExternalIP
.isEmpty())
5938 reannounceToAllTrackers();
5939 m_lastExternalIP
= externalIP
;
5943 void SessionImpl::handleSessionErrorAlert(const lt::session_error_alert
*alert
) const
5945 LogMsg(tr("BitTorrent session encountered a serious error. Reason: \"%1\"")
5946 .arg(QString::fromStdString(alert
->message())), Log::CRITICAL
);
5949 void SessionImpl::handleSessionStatsAlert(const lt::session_stats_alert
*alert
)
5951 if (m_refreshEnqueued
)
5952 m_refreshEnqueued
= false;
5956 const int64_t interval
= lt::total_microseconds(alert
->timestamp() - m_statsLastTimestamp
);
5960 m_statsLastTimestamp
= alert
->timestamp();
5962 const auto stats
= alert
->counters();
5964 m_status
.hasIncomingConnections
= static_cast<bool>(stats
[m_metricIndices
.net
.hasIncomingConnections
]);
5966 const int64_t ipOverheadDownload
= stats
[m_metricIndices
.net
.recvIPOverheadBytes
];
5967 const int64_t ipOverheadUpload
= stats
[m_metricIndices
.net
.sentIPOverheadBytes
];
5968 const int64_t totalDownload
= stats
[m_metricIndices
.net
.recvBytes
] + ipOverheadDownload
;
5969 const int64_t totalUpload
= stats
[m_metricIndices
.net
.sentBytes
] + ipOverheadUpload
;
5970 const int64_t totalPayloadDownload
= stats
[m_metricIndices
.net
.recvPayloadBytes
];
5971 const int64_t totalPayloadUpload
= stats
[m_metricIndices
.net
.sentPayloadBytes
];
5972 const int64_t trackerDownload
= stats
[m_metricIndices
.net
.recvTrackerBytes
];
5973 const int64_t trackerUpload
= stats
[m_metricIndices
.net
.sentTrackerBytes
];
5974 const int64_t dhtDownload
= stats
[m_metricIndices
.dht
.dhtBytesIn
];
5975 const int64_t dhtUpload
= stats
[m_metricIndices
.dht
.dhtBytesOut
];
5977 const auto calcRate
= [interval
](const qint64 previous
, const qint64 current
) -> qint64
5979 Q_ASSERT(current
>= previous
);
5980 Q_ASSERT(interval
>= 0);
5981 return (((current
- previous
) * lt::microseconds(1s
).count()) / interval
);
5984 m_status
.payloadDownloadRate
= calcRate(m_status
.totalPayloadDownload
, totalPayloadDownload
);
5985 m_status
.payloadUploadRate
= calcRate(m_status
.totalPayloadUpload
, totalPayloadUpload
);
5986 m_status
.downloadRate
= calcRate(m_status
.totalDownload
, totalDownload
);
5987 m_status
.uploadRate
= calcRate(m_status
.totalUpload
, totalUpload
);
5988 m_status
.ipOverheadDownloadRate
= calcRate(m_status
.ipOverheadDownload
, ipOverheadDownload
);
5989 m_status
.ipOverheadUploadRate
= calcRate(m_status
.ipOverheadUpload
, ipOverheadUpload
);
5990 m_status
.dhtDownloadRate
= calcRate(m_status
.dhtDownload
, dhtDownload
);
5991 m_status
.dhtUploadRate
= calcRate(m_status
.dhtUpload
, dhtUpload
);
5992 m_status
.trackerDownloadRate
= calcRate(m_status
.trackerDownload
, trackerDownload
);
5993 m_status
.trackerUploadRate
= calcRate(m_status
.trackerUpload
, trackerUpload
);
5995 m_status
.totalPayloadDownload
= totalPayloadDownload
;
5996 m_status
.totalPayloadUpload
= totalPayloadUpload
;
5997 m_status
.ipOverheadDownload
= ipOverheadDownload
;
5998 m_status
.ipOverheadUpload
= ipOverheadUpload
;
5999 m_status
.trackerDownload
= trackerDownload
;
6000 m_status
.trackerUpload
= trackerUpload
;
6001 m_status
.dhtDownload
= dhtDownload
;
6002 m_status
.dhtUpload
= dhtUpload
;
6003 m_status
.totalWasted
= stats
[m_metricIndices
.net
.recvRedundantBytes
]
6004 + stats
[m_metricIndices
.net
.recvFailedBytes
];
6005 m_status
.dhtNodes
= stats
[m_metricIndices
.dht
.dhtNodes
];
6006 m_status
.diskReadQueue
= stats
[m_metricIndices
.peer
.numPeersUpDisk
];
6007 m_status
.diskWriteQueue
= stats
[m_metricIndices
.peer
.numPeersDownDisk
];
6008 m_status
.peersCount
= stats
[m_metricIndices
.peer
.numPeersConnected
];
6010 if (totalDownload
> m_status
.totalDownload
)
6012 m_status
.totalDownload
= totalDownload
;
6013 m_isStatisticsDirty
= true;
6016 if (totalUpload
> m_status
.totalUpload
)
6018 m_status
.totalUpload
= totalUpload
;
6019 m_isStatisticsDirty
= true;
6022 m_status
.allTimeDownload
= m_previouslyDownloaded
+ m_status
.totalDownload
;
6023 m_status
.allTimeUpload
= m_previouslyUploaded
+ m_status
.totalUpload
;
6025 if (m_saveStatisticsInterval
> 0)
6027 const auto saveInterval
= std::chrono::duration_cast
<std::chrono::milliseconds
>(std::chrono::minutes(m_saveStatisticsInterval
));
6028 if (m_statisticsLastUpdateTimer
.hasExpired(saveInterval
.count()))
6034 m_cacheStatus
.totalUsedBuffers
= stats
[m_metricIndices
.disk
.diskBlocksInUse
];
6035 m_cacheStatus
.jobQueueLength
= stats
[m_metricIndices
.disk
.queuedDiskJobs
];
6037 #ifndef QBT_USES_LIBTORRENT2
6038 const int64_t numBlocksRead
= stats
[m_metricIndices
.disk
.numBlocksRead
];
6039 const int64_t numBlocksCacheHits
= stats
[m_metricIndices
.disk
.numBlocksCacheHits
];
6040 m_cacheStatus
.readRatio
= static_cast<qreal
>(numBlocksCacheHits
) / std::max
<int64_t>((numBlocksCacheHits
+ numBlocksRead
), 1);
6043 const int64_t totalJobs
= stats
[m_metricIndices
.disk
.writeJobs
] + stats
[m_metricIndices
.disk
.readJobs
]
6044 + stats
[m_metricIndices
.disk
.hashJobs
];
6045 m_cacheStatus
.averageJobTime
= (totalJobs
> 0)
6046 ? (stats
[m_metricIndices
.disk
.diskJobTime
] / totalJobs
) : 0;
6048 emit
statsUpdated();
6051 void SessionImpl::handleAlertsDroppedAlert(const lt::alerts_dropped_alert
*alert
) const
6053 LogMsg(tr("Error: Internal alert queue is full and alerts are dropped, you might see degraded performance. Dropped alert type: \"%1\". Message: \"%2\"")
6054 .arg(QString::fromStdString(alert
->dropped_alerts
.to_string()), QString::fromStdString(alert
->message())), Log::CRITICAL
);
6057 void SessionImpl::handleStorageMovedAlert(const lt::storage_moved_alert
*alert
)
6059 Q_ASSERT(!m_moveStorageQueue
.isEmpty());
6061 const MoveStorageJob
¤tJob
= m_moveStorageQueue
.first();
6062 Q_ASSERT(currentJob
.torrentHandle
== alert
->handle
);
6064 const Path newPath
{QString::fromUtf8(alert
->storage_path())};
6065 Q_ASSERT(newPath
== currentJob
.path
);
6067 #ifdef QBT_USES_LIBTORRENT2
6068 const auto id
= TorrentID::fromInfoHash(currentJob
.torrentHandle
.info_hashes());
6070 const auto id
= TorrentID::fromInfoHash(currentJob
.torrentHandle
.info_hash());
6073 TorrentImpl
*torrent
= m_torrents
.value(id
);
6074 const QString torrentName
= (torrent
? torrent
->name() : id
.toString());
6075 LogMsg(tr("Moved torrent successfully. Torrent: \"%1\". Destination: \"%2\"").arg(torrentName
, newPath
.toString()));
6077 handleMoveTorrentStorageJobFinished(newPath
);
6080 void SessionImpl::handleStorageMovedFailedAlert(const lt::storage_moved_failed_alert
*alert
)
6082 Q_ASSERT(!m_moveStorageQueue
.isEmpty());
6084 const MoveStorageJob
¤tJob
= m_moveStorageQueue
.first();
6085 Q_ASSERT(currentJob
.torrentHandle
== alert
->handle
);
6087 #ifdef QBT_USES_LIBTORRENT2
6088 const auto id
= TorrentID::fromInfoHash(currentJob
.torrentHandle
.info_hashes());
6090 const auto id
= TorrentID::fromInfoHash(currentJob
.torrentHandle
.info_hash());
6093 TorrentImpl
*torrent
= m_torrents
.value(id
);
6094 const QString torrentName
= (torrent
? torrent
->name() : id
.toString());
6095 const Path currentLocation
= (torrent
? torrent
->actualStorageLocation()
6096 : Path(alert
->handle
.status(lt::torrent_handle::query_save_path
).save_path
));
6097 const QString errorMessage
= QString::fromStdString(alert
->message());
6098 LogMsg(tr("Failed to move torrent. Torrent: \"%1\". Source: \"%2\". Destination: \"%3\". Reason: \"%4\"")
6099 .arg(torrentName
, currentLocation
.toString(), currentJob
.path
.toString(), errorMessage
), Log::WARNING
);
6101 handleMoveTorrentStorageJobFinished(currentLocation
);
6104 void SessionImpl::handleStateUpdateAlert(const lt::state_update_alert
*alert
)
6106 QList
<Torrent
*> updatedTorrents
;
6107 updatedTorrents
.reserve(static_cast<decltype(updatedTorrents
)::size_type
>(alert
->status
.size()));
6109 for (const lt::torrent_status
&status
: alert
->status
)
6111 #ifdef QBT_USES_LIBTORRENT2
6112 const auto id
= TorrentID::fromInfoHash(status
.info_hashes
);
6114 const auto id
= TorrentID::fromInfoHash(status
.info_hash
);
6116 TorrentImpl
*const torrent
= m_torrents
.value(id
);
6120 torrent
->handleStateUpdate(status
);
6121 updatedTorrents
.push_back(torrent
);
6124 if (!updatedTorrents
.isEmpty())
6125 emit
torrentsUpdated(updatedTorrents
);
6127 if (!m_pendingFinishedTorrents
.isEmpty())
6129 for (TorrentImpl
*torrent
: m_pendingFinishedTorrents
)
6131 LogMsg(tr("Torrent download finished. Torrent: \"%1\"").arg(torrent
->name()));
6132 emit
torrentFinished(torrent
);
6134 if (const Path exportPath
= finishedTorrentExportDirectory(); !exportPath
.isEmpty())
6135 exportTorrentFile(torrent
, exportPath
);
6137 processTorrentShareLimits(torrent
);
6140 m_pendingFinishedTorrents
.clear();
6142 const bool hasUnfinishedTorrents
= std::any_of(m_torrents
.cbegin(), m_torrents
.cend(), [](const TorrentImpl
*torrent
)
6144 return !(torrent
->isFinished() || torrent
->isStopped() || torrent
->isErrored());
6146 if (!hasUnfinishedTorrents
)
6147 emit
allTorrentsFinished();
6150 if (m_needSaveTorrentsQueue
)
6151 saveTorrentsQueue();
6153 if (m_refreshEnqueued
)
6154 m_refreshEnqueued
= false;
6159 void SessionImpl::handleSocks5Alert(const lt::socks5_alert
*alert
) const
6163 const auto addr
= alert
->ip
.address();
6164 const QString endpoint
= (addr
.is_v6() ? u
"[%1]:%2"_s
: u
"%1:%2"_s
)
6165 .arg(QString::fromStdString(addr
.to_string()), QString::number(alert
->ip
.port()));
6166 LogMsg(tr("SOCKS5 proxy error. Address: %1. Message: \"%2\".")
6167 .arg(endpoint
, QString::fromLocal8Bit(alert
->error
.message().c_str()))
6172 void SessionImpl::handleI2PAlert(const lt::i2p_alert
*alert
) const
6176 LogMsg(tr("I2P error. Message: \"%1\".")
6177 .arg(QString::fromStdString(alert
->message())), Log::WARNING
);
6181 void SessionImpl::handleTrackerAlert(const lt::tracker_alert
*alert
)
6183 TorrentImpl
*torrent
= m_torrents
.value(alert
->handle
.info_hash());
6187 QMap
<int, int> &updateInfo
= m_updatedTrackerStatuses
[torrent
->nativeHandle()][std::string(alert
->tracker_url())][alert
->local_endpoint
];
6189 if (alert
->type() == lt::tracker_reply_alert::alert_type
)
6191 const int numPeers
= static_cast<const lt::tracker_reply_alert
*>(alert
)->num_peers
;
6192 #ifdef QBT_USES_LIBTORRENT2
6193 const int protocolVersionNum
= (static_cast<const lt::tracker_reply_alert
*>(alert
)->version
== lt::protocol_version::V1
) ? 1 : 2;
6195 const int protocolVersionNum
= 1;
6197 updateInfo
.insert(protocolVersionNum
, numPeers
);
6201 #ifdef QBT_USES_LIBTORRENT2
6202 void SessionImpl::handleTorrentConflictAlert(const lt::torrent_conflict_alert
*alert
)
6204 const auto torrentIDv1
= TorrentID::fromSHA1Hash(alert
->metadata
->info_hashes().v1
);
6205 const auto torrentIDv2
= TorrentID::fromSHA256Hash(alert
->metadata
->info_hashes().v2
);
6206 TorrentImpl
*torrent1
= m_torrents
.value(torrentIDv1
);
6207 TorrentImpl
*torrent2
= m_torrents
.value(torrentIDv2
);
6211 removeTorrent(torrentIDv1
);
6213 cancelDownloadMetadata(torrentIDv1
);
6215 invokeAsync([torrentHandle
= torrent2
->nativeHandle(), metadata
= alert
->metadata
]
6219 torrentHandle
.set_metadata(metadata
->info_section());
6221 catch (const std::exception
&) {}
6227 cancelDownloadMetadata(torrentIDv2
);
6229 invokeAsync([torrentHandle
= torrent1
->nativeHandle(), metadata
= alert
->metadata
]
6233 torrentHandle
.set_metadata(metadata
->info_section());
6235 catch (const std::exception
&) {}
6240 cancelDownloadMetadata(torrentIDv1
);
6241 cancelDownloadMetadata(torrentIDv2
);
6244 if (!torrent1
|| !torrent2
)
6245 emit
metadataDownloaded(TorrentInfo(*alert
->metadata
));
6249 void SessionImpl::processTrackerStatuses()
6251 if (m_updatedTrackerStatuses
.isEmpty())
6254 for (auto it
= m_updatedTrackerStatuses
.cbegin(); it
!= m_updatedTrackerStatuses
.cend(); ++it
)
6255 updateTrackerEntryStatuses(it
.key(), it
.value());
6257 m_updatedTrackerStatuses
.clear();
6260 void SessionImpl::saveStatistics() const
6262 if (!m_isStatisticsDirty
)
6265 const QVariantHash stats
{
6266 {u
"AlltimeDL"_s
, m_status
.allTimeDownload
},
6267 {u
"AlltimeUL"_s
, m_status
.allTimeUpload
}};
6268 std::unique_ptr
<QSettings
> settings
= Profile::instance()->applicationSettings(u
"qBittorrent-data"_s
);
6269 settings
->setValue(u
"Stats/AllStats"_s
, stats
);
6271 m_statisticsLastUpdateTimer
.start();
6272 m_isStatisticsDirty
= false;
6275 void SessionImpl::loadStatistics()
6277 const std::unique_ptr
<QSettings
> settings
= Profile::instance()->applicationSettings(u
"qBittorrent-data"_s
);
6278 const QVariantHash value
= settings
->value(u
"Stats/AllStats"_s
).toHash();
6280 m_previouslyDownloaded
= value
[u
"AlltimeDL"_s
].toLongLong();
6281 m_previouslyUploaded
= value
[u
"AlltimeUL"_s
].toLongLong();
6284 void SessionImpl::updateTrackerEntryStatuses(lt::torrent_handle torrentHandle
, QHash
<std::string
, QHash
<lt::tcp::endpoint
, QMap
<int, int>>> updatedTrackers
)
6286 invokeAsync([this, torrentHandle
= std::move(torrentHandle
), updatedTrackers
= std::move(updatedTrackers
)]() mutable
6290 std::vector
<lt::announce_entry
> nativeTrackers
= torrentHandle
.trackers();
6291 invoke([this, torrentHandle
, nativeTrackers
= std::move(nativeTrackers
)
6292 , updatedTrackers
= std::move(updatedTrackers
)]
6294 TorrentImpl
*torrent
= m_torrents
.value(torrentHandle
.info_hash());
6295 if (!torrent
|| torrent
->isStopped())
6298 QHash
<QString
, TrackerEntryStatus
> trackers
;
6299 trackers
.reserve(updatedTrackers
.size());
6300 for (const lt::announce_entry
&announceEntry
: nativeTrackers
)
6302 const auto updatedTrackersIter
= updatedTrackers
.find(announceEntry
.url
);
6303 if (updatedTrackersIter
== updatedTrackers
.end())
6306 const auto &updateInfo
= updatedTrackersIter
.value();
6307 TrackerEntryStatus status
= torrent
->updateTrackerEntryStatus(announceEntry
, updateInfo
);
6308 const QString url
= status
.url
;
6309 trackers
.emplace(url
, std::move(status
));
6312 emit
trackerEntryStatusesUpdated(torrent
, trackers
);
6315 catch (const std::exception
&)
6321 void SessionImpl::handleRemovedTorrent(const TorrentID
&torrentID
, const QString
&partfileRemoveError
)
6323 const auto removingTorrentDataIter
= m_removingTorrents
.find(torrentID
);
6324 if (removingTorrentDataIter
== m_removingTorrents
.end())
6327 if (!partfileRemoveError
.isEmpty())
6329 LogMsg(tr("Failed to remove partfile. Torrent: \"%1\". Reason: \"%2\".")
6330 .arg(removingTorrentDataIter
->name
, partfileRemoveError
)
6334 if ((removingTorrentDataIter
->removeOption
== TorrentRemoveOption::RemoveContent
)
6335 && !removingTorrentDataIter
->contentStoragePath
.isEmpty())
6337 QMetaObject::invokeMethod(m_torrentContentRemover
, [this, jobData
= *removingTorrentDataIter
]
6339 m_torrentContentRemover
->performJob(jobData
.name
, jobData
.contentStoragePath
6340 , jobData
.fileNames
, m_torrentContentRemoveOption
);
6344 m_removingTorrents
.erase(removingTorrentDataIter
);