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;
115 const int STATISTICS_SAVE_INTERVAL
= std::chrono::milliseconds(15min
).count();
119 const char PEER_ID
[] = "qB";
120 const auto USER_AGENT
= QStringLiteral("qBittorrent/" QBT_VERSION_2
);
121 const QString DEFAULT_DHT_BOOTSTRAP_NODES
= u
"dht.libtorrent.org:25401, dht.transmissionbt.com:6881, router.bittorrent.com:6881, router.utorrent.com:6881, dht.aelitis.com:6881"_s
;
123 void torrentQueuePositionUp(const lt::torrent_handle
&handle
)
127 handle
.queue_position_up();
129 catch (const std::exception
&exc
)
131 qDebug() << Q_FUNC_INFO
<< " fails: " << exc
.what();
135 void torrentQueuePositionDown(const lt::torrent_handle
&handle
)
139 handle
.queue_position_down();
141 catch (const std::exception
&exc
)
143 qDebug() << Q_FUNC_INFO
<< " fails: " << exc
.what();
147 void torrentQueuePositionTop(const lt::torrent_handle
&handle
)
151 handle
.queue_position_top();
153 catch (const std::exception
&exc
)
155 qDebug() << Q_FUNC_INFO
<< " fails: " << exc
.what();
159 void torrentQueuePositionBottom(const lt::torrent_handle
&handle
)
163 handle
.queue_position_bottom();
165 catch (const std::exception
&exc
)
167 qDebug() << Q_FUNC_INFO
<< " fails: " << exc
.what();
171 QMap
<QString
, CategoryOptions
> expandCategories(const QMap
<QString
, CategoryOptions
> &categories
)
173 QMap
<QString
, CategoryOptions
> expanded
= categories
;
175 for (auto i
= categories
.cbegin(); i
!= categories
.cend(); ++i
)
177 const QString
&category
= i
.key();
178 for (const QString
&subcat
: asConst(Session::expandCategory(category
)))
180 if (!expanded
.contains(subcat
))
181 expanded
[subcat
] = {};
188 QString
toString(const lt::socket_type_t socketType
)
192 #ifdef QBT_USES_LIBTORRENT2
193 case lt::socket_type_t::http
:
195 case lt::socket_type_t::http_ssl
:
196 return u
"HTTP_SSL"_s
;
198 case lt::socket_type_t::i2p
:
200 case lt::socket_type_t::socks5
:
202 #ifdef QBT_USES_LIBTORRENT2
203 case lt::socket_type_t::socks5_ssl
:
204 return u
"SOCKS5_SSL"_s
;
206 case lt::socket_type_t::tcp
:
208 case lt::socket_type_t::tcp_ssl
:
210 #ifdef QBT_USES_LIBTORRENT2
211 case lt::socket_type_t::utp
:
214 case lt::socket_type_t::udp
:
217 case lt::socket_type_t::utp_ssl
:
223 QString
toString(const lt::address
&address
)
227 return QString::fromLatin1(address
.to_string().c_str());
229 catch (const std::exception
&)
231 // suppress conversion error
236 template <typename T
>
239 LowerLimited(T limit
, T ret
)
245 explicit LowerLimited(T limit
)
246 : LowerLimited(limit
, limit
)
250 T
operator()(T val
) const
252 return val
<= m_limit
? m_ret
: val
;
260 template <typename T
>
261 LowerLimited
<T
> lowerLimited(T limit
) { return LowerLimited
<T
>(limit
); }
263 template <typename T
>
264 LowerLimited
<T
> lowerLimited(T limit
, T ret
) { return LowerLimited
<T
>(limit
, ret
); }
266 template <typename T
>
267 auto clampValue(const T lower
, const T upper
)
269 return [lower
, upper
](const T value
) -> T
271 return std::clamp(value
, lower
, upper
);
276 QString
convertIfaceNameToGuid(const QString
&name
)
278 // Under Windows XP or on Qt version <= 5.5 'name' will be a GUID already.
279 const QUuid
uuid(name
);
281 return uuid
.toString().toUpper(); // Libtorrent expects the GUID in uppercase
283 const std::wstring nameWStr
= name
.toStdWString();
285 const LONG res
= ::ConvertInterfaceNameToLuidW(nameWStr
.c_str(), &luid
);
289 if (::ConvertInterfaceLuidToGuid(&luid
, &guid
) == 0)
290 return QUuid(guid
).toString().toUpper();
297 constexpr lt::move_flags_t
toNative(const MoveStorageMode mode
)
303 case MoveStorageMode::FailIfExist
:
304 return lt::move_flags_t::fail_if_exist
;
305 case MoveStorageMode::KeepExistingFiles
:
306 return lt::move_flags_t::dont_replace
;
307 case MoveStorageMode::Overwrite
:
308 return lt::move_flags_t::always_replace_files
;
313 struct BitTorrent::SessionImpl::ResumeSessionContext final
: public QObject
315 using QObject::QObject
;
317 ResumeDataStorage
*startupStorage
= nullptr;
318 ResumeDataStorageType currentStorageType
= ResumeDataStorageType::Legacy
;
319 QList
<LoadedResumeData
> loadedResumeData
;
320 int processingResumeDataCount
= 0;
321 int64_t totalResumeDataCount
= 0;
322 int64_t finishedResumeDataCount
= 0;
323 bool isLoadFinished
= false;
324 bool isLoadedResumeDataHandlingEnqueued
= false;
325 QSet
<QString
> recoveredCategories
;
326 #ifdef QBT_USES_LIBTORRENT2
327 QSet
<TorrentID
> indexedTorrents
;
328 QSet
<TorrentID
> skippedIDs
;
332 const int addTorrentParamsId
= qRegisterMetaType
<AddTorrentParams
>();
334 Session
*SessionImpl::m_instance
= nullptr;
336 void Session::initInstance()
338 if (!SessionImpl::m_instance
)
339 SessionImpl::m_instance
= new SessionImpl
;
342 void Session::freeInstance()
344 delete SessionImpl::m_instance
;
345 SessionImpl::m_instance
= nullptr;
348 Session
*Session::instance()
350 return SessionImpl::m_instance
;
353 bool Session::isValidCategoryName(const QString
&name
)
355 const QRegularExpression re
{uR
"(^([^\\\/]|[^\\\/]([^\\\/]|\/(?=[^\/]))*[^\\\/])$)"_s
};
356 return (name
.isEmpty() || (name
.indexOf(re
) == 0));
359 QString
Session::subcategoryName(const QString
&category
)
361 const int sepIndex
= category
.lastIndexOf(u
'/');
363 return category
.mid(sepIndex
+ 1);
368 QString
Session::parentCategoryName(const QString
&category
)
370 const int sepIndex
= category
.lastIndexOf(u
'/');
372 return category
.left(sepIndex
);
377 QStringList
Session::expandCategory(const QString
&category
)
381 while ((index
= category
.indexOf(u
'/', index
)) >= 0)
383 result
<< category
.left(index
);
391 #define BITTORRENT_KEY(name) u"BitTorrent/" name
392 #define BITTORRENT_SESSION_KEY(name) BITTORRENT_KEY(u"Session/") name
394 SessionImpl::SessionImpl(QObject
*parent
)
396 , m_DHTBootstrapNodes(BITTORRENT_SESSION_KEY(u
"DHTBootstrapNodes"_s
), DEFAULT_DHT_BOOTSTRAP_NODES
)
397 , m_isDHTEnabled(BITTORRENT_SESSION_KEY(u
"DHTEnabled"_s
), true)
398 , m_isLSDEnabled(BITTORRENT_SESSION_KEY(u
"LSDEnabled"_s
), true)
399 , m_isPeXEnabled(BITTORRENT_SESSION_KEY(u
"PeXEnabled"_s
), true)
400 , m_isIPFilteringEnabled(BITTORRENT_SESSION_KEY(u
"IPFilteringEnabled"_s
), false)
401 , m_isTrackerFilteringEnabled(BITTORRENT_SESSION_KEY(u
"TrackerFilteringEnabled"_s
), false)
402 , m_IPFilterFile(BITTORRENT_SESSION_KEY(u
"IPFilter"_s
))
403 , m_announceToAllTrackers(BITTORRENT_SESSION_KEY(u
"AnnounceToAllTrackers"_s
), false)
404 , m_announceToAllTiers(BITTORRENT_SESSION_KEY(u
"AnnounceToAllTiers"_s
), true)
405 , m_asyncIOThreads(BITTORRENT_SESSION_KEY(u
"AsyncIOThreadsCount"_s
), 10)
406 , m_hashingThreads(BITTORRENT_SESSION_KEY(u
"HashingThreadsCount"_s
), 1)
407 , m_filePoolSize(BITTORRENT_SESSION_KEY(u
"FilePoolSize"_s
), 100)
408 , m_checkingMemUsage(BITTORRENT_SESSION_KEY(u
"CheckingMemUsageSize"_s
), 32)
409 , m_diskCacheSize(BITTORRENT_SESSION_KEY(u
"DiskCacheSize"_s
), -1)
410 , m_diskCacheTTL(BITTORRENT_SESSION_KEY(u
"DiskCacheTTL"_s
), 60)
411 , m_diskQueueSize(BITTORRENT_SESSION_KEY(u
"DiskQueueSize"_s
), (1024 * 1024))
412 , m_diskIOType(BITTORRENT_SESSION_KEY(u
"DiskIOType"_s
), DiskIOType::Default
)
413 , m_diskIOReadMode(BITTORRENT_SESSION_KEY(u
"DiskIOReadMode"_s
), DiskIOReadMode::EnableOSCache
)
414 , m_diskIOWriteMode(BITTORRENT_SESSION_KEY(u
"DiskIOWriteMode"_s
), DiskIOWriteMode::EnableOSCache
)
416 , m_coalesceReadWriteEnabled(BITTORRENT_SESSION_KEY(u
"CoalesceReadWrite"_s
), true)
418 , m_coalesceReadWriteEnabled(BITTORRENT_SESSION_KEY(u
"CoalesceReadWrite"_s
), false)
420 , m_usePieceExtentAffinity(BITTORRENT_SESSION_KEY(u
"PieceExtentAffinity"_s
), false)
421 , m_isSuggestMode(BITTORRENT_SESSION_KEY(u
"SuggestMode"_s
), false)
422 , m_sendBufferWatermark(BITTORRENT_SESSION_KEY(u
"SendBufferWatermark"_s
), 500)
423 , m_sendBufferLowWatermark(BITTORRENT_SESSION_KEY(u
"SendBufferLowWatermark"_s
), 10)
424 , m_sendBufferWatermarkFactor(BITTORRENT_SESSION_KEY(u
"SendBufferWatermarkFactor"_s
), 50)
425 , m_connectionSpeed(BITTORRENT_SESSION_KEY(u
"ConnectionSpeed"_s
), 30)
426 , m_socketSendBufferSize(BITTORRENT_SESSION_KEY(u
"SocketSendBufferSize"_s
), 0)
427 , m_socketReceiveBufferSize(BITTORRENT_SESSION_KEY(u
"SocketReceiveBufferSize"_s
), 0)
428 , m_socketBacklogSize(BITTORRENT_SESSION_KEY(u
"SocketBacklogSize"_s
), 30)
429 , m_isAnonymousModeEnabled(BITTORRENT_SESSION_KEY(u
"AnonymousModeEnabled"_s
), false)
430 , m_isQueueingEnabled(BITTORRENT_SESSION_KEY(u
"QueueingSystemEnabled"_s
), false)
431 , m_maxActiveDownloads(BITTORRENT_SESSION_KEY(u
"MaxActiveDownloads"_s
), 3, lowerLimited(-1))
432 , m_maxActiveUploads(BITTORRENT_SESSION_KEY(u
"MaxActiveUploads"_s
), 3, lowerLimited(-1))
433 , m_maxActiveTorrents(BITTORRENT_SESSION_KEY(u
"MaxActiveTorrents"_s
), 5, lowerLimited(-1))
434 , m_ignoreSlowTorrentsForQueueing(BITTORRENT_SESSION_KEY(u
"IgnoreSlowTorrentsForQueueing"_s
), false)
435 , m_downloadRateForSlowTorrents(BITTORRENT_SESSION_KEY(u
"SlowTorrentsDownloadRate"_s
), 2)
436 , m_uploadRateForSlowTorrents(BITTORRENT_SESSION_KEY(u
"SlowTorrentsUploadRate"_s
), 2)
437 , m_slowTorrentsInactivityTimer(BITTORRENT_SESSION_KEY(u
"SlowTorrentsInactivityTimer"_s
), 60)
438 , m_outgoingPortsMin(BITTORRENT_SESSION_KEY(u
"OutgoingPortsMin"_s
), 0)
439 , m_outgoingPortsMax(BITTORRENT_SESSION_KEY(u
"OutgoingPortsMax"_s
), 0)
440 , m_UPnPLeaseDuration(BITTORRENT_SESSION_KEY(u
"UPnPLeaseDuration"_s
), 0)
441 , m_peerToS(BITTORRENT_SESSION_KEY(u
"PeerToS"_s
), 0x04)
442 , m_ignoreLimitsOnLAN(BITTORRENT_SESSION_KEY(u
"IgnoreLimitsOnLAN"_s
), false)
443 , m_includeOverheadInLimits(BITTORRENT_SESSION_KEY(u
"IncludeOverheadInLimits"_s
), false)
444 , m_announceIP(BITTORRENT_SESSION_KEY(u
"AnnounceIP"_s
))
445 , m_maxConcurrentHTTPAnnounces(BITTORRENT_SESSION_KEY(u
"MaxConcurrentHTTPAnnounces"_s
), 50)
446 , m_isReannounceWhenAddressChangedEnabled(BITTORRENT_SESSION_KEY(u
"ReannounceWhenAddressChanged"_s
), false)
447 , m_stopTrackerTimeout(BITTORRENT_SESSION_KEY(u
"StopTrackerTimeout"_s
), 2)
448 , m_maxConnections(BITTORRENT_SESSION_KEY(u
"MaxConnections"_s
), 500, lowerLimited(0, -1))
449 , m_maxUploads(BITTORRENT_SESSION_KEY(u
"MaxUploads"_s
), 20, lowerLimited(0, -1))
450 , m_maxConnectionsPerTorrent(BITTORRENT_SESSION_KEY(u
"MaxConnectionsPerTorrent"_s
), 100, lowerLimited(0, -1))
451 , m_maxUploadsPerTorrent(BITTORRENT_SESSION_KEY(u
"MaxUploadsPerTorrent"_s
), 4, lowerLimited(0, -1))
452 , m_btProtocol(BITTORRENT_SESSION_KEY(u
"BTProtocol"_s
), BTProtocol::Both
453 , clampValue(BTProtocol::Both
, BTProtocol::UTP
))
454 , m_isUTPRateLimited(BITTORRENT_SESSION_KEY(u
"uTPRateLimited"_s
), true)
455 , m_utpMixedMode(BITTORRENT_SESSION_KEY(u
"uTPMixedMode"_s
), MixedModeAlgorithm::TCP
456 , clampValue(MixedModeAlgorithm::TCP
, MixedModeAlgorithm::Proportional
))
457 , m_IDNSupportEnabled(BITTORRENT_SESSION_KEY(u
"IDNSupportEnabled"_s
), false)
458 , m_multiConnectionsPerIpEnabled(BITTORRENT_SESSION_KEY(u
"MultiConnectionsPerIp"_s
), false)
459 , m_validateHTTPSTrackerCertificate(BITTORRENT_SESSION_KEY(u
"ValidateHTTPSTrackerCertificate"_s
), true)
460 , m_SSRFMitigationEnabled(BITTORRENT_SESSION_KEY(u
"SSRFMitigation"_s
), true)
461 , m_blockPeersOnPrivilegedPorts(BITTORRENT_SESSION_KEY(u
"BlockPeersOnPrivilegedPorts"_s
), false)
462 , m_isAddTrackersEnabled(BITTORRENT_SESSION_KEY(u
"AddTrackersEnabled"_s
), false)
463 , m_additionalTrackers(BITTORRENT_SESSION_KEY(u
"AdditionalTrackers"_s
))
464 , m_globalMaxRatio(BITTORRENT_SESSION_KEY(u
"GlobalMaxRatio"_s
), -1, [](qreal r
) { return r
< 0 ? -1. : r
;})
465 , m_globalMaxSeedingMinutes(BITTORRENT_SESSION_KEY(u
"GlobalMaxSeedingMinutes"_s
), -1, lowerLimited(-1))
466 , m_globalMaxInactiveSeedingMinutes(BITTORRENT_SESSION_KEY(u
"GlobalMaxInactiveSeedingMinutes"_s
), -1, lowerLimited(-1))
467 , m_isAddTorrentToQueueTop(BITTORRENT_SESSION_KEY(u
"AddTorrentToTopOfQueue"_s
), false)
468 , m_isAddTorrentStopped(BITTORRENT_SESSION_KEY(u
"AddTorrentStopped"_s
), false)
469 , m_torrentStopCondition(BITTORRENT_SESSION_KEY(u
"TorrentStopCondition"_s
), Torrent::StopCondition::None
)
470 , m_torrentContentLayout(BITTORRENT_SESSION_KEY(u
"TorrentContentLayout"_s
), TorrentContentLayout::Original
)
471 , m_isAppendExtensionEnabled(BITTORRENT_SESSION_KEY(u
"AddExtensionToIncompleteFiles"_s
), false)
472 , m_isUnwantedFolderEnabled(BITTORRENT_SESSION_KEY(u
"UseUnwantedFolder"_s
), false)
473 , m_refreshInterval(BITTORRENT_SESSION_KEY(u
"RefreshInterval"_s
), 1500)
474 , m_isPreallocationEnabled(BITTORRENT_SESSION_KEY(u
"Preallocation"_s
), false)
475 , m_torrentExportDirectory(BITTORRENT_SESSION_KEY(u
"TorrentExportDirectory"_s
))
476 , m_finishedTorrentExportDirectory(BITTORRENT_SESSION_KEY(u
"FinishedTorrentExportDirectory"_s
))
477 , m_globalDownloadSpeedLimit(BITTORRENT_SESSION_KEY(u
"GlobalDLSpeedLimit"_s
), 0, lowerLimited(0))
478 , m_globalUploadSpeedLimit(BITTORRENT_SESSION_KEY(u
"GlobalUPSpeedLimit"_s
), 0, lowerLimited(0))
479 , m_altGlobalDownloadSpeedLimit(BITTORRENT_SESSION_KEY(u
"AlternativeGlobalDLSpeedLimit"_s
), 10, lowerLimited(0))
480 , m_altGlobalUploadSpeedLimit(BITTORRENT_SESSION_KEY(u
"AlternativeGlobalUPSpeedLimit"_s
), 10, lowerLimited(0))
481 , m_isAltGlobalSpeedLimitEnabled(BITTORRENT_SESSION_KEY(u
"UseAlternativeGlobalSpeedLimit"_s
), false)
482 , m_isBandwidthSchedulerEnabled(BITTORRENT_SESSION_KEY(u
"BandwidthSchedulerEnabled"_s
), false)
483 , m_isPerformanceWarningEnabled(BITTORRENT_SESSION_KEY(u
"PerformanceWarning"_s
), false)
484 , m_saveResumeDataInterval(BITTORRENT_SESSION_KEY(u
"SaveResumeDataInterval"_s
), 60)
485 , m_shutdownTimeout(BITTORRENT_SESSION_KEY(u
"ShutdownTimeout"_s
), -1)
486 , m_port(BITTORRENT_SESSION_KEY(u
"Port"_s
), -1)
487 , m_sslEnabled(BITTORRENT_SESSION_KEY(u
"SSL/Enabled"_s
), false)
488 , m_sslPort(BITTORRENT_SESSION_KEY(u
"SSL/Port"_s
), -1)
489 , m_networkInterface(BITTORRENT_SESSION_KEY(u
"Interface"_s
))
490 , m_networkInterfaceName(BITTORRENT_SESSION_KEY(u
"InterfaceName"_s
))
491 , m_networkInterfaceAddress(BITTORRENT_SESSION_KEY(u
"InterfaceAddress"_s
))
492 , m_encryption(BITTORRENT_SESSION_KEY(u
"Encryption"_s
), 0)
493 , m_maxActiveCheckingTorrents(BITTORRENT_SESSION_KEY(u
"MaxActiveCheckingTorrents"_s
), 1)
494 , m_isProxyPeerConnectionsEnabled(BITTORRENT_SESSION_KEY(u
"ProxyPeerConnections"_s
), false)
495 , m_chokingAlgorithm(BITTORRENT_SESSION_KEY(u
"ChokingAlgorithm"_s
), ChokingAlgorithm::FixedSlots
496 , clampValue(ChokingAlgorithm::FixedSlots
, ChokingAlgorithm::RateBased
))
497 , m_seedChokingAlgorithm(BITTORRENT_SESSION_KEY(u
"SeedChokingAlgorithm"_s
), SeedChokingAlgorithm::FastestUpload
498 , clampValue(SeedChokingAlgorithm::RoundRobin
, SeedChokingAlgorithm::AntiLeech
))
499 , m_storedTags(BITTORRENT_SESSION_KEY(u
"Tags"_s
))
500 , m_shareLimitAction(BITTORRENT_SESSION_KEY(u
"ShareLimitAction"_s
), ShareLimitAction::Stop
501 , [](const ShareLimitAction action
) { return (action
== ShareLimitAction::Default
) ? ShareLimitAction::Stop
: action
; })
502 , m_savePath(BITTORRENT_SESSION_KEY(u
"DefaultSavePath"_s
), specialFolderLocation(SpecialFolder::Downloads
))
503 , m_downloadPath(BITTORRENT_SESSION_KEY(u
"TempPath"_s
), (savePath() / Path(u
"temp"_s
)))
504 , m_isDownloadPathEnabled(BITTORRENT_SESSION_KEY(u
"TempPathEnabled"_s
), false)
505 , m_isSubcategoriesEnabled(BITTORRENT_SESSION_KEY(u
"SubcategoriesEnabled"_s
), false)
506 , m_useCategoryPathsInManualMode(BITTORRENT_SESSION_KEY(u
"UseCategoryPathsInManualMode"_s
), false)
507 , m_isAutoTMMDisabledByDefault(BITTORRENT_SESSION_KEY(u
"DisableAutoTMMByDefault"_s
), true)
508 , m_isDisableAutoTMMWhenCategoryChanged(BITTORRENT_SESSION_KEY(u
"DisableAutoTMMTriggers/CategoryChanged"_s
), false)
509 , m_isDisableAutoTMMWhenDefaultSavePathChanged(BITTORRENT_SESSION_KEY(u
"DisableAutoTMMTriggers/DefaultSavePathChanged"_s
), true)
510 , m_isDisableAutoTMMWhenCategorySavePathChanged(BITTORRENT_SESSION_KEY(u
"DisableAutoTMMTriggers/CategorySavePathChanged"_s
), true)
511 , m_isTrackerEnabled(BITTORRENT_KEY(u
"TrackerEnabled"_s
), false)
512 , m_peerTurnover(BITTORRENT_SESSION_KEY(u
"PeerTurnover"_s
), 4)
513 , m_peerTurnoverCutoff(BITTORRENT_SESSION_KEY(u
"PeerTurnoverCutOff"_s
), 90)
514 , m_peerTurnoverInterval(BITTORRENT_SESSION_KEY(u
"PeerTurnoverInterval"_s
), 300)
515 , m_requestQueueSize(BITTORRENT_SESSION_KEY(u
"RequestQueueSize"_s
), 500)
516 , m_isExcludedFileNamesEnabled(BITTORRENT_KEY(u
"ExcludedFileNamesEnabled"_s
), false)
517 , m_excludedFileNames(BITTORRENT_SESSION_KEY(u
"ExcludedFileNames"_s
))
518 , m_bannedIPs(u
"State/BannedIPs"_s
, QStringList(), Algorithm::sorted
<QStringList
>)
519 , m_resumeDataStorageType(BITTORRENT_SESSION_KEY(u
"ResumeDataStorageType"_s
), ResumeDataStorageType::Legacy
)
520 , m_isMergeTrackersEnabled(BITTORRENT_KEY(u
"MergeTrackersEnabled"_s
), false)
521 , m_isI2PEnabled
{BITTORRENT_SESSION_KEY(u
"I2P/Enabled"_s
), false}
522 , m_I2PAddress
{BITTORRENT_SESSION_KEY(u
"I2P/Address"_s
), u
"127.0.0.1"_s
}
523 , m_I2PPort
{BITTORRENT_SESSION_KEY(u
"I2P/Port"_s
), 7656}
524 , m_I2PMixedMode
{BITTORRENT_SESSION_KEY(u
"I2P/MixedMode"_s
), false}
525 , m_I2PInboundQuantity
{BITTORRENT_SESSION_KEY(u
"I2P/InboundQuantity"_s
), 3}
526 , m_I2POutboundQuantity
{BITTORRENT_SESSION_KEY(u
"I2P/OutboundQuantity"_s
), 3}
527 , m_I2PInboundLength
{BITTORRENT_SESSION_KEY(u
"I2P/InboundLength"_s
), 3}
528 , m_I2POutboundLength
{BITTORRENT_SESSION_KEY(u
"I2P/OutboundLength"_s
), 3}
529 , m_torrentContentRemoveOption
{BITTORRENT_SESSION_KEY(u
"TorrentContentRemoveOption"_s
), TorrentContentRemoveOption::MoveToTrash
}
530 , m_startPaused
{BITTORRENT_SESSION_KEY(u
"StartPaused"_s
)}
531 , m_seedingLimitTimer
{new QTimer(this)}
532 , m_resumeDataTimer
{new QTimer(this)}
533 , m_ioThread
{new QThread
}
534 , m_asyncWorker
{new QThreadPool(this)}
535 , m_recentErroredTorrentsTimer
{new QTimer(this)}
537 // It is required to perform async access to libtorrent sequentially
538 m_asyncWorker
->setMaxThreadCount(1);
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 QVector
<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 QVector
<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 QVector
<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 QVector
<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 QVector
<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 QVector
<Torrent
*> SessionImpl::torrents() const
2612 QVector
<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 (findTorrent(infoHash
))
2717 // It looks illogical that we don't just use an existing handle,
2718 // but as previous experience has shown, it actually creates unnecessary
2719 // problems and unwanted behavior due to the fact that it was originally
2720 // added with parameters other than those provided by the user.
2721 cancelDownloadMetadata(id
);
2722 if (infoHash
.isHybrid())
2723 cancelDownloadMetadata(altID
);
2725 LoadTorrentParams loadTorrentParams
= initLoadTorrentParams(addTorrentParams
);
2726 lt::add_torrent_params
&p
= loadTorrentParams
.ltAddTorrentParams
;
2727 p
= source
.ltAddTorrentParams();
2729 bool isFindingIncompleteFiles
= false;
2731 const bool useAutoTMM
= loadTorrentParams
.useAutoTMM
;
2732 const Path actualSavePath
= useAutoTMM
? categorySavePath(loadTorrentParams
.category
) : loadTorrentParams
.savePath
;
2736 // Torrent that is being added with metadata is considered to be added as stopped
2737 // if "metadata received" stop condition is set for it.
2738 if (loadTorrentParams
.stopCondition
== Torrent::StopCondition::MetadataReceived
)
2740 loadTorrentParams
.stopped
= true;
2741 loadTorrentParams
.stopCondition
= Torrent::StopCondition::None
;
2744 const TorrentInfo
&torrentInfo
= *source
.info();
2746 Q_ASSERT(addTorrentParams
.filePaths
.isEmpty() || (addTorrentParams
.filePaths
.size() == torrentInfo
.filesCount()));
2748 PathList filePaths
= addTorrentParams
.filePaths
;
2749 if (filePaths
.isEmpty())
2751 filePaths
= torrentInfo
.filePaths();
2752 if (loadTorrentParams
.contentLayout
!= TorrentContentLayout::Original
)
2754 const Path originalRootFolder
= Path::findRootFolder(filePaths
);
2755 const auto originalContentLayout
= (originalRootFolder
.isEmpty()
2756 ? TorrentContentLayout::NoSubfolder
: TorrentContentLayout::Subfolder
);
2757 if (loadTorrentParams
.contentLayout
!= originalContentLayout
)
2759 if (loadTorrentParams
.contentLayout
== TorrentContentLayout::NoSubfolder
)
2760 Path::stripRootFolder(filePaths
);
2762 Path::addRootFolder(filePaths
, filePaths
.at(0).removedExtension());
2767 // if torrent name wasn't explicitly set we handle the case of
2768 // initial renaming of torrent content and rename torrent accordingly
2769 if (loadTorrentParams
.name
.isEmpty())
2771 QString contentName
= Path::findRootFolder(filePaths
).toString();
2772 if (contentName
.isEmpty() && (filePaths
.size() == 1))
2773 contentName
= filePaths
.at(0).filename();
2775 if (!contentName
.isEmpty() && (contentName
!= torrentInfo
.name()))
2776 loadTorrentParams
.name
= contentName
;
2779 if (!loadTorrentParams
.hasFinishedStatus
)
2781 const Path actualDownloadPath
= useAutoTMM
2782 ? categoryDownloadPath(loadTorrentParams
.category
) : loadTorrentParams
.downloadPath
;
2783 findIncompleteFiles(torrentInfo
, actualSavePath
, actualDownloadPath
, filePaths
);
2784 isFindingIncompleteFiles
= true;
2787 const auto nativeIndexes
= torrentInfo
.nativeIndexes();
2788 if (!isFindingIncompleteFiles
)
2790 for (int index
= 0; index
< filePaths
.size(); ++index
)
2791 p
.renamed_files
[nativeIndexes
[index
]] = filePaths
.at(index
).toString().toStdString();
2794 Q_ASSERT(p
.file_priorities
.empty());
2795 Q_ASSERT(addTorrentParams
.filePriorities
.isEmpty() || (addTorrentParams
.filePriorities
.size() == nativeIndexes
.size()));
2797 QList
<DownloadPriority
> filePriorities
= addTorrentParams
.filePriorities
;
2799 if (filePriorities
.isEmpty() && isExcludedFileNamesEnabled())
2801 // Check file name blacklist when priorities are not explicitly set
2802 applyFilenameFilter(filePaths
, filePriorities
);
2805 const int internalFilesCount
= torrentInfo
.nativeInfo()->files().num_files(); // including .pad files
2806 // Use qBittorrent default priority rather than libtorrent's (4)
2807 p
.file_priorities
= std::vector(internalFilesCount
, LT::toNative(DownloadPriority::Normal
));
2809 if (!filePriorities
.isEmpty())
2811 for (int i
= 0; i
< filePriorities
.size(); ++i
)
2812 p
.file_priorities
[LT::toUnderlyingType(nativeIndexes
[i
])] = LT::toNative(filePriorities
[i
]);
2819 if (loadTorrentParams
.name
.isEmpty() && !p
.name
.empty())
2820 loadTorrentParams
.name
= QString::fromStdString(p
.name
);
2823 p
.save_path
= actualSavePath
.toString().toStdString();
2825 if (isAddTrackersEnabled() && !(hasMetadata
&& p
.ti
->priv()))
2827 const auto maxTierIter
= std::max_element(p
.tracker_tiers
.cbegin(), p
.tracker_tiers
.cend());
2828 const int baseTier
= (maxTierIter
!= p
.tracker_tiers
.cend()) ? (*maxTierIter
+ 1) : 0;
2830 p
.trackers
.reserve(p
.trackers
.size() + static_cast<std::size_t>(m_additionalTrackerEntries
.size()));
2831 p
.tracker_tiers
.reserve(p
.trackers
.size() + static_cast<std::size_t>(m_additionalTrackerEntries
.size()));
2832 p
.tracker_tiers
.resize(p
.trackers
.size(), 0);
2833 for (const TrackerEntry
&trackerEntry
: asConst(m_additionalTrackerEntries
))
2835 p
.trackers
.emplace_back(trackerEntry
.url
.toStdString());
2836 p
.tracker_tiers
.emplace_back(Utils::Number::clampingAdd(trackerEntry
.tier
, baseTier
));
2840 p
.upload_limit
= addTorrentParams
.uploadLimit
;
2841 p
.download_limit
= addTorrentParams
.downloadLimit
;
2843 // Preallocation mode
2844 p
.storage_mode
= isPreallocationEnabled() ? lt::storage_mode_allocate
: lt::storage_mode_sparse
;
2846 if (addTorrentParams
.sequential
)
2847 p
.flags
|= lt::torrent_flags::sequential_download
;
2849 p
.flags
&= ~lt::torrent_flags::sequential_download
;
2852 // Skip checking and directly start seeding
2853 if (addTorrentParams
.skipChecking
)
2854 p
.flags
|= lt::torrent_flags::seed_mode
;
2856 p
.flags
&= ~lt::torrent_flags::seed_mode
;
2858 if (loadTorrentParams
.stopped
|| (loadTorrentParams
.operatingMode
== TorrentOperatingMode::AutoManaged
))
2859 p
.flags
|= lt::torrent_flags::paused
;
2861 p
.flags
&= ~lt::torrent_flags::paused
;
2862 if (loadTorrentParams
.stopped
|| (loadTorrentParams
.operatingMode
== TorrentOperatingMode::Forced
))
2863 p
.flags
&= ~lt::torrent_flags::auto_managed
;
2865 p
.flags
|= lt::torrent_flags::auto_managed
;
2867 p
.flags
|= lt::torrent_flags::duplicate_is_error
;
2869 p
.added_time
= std::time(nullptr);
2872 p
.max_connections
= maxConnectionsPerTorrent();
2873 p
.max_uploads
= maxUploadsPerTorrent();
2875 p
.userdata
= LTClientData(new ExtensionData
);
2876 #ifndef QBT_USES_LIBTORRENT2
2877 p
.storage
= customStorageConstructor
;
2880 m_loadingTorrents
.insert(id
, loadTorrentParams
);
2881 if (infoHash
.isHybrid())
2882 m_hybridTorrentsByAltID
.insert(altID
, nullptr);
2883 if (!isFindingIncompleteFiles
)
2884 m_nativeSession
->async_add_torrent(p
);
2889 void SessionImpl::findIncompleteFiles(const TorrentInfo
&torrentInfo
, const Path
&savePath
2890 , const Path
&downloadPath
, const PathList
&filePaths
) const
2892 Q_ASSERT(filePaths
.isEmpty() || (filePaths
.size() == torrentInfo
.filesCount()));
2894 const auto searchId
= TorrentID::fromInfoHash(torrentInfo
.infoHash());
2895 const PathList originalFileNames
= (filePaths
.isEmpty() ? torrentInfo
.filePaths() : filePaths
);
2896 QMetaObject::invokeMethod(m_fileSearcher
, [=, this]
2898 m_fileSearcher
->search(searchId
, originalFileNames
, savePath
, downloadPath
, isAppendExtensionEnabled());
2902 void SessionImpl::enablePortMapping()
2906 if (m_isPortMappingEnabled
)
2909 lt::settings_pack settingsPack
;
2910 settingsPack
.set_bool(lt::settings_pack::enable_upnp
, true);
2911 settingsPack
.set_bool(lt::settings_pack::enable_natpmp
, true);
2912 m_nativeSession
->apply_settings(std::move(settingsPack
));
2914 m_isPortMappingEnabled
= true;
2916 LogMsg(tr("UPnP/NAT-PMP support: ON"), Log::INFO
);
2920 void SessionImpl::disablePortMapping()
2924 if (!m_isPortMappingEnabled
)
2927 lt::settings_pack settingsPack
;
2928 settingsPack
.set_bool(lt::settings_pack::enable_upnp
, false);
2929 settingsPack
.set_bool(lt::settings_pack::enable_natpmp
, false);
2930 m_nativeSession
->apply_settings(std::move(settingsPack
));
2932 m_mappedPorts
.clear();
2933 m_isPortMappingEnabled
= false;
2935 LogMsg(tr("UPnP/NAT-PMP support: OFF"), Log::INFO
);
2939 void SessionImpl::addMappedPorts(const QSet
<quint16
> &ports
)
2941 invokeAsync([this, ports
]
2943 if (!m_isPortMappingEnabled
)
2946 for (const quint16 port
: ports
)
2948 if (!m_mappedPorts
.contains(port
))
2949 m_mappedPorts
.insert(port
, m_nativeSession
->add_port_mapping(lt::session::tcp
, port
, port
));
2954 void SessionImpl::removeMappedPorts(const QSet
<quint16
> &ports
)
2956 invokeAsync([this, ports
]
2958 if (!m_isPortMappingEnabled
)
2961 Algorithm::removeIf(m_mappedPorts
, [this, ports
](const quint16 port
, const std::vector
<lt::port_mapping_t
> &handles
)
2963 if (!ports
.contains(port
))
2966 for (const lt::port_mapping_t
&handle
: handles
)
2967 m_nativeSession
->delete_port_mapping(handle
);
2974 void SessionImpl::invokeAsync(std::function
<void ()> func
)
2976 m_asyncWorker
->start(std::move(func
));
2979 // Add a torrent to libtorrent session in hidden mode
2980 // and force it to download its metadata
2981 bool SessionImpl::downloadMetadata(const TorrentDescriptor
&torrentDescr
)
2983 Q_ASSERT(!torrentDescr
.info().has_value());
2984 if (torrentDescr
.info().has_value()) [[unlikely
]]
2987 const InfoHash infoHash
= torrentDescr
.infoHash();
2989 // We should not add torrent if it's already
2990 // processed or adding to session
2991 if (isKnownTorrent(infoHash
))
2994 lt::add_torrent_params p
= torrentDescr
.ltAddTorrentParams();
2996 if (isAddTrackersEnabled())
2998 // Use "additional trackers" when metadata retrieving (this can help when the DHT nodes are few)
3000 const auto maxTierIter
= std::max_element(p
.tracker_tiers
.cbegin(), p
.tracker_tiers
.cend());
3001 const int baseTier
= (maxTierIter
!= p
.tracker_tiers
.cend()) ? (*maxTierIter
+ 1) : 0;
3003 p
.trackers
.reserve(p
.trackers
.size() + static_cast<std::size_t>(m_additionalTrackerEntries
.size()));
3004 p
.tracker_tiers
.reserve(p
.trackers
.size() + static_cast<std::size_t>(m_additionalTrackerEntries
.size()));
3005 p
.tracker_tiers
.resize(p
.trackers
.size(), 0);
3006 for (const TrackerEntry
&trackerEntry
: asConst(m_additionalTrackerEntries
))
3008 p
.trackers
.emplace_back(trackerEntry
.url
.toStdString());
3009 p
.tracker_tiers
.emplace_back(Utils::Number::clampingAdd(trackerEntry
.tier
, baseTier
));
3014 // Preallocation mode
3015 if (isPreallocationEnabled())
3016 p
.storage_mode
= lt::storage_mode_allocate
;
3018 p
.storage_mode
= lt::storage_mode_sparse
;
3021 p
.max_connections
= maxConnectionsPerTorrent();
3022 p
.max_uploads
= maxUploadsPerTorrent();
3024 const auto id
= TorrentID::fromInfoHash(infoHash
);
3025 const Path savePath
= Utils::Fs::tempPath() / Path(id
.toString());
3026 p
.save_path
= savePath
.toString().toStdString();
3029 p
.flags
&= ~lt::torrent_flags::paused
;
3030 p
.flags
&= ~lt::torrent_flags::auto_managed
;
3032 // Solution to avoid accidental file writes
3033 p
.flags
|= lt::torrent_flags::upload_mode
;
3035 #ifndef QBT_USES_LIBTORRENT2
3036 p
.storage
= customStorageConstructor
;
3039 // Adding torrent to libtorrent session
3040 m_nativeSession
->async_add_torrent(p
);
3041 m_downloadedMetadata
.insert(id
, {});
3046 void SessionImpl::exportTorrentFile(const Torrent
*torrent
, const Path
&folderPath
)
3048 if (!folderPath
.exists() && !Utils::Fs::mkpath(folderPath
))
3051 const QString validName
= Utils::Fs::toValidFileName(torrent
->name());
3052 QString torrentExportFilename
= u
"%1.torrent"_s
.arg(validName
);
3053 Path newTorrentPath
= folderPath
/ Path(torrentExportFilename
);
3055 while (newTorrentPath
.exists())
3057 // Append number to torrent name to make it unique
3058 torrentExportFilename
= u
"%1 %2.torrent"_s
.arg(validName
).arg(++counter
);
3059 newTorrentPath
= folderPath
/ Path(torrentExportFilename
);
3062 const nonstd::expected
<void, QString
> result
= torrent
->exportToFile(newTorrentPath
);
3065 LogMsg(tr("Failed to export torrent. Torrent: \"%1\". Destination: \"%2\". Reason: \"%3\"")
3066 .arg(torrent
->name(), newTorrentPath
.toString(), result
.error()), Log::WARNING
);
3070 void SessionImpl::generateResumeData()
3072 for (TorrentImpl
*const torrent
: asConst(m_torrents
))
3074 if (torrent
->needSaveResumeData())
3075 torrent
->requestResumeData();
3080 void SessionImpl::saveResumeData()
3082 for (TorrentImpl
*torrent
: asConst(m_torrents
))
3084 // When the session is terminated due to unrecoverable error
3085 // some of the torrent handles can be corrupted
3088 torrent
->requestResumeData(lt::torrent_handle::only_if_modified
);
3090 catch (const std::exception
&) {}
3093 // clear queued storage move jobs except the current ongoing one
3094 if (m_moveStorageQueue
.size() > 1)
3095 m_moveStorageQueue
.resize(1);
3097 QElapsedTimer timer
;
3100 while ((m_numResumeData
> 0) || !m_moveStorageQueue
.isEmpty() || m_needSaveTorrentsQueue
)
3102 const lt::seconds waitTime
{5};
3103 const lt::seconds expireTime
{30};
3105 // only terminate when no storage is moving
3106 if (timer
.hasExpired(lt::total_milliseconds(expireTime
)) && m_moveStorageQueue
.isEmpty())
3108 LogMsg(tr("Aborted saving resume data. Number of outstanding torrents: %1").arg(QString::number(m_numResumeData
))
3113 const std::vector
<lt::alert
*> alerts
= getPendingAlerts(waitTime
);
3115 bool hasWantedAlert
= false;
3116 for (const lt::alert
*alert
: alerts
)
3118 if (const int alertType
= alert
->type();
3119 (alertType
== lt::save_resume_data_alert::alert_type
) || (alertType
== lt::save_resume_data_failed_alert::alert_type
)
3120 || (alertType
== lt::storage_moved_alert::alert_type
) || (alertType
== lt::storage_moved_failed_alert::alert_type
)
3121 || (alertType
== lt::state_update_alert::alert_type
))
3123 hasWantedAlert
= true;
3134 void SessionImpl::saveTorrentsQueue()
3136 QVector
<TorrentID
> queue
;
3137 for (const TorrentImpl
*torrent
: asConst(m_torrents
))
3139 if (const int queuePos
= torrent
->queuePosition(); queuePos
>= 0)
3141 if (queuePos
>= queue
.size())
3142 queue
.resize(queuePos
+ 1);
3143 queue
[queuePos
] = torrent
->id();
3147 m_resumeDataStorage
->storeQueue(queue
);
3148 m_needSaveTorrentsQueue
= false;
3151 void SessionImpl::removeTorrentsQueue()
3153 m_resumeDataStorage
->storeQueue({});
3154 m_torrentsQueueChanged
= false;
3155 m_needSaveTorrentsQueue
= false;
3158 void SessionImpl::setSavePath(const Path
&path
)
3160 const auto newPath
= (path
.isAbsolute() ? path
: (specialFolderLocation(SpecialFolder::Downloads
) / path
));
3161 if (newPath
== m_savePath
)
3164 if (isDisableAutoTMMWhenDefaultSavePathChanged())
3166 QSet
<QString
> affectedCatogories
{{}}; // includes default (unnamed) category
3167 for (auto it
= m_categories
.cbegin(); it
!= m_categories
.cend(); ++it
)
3169 const QString
&categoryName
= it
.key();
3170 const CategoryOptions
&categoryOptions
= it
.value();
3171 if (categoryOptions
.savePath
.isRelative())
3172 affectedCatogories
.insert(categoryName
);
3175 for (TorrentImpl
*const torrent
: asConst(m_torrents
))
3177 if (affectedCatogories
.contains(torrent
->category()))
3178 torrent
->setAutoTMMEnabled(false);
3182 m_savePath
= newPath
;
3183 for (TorrentImpl
*const torrent
: asConst(m_torrents
))
3184 torrent
->handleCategoryOptionsChanged();
3187 void SessionImpl::setDownloadPath(const Path
&path
)
3189 const Path newPath
= (path
.isAbsolute() ? path
: (savePath() / Path(u
"temp"_s
) / path
));
3190 if (newPath
== m_downloadPath
)
3193 if (isDisableAutoTMMWhenDefaultSavePathChanged())
3195 QSet
<QString
> affectedCatogories
{{}}; // includes default (unnamed) category
3196 for (auto it
= m_categories
.cbegin(); it
!= m_categories
.cend(); ++it
)
3198 const QString
&categoryName
= it
.key();
3199 const CategoryOptions
&categoryOptions
= it
.value();
3200 const DownloadPathOption downloadPathOption
=
3201 categoryOptions
.downloadPath
.value_or(DownloadPathOption
{isDownloadPathEnabled(), downloadPath()});
3202 if (downloadPathOption
.enabled
&& downloadPathOption
.path
.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_downloadPath
= newPath
;
3214 for (TorrentImpl
*const torrent
: asConst(m_torrents
))
3215 torrent
->handleCategoryOptionsChanged();
3218 QStringList
SessionImpl::getListeningIPs() const
3222 const QString ifaceName
= networkInterface();
3223 const QString ifaceAddr
= networkInterfaceAddress();
3224 const QHostAddress
configuredAddr(ifaceAddr
);
3225 const bool allIPv4
= (ifaceAddr
== u
"0.0.0.0"); // Means All IPv4 addresses
3226 const bool allIPv6
= (ifaceAddr
== u
"::"); // Means All IPv6 addresses
3228 if (!ifaceAddr
.isEmpty() && !allIPv4
&& !allIPv6
&& configuredAddr
.isNull())
3230 LogMsg(tr("The configured network address is invalid. Address: \"%1\"").arg(ifaceAddr
), Log::CRITICAL
);
3231 // Pass the invalid user configured interface name/address to libtorrent
3232 // in hopes that it will come online later.
3233 // This will not cause IP leak but allow user to reconnect the interface
3234 // and re-establish connection without restarting the client.
3235 IPs
.append(ifaceAddr
);
3239 if (ifaceName
.isEmpty())
3241 if (ifaceAddr
.isEmpty())
3242 return {u
"0.0.0.0"_s
, u
"::"_s
}; // Indicates all interfaces + all addresses (aka default)
3245 return {u
"0.0.0.0"_s
};
3251 const auto checkAndAddIP
= [allIPv4
, allIPv6
, &IPs
](const QHostAddress
&addr
, const QHostAddress
&match
)
3253 if ((allIPv4
&& (addr
.protocol() != QAbstractSocket::IPv4Protocol
))
3254 || (allIPv6
&& (addr
.protocol() != QAbstractSocket::IPv6Protocol
)))
3257 if ((match
== addr
) || allIPv4
|| allIPv6
)
3258 IPs
.append(addr
.toString());
3261 if (ifaceName
.isEmpty())
3263 const QList
<QHostAddress
> addresses
= QNetworkInterface::allAddresses();
3264 for (const auto &addr
: addresses
)
3265 checkAndAddIP(addr
, configuredAddr
);
3267 // At this point ifaceAddr was non-empty
3268 // If IPs.isEmpty() it means the configured Address was not found
3271 LogMsg(tr("Failed to find the configured network address to listen on. Address: \"%1\"")
3272 .arg(ifaceAddr
), Log::CRITICAL
);
3273 IPs
.append(ifaceAddr
);
3279 // Attempt to listen on provided interface
3280 const QNetworkInterface networkIFace
= QNetworkInterface::interfaceFromName(ifaceName
);
3281 if (!networkIFace
.isValid())
3283 qDebug("Invalid network interface: %s", qUtf8Printable(ifaceName
));
3284 LogMsg(tr("The configured network interface is invalid. Interface: \"%1\"").arg(ifaceName
), Log::CRITICAL
);
3285 IPs
.append(ifaceName
);
3289 if (ifaceAddr
.isEmpty())
3291 IPs
.append(ifaceName
);
3292 return IPs
; // On Windows calling code converts it to GUID
3295 const QList
<QNetworkAddressEntry
> addresses
= networkIFace
.addressEntries();
3296 qDebug() << "This network interface has " << addresses
.size() << " IP addresses";
3297 for (const QNetworkAddressEntry
&entry
: addresses
)
3298 checkAndAddIP(entry
.ip(), configuredAddr
);
3300 // Make sure there is at least one IP
3301 // At this point there was an explicit interface and an explicit address set
3302 // and the address should have been found
3305 LogMsg(tr("Failed to find the configured network address to listen on. Address: \"%1\"")
3306 .arg(ifaceAddr
), Log::CRITICAL
);
3307 IPs
.append(ifaceAddr
);
3313 // Set the ports range in which is chosen the port
3314 // the BitTorrent session will listen to
3315 void SessionImpl::configureListeningInterface()
3317 m_listenInterfaceConfigured
= false;
3318 configureDeferred();
3321 int SessionImpl::globalDownloadSpeedLimit() const
3323 // Unfortunately the value was saved as KiB instead of B.
3324 // But it is better to pass it around internally(+ webui) as Bytes.
3325 return m_globalDownloadSpeedLimit
* 1024;
3328 void SessionImpl::setGlobalDownloadSpeedLimit(const int limit
)
3330 // Unfortunately the value was saved as KiB instead of B.
3331 // But it is better to pass it around internally(+ webui) as Bytes.
3332 if (limit
== globalDownloadSpeedLimit())
3336 m_globalDownloadSpeedLimit
= 0;
3337 else if (limit
<= 1024)
3338 m_globalDownloadSpeedLimit
= 1;
3340 m_globalDownloadSpeedLimit
= (limit
/ 1024);
3342 if (!isAltGlobalSpeedLimitEnabled())
3343 configureDeferred();
3346 int SessionImpl::globalUploadSpeedLimit() const
3348 // Unfortunately the value was saved as KiB instead of B.
3349 // But it is better to pass it around internally(+ webui) as Bytes.
3350 return m_globalUploadSpeedLimit
* 1024;
3353 void SessionImpl::setGlobalUploadSpeedLimit(const int limit
)
3355 // Unfortunately the value was saved as KiB instead of B.
3356 // But it is better to pass it around internally(+ webui) as Bytes.
3357 if (limit
== globalUploadSpeedLimit())
3361 m_globalUploadSpeedLimit
= 0;
3362 else if (limit
<= 1024)
3363 m_globalUploadSpeedLimit
= 1;
3365 m_globalUploadSpeedLimit
= (limit
/ 1024);
3367 if (!isAltGlobalSpeedLimitEnabled())
3368 configureDeferred();
3371 int SessionImpl::altGlobalDownloadSpeedLimit() const
3373 // Unfortunately the value was saved as KiB instead of B.
3374 // But it is better to pass it around internally(+ webui) as Bytes.
3375 return m_altGlobalDownloadSpeedLimit
* 1024;
3378 void SessionImpl::setAltGlobalDownloadSpeedLimit(const int limit
)
3380 // Unfortunately the value was saved as KiB instead of B.
3381 // But it is better to pass it around internally(+ webui) as Bytes.
3382 if (limit
== altGlobalDownloadSpeedLimit())
3386 m_altGlobalDownloadSpeedLimit
= 0;
3387 else if (limit
<= 1024)
3388 m_altGlobalDownloadSpeedLimit
= 1;
3390 m_altGlobalDownloadSpeedLimit
= (limit
/ 1024);
3392 if (isAltGlobalSpeedLimitEnabled())
3393 configureDeferred();
3396 int SessionImpl::altGlobalUploadSpeedLimit() const
3398 // Unfortunately the value was saved as KiB instead of B.
3399 // But it is better to pass it around internally(+ webui) as Bytes.
3400 return m_altGlobalUploadSpeedLimit
* 1024;
3403 void SessionImpl::setAltGlobalUploadSpeedLimit(const int limit
)
3405 // Unfortunately the value was saved as KiB instead of B.
3406 // But it is better to pass it around internally(+ webui) as Bytes.
3407 if (limit
== altGlobalUploadSpeedLimit())
3411 m_altGlobalUploadSpeedLimit
= 0;
3412 else if (limit
<= 1024)
3413 m_altGlobalUploadSpeedLimit
= 1;
3415 m_altGlobalUploadSpeedLimit
= (limit
/ 1024);
3417 if (isAltGlobalSpeedLimitEnabled())
3418 configureDeferred();
3421 int SessionImpl::downloadSpeedLimit() const
3423 return isAltGlobalSpeedLimitEnabled()
3424 ? altGlobalDownloadSpeedLimit()
3425 : globalDownloadSpeedLimit();
3428 void SessionImpl::setDownloadSpeedLimit(const int limit
)
3430 if (isAltGlobalSpeedLimitEnabled())
3431 setAltGlobalDownloadSpeedLimit(limit
);
3433 setGlobalDownloadSpeedLimit(limit
);
3436 int SessionImpl::uploadSpeedLimit() const
3438 return isAltGlobalSpeedLimitEnabled()
3439 ? altGlobalUploadSpeedLimit()
3440 : globalUploadSpeedLimit();
3443 void SessionImpl::setUploadSpeedLimit(const int limit
)
3445 if (isAltGlobalSpeedLimitEnabled())
3446 setAltGlobalUploadSpeedLimit(limit
);
3448 setGlobalUploadSpeedLimit(limit
);
3451 bool SessionImpl::isAltGlobalSpeedLimitEnabled() const
3453 return m_isAltGlobalSpeedLimitEnabled
;
3456 void SessionImpl::setAltGlobalSpeedLimitEnabled(const bool enabled
)
3458 if (enabled
== isAltGlobalSpeedLimitEnabled()) return;
3460 // Save new state to remember it on startup
3461 m_isAltGlobalSpeedLimitEnabled
= enabled
;
3462 applyBandwidthLimits();
3464 emit
speedLimitModeChanged(m_isAltGlobalSpeedLimitEnabled
);
3467 bool SessionImpl::isBandwidthSchedulerEnabled() const
3469 return m_isBandwidthSchedulerEnabled
;
3472 void SessionImpl::setBandwidthSchedulerEnabled(const bool enabled
)
3474 if (enabled
!= isBandwidthSchedulerEnabled())
3476 m_isBandwidthSchedulerEnabled
= enabled
;
3478 enableBandwidthScheduler();
3480 delete m_bwScheduler
;
3484 bool SessionImpl::isPerformanceWarningEnabled() const
3486 return m_isPerformanceWarningEnabled
;
3489 void SessionImpl::setPerformanceWarningEnabled(const bool enable
)
3491 if (enable
== m_isPerformanceWarningEnabled
)
3494 m_isPerformanceWarningEnabled
= enable
;
3495 configureDeferred();
3498 int SessionImpl::saveResumeDataInterval() const
3500 return m_saveResumeDataInterval
;
3503 void SessionImpl::setSaveResumeDataInterval(const int value
)
3505 if (value
== m_saveResumeDataInterval
)
3508 m_saveResumeDataInterval
= value
;
3512 m_resumeDataTimer
->setInterval(std::chrono::minutes(value
));
3513 m_resumeDataTimer
->start();
3517 m_resumeDataTimer
->stop();
3521 int SessionImpl::shutdownTimeout() const
3523 return m_shutdownTimeout
;
3526 void SessionImpl::setShutdownTimeout(const int value
)
3528 m_shutdownTimeout
= value
;
3531 int SessionImpl::port() const
3536 void SessionImpl::setPort(const int port
)
3541 configureListeningInterface();
3543 if (isReannounceWhenAddressChangedEnabled())
3544 reannounceToAllTrackers();
3548 bool SessionImpl::isSSLEnabled() const
3550 return m_sslEnabled
;
3553 void SessionImpl::setSSLEnabled(const bool enabled
)
3555 if (enabled
== isSSLEnabled())
3558 m_sslEnabled
= enabled
;
3559 configureListeningInterface();
3561 if (isReannounceWhenAddressChangedEnabled())
3562 reannounceToAllTrackers();
3565 int SessionImpl::sslPort() const
3570 void SessionImpl::setSSLPort(const int port
)
3572 if (port
== sslPort())
3576 configureListeningInterface();
3578 if (isReannounceWhenAddressChangedEnabled())
3579 reannounceToAllTrackers();
3582 QString
SessionImpl::networkInterface() const
3584 return m_networkInterface
;
3587 void SessionImpl::setNetworkInterface(const QString
&iface
)
3589 if (iface
!= networkInterface())
3591 m_networkInterface
= iface
;
3592 configureListeningInterface();
3596 QString
SessionImpl::networkInterfaceName() const
3598 return m_networkInterfaceName
;
3601 void SessionImpl::setNetworkInterfaceName(const QString
&name
)
3603 m_networkInterfaceName
= name
;
3606 QString
SessionImpl::networkInterfaceAddress() const
3608 return m_networkInterfaceAddress
;
3611 void SessionImpl::setNetworkInterfaceAddress(const QString
&address
)
3613 if (address
!= networkInterfaceAddress())
3615 m_networkInterfaceAddress
= address
;
3616 configureListeningInterface();
3620 int SessionImpl::encryption() const
3622 return m_encryption
;
3625 void SessionImpl::setEncryption(const int state
)
3627 if (state
!= encryption())
3629 m_encryption
= state
;
3630 configureDeferred();
3631 LogMsg(tr("Encryption support: %1").arg(
3632 state
== 0 ? tr("ON") : ((state
== 1) ? tr("FORCED") : tr("OFF")))
3637 int SessionImpl::maxActiveCheckingTorrents() const
3639 return m_maxActiveCheckingTorrents
;
3642 void SessionImpl::setMaxActiveCheckingTorrents(const int val
)
3644 if (val
== m_maxActiveCheckingTorrents
)
3647 m_maxActiveCheckingTorrents
= val
;
3648 configureDeferred();
3651 bool SessionImpl::isI2PEnabled() const
3653 return m_isI2PEnabled
;
3656 void SessionImpl::setI2PEnabled(const bool enabled
)
3658 if (m_isI2PEnabled
!= enabled
)
3660 m_isI2PEnabled
= enabled
;
3661 configureDeferred();
3665 QString
SessionImpl::I2PAddress() const
3667 return m_I2PAddress
;
3670 void SessionImpl::setI2PAddress(const QString
&address
)
3672 if (m_I2PAddress
!= address
)
3674 m_I2PAddress
= address
;
3675 configureDeferred();
3679 int SessionImpl::I2PPort() const
3684 void SessionImpl::setI2PPort(int port
)
3686 if (m_I2PPort
!= port
)
3689 configureDeferred();
3693 bool SessionImpl::I2PMixedMode() const
3695 return m_I2PMixedMode
;
3698 void SessionImpl::setI2PMixedMode(const bool enabled
)
3700 if (m_I2PMixedMode
!= enabled
)
3702 m_I2PMixedMode
= enabled
;
3703 configureDeferred();
3707 int SessionImpl::I2PInboundQuantity() const
3709 return m_I2PInboundQuantity
;
3712 void SessionImpl::setI2PInboundQuantity(const int value
)
3714 if (value
== m_I2PInboundQuantity
)
3717 m_I2PInboundQuantity
= value
;
3718 configureDeferred();
3721 int SessionImpl::I2POutboundQuantity() const
3723 return m_I2POutboundQuantity
;
3726 void SessionImpl::setI2POutboundQuantity(const int value
)
3728 if (value
== m_I2POutboundQuantity
)
3731 m_I2POutboundQuantity
= value
;
3732 configureDeferred();
3735 int SessionImpl::I2PInboundLength() const
3737 return m_I2PInboundLength
;
3740 void SessionImpl::setI2PInboundLength(const int value
)
3742 if (value
== m_I2PInboundLength
)
3745 m_I2PInboundLength
= value
;
3746 configureDeferred();
3749 int SessionImpl::I2POutboundLength() const
3751 return m_I2POutboundLength
;
3754 void SessionImpl::setI2POutboundLength(const int value
)
3756 if (value
== m_I2POutboundLength
)
3759 m_I2POutboundLength
= value
;
3760 configureDeferred();
3763 bool SessionImpl::isProxyPeerConnectionsEnabled() const
3765 return m_isProxyPeerConnectionsEnabled
;
3768 void SessionImpl::setProxyPeerConnectionsEnabled(const bool enabled
)
3770 if (enabled
!= isProxyPeerConnectionsEnabled())
3772 m_isProxyPeerConnectionsEnabled
= enabled
;
3773 configureDeferred();
3777 ChokingAlgorithm
SessionImpl::chokingAlgorithm() const
3779 return m_chokingAlgorithm
;
3782 void SessionImpl::setChokingAlgorithm(const ChokingAlgorithm mode
)
3784 if (mode
== m_chokingAlgorithm
) return;
3786 m_chokingAlgorithm
= mode
;
3787 configureDeferred();
3790 SeedChokingAlgorithm
SessionImpl::seedChokingAlgorithm() const
3792 return m_seedChokingAlgorithm
;
3795 void SessionImpl::setSeedChokingAlgorithm(const SeedChokingAlgorithm mode
)
3797 if (mode
== m_seedChokingAlgorithm
) return;
3799 m_seedChokingAlgorithm
= mode
;
3800 configureDeferred();
3803 bool SessionImpl::isAddTrackersEnabled() const
3805 return m_isAddTrackersEnabled
;
3808 void SessionImpl::setAddTrackersEnabled(const bool enabled
)
3810 m_isAddTrackersEnabled
= enabled
;
3813 QString
SessionImpl::additionalTrackers() const
3815 return m_additionalTrackers
;
3818 void SessionImpl::setAdditionalTrackers(const QString
&trackers
)
3820 if (trackers
== additionalTrackers())
3823 m_additionalTrackers
= trackers
;
3824 populateAdditionalTrackers();
3827 bool SessionImpl::isIPFilteringEnabled() const
3829 return m_isIPFilteringEnabled
;
3832 void SessionImpl::setIPFilteringEnabled(const bool enabled
)
3834 if (enabled
!= m_isIPFilteringEnabled
)
3836 m_isIPFilteringEnabled
= enabled
;
3837 m_IPFilteringConfigured
= false;
3838 configureDeferred();
3842 Path
SessionImpl::IPFilterFile() const
3844 return m_IPFilterFile
;
3847 void SessionImpl::setIPFilterFile(const Path
&path
)
3849 if (path
!= IPFilterFile())
3851 m_IPFilterFile
= path
;
3852 m_IPFilteringConfigured
= false;
3853 configureDeferred();
3857 bool SessionImpl::isExcludedFileNamesEnabled() const
3859 return m_isExcludedFileNamesEnabled
;
3862 void SessionImpl::setExcludedFileNamesEnabled(const bool enabled
)
3864 if (m_isExcludedFileNamesEnabled
== enabled
)
3867 m_isExcludedFileNamesEnabled
= enabled
;
3870 populateExcludedFileNamesRegExpList();
3872 m_excludedFileNamesRegExpList
.clear();
3875 QStringList
SessionImpl::excludedFileNames() const
3877 return m_excludedFileNames
;
3880 void SessionImpl::setExcludedFileNames(const QStringList
&excludedFileNames
)
3882 if (excludedFileNames
!= m_excludedFileNames
)
3884 m_excludedFileNames
= excludedFileNames
;
3885 populateExcludedFileNamesRegExpList();
3889 void SessionImpl::populateExcludedFileNamesRegExpList()
3891 const QStringList excludedNames
= excludedFileNames();
3893 m_excludedFileNamesRegExpList
.clear();
3894 m_excludedFileNamesRegExpList
.reserve(excludedNames
.size());
3896 for (const QString
&str
: excludedNames
)
3898 const QString pattern
= QRegularExpression::wildcardToRegularExpression(str
);
3899 const QRegularExpression re
{pattern
, QRegularExpression::CaseInsensitiveOption
};
3900 m_excludedFileNamesRegExpList
.append(re
);
3904 void SessionImpl::applyFilenameFilter(const PathList
&files
, QList
<DownloadPriority
> &priorities
)
3906 if (!isExcludedFileNamesEnabled())
3909 const auto isFilenameExcluded
= [patterns
= m_excludedFileNamesRegExpList
](const Path
&fileName
)
3911 return std::any_of(patterns
.begin(), patterns
.end(), [&fileName
](const QRegularExpression
&re
)
3913 Path path
= fileName
;
3914 while (!re
.match(path
.filename()).hasMatch())
3916 path
= path
.parentPath();
3924 priorities
.resize(files
.count(), DownloadPriority::Normal
);
3925 for (int i
= 0; i
< priorities
.size(); ++i
)
3927 if (priorities
[i
] == BitTorrent::DownloadPriority::Ignored
)
3930 if (isFilenameExcluded(files
.at(i
)))
3931 priorities
[i
] = BitTorrent::DownloadPriority::Ignored
;
3935 void SessionImpl::setBannedIPs(const QStringList
&newList
)
3937 if (newList
== m_bannedIPs
)
3938 return; // do nothing
3939 // here filter out incorrect IP
3940 QStringList filteredList
;
3941 for (const QString
&ip
: newList
)
3943 if (Utils::Net::isValidIP(ip
))
3945 // the same IPv6 addresses could be written in different forms;
3946 // QHostAddress::toString() result format follows RFC5952;
3947 // thus we avoid duplicate entries pointing to the same address
3948 filteredList
<< QHostAddress(ip
).toString();
3952 LogMsg(tr("Rejected invalid IP address while applying the list of banned IP addresses. IP: \"%1\"")
3957 // now we have to sort IPs and make them unique
3958 filteredList
.sort();
3959 filteredList
.removeDuplicates();
3960 // Again ensure that the new list is different from the stored one.
3961 if (filteredList
== m_bannedIPs
)
3962 return; // do nothing
3963 // store to session settings
3964 // also here we have to recreate filter list including 3rd party ban file
3965 // and install it again into m_session
3966 m_bannedIPs
= filteredList
;
3967 m_IPFilteringConfigured
= false;
3968 configureDeferred();
3971 ResumeDataStorageType
SessionImpl::resumeDataStorageType() const
3973 return m_resumeDataStorageType
;
3976 void SessionImpl::setResumeDataStorageType(const ResumeDataStorageType type
)
3978 m_resumeDataStorageType
= type
;
3981 bool SessionImpl::isMergeTrackersEnabled() const
3983 return m_isMergeTrackersEnabled
;
3986 void SessionImpl::setMergeTrackersEnabled(const bool enabled
)
3988 m_isMergeTrackersEnabled
= enabled
;
3991 bool SessionImpl::isStartPaused() const
3993 return m_startPaused
.get(false);
3996 void SessionImpl::setStartPaused(const bool value
)
3998 m_startPaused
= value
;
4001 TorrentContentRemoveOption
SessionImpl::torrentContentRemoveOption() const
4003 return m_torrentContentRemoveOption
;
4006 void SessionImpl::setTorrentContentRemoveOption(const TorrentContentRemoveOption option
)
4008 m_torrentContentRemoveOption
= option
;
4011 QStringList
SessionImpl::bannedIPs() const
4016 bool SessionImpl::isRestored() const
4018 return m_isRestored
;
4021 bool SessionImpl::isPaused() const
4026 void SessionImpl::pause()
4031 m_nativeSession
->pause();
4038 void SessionImpl::resume()
4043 m_nativeSession
->resume();
4050 int SessionImpl::maxConnectionsPerTorrent() const
4052 return m_maxConnectionsPerTorrent
;
4055 void SessionImpl::setMaxConnectionsPerTorrent(int max
)
4057 max
= (max
> 0) ? max
: -1;
4058 if (max
!= maxConnectionsPerTorrent())
4060 m_maxConnectionsPerTorrent
= max
;
4062 for (const TorrentImpl
*torrent
: asConst(m_torrents
))
4066 torrent
->nativeHandle().set_max_connections(max
);
4068 catch (const std::exception
&) {}
4073 int SessionImpl::maxUploadsPerTorrent() const
4075 return m_maxUploadsPerTorrent
;
4078 void SessionImpl::setMaxUploadsPerTorrent(int max
)
4080 max
= (max
> 0) ? max
: -1;
4081 if (max
!= maxUploadsPerTorrent())
4083 m_maxUploadsPerTorrent
= max
;
4085 for (const TorrentImpl
*torrent
: asConst(m_torrents
))
4089 torrent
->nativeHandle().set_max_uploads(max
);
4091 catch (const std::exception
&) {}
4096 bool SessionImpl::announceToAllTrackers() const
4098 return m_announceToAllTrackers
;
4101 void SessionImpl::setAnnounceToAllTrackers(const bool val
)
4103 if (val
!= m_announceToAllTrackers
)
4105 m_announceToAllTrackers
= val
;
4106 configureDeferred();
4110 bool SessionImpl::announceToAllTiers() const
4112 return m_announceToAllTiers
;
4115 void SessionImpl::setAnnounceToAllTiers(const bool val
)
4117 if (val
!= m_announceToAllTiers
)
4119 m_announceToAllTiers
= val
;
4120 configureDeferred();
4124 int SessionImpl::peerTurnover() const
4126 return m_peerTurnover
;
4129 void SessionImpl::setPeerTurnover(const int val
)
4131 if (val
== m_peerTurnover
)
4134 m_peerTurnover
= val
;
4135 configureDeferred();
4138 int SessionImpl::peerTurnoverCutoff() const
4140 return m_peerTurnoverCutoff
;
4143 void SessionImpl::setPeerTurnoverCutoff(const int val
)
4145 if (val
== m_peerTurnoverCutoff
)
4148 m_peerTurnoverCutoff
= val
;
4149 configureDeferred();
4152 int SessionImpl::peerTurnoverInterval() const
4154 return m_peerTurnoverInterval
;
4157 void SessionImpl::setPeerTurnoverInterval(const int val
)
4159 if (val
== m_peerTurnoverInterval
)
4162 m_peerTurnoverInterval
= val
;
4163 configureDeferred();
4166 DiskIOType
SessionImpl::diskIOType() const
4168 return m_diskIOType
;
4171 void SessionImpl::setDiskIOType(const DiskIOType type
)
4173 if (type
!= m_diskIOType
)
4175 m_diskIOType
= type
;
4179 int SessionImpl::requestQueueSize() const
4181 return m_requestQueueSize
;
4184 void SessionImpl::setRequestQueueSize(const int val
)
4186 if (val
== m_requestQueueSize
)
4189 m_requestQueueSize
= val
;
4190 configureDeferred();
4193 int SessionImpl::asyncIOThreads() const
4195 return std::clamp(m_asyncIOThreads
.get(), 1, 1024);
4198 void SessionImpl::setAsyncIOThreads(const int num
)
4200 if (num
== m_asyncIOThreads
)
4203 m_asyncIOThreads
= num
;
4204 configureDeferred();
4207 int SessionImpl::hashingThreads() const
4209 return std::clamp(m_hashingThreads
.get(), 1, 1024);
4212 void SessionImpl::setHashingThreads(const int num
)
4214 if (num
== m_hashingThreads
)
4217 m_hashingThreads
= num
;
4218 configureDeferred();
4221 int SessionImpl::filePoolSize() const
4223 return m_filePoolSize
;
4226 void SessionImpl::setFilePoolSize(const int size
)
4228 if (size
== m_filePoolSize
)
4231 m_filePoolSize
= size
;
4232 configureDeferred();
4235 int SessionImpl::checkingMemUsage() const
4237 return std::max(1, m_checkingMemUsage
.get());
4240 void SessionImpl::setCheckingMemUsage(int size
)
4242 size
= std::max(size
, 1);
4244 if (size
== m_checkingMemUsage
)
4247 m_checkingMemUsage
= size
;
4248 configureDeferred();
4251 int SessionImpl::diskCacheSize() const
4253 #ifdef QBT_APP_64BIT
4254 return std::min(m_diskCacheSize
.get(), 33554431); // 32768GiB
4256 // When build as 32bit binary, set the maximum at less than 2GB to prevent crashes
4257 // allocate 1536MiB and leave 512MiB to the rest of program data in RAM
4258 return std::min(m_diskCacheSize
.get(), 1536);
4262 void SessionImpl::setDiskCacheSize(int size
)
4264 #ifdef QBT_APP_64BIT
4265 size
= std::min(size
, 33554431); // 32768GiB
4267 // allocate 1536MiB and leave 512MiB to the rest of program data in RAM
4268 size
= std::min(size
, 1536);
4270 if (size
!= m_diskCacheSize
)
4272 m_diskCacheSize
= size
;
4273 configureDeferred();
4277 int SessionImpl::diskCacheTTL() const
4279 return m_diskCacheTTL
;
4282 void SessionImpl::setDiskCacheTTL(const int ttl
)
4284 if (ttl
!= m_diskCacheTTL
)
4286 m_diskCacheTTL
= ttl
;
4287 configureDeferred();
4291 qint64
SessionImpl::diskQueueSize() const
4293 return m_diskQueueSize
;
4296 void SessionImpl::setDiskQueueSize(const qint64 size
)
4298 if (size
== m_diskQueueSize
)
4301 m_diskQueueSize
= size
;
4302 configureDeferred();
4305 DiskIOReadMode
SessionImpl::diskIOReadMode() const
4307 return m_diskIOReadMode
;
4310 void SessionImpl::setDiskIOReadMode(const DiskIOReadMode mode
)
4312 if (mode
== m_diskIOReadMode
)
4315 m_diskIOReadMode
= mode
;
4316 configureDeferred();
4319 DiskIOWriteMode
SessionImpl::diskIOWriteMode() const
4321 return m_diskIOWriteMode
;
4324 void SessionImpl::setDiskIOWriteMode(const DiskIOWriteMode mode
)
4326 if (mode
== m_diskIOWriteMode
)
4329 m_diskIOWriteMode
= mode
;
4330 configureDeferred();
4333 bool SessionImpl::isCoalesceReadWriteEnabled() const
4335 return m_coalesceReadWriteEnabled
;
4338 void SessionImpl::setCoalesceReadWriteEnabled(const bool enabled
)
4340 if (enabled
== m_coalesceReadWriteEnabled
) return;
4342 m_coalesceReadWriteEnabled
= enabled
;
4343 configureDeferred();
4346 bool SessionImpl::isSuggestModeEnabled() const
4348 return m_isSuggestMode
;
4351 bool SessionImpl::usePieceExtentAffinity() const
4353 return m_usePieceExtentAffinity
;
4356 void SessionImpl::setPieceExtentAffinity(const bool enabled
)
4358 if (enabled
== m_usePieceExtentAffinity
) return;
4360 m_usePieceExtentAffinity
= enabled
;
4361 configureDeferred();
4364 void SessionImpl::setSuggestMode(const bool mode
)
4366 if (mode
== m_isSuggestMode
) return;
4368 m_isSuggestMode
= mode
;
4369 configureDeferred();
4372 int SessionImpl::sendBufferWatermark() const
4374 return m_sendBufferWatermark
;
4377 void SessionImpl::setSendBufferWatermark(const int value
)
4379 if (value
== m_sendBufferWatermark
) return;
4381 m_sendBufferWatermark
= value
;
4382 configureDeferred();
4385 int SessionImpl::sendBufferLowWatermark() const
4387 return m_sendBufferLowWatermark
;
4390 void SessionImpl::setSendBufferLowWatermark(const int value
)
4392 if (value
== m_sendBufferLowWatermark
) return;
4394 m_sendBufferLowWatermark
= value
;
4395 configureDeferred();
4398 int SessionImpl::sendBufferWatermarkFactor() const
4400 return m_sendBufferWatermarkFactor
;
4403 void SessionImpl::setSendBufferWatermarkFactor(const int value
)
4405 if (value
== m_sendBufferWatermarkFactor
) return;
4407 m_sendBufferWatermarkFactor
= value
;
4408 configureDeferred();
4411 int SessionImpl::connectionSpeed() const
4413 return m_connectionSpeed
;
4416 void SessionImpl::setConnectionSpeed(const int value
)
4418 if (value
== m_connectionSpeed
) return;
4420 m_connectionSpeed
= value
;
4421 configureDeferred();
4424 int SessionImpl::socketSendBufferSize() const
4426 return m_socketSendBufferSize
;
4429 void SessionImpl::setSocketSendBufferSize(const int value
)
4431 if (value
== m_socketSendBufferSize
)
4434 m_socketSendBufferSize
= value
;
4435 configureDeferred();
4438 int SessionImpl::socketReceiveBufferSize() const
4440 return m_socketReceiveBufferSize
;
4443 void SessionImpl::setSocketReceiveBufferSize(const int value
)
4445 if (value
== m_socketReceiveBufferSize
)
4448 m_socketReceiveBufferSize
= value
;
4449 configureDeferred();
4452 int SessionImpl::socketBacklogSize() const
4454 return m_socketBacklogSize
;
4457 void SessionImpl::setSocketBacklogSize(const int value
)
4459 if (value
== m_socketBacklogSize
) return;
4461 m_socketBacklogSize
= value
;
4462 configureDeferred();
4465 bool SessionImpl::isAnonymousModeEnabled() const
4467 return m_isAnonymousModeEnabled
;
4470 void SessionImpl::setAnonymousModeEnabled(const bool enabled
)
4472 if (enabled
!= m_isAnonymousModeEnabled
)
4474 m_isAnonymousModeEnabled
= enabled
;
4475 configureDeferred();
4476 LogMsg(tr("Anonymous mode: %1").arg(isAnonymousModeEnabled() ? tr("ON") : tr("OFF"))
4481 bool SessionImpl::isQueueingSystemEnabled() const
4483 return m_isQueueingEnabled
;
4486 void SessionImpl::setQueueingSystemEnabled(const bool enabled
)
4488 if (enabled
!= m_isQueueingEnabled
)
4490 m_isQueueingEnabled
= enabled
;
4491 configureDeferred();
4494 m_torrentsQueueChanged
= true;
4496 removeTorrentsQueue();
4498 for (TorrentImpl
*torrent
: asConst(m_torrents
))
4499 torrent
->handleQueueingModeChanged();
4503 int SessionImpl::maxActiveDownloads() const
4505 return m_maxActiveDownloads
;
4508 void SessionImpl::setMaxActiveDownloads(int max
)
4510 max
= std::max(max
, -1);
4511 if (max
!= m_maxActiveDownloads
)
4513 m_maxActiveDownloads
= max
;
4514 configureDeferred();
4518 int SessionImpl::maxActiveUploads() const
4520 return m_maxActiveUploads
;
4523 void SessionImpl::setMaxActiveUploads(int max
)
4525 max
= std::max(max
, -1);
4526 if (max
!= m_maxActiveUploads
)
4528 m_maxActiveUploads
= max
;
4529 configureDeferred();
4533 int SessionImpl::maxActiveTorrents() const
4535 return m_maxActiveTorrents
;
4538 void SessionImpl::setMaxActiveTorrents(int max
)
4540 max
= std::max(max
, -1);
4541 if (max
!= m_maxActiveTorrents
)
4543 m_maxActiveTorrents
= max
;
4544 configureDeferred();
4548 bool SessionImpl::ignoreSlowTorrentsForQueueing() const
4550 return m_ignoreSlowTorrentsForQueueing
;
4553 void SessionImpl::setIgnoreSlowTorrentsForQueueing(const bool ignore
)
4555 if (ignore
!= m_ignoreSlowTorrentsForQueueing
)
4557 m_ignoreSlowTorrentsForQueueing
= ignore
;
4558 configureDeferred();
4562 int SessionImpl::downloadRateForSlowTorrents() const
4564 return m_downloadRateForSlowTorrents
;
4567 void SessionImpl::setDownloadRateForSlowTorrents(const int rateInKibiBytes
)
4569 if (rateInKibiBytes
== m_downloadRateForSlowTorrents
)
4572 m_downloadRateForSlowTorrents
= rateInKibiBytes
;
4573 configureDeferred();
4576 int SessionImpl::uploadRateForSlowTorrents() const
4578 return m_uploadRateForSlowTorrents
;
4581 void SessionImpl::setUploadRateForSlowTorrents(const int rateInKibiBytes
)
4583 if (rateInKibiBytes
== m_uploadRateForSlowTorrents
)
4586 m_uploadRateForSlowTorrents
= rateInKibiBytes
;
4587 configureDeferred();
4590 int SessionImpl::slowTorrentsInactivityTimer() const
4592 return m_slowTorrentsInactivityTimer
;
4595 void SessionImpl::setSlowTorrentsInactivityTimer(const int timeInSeconds
)
4597 if (timeInSeconds
== m_slowTorrentsInactivityTimer
)
4600 m_slowTorrentsInactivityTimer
= timeInSeconds
;
4601 configureDeferred();
4604 int SessionImpl::outgoingPortsMin() const
4606 return m_outgoingPortsMin
;
4609 void SessionImpl::setOutgoingPortsMin(const int min
)
4611 if (min
!= m_outgoingPortsMin
)
4613 m_outgoingPortsMin
= min
;
4614 configureDeferred();
4618 int SessionImpl::outgoingPortsMax() const
4620 return m_outgoingPortsMax
;
4623 void SessionImpl::setOutgoingPortsMax(const int max
)
4625 if (max
!= m_outgoingPortsMax
)
4627 m_outgoingPortsMax
= max
;
4628 configureDeferred();
4632 int SessionImpl::UPnPLeaseDuration() const
4634 return m_UPnPLeaseDuration
;
4637 void SessionImpl::setUPnPLeaseDuration(const int duration
)
4639 if (duration
!= m_UPnPLeaseDuration
)
4641 m_UPnPLeaseDuration
= duration
;
4642 configureDeferred();
4646 int SessionImpl::peerToS() const
4651 void SessionImpl::setPeerToS(const int value
)
4653 if (value
== m_peerToS
)
4657 configureDeferred();
4660 bool SessionImpl::ignoreLimitsOnLAN() const
4662 return m_ignoreLimitsOnLAN
;
4665 void SessionImpl::setIgnoreLimitsOnLAN(const bool ignore
)
4667 if (ignore
!= m_ignoreLimitsOnLAN
)
4669 m_ignoreLimitsOnLAN
= ignore
;
4670 configureDeferred();
4674 bool SessionImpl::includeOverheadInLimits() const
4676 return m_includeOverheadInLimits
;
4679 void SessionImpl::setIncludeOverheadInLimits(const bool include
)
4681 if (include
!= m_includeOverheadInLimits
)
4683 m_includeOverheadInLimits
= include
;
4684 configureDeferred();
4688 QString
SessionImpl::announceIP() const
4690 return m_announceIP
;
4693 void SessionImpl::setAnnounceIP(const QString
&ip
)
4695 if (ip
!= m_announceIP
)
4698 configureDeferred();
4702 int SessionImpl::maxConcurrentHTTPAnnounces() const
4704 return m_maxConcurrentHTTPAnnounces
;
4707 void SessionImpl::setMaxConcurrentHTTPAnnounces(const int value
)
4709 if (value
== m_maxConcurrentHTTPAnnounces
)
4712 m_maxConcurrentHTTPAnnounces
= value
;
4713 configureDeferred();
4716 bool SessionImpl::isReannounceWhenAddressChangedEnabled() const
4718 return m_isReannounceWhenAddressChangedEnabled
;
4721 void SessionImpl::setReannounceWhenAddressChangedEnabled(const bool enabled
)
4723 if (enabled
== m_isReannounceWhenAddressChangedEnabled
)
4726 m_isReannounceWhenAddressChangedEnabled
= enabled
;
4729 void SessionImpl::reannounceToAllTrackers() const
4731 for (const TorrentImpl
*torrent
: asConst(m_torrents
))
4735 torrent
->nativeHandle().force_reannounce(0, -1, lt::torrent_handle::ignore_min_interval
);
4737 catch (const std::exception
&) {}
4741 int SessionImpl::stopTrackerTimeout() const
4743 return m_stopTrackerTimeout
;
4746 void SessionImpl::setStopTrackerTimeout(const int value
)
4748 if (value
== m_stopTrackerTimeout
)
4751 m_stopTrackerTimeout
= value
;
4752 configureDeferred();
4755 int SessionImpl::maxConnections() const
4757 return m_maxConnections
;
4760 void SessionImpl::setMaxConnections(int max
)
4762 max
= (max
> 0) ? max
: -1;
4763 if (max
!= m_maxConnections
)
4765 m_maxConnections
= max
;
4766 configureDeferred();
4770 int SessionImpl::maxUploads() const
4772 return m_maxUploads
;
4775 void SessionImpl::setMaxUploads(int max
)
4777 max
= (max
> 0) ? max
: -1;
4778 if (max
!= m_maxUploads
)
4781 configureDeferred();
4785 BTProtocol
SessionImpl::btProtocol() const
4787 return m_btProtocol
;
4790 void SessionImpl::setBTProtocol(const BTProtocol protocol
)
4792 if ((protocol
< BTProtocol::Both
) || (BTProtocol::UTP
< protocol
))
4795 if (protocol
== m_btProtocol
) return;
4797 m_btProtocol
= protocol
;
4798 configureDeferred();
4801 bool SessionImpl::isUTPRateLimited() const
4803 return m_isUTPRateLimited
;
4806 void SessionImpl::setUTPRateLimited(const bool limited
)
4808 if (limited
!= m_isUTPRateLimited
)
4810 m_isUTPRateLimited
= limited
;
4811 configureDeferred();
4815 MixedModeAlgorithm
SessionImpl::utpMixedMode() const
4817 return m_utpMixedMode
;
4820 void SessionImpl::setUtpMixedMode(const MixedModeAlgorithm mode
)
4822 if (mode
== m_utpMixedMode
) return;
4824 m_utpMixedMode
= mode
;
4825 configureDeferred();
4828 bool SessionImpl::isIDNSupportEnabled() const
4830 return m_IDNSupportEnabled
;
4833 void SessionImpl::setIDNSupportEnabled(const bool enabled
)
4835 if (enabled
== m_IDNSupportEnabled
) return;
4837 m_IDNSupportEnabled
= enabled
;
4838 configureDeferred();
4841 bool SessionImpl::multiConnectionsPerIpEnabled() const
4843 return m_multiConnectionsPerIpEnabled
;
4846 void SessionImpl::setMultiConnectionsPerIpEnabled(const bool enabled
)
4848 if (enabled
== m_multiConnectionsPerIpEnabled
) return;
4850 m_multiConnectionsPerIpEnabled
= enabled
;
4851 configureDeferred();
4854 bool SessionImpl::validateHTTPSTrackerCertificate() const
4856 return m_validateHTTPSTrackerCertificate
;
4859 void SessionImpl::setValidateHTTPSTrackerCertificate(const bool enabled
)
4861 if (enabled
== m_validateHTTPSTrackerCertificate
) return;
4863 m_validateHTTPSTrackerCertificate
= enabled
;
4864 configureDeferred();
4867 bool SessionImpl::isSSRFMitigationEnabled() const
4869 return m_SSRFMitigationEnabled
;
4872 void SessionImpl::setSSRFMitigationEnabled(const bool enabled
)
4874 if (enabled
== m_SSRFMitigationEnabled
) return;
4876 m_SSRFMitigationEnabled
= enabled
;
4877 configureDeferred();
4880 bool SessionImpl::blockPeersOnPrivilegedPorts() const
4882 return m_blockPeersOnPrivilegedPorts
;
4885 void SessionImpl::setBlockPeersOnPrivilegedPorts(const bool enabled
)
4887 if (enabled
== m_blockPeersOnPrivilegedPorts
) return;
4889 m_blockPeersOnPrivilegedPorts
= enabled
;
4890 configureDeferred();
4893 bool SessionImpl::isTrackerFilteringEnabled() const
4895 return m_isTrackerFilteringEnabled
;
4898 void SessionImpl::setTrackerFilteringEnabled(const bool enabled
)
4900 if (enabled
!= m_isTrackerFilteringEnabled
)
4902 m_isTrackerFilteringEnabled
= enabled
;
4903 configureDeferred();
4907 bool SessionImpl::isListening() const
4909 return m_nativeSessionExtension
->isSessionListening();
4912 ShareLimitAction
SessionImpl::shareLimitAction() const
4914 return m_shareLimitAction
;
4917 void SessionImpl::setShareLimitAction(const ShareLimitAction act
)
4919 Q_ASSERT(act
!= ShareLimitAction::Default
);
4921 m_shareLimitAction
= act
;
4924 bool SessionImpl::isKnownTorrent(const InfoHash
&infoHash
) const
4926 const bool isHybrid
= infoHash
.isHybrid();
4927 const auto id
= TorrentID::fromInfoHash(infoHash
);
4928 // alternative ID can be useful to find existing torrent
4929 // in case if hybrid torrent was added by v1 info hash
4930 const auto altID
= (isHybrid
? TorrentID::fromSHA1Hash(infoHash
.v1()) : TorrentID());
4932 if (m_loadingTorrents
.contains(id
) || (isHybrid
&& m_loadingTorrents
.contains(altID
)))
4934 if (m_downloadedMetadata
.contains(id
) || (isHybrid
&& m_downloadedMetadata
.contains(altID
)))
4936 return findTorrent(infoHash
);
4939 void SessionImpl::updateSeedingLimitTimer()
4941 if ((globalMaxRatio() == Torrent::NO_RATIO_LIMIT
) && !hasPerTorrentRatioLimit()
4942 && (globalMaxSeedingMinutes() == Torrent::NO_SEEDING_TIME_LIMIT
) && !hasPerTorrentSeedingTimeLimit()
4943 && (globalMaxInactiveSeedingMinutes() == Torrent::NO_INACTIVE_SEEDING_TIME_LIMIT
) && !hasPerTorrentInactiveSeedingTimeLimit())
4945 if (m_seedingLimitTimer
->isActive())
4946 m_seedingLimitTimer
->stop();
4948 else if (!m_seedingLimitTimer
->isActive())
4950 m_seedingLimitTimer
->start();
4954 void SessionImpl::handleTorrentShareLimitChanged(TorrentImpl
*const)
4956 updateSeedingLimitTimer();
4959 void SessionImpl::handleTorrentNameChanged(TorrentImpl
*const)
4963 void SessionImpl::handleTorrentSavePathChanged(TorrentImpl
*const torrent
)
4965 emit
torrentSavePathChanged(torrent
);
4968 void SessionImpl::handleTorrentCategoryChanged(TorrentImpl
*const torrent
, const QString
&oldCategory
)
4970 emit
torrentCategoryChanged(torrent
, oldCategory
);
4973 void SessionImpl::handleTorrentTagAdded(TorrentImpl
*const torrent
, const Tag
&tag
)
4975 emit
torrentTagAdded(torrent
, tag
);
4978 void SessionImpl::handleTorrentTagRemoved(TorrentImpl
*const torrent
, const Tag
&tag
)
4980 emit
torrentTagRemoved(torrent
, tag
);
4983 void SessionImpl::handleTorrentSavingModeChanged(TorrentImpl
*const torrent
)
4985 emit
torrentSavingModeChanged(torrent
);
4988 void SessionImpl::handleTorrentTrackersAdded(TorrentImpl
*const torrent
, const QVector
<TrackerEntry
> &newTrackers
)
4990 for (const TrackerEntry
&newTracker
: newTrackers
)
4991 LogMsg(tr("Added tracker to torrent. Torrent: \"%1\". Tracker: \"%2\"").arg(torrent
->name(), newTracker
.url
));
4992 emit
trackersAdded(torrent
, newTrackers
);
4995 void SessionImpl::handleTorrentTrackersRemoved(TorrentImpl
*const torrent
, const QStringList
&deletedTrackers
)
4997 for (const QString
&deletedTracker
: deletedTrackers
)
4998 LogMsg(tr("Removed tracker from torrent. Torrent: \"%1\". Tracker: \"%2\"").arg(torrent
->name(), deletedTracker
));
4999 emit
trackersRemoved(torrent
, deletedTrackers
);
5002 void SessionImpl::handleTorrentTrackersChanged(TorrentImpl
*const torrent
)
5004 emit
trackersChanged(torrent
);
5007 void SessionImpl::handleTorrentUrlSeedsAdded(TorrentImpl
*const torrent
, const QVector
<QUrl
> &newUrlSeeds
)
5009 for (const QUrl
&newUrlSeed
: newUrlSeeds
)
5010 LogMsg(tr("Added URL seed to torrent. Torrent: \"%1\". URL: \"%2\"").arg(torrent
->name(), newUrlSeed
.toString()));
5013 void SessionImpl::handleTorrentUrlSeedsRemoved(TorrentImpl
*const torrent
, const QVector
<QUrl
> &urlSeeds
)
5015 for (const QUrl
&urlSeed
: urlSeeds
)
5016 LogMsg(tr("Removed URL seed from torrent. Torrent: \"%1\". URL: \"%2\"").arg(torrent
->name(), urlSeed
.toString()));
5019 void SessionImpl::handleTorrentMetadataReceived(TorrentImpl
*const torrent
)
5021 if (!torrentExportDirectory().isEmpty())
5022 exportTorrentFile(torrent
, torrentExportDirectory());
5024 emit
torrentMetadataReceived(torrent
);
5027 void SessionImpl::handleTorrentStopped(TorrentImpl
*const torrent
)
5029 torrent
->resetTrackerEntryStatuses();
5031 const QVector
<TrackerEntryStatus
> trackers
= torrent
->trackers();
5032 QHash
<QString
, TrackerEntryStatus
> updatedTrackers
;
5033 updatedTrackers
.reserve(trackers
.size());
5035 for (const TrackerEntryStatus
&status
: trackers
)
5036 updatedTrackers
.emplace(status
.url
, status
);
5037 emit
trackerEntryStatusesUpdated(torrent
, updatedTrackers
);
5039 LogMsg(tr("Torrent stopped. Torrent: \"%1\"").arg(torrent
->name()));
5040 emit
torrentStopped(torrent
);
5043 void SessionImpl::handleTorrentStarted(TorrentImpl
*const torrent
)
5045 LogMsg(tr("Torrent resumed. Torrent: \"%1\"").arg(torrent
->name()));
5046 emit
torrentStarted(torrent
);
5049 void SessionImpl::handleTorrentChecked(TorrentImpl
*const torrent
)
5051 emit
torrentFinishedChecking(torrent
);
5054 void SessionImpl::handleTorrentFinished(TorrentImpl
*const torrent
)
5056 m_pendingFinishedTorrents
.append(torrent
);
5059 void SessionImpl::handleTorrentResumeDataReady(TorrentImpl
*const torrent
, const LoadTorrentParams
&data
)
5061 m_resumeDataStorage
->store(torrent
->id(), data
);
5062 const auto iter
= m_changedTorrentIDs
.find(torrent
->id());
5063 if (iter
!= m_changedTorrentIDs
.end())
5065 m_resumeDataStorage
->remove(iter
.value());
5066 m_changedTorrentIDs
.erase(iter
);
5070 void SessionImpl::handleTorrentInfoHashChanged(TorrentImpl
*torrent
, const InfoHash
&prevInfoHash
)
5072 Q_ASSERT(torrent
->infoHash().isHybrid());
5074 m_hybridTorrentsByAltID
.insert(TorrentID::fromSHA1Hash(torrent
->infoHash().v1()), torrent
);
5076 const auto prevID
= TorrentID::fromInfoHash(prevInfoHash
);
5077 const TorrentID currentID
= torrent
->id();
5078 if (currentID
!= prevID
)
5080 m_torrents
[torrent
->id()] = m_torrents
.take(prevID
);
5081 m_changedTorrentIDs
[torrent
->id()] = prevID
;
5085 void SessionImpl::handleTorrentStorageMovingStateChanged(TorrentImpl
*torrent
)
5087 emit
torrentsUpdated({torrent
});
5090 bool SessionImpl::addMoveTorrentStorageJob(TorrentImpl
*torrent
, const Path
&newPath
, const MoveStorageMode mode
, const MoveStorageContext context
)
5094 const lt::torrent_handle torrentHandle
= torrent
->nativeHandle();
5095 const Path currentLocation
= torrent
->actualStorageLocation();
5096 const bool torrentHasActiveJob
= !m_moveStorageQueue
.isEmpty() && (m_moveStorageQueue
.first().torrentHandle
== torrentHandle
);
5098 if (m_moveStorageQueue
.size() > 1)
5100 auto iter
= std::find_if((m_moveStorageQueue
.begin() + 1), m_moveStorageQueue
.end()
5101 , [&torrentHandle
](const MoveStorageJob
&job
)
5103 return job
.torrentHandle
== torrentHandle
;
5106 if (iter
!= m_moveStorageQueue
.end())
5108 // remove existing inactive job
5109 torrent
->handleMoveStorageJobFinished(currentLocation
, iter
->context
, torrentHasActiveJob
);
5110 LogMsg(tr("Torrent move canceled. Torrent: \"%1\". Source: \"%2\". Destination: \"%3\"").arg(torrent
->name(), currentLocation
.toString(), iter
->path
.toString()));
5111 m_moveStorageQueue
.erase(iter
);
5115 if (torrentHasActiveJob
)
5117 // if there is active job for this torrent prevent creating meaningless
5118 // job that will move torrent to the same location as current one
5119 if (m_moveStorageQueue
.first().path
== newPath
)
5121 LogMsg(tr("Failed to enqueue torrent move. Torrent: \"%1\". Source: \"%2\". Destination: \"%3\". Reason: torrent is currently moving to the destination")
5122 .arg(torrent
->name(), currentLocation
.toString(), newPath
.toString()));
5128 if (currentLocation
== newPath
)
5130 LogMsg(tr("Failed to enqueue torrent move. Torrent: \"%1\". Source: \"%2\" Destination: \"%3\". Reason: both paths point to the same location")
5131 .arg(torrent
->name(), currentLocation
.toString(), newPath
.toString()));
5136 const MoveStorageJob moveStorageJob
{torrentHandle
, newPath
, mode
, context
};
5137 m_moveStorageQueue
<< moveStorageJob
;
5138 LogMsg(tr("Enqueued torrent move. Torrent: \"%1\". Source: \"%2\". Destination: \"%3\"").arg(torrent
->name(), currentLocation
.toString(), newPath
.toString()));
5140 if (m_moveStorageQueue
.size() == 1)
5141 moveTorrentStorage(moveStorageJob
);
5146 void SessionImpl::moveTorrentStorage(const MoveStorageJob
&job
) const
5148 #ifdef QBT_USES_LIBTORRENT2
5149 const auto id
= TorrentID::fromInfoHash(job
.torrentHandle
.info_hashes());
5151 const auto id
= TorrentID::fromInfoHash(job
.torrentHandle
.info_hash());
5153 const TorrentImpl
*torrent
= m_torrents
.value(id
);
5154 const QString torrentName
= (torrent
? torrent
->name() : id
.toString());
5155 LogMsg(tr("Start moving torrent. Torrent: \"%1\". Destination: \"%2\"").arg(torrentName
, job
.path
.toString()));
5157 job
.torrentHandle
.move_storage(job
.path
.toString().toStdString(), toNative(job
.mode
));
5160 void SessionImpl::handleMoveTorrentStorageJobFinished(const Path
&newPath
)
5162 const MoveStorageJob finishedJob
= m_moveStorageQueue
.takeFirst();
5163 if (!m_moveStorageQueue
.isEmpty())
5164 moveTorrentStorage(m_moveStorageQueue
.first());
5166 const auto iter
= std::find_if(m_moveStorageQueue
.cbegin(), m_moveStorageQueue
.cend()
5167 , [&finishedJob
](const MoveStorageJob
&job
)
5169 return job
.torrentHandle
== finishedJob
.torrentHandle
;
5172 const bool torrentHasOutstandingJob
= (iter
!= m_moveStorageQueue
.cend());
5174 TorrentImpl
*torrent
= m_torrents
.value(finishedJob
.torrentHandle
.info_hash());
5177 torrent
->handleMoveStorageJobFinished(newPath
, finishedJob
.context
, torrentHasOutstandingJob
);
5179 else if (!torrentHasOutstandingJob
)
5181 // Last job is completed for torrent that being removing, so actually remove it
5182 const lt::torrent_handle nativeHandle
{finishedJob
.torrentHandle
};
5183 const RemovingTorrentData
&removingTorrentData
= m_removingTorrents
[nativeHandle
.info_hash()];
5184 if (removingTorrentData
.removeOption
== TorrentRemoveOption::KeepContent
)
5185 m_nativeSession
->remove_torrent(nativeHandle
, lt::session::delete_partfile
);
5189 void SessionImpl::storeCategories() const
5191 QJsonObject jsonObj
;
5192 for (auto it
= m_categories
.cbegin(); it
!= m_categories
.cend(); ++it
)
5194 const QString
&categoryName
= it
.key();
5195 const CategoryOptions
&categoryOptions
= it
.value();
5196 jsonObj
[categoryName
] = categoryOptions
.toJSON();
5199 const Path path
= specialFolderLocation(SpecialFolder::Config
) / CATEGORIES_FILE_NAME
;
5200 const QByteArray data
= QJsonDocument(jsonObj
).toJson();
5201 const nonstd::expected
<void, QString
> result
= Utils::IO::saveToFile(path
, data
);
5204 LogMsg(tr("Failed to save Categories configuration. File: \"%1\". Error: \"%2\"")
5205 .arg(path
.toString(), result
.error()), Log::WARNING
);
5209 void SessionImpl::upgradeCategories()
5211 const auto legacyCategories
= SettingValue
<QVariantMap
>(u
"BitTorrent/Session/Categories"_s
).get();
5212 for (auto it
= legacyCategories
.cbegin(); it
!= legacyCategories
.cend(); ++it
)
5214 const QString
&categoryName
= it
.key();
5215 CategoryOptions categoryOptions
;
5216 categoryOptions
.savePath
= Path(it
.value().toString());
5217 m_categories
[categoryName
] = categoryOptions
;
5223 void SessionImpl::loadCategories()
5225 m_categories
.clear();
5227 const Path path
= specialFolderLocation(SpecialFolder::Config
) / CATEGORIES_FILE_NAME
;
5230 // TODO: Remove the following upgrade code in v4.5
5231 // == BEGIN UPGRADE CODE ==
5232 upgradeCategories();
5233 m_needUpgradeDownloadPath
= true;
5234 // == END UPGRADE CODE ==
5239 const int fileMaxSize
= 1024 * 1024;
5240 const auto readResult
= Utils::IO::readFile(path
, fileMaxSize
);
5243 LogMsg(tr("Failed to load Categories. %1").arg(readResult
.error().message
), Log::WARNING
);
5247 QJsonParseError jsonError
;
5248 const QJsonDocument jsonDoc
= QJsonDocument::fromJson(readResult
.value(), &jsonError
);
5249 if (jsonError
.error
!= QJsonParseError::NoError
)
5251 LogMsg(tr("Failed to parse Categories configuration. File: \"%1\". Error: \"%2\"")
5252 .arg(path
.toString(), jsonError
.errorString()), Log::WARNING
);
5256 if (!jsonDoc
.isObject())
5258 LogMsg(tr("Failed to load Categories configuration. File: \"%1\". Error: \"Invalid data format\"")
5259 .arg(path
.toString()), Log::WARNING
);
5263 const QJsonObject jsonObj
= jsonDoc
.object();
5264 for (auto it
= jsonObj
.constBegin(); it
!= jsonObj
.constEnd(); ++it
)
5266 const QString
&categoryName
= it
.key();
5267 const auto categoryOptions
= CategoryOptions::fromJSON(it
.value().toObject());
5268 m_categories
[categoryName
] = categoryOptions
;
5272 bool SessionImpl::hasPerTorrentRatioLimit() const
5274 return std::any_of(m_torrents
.cbegin(), m_torrents
.cend(), [](const TorrentImpl
*torrent
)
5276 return (torrent
->ratioLimit() >= 0);
5280 bool SessionImpl::hasPerTorrentSeedingTimeLimit() const
5282 return std::any_of(m_torrents
.cbegin(), m_torrents
.cend(), [](const TorrentImpl
*torrent
)
5284 return (torrent
->seedingTimeLimit() >= 0);
5288 bool SessionImpl::hasPerTorrentInactiveSeedingTimeLimit() const
5290 return std::any_of(m_torrents
.cbegin(), m_torrents
.cend(), [](const TorrentImpl
*torrent
)
5292 return (torrent
->inactiveSeedingTimeLimit() >= 0);
5296 void SessionImpl::configureDeferred()
5298 if (m_deferredConfigureScheduled
)
5301 m_deferredConfigureScheduled
= true;
5302 QMetaObject::invokeMethod(this, qOverload
<>(&SessionImpl::configure
), Qt::QueuedConnection
);
5305 // Enable IP Filtering
5306 // this method creates ban list from scratch combining user ban list and 3rd party ban list file
5307 void SessionImpl::enableIPFilter()
5309 qDebug("Enabling IPFilter");
5310 // 1. Parse the IP filter
5311 // 2. In the slot add the manually banned IPs to the provided lt::ip_filter
5312 // 3. Set the ip_filter in one go so there isn't a time window where there isn't an ip_filter
5313 // set between clearing the old one and setting the new one.
5314 if (!m_filterParser
)
5316 m_filterParser
= new FilterParserThread(this);
5317 connect(m_filterParser
.data(), &FilterParserThread::IPFilterParsed
, this, &SessionImpl::handleIPFilterParsed
);
5318 connect(m_filterParser
.data(), &FilterParserThread::IPFilterError
, this, &SessionImpl::handleIPFilterError
);
5320 m_filterParser
->processFilterFile(IPFilterFile());
5323 // Disable IP Filtering
5324 void SessionImpl::disableIPFilter()
5326 qDebug("Disabling IPFilter");
5329 disconnect(m_filterParser
.data(), nullptr, this, nullptr);
5330 delete m_filterParser
;
5333 // Add the banned IPs after the IPFilter disabling
5334 // which creates an empty filter and overrides all previously
5336 lt::ip_filter filter
;
5337 processBannedIPs(filter
);
5338 m_nativeSession
->set_ip_filter(filter
);
5341 const SessionStatus
&SessionImpl::status() const
5346 const CacheStatus
&SessionImpl::cacheStatus() const
5348 return m_cacheStatus
;
5351 void SessionImpl::enqueueRefresh()
5353 Q_ASSERT(!m_refreshEnqueued
);
5355 QTimer::singleShot(refreshInterval(), Qt::CoarseTimer
, this, [this]
5357 m_nativeSession
->post_torrent_updates();
5358 m_nativeSession
->post_session_stats();
5360 if (m_torrentsQueueChanged
)
5362 m_torrentsQueueChanged
= false;
5363 m_needSaveTorrentsQueue
= true;
5367 m_refreshEnqueued
= true;
5370 void SessionImpl::handleIPFilterParsed(const int ruleCount
)
5374 lt::ip_filter filter
= m_filterParser
->IPfilter();
5375 processBannedIPs(filter
);
5376 m_nativeSession
->set_ip_filter(filter
);
5378 LogMsg(tr("Successfully parsed the IP filter file. Number of rules applied: %1").arg(ruleCount
));
5379 emit
IPFilterParsed(false, ruleCount
);
5382 void SessionImpl::handleIPFilterError()
5384 lt::ip_filter filter
;
5385 processBannedIPs(filter
);
5386 m_nativeSession
->set_ip_filter(filter
);
5388 LogMsg(tr("Failed to parse the IP filter file"), Log::WARNING
);
5389 emit
IPFilterParsed(true, 0);
5392 std::vector
<lt::alert
*> SessionImpl::getPendingAlerts(const lt::time_duration time
) const
5394 if (time
> lt::time_duration::zero())
5395 m_nativeSession
->wait_for_alert(time
);
5397 std::vector
<lt::alert
*> alerts
;
5398 m_nativeSession
->pop_alerts(&alerts
);
5402 TorrentContentLayout
SessionImpl::torrentContentLayout() const
5404 return m_torrentContentLayout
;
5407 void SessionImpl::setTorrentContentLayout(const TorrentContentLayout value
)
5409 m_torrentContentLayout
= value
;
5412 // Read alerts sent by libtorrent session
5413 void SessionImpl::readAlerts()
5415 const std::vector
<lt::alert
*> alerts
= getPendingAlerts();
5417 Q_ASSERT(m_loadedTorrents
.isEmpty());
5418 Q_ASSERT(m_receivedAddTorrentAlertsCount
== 0);
5421 m_loadedTorrents
.reserve(MAX_PROCESSING_RESUMEDATA_COUNT
);
5423 for (const lt::alert
*a
: alerts
)
5426 if (m_receivedAddTorrentAlertsCount
> 0)
5428 emit
addTorrentAlertsReceived(m_receivedAddTorrentAlertsCount
);
5429 m_receivedAddTorrentAlertsCount
= 0;
5431 if (!m_loadedTorrents
.isEmpty())
5434 m_torrentsQueueChanged
= true;
5436 emit
torrentsLoaded(m_loadedTorrents
);
5437 m_loadedTorrents
.clear();
5441 processTrackerStatuses();
5444 void SessionImpl::handleAddTorrentAlert(const lt::add_torrent_alert
*alert
)
5446 ++m_receivedAddTorrentAlertsCount
;
5450 const QString msg
= QString::fromStdString(alert
->message());
5451 LogMsg(tr("Failed to load torrent. Reason: \"%1\"").arg(msg
), Log::WARNING
);
5452 emit
loadTorrentFailed(msg
);
5454 const lt::add_torrent_params
¶ms
= alert
->params
;
5455 const bool hasMetadata
= (params
.ti
&& params
.ti
->is_valid());
5457 #ifdef QBT_USES_LIBTORRENT2
5458 const InfoHash infoHash
{(hasMetadata
? params
.ti
->info_hashes() : params
.info_hashes
)};
5459 if (infoHash
.isHybrid())
5460 m_hybridTorrentsByAltID
.remove(TorrentID::fromSHA1Hash(infoHash
.v1()));
5462 const InfoHash infoHash
{(hasMetadata
? params
.ti
->info_hash() : params
.info_hash
)};
5464 if (const auto loadingTorrentsIter
= m_loadingTorrents
.find(TorrentID::fromInfoHash(infoHash
))
5465 ; loadingTorrentsIter
!= m_loadingTorrents
.end())
5467 emit
addTorrentFailed(infoHash
, msg
);
5468 m_loadingTorrents
.erase(loadingTorrentsIter
);
5470 else if (const auto downloadedMetadataIter
= m_downloadedMetadata
.find(TorrentID::fromInfoHash(infoHash
))
5471 ; downloadedMetadataIter
!= m_downloadedMetadata
.end())
5473 m_downloadedMetadata
.erase(downloadedMetadataIter
);
5474 if (infoHash
.isHybrid())
5476 // index hybrid magnet links by both v1 and v2 info hashes
5477 const auto altID
= TorrentID::fromSHA1Hash(infoHash
.v1());
5478 m_downloadedMetadata
.remove(altID
);
5485 #ifdef QBT_USES_LIBTORRENT2
5486 const InfoHash infoHash
{alert
->handle
.info_hashes()};
5488 const InfoHash infoHash
{alert
->handle
.info_hash()};
5490 const auto torrentID
= TorrentID::fromInfoHash(infoHash
);
5492 if (const auto loadingTorrentsIter
= m_loadingTorrents
.find(torrentID
)
5493 ; loadingTorrentsIter
!= m_loadingTorrents
.end())
5495 const LoadTorrentParams params
= loadingTorrentsIter
.value();
5496 m_loadingTorrents
.erase(loadingTorrentsIter
);
5498 Torrent
*torrent
= createTorrent(alert
->handle
, params
);
5499 m_loadedTorrents
.append(torrent
);
5501 else if (const auto downloadedMetadataIter
= m_downloadedMetadata
.find(torrentID
)
5502 ; downloadedMetadataIter
!= m_downloadedMetadata
.end())
5504 downloadedMetadataIter
.value() = alert
->handle
;
5505 if (infoHash
.isHybrid())
5507 // index hybrid magnet links by both v1 and v2 info hashes
5508 const auto altID
= TorrentID::fromSHA1Hash(infoHash
.v1());
5509 m_downloadedMetadata
[altID
] = alert
->handle
;
5514 void SessionImpl::handleAlert(const lt::alert
*alert
)
5518 switch (alert
->type())
5520 #ifdef QBT_USES_LIBTORRENT2
5521 case lt::file_prio_alert::alert_type
:
5523 case lt::file_renamed_alert::alert_type
:
5524 case lt::file_rename_failed_alert::alert_type
:
5525 case lt::file_completed_alert::alert_type
:
5526 case lt::torrent_finished_alert::alert_type
:
5527 case lt::save_resume_data_alert::alert_type
:
5528 case lt::save_resume_data_failed_alert::alert_type
:
5529 case lt::torrent_paused_alert::alert_type
:
5530 case lt::torrent_resumed_alert::alert_type
:
5531 case lt::fastresume_rejected_alert::alert_type
:
5532 case lt::torrent_checked_alert::alert_type
:
5533 case lt::metadata_received_alert::alert_type
:
5534 case lt::performance_alert::alert_type
:
5535 dispatchTorrentAlert(static_cast<const lt::torrent_alert
*>(alert
));
5537 case lt::state_update_alert::alert_type
:
5538 handleStateUpdateAlert(static_cast<const lt::state_update_alert
*>(alert
));
5540 case lt::session_error_alert::alert_type
:
5541 handleSessionErrorAlert(static_cast<const lt::session_error_alert
*>(alert
));
5543 case lt::session_stats_alert::alert_type
:
5544 handleSessionStatsAlert(static_cast<const lt::session_stats_alert
*>(alert
));
5546 case lt::tracker_announce_alert::alert_type
:
5547 case lt::tracker_error_alert::alert_type
:
5548 case lt::tracker_reply_alert::alert_type
:
5549 case lt::tracker_warning_alert::alert_type
:
5550 handleTrackerAlert(static_cast<const lt::tracker_alert
*>(alert
));
5552 case lt::file_error_alert::alert_type
:
5553 handleFileErrorAlert(static_cast<const lt::file_error_alert
*>(alert
));
5555 case lt::add_torrent_alert::alert_type
:
5556 handleAddTorrentAlert(static_cast<const lt::add_torrent_alert
*>(alert
));
5558 case lt::torrent_removed_alert::alert_type
:
5559 handleTorrentRemovedAlert(static_cast<const lt::torrent_removed_alert
*>(alert
));
5561 case lt::torrent_deleted_alert::alert_type
:
5562 handleTorrentDeletedAlert(static_cast<const lt::torrent_deleted_alert
*>(alert
));
5564 case lt::torrent_delete_failed_alert::alert_type
:
5565 handleTorrentDeleteFailedAlert(static_cast<const lt::torrent_delete_failed_alert
*>(alert
));
5567 case lt::torrent_need_cert_alert::alert_type
:
5568 handleTorrentNeedCertAlert(static_cast<const lt::torrent_need_cert_alert
*>(alert
));
5570 case lt::portmap_error_alert::alert_type
:
5571 handlePortmapWarningAlert(static_cast<const lt::portmap_error_alert
*>(alert
));
5573 case lt::portmap_alert::alert_type
:
5574 handlePortmapAlert(static_cast<const lt::portmap_alert
*>(alert
));
5576 case lt::peer_blocked_alert::alert_type
:
5577 handlePeerBlockedAlert(static_cast<const lt::peer_blocked_alert
*>(alert
));
5579 case lt::peer_ban_alert::alert_type
:
5580 handlePeerBanAlert(static_cast<const lt::peer_ban_alert
*>(alert
));
5582 case lt::url_seed_alert::alert_type
:
5583 handleUrlSeedAlert(static_cast<const lt::url_seed_alert
*>(alert
));
5585 case lt::listen_succeeded_alert::alert_type
:
5586 handleListenSucceededAlert(static_cast<const lt::listen_succeeded_alert
*>(alert
));
5588 case lt::listen_failed_alert::alert_type
:
5589 handleListenFailedAlert(static_cast<const lt::listen_failed_alert
*>(alert
));
5591 case lt::external_ip_alert::alert_type
:
5592 handleExternalIPAlert(static_cast<const lt::external_ip_alert
*>(alert
));
5594 case lt::alerts_dropped_alert::alert_type
:
5595 handleAlertsDroppedAlert(static_cast<const lt::alerts_dropped_alert
*>(alert
));
5597 case lt::storage_moved_alert::alert_type
:
5598 handleStorageMovedAlert(static_cast<const lt::storage_moved_alert
*>(alert
));
5600 case lt::storage_moved_failed_alert::alert_type
:
5601 handleStorageMovedFailedAlert(static_cast<const lt::storage_moved_failed_alert
*>(alert
));
5603 case lt::socks5_alert::alert_type
:
5604 handleSocks5Alert(static_cast<const lt::socks5_alert
*>(alert
));
5606 case lt::i2p_alert::alert_type
:
5607 handleI2PAlert(static_cast<const lt::i2p_alert
*>(alert
));
5609 #ifdef QBT_USES_LIBTORRENT2
5610 case lt::torrent_conflict_alert::alert_type
:
5611 handleTorrentConflictAlert(static_cast<const lt::torrent_conflict_alert
*>(alert
));
5616 catch (const std::exception
&exc
)
5618 qWarning() << "Caught exception in " << Q_FUNC_INFO
<< ": " << QString::fromStdString(exc
.what());
5622 void SessionImpl::dispatchTorrentAlert(const lt::torrent_alert
*alert
)
5624 // The torrent can be deleted between the time the resume data was requested and
5625 // the time we received the appropriate alert. We have to decrease `m_numResumeData` anyway,
5626 // so we do this before checking for an existing torrent.
5627 if ((alert
->type() == lt::save_resume_data_alert::alert_type
)
5628 || (alert
->type() == lt::save_resume_data_failed_alert::alert_type
))
5633 const TorrentID torrentID
{alert
->handle
.info_hash()};
5634 TorrentImpl
*torrent
= m_torrents
.value(torrentID
);
5635 #ifdef QBT_USES_LIBTORRENT2
5636 if (!torrent
&& (alert
->type() == lt::metadata_received_alert::alert_type
))
5638 const InfoHash infoHash
{alert
->handle
.info_hashes()};
5639 if (infoHash
.isHybrid())
5640 torrent
= m_torrents
.value(TorrentID::fromSHA1Hash(infoHash
.v1()));
5646 torrent
->handleAlert(alert
);
5650 switch (alert
->type())
5652 case lt::metadata_received_alert::alert_type
:
5653 handleMetadataReceivedAlert(static_cast<const lt::metadata_received_alert
*>(alert
));
5658 TorrentImpl
*SessionImpl::createTorrent(const lt::torrent_handle
&nativeHandle
, const LoadTorrentParams
¶ms
)
5660 auto *const torrent
= new TorrentImpl(this, m_nativeSession
, nativeHandle
, params
);
5661 m_torrents
.insert(torrent
->id(), torrent
);
5662 if (const InfoHash infoHash
= torrent
->infoHash(); infoHash
.isHybrid())
5663 m_hybridTorrentsByAltID
.insert(TorrentID::fromSHA1Hash(infoHash
.v1()), torrent
);
5667 if (params
.addToQueueTop
)
5668 nativeHandle
.queue_position_top();
5670 torrent
->requestResumeData(lt::torrent_handle::save_info_dict
);
5672 // The following is useless for newly added magnet
5673 if (torrent
->hasMetadata())
5675 if (!torrentExportDirectory().isEmpty())
5676 exportTorrentFile(torrent
, torrentExportDirectory());
5680 if (((torrent
->ratioLimit() >= 0) || (torrent
->seedingTimeLimit() >= 0))
5681 && !m_seedingLimitTimer
->isActive())
5683 m_seedingLimitTimer
->start();
5688 LogMsg(tr("Restored torrent. Torrent: \"%1\"").arg(torrent
->name()));
5692 LogMsg(tr("Added new torrent. Torrent: \"%1\"").arg(torrent
->name()));
5693 emit
torrentAdded(torrent
);
5696 // Torrent could have error just after adding to libtorrent
5697 if (torrent
->hasError())
5698 LogMsg(tr("Torrent errored. Torrent: \"%1\". Error: \"%2\"").arg(torrent
->name(), torrent
->error()), Log::WARNING
);
5703 void SessionImpl::handleTorrentRemovedAlert(const lt::torrent_removed_alert */
*alert*/
)
5705 // We cannot consider `torrent_removed_alert` as a starting point for removing content,
5706 // because it has an inconsistent posting time between different versions of libtorrent,
5707 // so files may still be in use in some cases.
5710 void SessionImpl::handleTorrentDeletedAlert(const lt::torrent_deleted_alert
*alert
)
5712 #ifdef QBT_USES_LIBTORRENT2
5713 const auto torrentID
= TorrentID::fromInfoHash(alert
->info_hashes
);
5715 const auto torrentID
= TorrentID::fromInfoHash(alert
->info_hash
);
5717 handleRemovedTorrent(torrentID
);
5720 void SessionImpl::handleTorrentDeleteFailedAlert(const lt::torrent_delete_failed_alert
*alert
)
5722 #ifdef QBT_USES_LIBTORRENT2
5723 const auto torrentID
= TorrentID::fromInfoHash(alert
->info_hashes
);
5725 const auto torrentID
= TorrentID::fromInfoHash(alert
->info_hash
);
5727 const auto errorMessage
= alert
->error
? QString::fromLocal8Bit(alert
->error
.message().c_str()) : QString();
5728 handleRemovedTorrent(torrentID
, errorMessage
);
5731 void SessionImpl::handleTorrentNeedCertAlert(const lt::torrent_need_cert_alert
*alert
)
5733 #ifdef QBT_USES_LIBTORRENT2
5734 const InfoHash infoHash
{alert
->handle
.info_hashes()};
5736 const InfoHash infoHash
{alert
->handle
.info_hash()};
5738 const auto torrentID
= TorrentID::fromInfoHash(infoHash
);
5740 TorrentImpl
*const torrent
= m_torrents
.value(torrentID
);
5741 if (!torrent
) [[unlikely
]]
5744 if (!torrent
->applySSLParameters())
5746 LogMsg(tr("Torrent is missing SSL parameters. Torrent: \"%1\". Message: \"%2\"").arg(torrent
->name(), QString::fromStdString(alert
->message()))
5751 void SessionImpl::handleMetadataReceivedAlert(const lt::metadata_received_alert
*alert
)
5753 const TorrentID torrentID
{alert
->handle
.info_hash()};
5756 if (const auto iter
= m_downloadedMetadata
.find(torrentID
); iter
!= m_downloadedMetadata
.end())
5759 m_downloadedMetadata
.erase(iter
);
5761 #ifdef QBT_USES_LIBTORRENT2
5762 const InfoHash infoHash
{alert
->handle
.info_hashes()};
5763 if (infoHash
.isHybrid())
5765 const auto altID
= TorrentID::fromSHA1Hash(infoHash
.v1());
5766 if (const auto iter
= m_downloadedMetadata
.find(altID
); iter
!= m_downloadedMetadata
.end())
5769 m_downloadedMetadata
.erase(iter
);
5775 const TorrentInfo metadata
{*alert
->handle
.torrent_file()};
5776 m_nativeSession
->remove_torrent(alert
->handle
, lt::session::delete_files
);
5778 emit
metadataDownloaded(metadata
);
5782 void SessionImpl::handleFileErrorAlert(const lt::file_error_alert
*alert
)
5784 TorrentImpl
*const torrent
= m_torrents
.value(alert
->handle
.info_hash());
5788 torrent
->handleAlert(alert
);
5790 const TorrentID id
= torrent
->id();
5791 if (!m_recentErroredTorrents
.contains(id
))
5793 m_recentErroredTorrents
.insert(id
);
5795 const QString msg
= QString::fromStdString(alert
->message());
5796 LogMsg(tr("File error alert. Torrent: \"%1\". File: \"%2\". Reason: \"%3\"")
5797 .arg(torrent
->name(), QString::fromUtf8(alert
->filename()), msg
)
5799 emit
fullDiskError(torrent
, msg
);
5802 m_recentErroredTorrentsTimer
->start();
5805 void SessionImpl::handlePortmapWarningAlert(const lt::portmap_error_alert
*alert
)
5807 LogMsg(tr("UPnP/NAT-PMP port mapping failed. Message: \"%1\"").arg(QString::fromStdString(alert
->message())), Log::WARNING
);
5810 void SessionImpl::handlePortmapAlert(const lt::portmap_alert
*alert
)
5812 qDebug("UPnP Success, msg: %s", alert
->message().c_str());
5813 LogMsg(tr("UPnP/NAT-PMP port mapping succeeded. Message: \"%1\"").arg(QString::fromStdString(alert
->message())), Log::INFO
);
5816 void SessionImpl::handlePeerBlockedAlert(const lt::peer_blocked_alert
*alert
)
5819 switch (alert
->reason
)
5821 case lt::peer_blocked_alert::ip_filter
:
5822 reason
= tr("IP filter", "this peer was blocked. Reason: IP filter.");
5824 case lt::peer_blocked_alert::port_filter
:
5825 reason
= tr("filtered port (%1)", "this peer was blocked. Reason: filtered port (8899).").arg(QString::number(alert
->endpoint
.port()));
5827 case lt::peer_blocked_alert::i2p_mixed
:
5828 reason
= tr("%1 mixed mode restrictions", "this peer was blocked. Reason: I2P mixed mode restrictions.").arg(u
"I2P"_s
); // don't translate I2P
5830 case lt::peer_blocked_alert::privileged_ports
:
5831 reason
= tr("privileged port (%1)", "this peer was blocked. Reason: privileged port (80).").arg(QString::number(alert
->endpoint
.port()));
5833 case lt::peer_blocked_alert::utp_disabled
:
5834 reason
= tr("%1 is disabled", "this peer was blocked. Reason: uTP is disabled.").arg(C_UTP
); // don't translate μTP
5836 case lt::peer_blocked_alert::tcp_disabled
:
5837 reason
= tr("%1 is disabled", "this peer was blocked. Reason: TCP is disabled.").arg(u
"TCP"_s
); // don't translate TCP
5841 const QString ip
{toString(alert
->endpoint
.address())};
5843 Logger::instance()->addPeer(ip
, true, reason
);
5846 void SessionImpl::handlePeerBanAlert(const lt::peer_ban_alert
*alert
)
5848 const QString ip
{toString(alert
->endpoint
.address())};
5850 Logger::instance()->addPeer(ip
, false);
5853 void SessionImpl::handleUrlSeedAlert(const lt::url_seed_alert
*alert
)
5855 const TorrentImpl
*torrent
= m_torrents
.value(alert
->handle
.info_hash());
5861 LogMsg(tr("URL seed DNS lookup failed. Torrent: \"%1\". URL: \"%2\". Error: \"%3\"")
5862 .arg(torrent
->name(), QString::fromUtf8(alert
->server_url()), QString::fromStdString(alert
->message()))
5867 LogMsg(tr("Received error message from URL seed. Torrent: \"%1\". URL: \"%2\". Message: \"%3\"")
5868 .arg(torrent
->name(), QString::fromUtf8(alert
->server_url()), QString::fromUtf8(alert
->error_message()))
5873 void SessionImpl::handleListenSucceededAlert(const lt::listen_succeeded_alert
*alert
)
5875 const QString proto
{toString(alert
->socket_type
)};
5876 LogMsg(tr("Successfully listening on IP. IP: \"%1\". Port: \"%2/%3\"")
5877 .arg(toString(alert
->address
), proto
, QString::number(alert
->port
)), Log::INFO
);
5880 void SessionImpl::handleListenFailedAlert(const lt::listen_failed_alert
*alert
)
5882 const QString proto
{toString(alert
->socket_type
)};
5883 LogMsg(tr("Failed to listen on IP. IP: \"%1\". Port: \"%2/%3\". Reason: \"%4\"")
5884 .arg(toString(alert
->address
), proto
, QString::number(alert
->port
)
5885 , QString::fromLocal8Bit(alert
->error
.message().c_str())), Log::CRITICAL
);
5888 void SessionImpl::handleExternalIPAlert(const lt::external_ip_alert
*alert
)
5890 const QString externalIP
{toString(alert
->external_address
)};
5891 LogMsg(tr("Detected external IP. IP: \"%1\"")
5892 .arg(externalIP
), Log::INFO
);
5894 if (m_lastExternalIP
!= externalIP
)
5896 if (isReannounceWhenAddressChangedEnabled() && !m_lastExternalIP
.isEmpty())
5897 reannounceToAllTrackers();
5898 m_lastExternalIP
= externalIP
;
5902 void SessionImpl::handleSessionErrorAlert(const lt::session_error_alert
*alert
) const
5904 LogMsg(tr("BitTorrent session encountered a serious error. Reason: \"%1\"")
5905 .arg(QString::fromStdString(alert
->message())), Log::CRITICAL
);
5908 void SessionImpl::handleSessionStatsAlert(const lt::session_stats_alert
*alert
)
5910 if (m_refreshEnqueued
)
5911 m_refreshEnqueued
= false;
5915 const int64_t interval
= lt::total_microseconds(alert
->timestamp() - m_statsLastTimestamp
);
5919 m_statsLastTimestamp
= alert
->timestamp();
5921 const auto stats
= alert
->counters();
5923 m_status
.hasIncomingConnections
= static_cast<bool>(stats
[m_metricIndices
.net
.hasIncomingConnections
]);
5925 const int64_t ipOverheadDownload
= stats
[m_metricIndices
.net
.recvIPOverheadBytes
];
5926 const int64_t ipOverheadUpload
= stats
[m_metricIndices
.net
.sentIPOverheadBytes
];
5927 const int64_t totalDownload
= stats
[m_metricIndices
.net
.recvBytes
] + ipOverheadDownload
;
5928 const int64_t totalUpload
= stats
[m_metricIndices
.net
.sentBytes
] + ipOverheadUpload
;
5929 const int64_t totalPayloadDownload
= stats
[m_metricIndices
.net
.recvPayloadBytes
];
5930 const int64_t totalPayloadUpload
= stats
[m_metricIndices
.net
.sentPayloadBytes
];
5931 const int64_t trackerDownload
= stats
[m_metricIndices
.net
.recvTrackerBytes
];
5932 const int64_t trackerUpload
= stats
[m_metricIndices
.net
.sentTrackerBytes
];
5933 const int64_t dhtDownload
= stats
[m_metricIndices
.dht
.dhtBytesIn
];
5934 const int64_t dhtUpload
= stats
[m_metricIndices
.dht
.dhtBytesOut
];
5936 const auto calcRate
= [interval
](const qint64 previous
, const qint64 current
) -> qint64
5938 Q_ASSERT(current
>= previous
);
5939 Q_ASSERT(interval
>= 0);
5940 return (((current
- previous
) * lt::microseconds(1s
).count()) / interval
);
5943 m_status
.payloadDownloadRate
= calcRate(m_status
.totalPayloadDownload
, totalPayloadDownload
);
5944 m_status
.payloadUploadRate
= calcRate(m_status
.totalPayloadUpload
, totalPayloadUpload
);
5945 m_status
.downloadRate
= calcRate(m_status
.totalDownload
, totalDownload
);
5946 m_status
.uploadRate
= calcRate(m_status
.totalUpload
, totalUpload
);
5947 m_status
.ipOverheadDownloadRate
= calcRate(m_status
.ipOverheadDownload
, ipOverheadDownload
);
5948 m_status
.ipOverheadUploadRate
= calcRate(m_status
.ipOverheadUpload
, ipOverheadUpload
);
5949 m_status
.dhtDownloadRate
= calcRate(m_status
.dhtDownload
, dhtDownload
);
5950 m_status
.dhtUploadRate
= calcRate(m_status
.dhtUpload
, dhtUpload
);
5951 m_status
.trackerDownloadRate
= calcRate(m_status
.trackerDownload
, trackerDownload
);
5952 m_status
.trackerUploadRate
= calcRate(m_status
.trackerUpload
, trackerUpload
);
5954 m_status
.totalPayloadDownload
= totalPayloadDownload
;
5955 m_status
.totalPayloadUpload
= totalPayloadUpload
;
5956 m_status
.ipOverheadDownload
= ipOverheadDownload
;
5957 m_status
.ipOverheadUpload
= ipOverheadUpload
;
5958 m_status
.trackerDownload
= trackerDownload
;
5959 m_status
.trackerUpload
= trackerUpload
;
5960 m_status
.dhtDownload
= dhtDownload
;
5961 m_status
.dhtUpload
= dhtUpload
;
5962 m_status
.totalWasted
= stats
[m_metricIndices
.net
.recvRedundantBytes
]
5963 + stats
[m_metricIndices
.net
.recvFailedBytes
];
5964 m_status
.dhtNodes
= stats
[m_metricIndices
.dht
.dhtNodes
];
5965 m_status
.diskReadQueue
= stats
[m_metricIndices
.peer
.numPeersUpDisk
];
5966 m_status
.diskWriteQueue
= stats
[m_metricIndices
.peer
.numPeersDownDisk
];
5967 m_status
.peersCount
= stats
[m_metricIndices
.peer
.numPeersConnected
];
5969 if (totalDownload
> m_status
.totalDownload
)
5971 m_status
.totalDownload
= totalDownload
;
5972 m_isStatisticsDirty
= true;
5975 if (totalUpload
> m_status
.totalUpload
)
5977 m_status
.totalUpload
= totalUpload
;
5978 m_isStatisticsDirty
= true;
5981 m_status
.allTimeDownload
= m_previouslyDownloaded
+ m_status
.totalDownload
;
5982 m_status
.allTimeUpload
= m_previouslyUploaded
+ m_status
.totalUpload
;
5984 if (m_statisticsLastUpdateTimer
.hasExpired(STATISTICS_SAVE_INTERVAL
))
5987 m_cacheStatus
.totalUsedBuffers
= stats
[m_metricIndices
.disk
.diskBlocksInUse
];
5988 m_cacheStatus
.jobQueueLength
= stats
[m_metricIndices
.disk
.queuedDiskJobs
];
5990 #ifndef QBT_USES_LIBTORRENT2
5991 const int64_t numBlocksRead
= stats
[m_metricIndices
.disk
.numBlocksRead
];
5992 const int64_t numBlocksCacheHits
= stats
[m_metricIndices
.disk
.numBlocksCacheHits
];
5993 m_cacheStatus
.readRatio
= static_cast<qreal
>(numBlocksCacheHits
) / std::max
<int64_t>((numBlocksCacheHits
+ numBlocksRead
), 1);
5996 const int64_t totalJobs
= stats
[m_metricIndices
.disk
.writeJobs
] + stats
[m_metricIndices
.disk
.readJobs
]
5997 + stats
[m_metricIndices
.disk
.hashJobs
];
5998 m_cacheStatus
.averageJobTime
= (totalJobs
> 0)
5999 ? (stats
[m_metricIndices
.disk
.diskJobTime
] / totalJobs
) : 0;
6001 emit
statsUpdated();
6004 void SessionImpl::handleAlertsDroppedAlert(const lt::alerts_dropped_alert
*alert
) const
6006 LogMsg(tr("Error: Internal alert queue is full and alerts are dropped, you might see degraded performance. Dropped alert type: \"%1\". Message: \"%2\"")
6007 .arg(QString::fromStdString(alert
->dropped_alerts
.to_string()), QString::fromStdString(alert
->message())), Log::CRITICAL
);
6010 void SessionImpl::handleStorageMovedAlert(const lt::storage_moved_alert
*alert
)
6012 Q_ASSERT(!m_moveStorageQueue
.isEmpty());
6014 const MoveStorageJob
¤tJob
= m_moveStorageQueue
.first();
6015 Q_ASSERT(currentJob
.torrentHandle
== alert
->handle
);
6017 const Path newPath
{QString::fromUtf8(alert
->storage_path())};
6018 Q_ASSERT(newPath
== currentJob
.path
);
6020 #ifdef QBT_USES_LIBTORRENT2
6021 const auto id
= TorrentID::fromInfoHash(currentJob
.torrentHandle
.info_hashes());
6023 const auto id
= TorrentID::fromInfoHash(currentJob
.torrentHandle
.info_hash());
6026 TorrentImpl
*torrent
= m_torrents
.value(id
);
6027 const QString torrentName
= (torrent
? torrent
->name() : id
.toString());
6028 LogMsg(tr("Moved torrent successfully. Torrent: \"%1\". Destination: \"%2\"").arg(torrentName
, newPath
.toString()));
6030 handleMoveTorrentStorageJobFinished(newPath
);
6033 void SessionImpl::handleStorageMovedFailedAlert(const lt::storage_moved_failed_alert
*alert
)
6035 Q_ASSERT(!m_moveStorageQueue
.isEmpty());
6037 const MoveStorageJob
¤tJob
= m_moveStorageQueue
.first();
6038 Q_ASSERT(currentJob
.torrentHandle
== alert
->handle
);
6040 #ifdef QBT_USES_LIBTORRENT2
6041 const auto id
= TorrentID::fromInfoHash(currentJob
.torrentHandle
.info_hashes());
6043 const auto id
= TorrentID::fromInfoHash(currentJob
.torrentHandle
.info_hash());
6046 TorrentImpl
*torrent
= m_torrents
.value(id
);
6047 const QString torrentName
= (torrent
? torrent
->name() : id
.toString());
6048 const Path currentLocation
= (torrent
? torrent
->actualStorageLocation()
6049 : Path(alert
->handle
.status(lt::torrent_handle::query_save_path
).save_path
));
6050 const QString errorMessage
= QString::fromStdString(alert
->message());
6051 LogMsg(tr("Failed to move torrent. Torrent: \"%1\". Source: \"%2\". Destination: \"%3\". Reason: \"%4\"")
6052 .arg(torrentName
, currentLocation
.toString(), currentJob
.path
.toString(), errorMessage
), Log::WARNING
);
6054 handleMoveTorrentStorageJobFinished(currentLocation
);
6057 void SessionImpl::handleStateUpdateAlert(const lt::state_update_alert
*alert
)
6059 QVector
<Torrent
*> updatedTorrents
;
6060 updatedTorrents
.reserve(static_cast<decltype(updatedTorrents
)::size_type
>(alert
->status
.size()));
6062 for (const lt::torrent_status
&status
: alert
->status
)
6064 #ifdef QBT_USES_LIBTORRENT2
6065 const auto id
= TorrentID::fromInfoHash(status
.info_hashes
);
6067 const auto id
= TorrentID::fromInfoHash(status
.info_hash
);
6069 TorrentImpl
*const torrent
= m_torrents
.value(id
);
6073 torrent
->handleStateUpdate(status
);
6074 updatedTorrents
.push_back(torrent
);
6077 if (!updatedTorrents
.isEmpty())
6078 emit
torrentsUpdated(updatedTorrents
);
6080 if (!m_pendingFinishedTorrents
.isEmpty())
6082 for (TorrentImpl
*torrent
: m_pendingFinishedTorrents
)
6084 LogMsg(tr("Torrent download finished. Torrent: \"%1\"").arg(torrent
->name()));
6085 emit
torrentFinished(torrent
);
6087 if (const Path exportPath
= finishedTorrentExportDirectory(); !exportPath
.isEmpty())
6088 exportTorrentFile(torrent
, exportPath
);
6090 processTorrentShareLimits(torrent
);
6093 m_pendingFinishedTorrents
.clear();
6095 const bool hasUnfinishedTorrents
= std::any_of(m_torrents
.cbegin(), m_torrents
.cend(), [](const TorrentImpl
*torrent
)
6097 return !(torrent
->isFinished() || torrent
->isStopped() || torrent
->isErrored());
6099 if (!hasUnfinishedTorrents
)
6100 emit
allTorrentsFinished();
6103 if (m_needSaveTorrentsQueue
)
6104 saveTorrentsQueue();
6106 if (m_refreshEnqueued
)
6107 m_refreshEnqueued
= false;
6112 void SessionImpl::handleSocks5Alert(const lt::socks5_alert
*alert
) const
6116 const auto addr
= alert
->ip
.address();
6117 const QString endpoint
= (addr
.is_v6() ? u
"[%1]:%2"_s
: u
"%1:%2"_s
)
6118 .arg(QString::fromStdString(addr
.to_string()), QString::number(alert
->ip
.port()));
6119 LogMsg(tr("SOCKS5 proxy error. Address: %1. Message: \"%2\".")
6120 .arg(endpoint
, QString::fromLocal8Bit(alert
->error
.message().c_str()))
6125 void SessionImpl::handleI2PAlert(const lt::i2p_alert
*alert
) const
6129 LogMsg(tr("I2P error. Message: \"%1\".")
6130 .arg(QString::fromStdString(alert
->message())), Log::WARNING
);
6134 void SessionImpl::handleTrackerAlert(const lt::tracker_alert
*alert
)
6136 TorrentImpl
*torrent
= m_torrents
.value(alert
->handle
.info_hash());
6140 QMap
<int, int> &updateInfo
= m_updatedTrackerStatuses
[torrent
->nativeHandle()][std::string(alert
->tracker_url())][alert
->local_endpoint
];
6142 if (alert
->type() == lt::tracker_reply_alert::alert_type
)
6144 const int numPeers
= static_cast<const lt::tracker_reply_alert
*>(alert
)->num_peers
;
6145 #ifdef QBT_USES_LIBTORRENT2
6146 const int protocolVersionNum
= (static_cast<const lt::tracker_reply_alert
*>(alert
)->version
== lt::protocol_version::V1
) ? 1 : 2;
6148 const int protocolVersionNum
= 1;
6150 updateInfo
.insert(protocolVersionNum
, numPeers
);
6154 #ifdef QBT_USES_LIBTORRENT2
6155 void SessionImpl::handleTorrentConflictAlert(const lt::torrent_conflict_alert
*alert
)
6157 const auto torrentIDv1
= TorrentID::fromSHA1Hash(alert
->metadata
->info_hashes().v1
);
6158 const auto torrentIDv2
= TorrentID::fromSHA256Hash(alert
->metadata
->info_hashes().v2
);
6159 TorrentImpl
*torrent1
= m_torrents
.value(torrentIDv1
);
6160 TorrentImpl
*torrent2
= m_torrents
.value(torrentIDv2
);
6164 removeTorrent(torrentIDv1
);
6166 cancelDownloadMetadata(torrentIDv1
);
6168 invokeAsync([torrentHandle
= torrent2
->nativeHandle(), metadata
= alert
->metadata
]
6172 torrentHandle
.set_metadata(metadata
->info_section());
6174 catch (const std::exception
&) {}
6180 cancelDownloadMetadata(torrentIDv2
);
6182 invokeAsync([torrentHandle
= torrent1
->nativeHandle(), metadata
= alert
->metadata
]
6186 torrentHandle
.set_metadata(metadata
->info_section());
6188 catch (const std::exception
&) {}
6193 cancelDownloadMetadata(torrentIDv1
);
6194 cancelDownloadMetadata(torrentIDv2
);
6197 if (!torrent1
|| !torrent2
)
6198 emit
metadataDownloaded(TorrentInfo(*alert
->metadata
));
6202 void SessionImpl::processTrackerStatuses()
6204 if (m_updatedTrackerStatuses
.isEmpty())
6207 for (auto it
= m_updatedTrackerStatuses
.cbegin(); it
!= m_updatedTrackerStatuses
.cend(); ++it
)
6208 updateTrackerEntryStatuses(it
.key(), it
.value());
6210 m_updatedTrackerStatuses
.clear();
6213 void SessionImpl::saveStatistics() const
6215 if (!m_isStatisticsDirty
)
6218 const QVariantHash stats
{
6219 {u
"AlltimeDL"_s
, m_status
.allTimeDownload
},
6220 {u
"AlltimeUL"_s
, m_status
.allTimeUpload
}};
6221 std::unique_ptr
<QSettings
> settings
= Profile::instance()->applicationSettings(u
"qBittorrent-data"_s
);
6222 settings
->setValue(u
"Stats/AllStats"_s
, stats
);
6224 m_statisticsLastUpdateTimer
.start();
6225 m_isStatisticsDirty
= false;
6228 void SessionImpl::loadStatistics()
6230 const std::unique_ptr
<QSettings
> settings
= Profile::instance()->applicationSettings(u
"qBittorrent-data"_s
);
6231 const QVariantHash value
= settings
->value(u
"Stats/AllStats"_s
).toHash();
6233 m_previouslyDownloaded
= value
[u
"AlltimeDL"_s
].toLongLong();
6234 m_previouslyUploaded
= value
[u
"AlltimeUL"_s
].toLongLong();
6237 void SessionImpl::updateTrackerEntryStatuses(lt::torrent_handle torrentHandle
, QHash
<std::string
, QHash
<lt::tcp::endpoint
, QMap
<int, int>>> updatedTrackers
)
6239 invokeAsync([this, torrentHandle
= std::move(torrentHandle
), updatedTrackers
= std::move(updatedTrackers
)]() mutable
6243 std::vector
<lt::announce_entry
> nativeTrackers
= torrentHandle
.trackers();
6244 invoke([this, torrentHandle
, nativeTrackers
= std::move(nativeTrackers
)
6245 , updatedTrackers
= std::move(updatedTrackers
)]
6247 TorrentImpl
*torrent
= m_torrents
.value(torrentHandle
.info_hash());
6248 if (!torrent
|| torrent
->isStopped())
6251 QHash
<QString
, TrackerEntryStatus
> trackers
;
6252 trackers
.reserve(updatedTrackers
.size());
6253 for (const lt::announce_entry
&announceEntry
: nativeTrackers
)
6255 const auto updatedTrackersIter
= updatedTrackers
.find(announceEntry
.url
);
6256 if (updatedTrackersIter
== updatedTrackers
.end())
6259 const auto &updateInfo
= updatedTrackersIter
.value();
6260 TrackerEntryStatus status
= torrent
->updateTrackerEntryStatus(announceEntry
, updateInfo
);
6261 const QString url
= status
.url
;
6262 trackers
.emplace(url
, std::move(status
));
6265 emit
trackerEntryStatusesUpdated(torrent
, trackers
);
6268 catch (const std::exception
&)
6274 void SessionImpl::handleRemovedTorrent(const TorrentID
&torrentID
, const QString
&partfileRemoveError
)
6276 const auto removingTorrentDataIter
= m_removingTorrents
.find(torrentID
);
6277 if (removingTorrentDataIter
== m_removingTorrents
.end())
6280 if (!partfileRemoveError
.isEmpty())
6282 LogMsg(tr("Failed to remove partfile. Torrent: \"%1\". Reason: \"%2\".")
6283 .arg(removingTorrentDataIter
->name
, partfileRemoveError
)
6287 if ((removingTorrentDataIter
->removeOption
== TorrentRemoveOption::RemoveContent
)
6288 && !removingTorrentDataIter
->contentStoragePath
.isEmpty())
6290 QMetaObject::invokeMethod(m_torrentContentRemover
, [this, jobData
= *removingTorrentDataIter
]
6292 m_torrentContentRemover
->performJob(jobData
.name
, jobData
.contentStoragePath
6293 , jobData
.fileNames
, m_torrentContentRemoveOption
);
6297 m_removingTorrents
.erase(removingTorrentDataIter
);