2 * Bittorrent Client using Qt and libtorrent.
3 * Copyright (C) 2015-2023 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>
64 #include <QHostAddress>
66 #include <QJsonDocument>
67 #include <QJsonObject>
69 #include <QNetworkAddressEntry>
70 #if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0))
71 #include <QNetworkConfigurationManager>
73 #include <QNetworkInterface>
74 #include <QRegularExpression>
77 #include <QThreadPool>
81 #include "base/algorithm.h"
82 #include "base/global.h"
83 #include "base/logger.h"
84 #include "base/net/downloadmanager.h"
85 #include "base/net/proxyconfigurationmanager.h"
86 #include "base/preferences.h"
87 #include "base/profile.h"
88 #include "base/torrentfileguard.h"
89 #include "base/torrentfilter.h"
90 #include "base/unicodestrings.h"
91 #include "base/utils/bytearray.h"
92 #include "base/utils/fs.h"
93 #include "base/utils/io.h"
94 #include "base/utils/misc.h"
95 #include "base/utils/net.h"
96 #include "base/utils/random.h"
97 #include "base/version.h"
98 #include "bandwidthscheduler.h"
99 #include "bencoderesumedatastorage.h"
101 #include "customstorage.h"
102 #include "dbresumedatastorage.h"
103 #include "downloadpriority.h"
104 #include "extensiondata.h"
105 #include "filesearcher.h"
106 #include "filterparserthread.h"
107 #include "loadtorrentparams.h"
108 #include "lttypecast.h"
109 #include "magneturi.h"
110 #include "nativesessionextension.h"
111 #include "portforwarderimpl.h"
112 #include "resumedatastorage.h"
113 #include "torrentimpl.h"
116 using namespace std::chrono_literals
;
117 using namespace BitTorrent
;
119 const Path CATEGORIES_FILE_NAME
{u
"categories.json"_qs
};
120 const int MAX_PROCESSING_RESUMEDATA_COUNT
= 50;
121 const int STATISTICS_SAVE_INTERVAL
= std::chrono::milliseconds(15min
).count();
123 #if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0))
126 uint
qHash(const std::string
&key
, uint seed
= 0)
128 return ::qHash(std::hash
<std::string
> {}(key
), seed
);
134 uint
qHash(const libtorrent::torrent_handle
&key
)
136 return static_cast<uint
>(libtorrent::hash_value(key
));
143 const char PEER_ID
[] = "qB";
144 const auto USER_AGENT
= QStringLiteral("qBittorrent/" QBT_VERSION_2
);
146 void torrentQueuePositionUp(const lt::torrent_handle
&handle
)
150 handle
.queue_position_up();
152 catch (const std::exception
&exc
)
154 qDebug() << Q_FUNC_INFO
<< " fails: " << exc
.what();
158 void torrentQueuePositionDown(const lt::torrent_handle
&handle
)
162 handle
.queue_position_down();
164 catch (const std::exception
&exc
)
166 qDebug() << Q_FUNC_INFO
<< " fails: " << exc
.what();
170 void torrentQueuePositionTop(const lt::torrent_handle
&handle
)
174 handle
.queue_position_top();
176 catch (const std::exception
&exc
)
178 qDebug() << Q_FUNC_INFO
<< " fails: " << exc
.what();
182 void torrentQueuePositionBottom(const lt::torrent_handle
&handle
)
186 handle
.queue_position_bottom();
188 catch (const std::exception
&exc
)
190 qDebug() << Q_FUNC_INFO
<< " fails: " << exc
.what();
194 QMap
<QString
, CategoryOptions
> expandCategories(const QMap
<QString
, CategoryOptions
> &categories
)
196 QMap
<QString
, CategoryOptions
> expanded
= categories
;
198 for (auto i
= categories
.cbegin(); i
!= categories
.cend(); ++i
)
200 const QString
&category
= i
.key();
201 for (const QString
&subcat
: asConst(Session::expandCategory(category
)))
203 if (!expanded
.contains(subcat
))
204 expanded
[subcat
] = {};
211 QString
toString(const lt::socket_type_t socketType
)
215 #ifdef QBT_USES_LIBTORRENT2
216 case lt::socket_type_t::http
:
218 case lt::socket_type_t::http_ssl
:
219 return u
"HTTP_SSL"_qs
;
221 case lt::socket_type_t::i2p
:
223 case lt::socket_type_t::socks5
:
225 #ifdef QBT_USES_LIBTORRENT2
226 case lt::socket_type_t::socks5_ssl
:
227 return u
"SOCKS5_SSL"_qs
;
229 case lt::socket_type_t::tcp
:
231 case lt::socket_type_t::tcp_ssl
:
232 return u
"TCP_SSL"_qs
;
233 #ifdef QBT_USES_LIBTORRENT2
234 case lt::socket_type_t::utp
:
237 case lt::socket_type_t::udp
:
240 case lt::socket_type_t::utp_ssl
:
241 return u
"UTP_SSL"_qs
;
243 return u
"INVALID"_qs
;
246 QString
toString(const lt::address
&address
)
250 return QString::fromLatin1(address
.to_string().c_str());
252 catch (const std::exception
&)
254 // suppress conversion error
259 template <typename T
>
262 LowerLimited(T limit
, T ret
)
268 explicit LowerLimited(T limit
)
269 : LowerLimited(limit
, limit
)
273 T
operator()(T val
) const
275 return val
<= m_limit
? m_ret
: val
;
283 template <typename T
>
284 LowerLimited
<T
> lowerLimited(T limit
) { return LowerLimited
<T
>(limit
); }
286 template <typename T
>
287 LowerLimited
<T
> lowerLimited(T limit
, T ret
) { return LowerLimited
<T
>(limit
, ret
); }
289 template <typename T
>
290 auto clampValue(const T lower
, const T upper
)
292 return [lower
, upper
](const T value
) -> T
303 QString
convertIfaceNameToGuid(const QString
&name
)
305 // Under Windows XP or on Qt version <= 5.5 'name' will be a GUID already.
306 const QUuid
uuid(name
);
308 return uuid
.toString().toUpper(); // Libtorrent expects the GUID in uppercase
310 const std::wstring nameWStr
= name
.toStdWString();
312 const LONG res
= ::ConvertInterfaceNameToLuidW(nameWStr
.c_str(), &luid
);
316 if (::ConvertInterfaceLuidToGuid(&luid
, &guid
) == 0)
317 return QUuid(guid
).toString().toUpper();
324 constexpr lt::move_flags_t
toNative(const MoveStorageMode mode
)
330 case MoveStorageMode::FailIfExist
:
331 return lt::move_flags_t::fail_if_exist
;
332 case MoveStorageMode::KeepExistingFiles
:
333 return lt::move_flags_t::dont_replace
;
334 case MoveStorageMode::Overwrite
:
335 return lt::move_flags_t::always_replace_files
;
340 struct BitTorrent::SessionImpl::ResumeSessionContext final
: public QObject
342 using QObject::QObject
;
344 ResumeDataStorage
*startupStorage
= nullptr;
345 ResumeDataStorageType currentStorageType
= ResumeDataStorageType::Legacy
;
346 QList
<LoadedResumeData
> loadedResumeData
;
347 int processingResumeDataCount
= 0;
348 int64_t totalResumeDataCount
= 0;
349 int64_t finishedResumeDataCount
= 0;
350 bool isLoadFinished
= false;
351 bool isLoadedResumeDataHandlingEnqueued
= false;
352 QSet
<QString
> recoveredCategories
;
353 #ifdef QBT_USES_LIBTORRENT2
354 QSet
<TorrentID
> indexedTorrents
;
355 QSet
<TorrentID
> skippedIDs
;
359 const int addTorrentParamsId
= qRegisterMetaType
<AddTorrentParams
>();
361 Session
*SessionImpl::m_instance
= nullptr;
363 void Session::initInstance()
365 if (!SessionImpl::m_instance
)
366 SessionImpl::m_instance
= new SessionImpl
;
369 void Session::freeInstance()
371 delete SessionImpl::m_instance
;
372 SessionImpl::m_instance
= nullptr;
375 Session
*Session::instance()
377 return SessionImpl::m_instance
;
380 bool Session::isValidCategoryName(const QString
&name
)
382 const QRegularExpression re
{uR
"(^([^\\\/]|[^\\\/]([^\\\/]|\/(?=[^\/]))*[^\\\/])$)"_qs
};
383 return (name
.isEmpty() || (name
.indexOf(re
) == 0));
386 bool Session::isValidTag(const QString
&tag
)
388 return (!tag
.trimmed().isEmpty() && !tag
.contains(u
','));
391 QStringList
Session::expandCategory(const QString
&category
)
395 while ((index
= category
.indexOf(u
'/', index
)) >= 0)
397 result
<< category
.left(index
);
405 #define BITTORRENT_KEY(name) u"BitTorrent/" name
406 #define BITTORRENT_SESSION_KEY(name) BITTORRENT_KEY(u"Session/") name
408 SessionImpl::SessionImpl(QObject
*parent
)
410 , m_isDHTEnabled(BITTORRENT_SESSION_KEY(u
"DHTEnabled"_qs
), true)
411 , m_isLSDEnabled(BITTORRENT_SESSION_KEY(u
"LSDEnabled"_qs
), true)
412 , m_isPeXEnabled(BITTORRENT_SESSION_KEY(u
"PeXEnabled"_qs
), true)
413 , m_isIPFilteringEnabled(BITTORRENT_SESSION_KEY(u
"IPFilteringEnabled"_qs
), false)
414 , m_isTrackerFilteringEnabled(BITTORRENT_SESSION_KEY(u
"TrackerFilteringEnabled"_qs
), false)
415 , m_IPFilterFile(BITTORRENT_SESSION_KEY(u
"IPFilter"_qs
))
416 , m_announceToAllTrackers(BITTORRENT_SESSION_KEY(u
"AnnounceToAllTrackers"_qs
), false)
417 , m_announceToAllTiers(BITTORRENT_SESSION_KEY(u
"AnnounceToAllTiers"_qs
), true)
418 , m_asyncIOThreads(BITTORRENT_SESSION_KEY(u
"AsyncIOThreadsCount"_qs
), 10)
419 , m_hashingThreads(BITTORRENT_SESSION_KEY(u
"HashingThreadsCount"_qs
), 1)
420 , m_filePoolSize(BITTORRENT_SESSION_KEY(u
"FilePoolSize"_qs
), 500)
421 , m_checkingMemUsage(BITTORRENT_SESSION_KEY(u
"CheckingMemUsageSize"_qs
), 32)
422 , m_diskCacheSize(BITTORRENT_SESSION_KEY(u
"DiskCacheSize"_qs
), -1)
423 , m_diskCacheTTL(BITTORRENT_SESSION_KEY(u
"DiskCacheTTL"_qs
), 60)
424 , m_diskQueueSize(BITTORRENT_SESSION_KEY(u
"DiskQueueSize"_qs
), (1024 * 1024))
425 , m_diskIOType(BITTORRENT_SESSION_KEY(u
"DiskIOType"_qs
), DiskIOType::Default
)
426 , m_diskIOReadMode(BITTORRENT_SESSION_KEY(u
"DiskIOReadMode"_qs
), DiskIOReadMode::EnableOSCache
)
427 , m_diskIOWriteMode(BITTORRENT_SESSION_KEY(u
"DiskIOWriteMode"_qs
), DiskIOWriteMode::EnableOSCache
)
429 , m_coalesceReadWriteEnabled(BITTORRENT_SESSION_KEY(u
"CoalesceReadWrite"_qs
), true)
431 , m_coalesceReadWriteEnabled(BITTORRENT_SESSION_KEY(u
"CoalesceReadWrite"_qs
), false)
433 , m_usePieceExtentAffinity(BITTORRENT_SESSION_KEY(u
"PieceExtentAffinity"_qs
), false)
434 , m_isSuggestMode(BITTORRENT_SESSION_KEY(u
"SuggestMode"_qs
), false)
435 , m_sendBufferWatermark(BITTORRENT_SESSION_KEY(u
"SendBufferWatermark"_qs
), 500)
436 , m_sendBufferLowWatermark(BITTORRENT_SESSION_KEY(u
"SendBufferLowWatermark"_qs
), 10)
437 , m_sendBufferWatermarkFactor(BITTORRENT_SESSION_KEY(u
"SendBufferWatermarkFactor"_qs
), 50)
438 , m_connectionSpeed(BITTORRENT_SESSION_KEY(u
"ConnectionSpeed"_qs
), 30)
439 , m_socketSendBufferSize(BITTORRENT_SESSION_KEY(u
"SocketSendBufferSize"_qs
), 0)
440 , m_socketReceiveBufferSize(BITTORRENT_SESSION_KEY(u
"SocketReceiveBufferSize"_qs
), 0)
441 , m_socketBacklogSize(BITTORRENT_SESSION_KEY(u
"SocketBacklogSize"_qs
), 30)
442 , m_isAnonymousModeEnabled(BITTORRENT_SESSION_KEY(u
"AnonymousModeEnabled"_qs
), false)
443 , m_isQueueingEnabled(BITTORRENT_SESSION_KEY(u
"QueueingSystemEnabled"_qs
), false)
444 , m_maxActiveDownloads(BITTORRENT_SESSION_KEY(u
"MaxActiveDownloads"_qs
), 3, lowerLimited(-1))
445 , m_maxActiveUploads(BITTORRENT_SESSION_KEY(u
"MaxActiveUploads"_qs
), 3, lowerLimited(-1))
446 , m_maxActiveTorrents(BITTORRENT_SESSION_KEY(u
"MaxActiveTorrents"_qs
), 5, lowerLimited(-1))
447 , m_ignoreSlowTorrentsForQueueing(BITTORRENT_SESSION_KEY(u
"IgnoreSlowTorrentsForQueueing"_qs
), false)
448 , m_downloadRateForSlowTorrents(BITTORRENT_SESSION_KEY(u
"SlowTorrentsDownloadRate"_qs
), 2)
449 , m_uploadRateForSlowTorrents(BITTORRENT_SESSION_KEY(u
"SlowTorrentsUploadRate"_qs
), 2)
450 , m_slowTorrentsInactivityTimer(BITTORRENT_SESSION_KEY(u
"SlowTorrentsInactivityTimer"_qs
), 60)
451 , m_outgoingPortsMin(BITTORRENT_SESSION_KEY(u
"OutgoingPortsMin"_qs
), 0)
452 , m_outgoingPortsMax(BITTORRENT_SESSION_KEY(u
"OutgoingPortsMax"_qs
), 0)
453 , m_UPnPLeaseDuration(BITTORRENT_SESSION_KEY(u
"UPnPLeaseDuration"_qs
), 0)
454 , m_peerToS(BITTORRENT_SESSION_KEY(u
"PeerToS"_qs
), 0x04)
455 , m_ignoreLimitsOnLAN(BITTORRENT_SESSION_KEY(u
"IgnoreLimitsOnLAN"_qs
), false)
456 , m_includeOverheadInLimits(BITTORRENT_SESSION_KEY(u
"IncludeOverheadInLimits"_qs
), false)
457 , m_announceIP(BITTORRENT_SESSION_KEY(u
"AnnounceIP"_qs
))
458 , m_maxConcurrentHTTPAnnounces(BITTORRENT_SESSION_KEY(u
"MaxConcurrentHTTPAnnounces"_qs
), 50)
459 , m_isReannounceWhenAddressChangedEnabled(BITTORRENT_SESSION_KEY(u
"ReannounceWhenAddressChanged"_qs
), false)
460 , m_stopTrackerTimeout(BITTORRENT_SESSION_KEY(u
"StopTrackerTimeout"_qs
), 5)
461 , m_maxConnections(BITTORRENT_SESSION_KEY(u
"MaxConnections"_qs
), 500, lowerLimited(0, -1))
462 , m_maxUploads(BITTORRENT_SESSION_KEY(u
"MaxUploads"_qs
), 20, lowerLimited(0, -1))
463 , m_maxConnectionsPerTorrent(BITTORRENT_SESSION_KEY(u
"MaxConnectionsPerTorrent"_qs
), 100, lowerLimited(0, -1))
464 , m_maxUploadsPerTorrent(BITTORRENT_SESSION_KEY(u
"MaxUploadsPerTorrent"_qs
), 4, lowerLimited(0, -1))
465 , m_btProtocol(BITTORRENT_SESSION_KEY(u
"BTProtocol"_qs
), BTProtocol::Both
466 , clampValue(BTProtocol::Both
, BTProtocol::UTP
))
467 , m_isUTPRateLimited(BITTORRENT_SESSION_KEY(u
"uTPRateLimited"_qs
), true)
468 , m_utpMixedMode(BITTORRENT_SESSION_KEY(u
"uTPMixedMode"_qs
), MixedModeAlgorithm::TCP
469 , clampValue(MixedModeAlgorithm::TCP
, MixedModeAlgorithm::Proportional
))
470 , m_IDNSupportEnabled(BITTORRENT_SESSION_KEY(u
"IDNSupportEnabled"_qs
), false)
471 , m_multiConnectionsPerIpEnabled(BITTORRENT_SESSION_KEY(u
"MultiConnectionsPerIp"_qs
), false)
472 , m_validateHTTPSTrackerCertificate(BITTORRENT_SESSION_KEY(u
"ValidateHTTPSTrackerCertificate"_qs
), true)
473 , m_SSRFMitigationEnabled(BITTORRENT_SESSION_KEY(u
"SSRFMitigation"_qs
), true)
474 , m_blockPeersOnPrivilegedPorts(BITTORRENT_SESSION_KEY(u
"BlockPeersOnPrivilegedPorts"_qs
), false)
475 , m_isAddTrackersEnabled(BITTORRENT_SESSION_KEY(u
"AddTrackersEnabled"_qs
), false)
476 , m_additionalTrackers(BITTORRENT_SESSION_KEY(u
"AdditionalTrackers"_qs
))
477 , m_globalMaxRatio(BITTORRENT_SESSION_KEY(u
"GlobalMaxRatio"_qs
), -1, [](qreal r
) { return r
< 0 ? -1. : r
;})
478 , m_globalMaxSeedingMinutes(BITTORRENT_SESSION_KEY(u
"GlobalMaxSeedingMinutes"_qs
), -1, lowerLimited(-1))
479 , m_isAddTorrentToQueueTop(BITTORRENT_SESSION_KEY(u
"AddTorrentToTopOfQueue"_qs
), false)
480 , m_isAddTorrentPaused(BITTORRENT_SESSION_KEY(u
"AddTorrentPaused"_qs
), false)
481 , m_torrentStopCondition(BITTORRENT_SESSION_KEY(u
"TorrentStopCondition"_qs
), Torrent::StopCondition::None
)
482 , m_torrentContentLayout(BITTORRENT_SESSION_KEY(u
"TorrentContentLayout"_qs
), TorrentContentLayout::Original
)
483 , m_isAppendExtensionEnabled(BITTORRENT_SESSION_KEY(u
"AddExtensionToIncompleteFiles"_qs
), false)
484 , m_refreshInterval(BITTORRENT_SESSION_KEY(u
"RefreshInterval"_qs
), 1500)
485 , m_isPreallocationEnabled(BITTORRENT_SESSION_KEY(u
"Preallocation"_qs
), false)
486 , m_torrentExportDirectory(BITTORRENT_SESSION_KEY(u
"TorrentExportDirectory"_qs
))
487 , m_finishedTorrentExportDirectory(BITTORRENT_SESSION_KEY(u
"FinishedTorrentExportDirectory"_qs
))
488 , m_globalDownloadSpeedLimit(BITTORRENT_SESSION_KEY(u
"GlobalDLSpeedLimit"_qs
), 0, lowerLimited(0))
489 , m_globalUploadSpeedLimit(BITTORRENT_SESSION_KEY(u
"GlobalUPSpeedLimit"_qs
), 0, lowerLimited(0))
490 , m_altGlobalDownloadSpeedLimit(BITTORRENT_SESSION_KEY(u
"AlternativeGlobalDLSpeedLimit"_qs
), 10, lowerLimited(0))
491 , m_altGlobalUploadSpeedLimit(BITTORRENT_SESSION_KEY(u
"AlternativeGlobalUPSpeedLimit"_qs
), 10, lowerLimited(0))
492 , m_isAltGlobalSpeedLimitEnabled(BITTORRENT_SESSION_KEY(u
"UseAlternativeGlobalSpeedLimit"_qs
), false)
493 , m_isBandwidthSchedulerEnabled(BITTORRENT_SESSION_KEY(u
"BandwidthSchedulerEnabled"_qs
), false)
494 , m_isPerformanceWarningEnabled(BITTORRENT_SESSION_KEY(u
"PerformanceWarning"_qs
), false)
495 , m_saveResumeDataInterval(BITTORRENT_SESSION_KEY(u
"SaveResumeDataInterval"_qs
), 60)
496 , m_port(BITTORRENT_SESSION_KEY(u
"Port"_qs
), -1)
497 , m_networkInterface(BITTORRENT_SESSION_KEY(u
"Interface"_qs
))
498 , m_networkInterfaceName(BITTORRENT_SESSION_KEY(u
"InterfaceName"_qs
))
499 , m_networkInterfaceAddress(BITTORRENT_SESSION_KEY(u
"InterfaceAddress"_qs
))
500 , m_encryption(BITTORRENT_SESSION_KEY(u
"Encryption"_qs
), 0)
501 , m_maxActiveCheckingTorrents(BITTORRENT_SESSION_KEY(u
"MaxActiveCheckingTorrents"_qs
), 1)
502 , m_isProxyPeerConnectionsEnabled(BITTORRENT_SESSION_KEY(u
"ProxyPeerConnections"_qs
), false)
503 , m_chokingAlgorithm(BITTORRENT_SESSION_KEY(u
"ChokingAlgorithm"_qs
), ChokingAlgorithm::FixedSlots
504 , clampValue(ChokingAlgorithm::FixedSlots
, ChokingAlgorithm::RateBased
))
505 , m_seedChokingAlgorithm(BITTORRENT_SESSION_KEY(u
"SeedChokingAlgorithm"_qs
), SeedChokingAlgorithm::FastestUpload
506 , clampValue(SeedChokingAlgorithm::RoundRobin
, SeedChokingAlgorithm::AntiLeech
))
507 , m_storedTags(BITTORRENT_SESSION_KEY(u
"Tags"_qs
))
508 , m_maxRatioAction(BITTORRENT_SESSION_KEY(u
"MaxRatioAction"_qs
), Pause
)
509 , m_savePath(BITTORRENT_SESSION_KEY(u
"DefaultSavePath"_qs
), specialFolderLocation(SpecialFolder::Downloads
))
510 , m_downloadPath(BITTORRENT_SESSION_KEY(u
"TempPath"_qs
), (savePath() / Path(u
"temp"_qs
)))
511 , m_isDownloadPathEnabled(BITTORRENT_SESSION_KEY(u
"TempPathEnabled"_qs
), false)
512 , m_isSubcategoriesEnabled(BITTORRENT_SESSION_KEY(u
"SubcategoriesEnabled"_qs
), false)
513 , m_useCategoryPathsInManualMode(BITTORRENT_SESSION_KEY(u
"UseCategoryPathsInManualMode"_qs
), false)
514 , m_isAutoTMMDisabledByDefault(BITTORRENT_SESSION_KEY(u
"DisableAutoTMMByDefault"_qs
), true)
515 , m_isDisableAutoTMMWhenCategoryChanged(BITTORRENT_SESSION_KEY(u
"DisableAutoTMMTriggers/CategoryChanged"_qs
), false)
516 , m_isDisableAutoTMMWhenDefaultSavePathChanged(BITTORRENT_SESSION_KEY(u
"DisableAutoTMMTriggers/DefaultSavePathChanged"_qs
), true)
517 , m_isDisableAutoTMMWhenCategorySavePathChanged(BITTORRENT_SESSION_KEY(u
"DisableAutoTMMTriggers/CategorySavePathChanged"_qs
), true)
518 , m_isTrackerEnabled(BITTORRENT_KEY(u
"TrackerEnabled"_qs
), false)
519 , m_peerTurnover(BITTORRENT_SESSION_KEY(u
"PeerTurnover"_qs
), 4)
520 , m_peerTurnoverCutoff(BITTORRENT_SESSION_KEY(u
"PeerTurnoverCutOff"_qs
), 90)
521 , m_peerTurnoverInterval(BITTORRENT_SESSION_KEY(u
"PeerTurnoverInterval"_qs
), 300)
522 , m_requestQueueSize(BITTORRENT_SESSION_KEY(u
"RequestQueueSize"_qs
), 500)
523 , m_isExcludedFileNamesEnabled(BITTORRENT_KEY(u
"ExcludedFileNamesEnabled"_qs
), false)
524 , m_excludedFileNames(BITTORRENT_SESSION_KEY(u
"ExcludedFileNames"_qs
))
525 , m_bannedIPs(u
"State/BannedIPs"_qs
, QStringList(), Algorithm::sorted
<QStringList
>)
526 , m_resumeDataStorageType(BITTORRENT_SESSION_KEY(u
"ResumeDataStorageType"_qs
), ResumeDataStorageType::Legacy
)
527 , m_isI2PEnabled
{BITTORRENT_SESSION_KEY(u
"I2P/Enabled"_qs
), false}
528 , m_I2PAddress
{BITTORRENT_SESSION_KEY(u
"I2P/Address"_qs
), u
"127.0.0.1"_qs
}
529 , m_I2PPort
{BITTORRENT_SESSION_KEY(u
"I2P/Port"_qs
), 7656}
530 , m_I2PMixedMode
{BITTORRENT_SESSION_KEY(u
"I2P/MixedMode"_qs
), false}
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)}
536 #if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0))
537 , m_networkManager
{new QNetworkConfigurationManager(this)}
540 // It is required to perform async access to libtorrent sequentially
541 m_asyncWorker
->setMaxThreadCount(1);
544 m_port
= Utils::Random::rand(1024, 65535);
546 m_recentErroredTorrentsTimer
->setSingleShot(true);
547 m_recentErroredTorrentsTimer
->setInterval(1s
);
548 connect(m_recentErroredTorrentsTimer
, &QTimer::timeout
549 , this, [this]() { m_recentErroredTorrents
.clear(); });
551 m_seedingLimitTimer
->setInterval(10s
);
552 connect(m_seedingLimitTimer
, &QTimer::timeout
, this, &SessionImpl::processShareLimits
);
554 initializeNativeSession();
555 configureComponents();
557 if (isBandwidthSchedulerEnabled())
558 enableBandwidthScheduler();
561 if (isSubcategoriesEnabled())
563 // if subcategories support changed manually
564 m_categories
= expandCategories(m_categories
);
567 const QStringList storedTags
= m_storedTags
.get();
568 m_tags
= {storedTags
.cbegin(), storedTags
.cend()};
570 updateSeedingLimitTimer();
571 populateAdditionalTrackers();
572 if (isExcludedFileNamesEnabled())
573 populateExcludedFileNamesRegExpList();
575 connect(Net::ProxyConfigurationManager::instance()
576 , &Net::ProxyConfigurationManager::proxyConfigurationChanged
577 , this, &SessionImpl::configureDeferred
);
579 #if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0))
580 // Network configuration monitor
581 connect(m_networkManager
, &QNetworkConfigurationManager::onlineStateChanged
, this, &SessionImpl::networkOnlineStateChanged
);
582 connect(m_networkManager
, &QNetworkConfigurationManager::configurationAdded
, this, &SessionImpl::networkConfigurationChange
);
583 connect(m_networkManager
, &QNetworkConfigurationManager::configurationRemoved
, this, &SessionImpl::networkConfigurationChange
);
584 connect(m_networkManager
, &QNetworkConfigurationManager::configurationChanged
, this, &SessionImpl::networkConfigurationChange
);
587 m_fileSearcher
= new FileSearcher
;
588 m_fileSearcher
->moveToThread(m_ioThread
.get());
589 connect(m_ioThread
.get(), &QThread::finished
, m_fileSearcher
, &QObject::deleteLater
);
590 connect(m_fileSearcher
, &FileSearcher::searchFinished
, this, &SessionImpl::fileSearchFinished
);
597 // initialize PortForwarder instance
598 new PortForwarderImpl(this);
600 // start embedded tracker
601 enableTracker(isTrackerEnabled());
606 SessionImpl::~SessionImpl()
608 m_nativeSession
->pause();
610 if (m_torrentsQueueChanged
)
612 m_nativeSession
->post_torrent_updates({});
613 m_torrentsQueueChanged
= false;
614 m_needSaveTorrentsQueue
= true;
617 // Do some bittorrent related saving
618 // After this, (ideally) no more important alerts will be generated/handled
623 // We must delete FilterParserThread
624 // before we delete lt::session
625 delete m_filterParser
;
627 // We must delete PortForwarderImpl before
628 // we delete lt::session
629 delete Net::PortForwarder::instance();
631 // We must stop "async worker" only after deletion
632 // of all the components that could potentially use it
633 m_asyncWorker
->clear();
634 m_asyncWorker
->waitForDone();
636 qDebug("Deleting libtorrent session...");
637 delete m_nativeSession
;
640 bool SessionImpl::isDHTEnabled() const
642 return m_isDHTEnabled
;
645 void SessionImpl::setDHTEnabled(bool enabled
)
647 if (enabled
!= m_isDHTEnabled
)
649 m_isDHTEnabled
= enabled
;
651 LogMsg(tr("Distributed Hash Table (DHT) support: %1").arg(enabled
? tr("ON") : tr("OFF")), Log::INFO
);
655 bool SessionImpl::isLSDEnabled() const
657 return m_isLSDEnabled
;
660 void SessionImpl::setLSDEnabled(const bool enabled
)
662 if (enabled
!= m_isLSDEnabled
)
664 m_isLSDEnabled
= enabled
;
666 LogMsg(tr("Local Peer Discovery support: %1").arg(enabled
? tr("ON") : tr("OFF"))
671 bool SessionImpl::isPeXEnabled() const
673 return m_isPeXEnabled
;
676 void SessionImpl::setPeXEnabled(const bool enabled
)
678 m_isPeXEnabled
= enabled
;
679 if (m_wasPexEnabled
!= enabled
)
680 LogMsg(tr("Restart is required to toggle Peer Exchange (PeX) support"), Log::WARNING
);
683 bool SessionImpl::isDownloadPathEnabled() const
685 return m_isDownloadPathEnabled
;
688 void SessionImpl::setDownloadPathEnabled(const bool enabled
)
690 if (enabled
!= isDownloadPathEnabled())
692 m_isDownloadPathEnabled
= enabled
;
693 for (TorrentImpl
*const torrent
: asConst(m_torrents
))
694 torrent
->handleCategoryOptionsChanged();
698 bool SessionImpl::isAppendExtensionEnabled() const
700 return m_isAppendExtensionEnabled
;
703 void SessionImpl::setAppendExtensionEnabled(const bool enabled
)
705 if (isAppendExtensionEnabled() != enabled
)
707 m_isAppendExtensionEnabled
= enabled
;
709 // append or remove .!qB extension for incomplete files
710 for (TorrentImpl
*const torrent
: asConst(m_torrents
))
711 torrent
->handleAppendExtensionToggled();
715 int SessionImpl::refreshInterval() const
717 return m_refreshInterval
;
720 void SessionImpl::setRefreshInterval(const int value
)
722 if (value
!= refreshInterval())
724 m_refreshInterval
= value
;
728 bool SessionImpl::isPreallocationEnabled() const
730 return m_isPreallocationEnabled
;
733 void SessionImpl::setPreallocationEnabled(const bool enabled
)
735 m_isPreallocationEnabled
= enabled
;
738 Path
SessionImpl::torrentExportDirectory() const
740 return m_torrentExportDirectory
;
743 void SessionImpl::setTorrentExportDirectory(const Path
&path
)
745 if (path
!= torrentExportDirectory())
746 m_torrentExportDirectory
= path
;
749 Path
SessionImpl::finishedTorrentExportDirectory() const
751 return m_finishedTorrentExportDirectory
;
754 void SessionImpl::setFinishedTorrentExportDirectory(const Path
&path
)
756 if (path
!= finishedTorrentExportDirectory())
757 m_finishedTorrentExportDirectory
= path
;
760 Path
SessionImpl::savePath() const
762 // TODO: Make sure it is always non-empty
766 Path
SessionImpl::downloadPath() const
768 // TODO: Make sure it is always non-empty
769 return m_downloadPath
;
772 QStringList
SessionImpl::categories() const
774 return m_categories
.keys();
777 CategoryOptions
SessionImpl::categoryOptions(const QString
&categoryName
) const
779 return m_categories
.value(categoryName
);
782 Path
SessionImpl::categorySavePath(const QString
&categoryName
) const
784 const Path basePath
= savePath();
785 if (categoryName
.isEmpty())
788 Path path
= m_categories
.value(categoryName
).savePath
;
789 if (path
.isEmpty()) // use implicit save path
790 path
= Utils::Fs::toValidPath(categoryName
);
792 return (path
.isAbsolute() ? path
: (basePath
/ path
));
795 Path
SessionImpl::categoryDownloadPath(const QString
&categoryName
) const
797 const CategoryOptions categoryOptions
= m_categories
.value(categoryName
);
798 const CategoryOptions::DownloadPathOption downloadPathOption
=
799 categoryOptions
.downloadPath
.value_or(CategoryOptions::DownloadPathOption
{isDownloadPathEnabled(), downloadPath()});
800 if (!downloadPathOption
.enabled
)
803 const Path basePath
= downloadPath();
804 if (categoryName
.isEmpty())
807 const Path path
= (!downloadPathOption
.path
.isEmpty()
808 ? downloadPathOption
.path
809 : Utils::Fs::toValidPath(categoryName
)); // use implicit download path
811 return (path
.isAbsolute() ? path
: (basePath
/ path
));
814 bool SessionImpl::addCategory(const QString
&name
, const CategoryOptions
&options
)
819 if (!isValidCategoryName(name
) || m_categories
.contains(name
))
822 if (isSubcategoriesEnabled())
824 for (const QString
&parent
: asConst(expandCategory(name
)))
826 if ((parent
!= name
) && !m_categories
.contains(parent
))
828 m_categories
[parent
] = {};
829 emit
categoryAdded(parent
);
834 m_categories
[name
] = options
;
836 emit
categoryAdded(name
);
841 bool SessionImpl::editCategory(const QString
&name
, const CategoryOptions
&options
)
843 const auto it
= m_categories
.find(name
);
844 if (it
== m_categories
.end())
847 CategoryOptions
¤tOptions
= it
.value();
848 if (options
== currentOptions
)
851 currentOptions
= options
;
853 if (isDisableAutoTMMWhenCategorySavePathChanged())
855 for (TorrentImpl
*const torrent
: asConst(m_torrents
))
857 if (torrent
->category() == name
)
858 torrent
->setAutoTMMEnabled(false);
863 for (TorrentImpl
*const torrent
: asConst(m_torrents
))
865 if (torrent
->category() == name
)
866 torrent
->handleCategoryOptionsChanged();
870 emit
categoryOptionsChanged(name
);
874 bool SessionImpl::removeCategory(const QString
&name
)
876 for (TorrentImpl
*const torrent
: asConst(m_torrents
))
878 if (torrent
->belongsToCategory(name
))
879 torrent
->setCategory(u
""_qs
);
882 // remove stored category and its subcategories if exist
884 if (isSubcategoriesEnabled())
886 // remove subcategories
887 const QString test
= name
+ u
'/';
888 Algorithm::removeIf(m_categories
, [this, &test
, &result
](const QString
&category
, const CategoryOptions
&)
890 if (category
.startsWith(test
))
893 emit
categoryRemoved(category
);
900 result
= (m_categories
.remove(name
) > 0) || result
;
904 // update stored categories
906 emit
categoryRemoved(name
);
912 bool SessionImpl::isSubcategoriesEnabled() const
914 return m_isSubcategoriesEnabled
;
917 void SessionImpl::setSubcategoriesEnabled(const bool value
)
919 if (isSubcategoriesEnabled() == value
) return;
923 // expand categories to include all parent categories
924 m_categories
= expandCategories(m_categories
);
925 // update stored categories
934 m_isSubcategoriesEnabled
= value
;
935 emit
subcategoriesSupportChanged();
938 bool SessionImpl::useCategoryPathsInManualMode() const
940 return m_useCategoryPathsInManualMode
;
943 void SessionImpl::setUseCategoryPathsInManualMode(const bool value
)
945 m_useCategoryPathsInManualMode
= value
;
948 Path
SessionImpl::suggestedSavePath(const QString
&categoryName
, std::optional
<bool> useAutoTMM
) const
950 const bool useCategoryPaths
= useAutoTMM
.value_or(!isAutoTMMDisabledByDefault()) || useCategoryPathsInManualMode();
951 const auto path
= (useCategoryPaths
? categorySavePath(categoryName
) : savePath());
955 Path
SessionImpl::suggestedDownloadPath(const QString
&categoryName
, std::optional
<bool> useAutoTMM
) const
957 const bool useCategoryPaths
= useAutoTMM
.value_or(!isAutoTMMDisabledByDefault()) || useCategoryPathsInManualMode();
958 const auto categoryDownloadPath
= this->categoryDownloadPath(categoryName
);
959 const auto path
= ((useCategoryPaths
&& !categoryDownloadPath
.isEmpty()) ? categoryDownloadPath
: downloadPath());
963 QSet
<QString
> SessionImpl::tags() const
968 bool SessionImpl::hasTag(const QString
&tag
) const
970 return m_tags
.contains(tag
);
973 bool SessionImpl::addTag(const QString
&tag
)
975 if (!isValidTag(tag
) || hasTag(tag
))
979 m_storedTags
= m_tags
.values();
984 bool SessionImpl::removeTag(const QString
&tag
)
986 if (m_tags
.remove(tag
))
988 for (TorrentImpl
*const torrent
: asConst(m_torrents
))
989 torrent
->removeTag(tag
);
990 m_storedTags
= m_tags
.values();
991 emit
tagRemoved(tag
);
997 bool SessionImpl::isAutoTMMDisabledByDefault() const
999 return m_isAutoTMMDisabledByDefault
;
1002 void SessionImpl::setAutoTMMDisabledByDefault(const bool value
)
1004 m_isAutoTMMDisabledByDefault
= value
;
1007 bool SessionImpl::isDisableAutoTMMWhenCategoryChanged() const
1009 return m_isDisableAutoTMMWhenCategoryChanged
;
1012 void SessionImpl::setDisableAutoTMMWhenCategoryChanged(const bool value
)
1014 m_isDisableAutoTMMWhenCategoryChanged
= value
;
1017 bool SessionImpl::isDisableAutoTMMWhenDefaultSavePathChanged() const
1019 return m_isDisableAutoTMMWhenDefaultSavePathChanged
;
1022 void SessionImpl::setDisableAutoTMMWhenDefaultSavePathChanged(const bool value
)
1024 m_isDisableAutoTMMWhenDefaultSavePathChanged
= value
;
1027 bool SessionImpl::isDisableAutoTMMWhenCategorySavePathChanged() const
1029 return m_isDisableAutoTMMWhenCategorySavePathChanged
;
1032 void SessionImpl::setDisableAutoTMMWhenCategorySavePathChanged(const bool value
)
1034 m_isDisableAutoTMMWhenCategorySavePathChanged
= value
;
1037 bool SessionImpl::isAddTorrentToQueueTop() const
1039 return m_isAddTorrentToQueueTop
;
1042 void SessionImpl::setAddTorrentToQueueTop(bool value
)
1044 m_isAddTorrentToQueueTop
= value
;
1047 bool SessionImpl::isAddTorrentPaused() const
1049 return m_isAddTorrentPaused
;
1052 void SessionImpl::setAddTorrentPaused(const bool value
)
1054 m_isAddTorrentPaused
= value
;
1057 Torrent::StopCondition
SessionImpl::torrentStopCondition() const
1059 return m_torrentStopCondition
;
1062 void SessionImpl::setTorrentStopCondition(const Torrent::StopCondition stopCondition
)
1064 m_torrentStopCondition
= stopCondition
;
1067 bool SessionImpl::isTrackerEnabled() const
1069 return m_isTrackerEnabled
;
1072 void SessionImpl::setTrackerEnabled(const bool enabled
)
1074 if (m_isTrackerEnabled
!= enabled
)
1075 m_isTrackerEnabled
= enabled
;
1077 // call enableTracker() unconditionally, otherwise port change won't trigger
1079 enableTracker(enabled
);
1082 qreal
SessionImpl::globalMaxRatio() const
1084 return m_globalMaxRatio
;
1087 // Torrents with a ratio superior to the given value will
1088 // be automatically deleted
1089 void SessionImpl::setGlobalMaxRatio(qreal ratio
)
1094 if (ratio
!= globalMaxRatio())
1096 m_globalMaxRatio
= ratio
;
1097 updateSeedingLimitTimer();
1101 int SessionImpl::globalMaxSeedingMinutes() const
1103 return m_globalMaxSeedingMinutes
;
1106 void SessionImpl::setGlobalMaxSeedingMinutes(int minutes
)
1111 if (minutes
!= globalMaxSeedingMinutes())
1113 m_globalMaxSeedingMinutes
= minutes
;
1114 updateSeedingLimitTimer();
1118 void SessionImpl::applyBandwidthLimits()
1120 lt::settings_pack settingsPack
;
1121 settingsPack
.set_int(lt::settings_pack::download_rate_limit
, downloadSpeedLimit());
1122 settingsPack
.set_int(lt::settings_pack::upload_rate_limit
, uploadSpeedLimit());
1123 m_nativeSession
->apply_settings(std::move(settingsPack
));
1126 void SessionImpl::configure()
1128 m_nativeSession
->apply_settings(loadLTSettings());
1129 configureComponents();
1131 m_deferredConfigureScheduled
= false;
1134 void SessionImpl::configureComponents()
1136 // This function contains components/actions that:
1137 // 1. Need to be setup at start up
1138 // 2. When deferred configure is called
1140 configurePeerClasses();
1142 if (!m_IPFilteringConfigured
)
1144 if (isIPFilteringEnabled())
1148 m_IPFilteringConfigured
= true;
1152 void SessionImpl::prepareStartup()
1154 qDebug("Initializing torrents resume data storage...");
1156 const Path dbPath
= specialFolderLocation(SpecialFolder::Data
) / Path(u
"torrents.db"_qs
);
1157 const bool dbStorageExists
= dbPath
.exists();
1159 auto *context
= new ResumeSessionContext(this);
1160 context
->currentStorageType
= resumeDataStorageType();
1162 if (context
->currentStorageType
== ResumeDataStorageType::SQLite
)
1164 m_resumeDataStorage
= new DBResumeDataStorage(dbPath
, this);
1166 if (!dbStorageExists
)
1168 const Path dataPath
= specialFolderLocation(SpecialFolder::Data
) / Path(u
"BT_backup"_qs
);
1169 context
->startupStorage
= new BencodeResumeDataStorage(dataPath
, this);
1174 const Path dataPath
= specialFolderLocation(SpecialFolder::Data
) / Path(u
"BT_backup"_qs
);
1175 m_resumeDataStorage
= new BencodeResumeDataStorage(dataPath
, this);
1177 if (dbStorageExists
)
1178 context
->startupStorage
= new DBResumeDataStorage(dbPath
, this);
1181 if (!context
->startupStorage
)
1182 context
->startupStorage
= m_resumeDataStorage
;
1184 connect(context
->startupStorage
, &ResumeDataStorage::loadStarted
, context
1185 , [this, context
](const QVector
<TorrentID
> &torrents
)
1187 context
->totalResumeDataCount
= torrents
.size();
1188 #ifdef QBT_USES_LIBTORRENT2
1189 context
->indexedTorrents
= QSet
<TorrentID
>(torrents
.cbegin(), torrents
.cend());
1192 handleLoadedResumeData(context
);
1195 connect(context
->startupStorage
, &ResumeDataStorage::loadFinished
, context
, [context
]()
1197 context
->isLoadFinished
= true;
1200 connect(this, &SessionImpl::torrentsLoaded
, context
, [this, context
](const QVector
<Torrent
*> &torrents
)
1202 context
->processingResumeDataCount
-= torrents
.count();
1203 context
->finishedResumeDataCount
+= torrents
.count();
1204 if (!context
->isLoadedResumeDataHandlingEnqueued
)
1206 QMetaObject::invokeMethod(this, [this, context
]() { handleLoadedResumeData(context
); }, Qt::QueuedConnection
);
1207 context
->isLoadedResumeDataHandlingEnqueued
= true;
1210 if (!m_refreshEnqueued
)
1212 m_nativeSession
->post_torrent_updates();
1213 m_refreshEnqueued
= true;
1216 emit
startupProgressUpdated((context
->finishedResumeDataCount
* 100.) / context
->totalResumeDataCount
);
1219 context
->startupStorage
->loadAll();
1222 void SessionImpl::handleLoadedResumeData(ResumeSessionContext
*context
)
1224 context
->isLoadedResumeDataHandlingEnqueued
= false;
1226 int count
= context
->processingResumeDataCount
;
1227 while (context
->processingResumeDataCount
< MAX_PROCESSING_RESUMEDATA_COUNT
)
1229 if (context
->loadedResumeData
.isEmpty())
1230 context
->loadedResumeData
= context
->startupStorage
->fetchLoadedResumeData();
1232 if (context
->loadedResumeData
.isEmpty())
1234 if (context
->processingResumeDataCount
== 0)
1236 if (context
->isLoadFinished
)
1238 endStartup(context
);
1240 else if (!context
->isLoadedResumeDataHandlingEnqueued
)
1242 QMetaObject::invokeMethod(this, [this, context
]() { handleLoadedResumeData(context
); }, Qt::QueuedConnection
);
1243 context
->isLoadedResumeDataHandlingEnqueued
= true;
1250 processNextResumeData(context
);
1254 context
->finishedResumeDataCount
+= (count
- context
->processingResumeDataCount
);
1257 void SessionImpl::processNextResumeData(ResumeSessionContext
*context
)
1259 const LoadedResumeData loadedResumeDataItem
= context
->loadedResumeData
.takeFirst();
1261 TorrentID torrentID
= loadedResumeDataItem
.torrentID
;
1262 #ifdef QBT_USES_LIBTORRENT2
1263 if (context
->skippedIDs
.contains(torrentID
))
1267 const nonstd::expected
<LoadTorrentParams
, QString
> &loadResumeDataResult
= loadedResumeDataItem
.result
;
1268 if (!loadResumeDataResult
)
1270 LogMsg(tr("Failed to resume torrent. Torrent: \"%1\". Reason: \"%2\"")
1271 .arg(torrentID
.toString(), loadResumeDataResult
.error()), Log::CRITICAL
);
1275 LoadTorrentParams resumeData
= *loadResumeDataResult
;
1276 bool needStore
= false;
1278 #ifdef QBT_USES_LIBTORRENT2
1279 const InfoHash infoHash
{(resumeData
.ltAddTorrentParams
.ti
1280 ? resumeData
.ltAddTorrentParams
.ti
->info_hashes()
1281 : resumeData
.ltAddTorrentParams
.info_hashes
)};
1282 const bool isHybrid
= infoHash
.isHybrid();
1283 const auto torrentIDv2
= TorrentID::fromInfoHash(infoHash
);
1284 const auto torrentIDv1
= TorrentID::fromSHA1Hash(infoHash
.v1());
1285 if (torrentID
== torrentIDv2
)
1287 if (isHybrid
&& context
->indexedTorrents
.contains(torrentIDv1
))
1289 // if we don't have metadata, try to find it in alternative "resume data"
1290 if (!resumeData
.ltAddTorrentParams
.ti
)
1292 const nonstd::expected
<LoadTorrentParams
, QString
> loadAltResumeDataResult
= context
->startupStorage
->load(torrentIDv1
);
1293 if (loadAltResumeDataResult
)
1294 resumeData
.ltAddTorrentParams
.ti
= loadAltResumeDataResult
->ltAddTorrentParams
.ti
;
1297 // remove alternative "resume data" and skip the attempt to load it
1298 m_resumeDataStorage
->remove(torrentIDv1
);
1299 context
->skippedIDs
.insert(torrentIDv1
);
1302 else if (torrentID
== torrentIDv1
)
1304 torrentID
= torrentIDv2
;
1306 m_resumeDataStorage
->remove(torrentIDv1
);
1308 if (context
->indexedTorrents
.contains(torrentID
))
1310 context
->skippedIDs
.insert(torrentID
);
1312 const nonstd::expected
<LoadTorrentParams
, QString
> loadPreferredResumeDataResult
= context
->startupStorage
->load(torrentID
);
1313 if (loadPreferredResumeDataResult
)
1315 std::shared_ptr
<lt::torrent_info
> ti
= resumeData
.ltAddTorrentParams
.ti
;
1316 resumeData
= *loadPreferredResumeDataResult
;
1317 if (!resumeData
.ltAddTorrentParams
.ti
)
1318 resumeData
.ltAddTorrentParams
.ti
= ti
;
1324 LogMsg(tr("Failed to resume torrent: inconsistent torrent ID is detected. Torrent: \"%1\"")
1325 .arg(torrentID
.toString()), Log::WARNING
);
1329 const lt::sha1_hash infoHash
= (resumeData
.ltAddTorrentParams
.ti
1330 ? resumeData
.ltAddTorrentParams
.ti
->info_hash()
1331 : resumeData
.ltAddTorrentParams
.info_hash
);
1332 if (torrentID
!= TorrentID::fromInfoHash(infoHash
))
1334 LogMsg(tr("Failed to resume torrent: inconsistent torrent ID is detected. Torrent: \"%1\"")
1335 .arg(torrentID
.toString()), Log::WARNING
);
1340 if (m_resumeDataStorage
!= context
->startupStorage
)
1343 // TODO: Remove the following upgrade code in v4.6
1344 // == BEGIN UPGRADE CODE ==
1347 if (m_needUpgradeDownloadPath
&& isDownloadPathEnabled() && !resumeData
.useAutoTMM
)
1349 resumeData
.downloadPath
= downloadPath();
1353 // == END UPGRADE CODE ==
1356 m_resumeDataStorage
->store(torrentID
, resumeData
);
1358 const QString category
= resumeData
.category
;
1359 bool isCategoryRecovered
= context
->recoveredCategories
.contains(category
);
1360 if (!category
.isEmpty() && (isCategoryRecovered
|| !m_categories
.contains(category
)))
1362 if (!isCategoryRecovered
)
1364 if (addCategory(category
))
1366 context
->recoveredCategories
.insert(category
);
1367 isCategoryRecovered
= true;
1368 LogMsg(tr("Detected inconsistent data: category is missing from the configuration file."
1369 " Category will be recovered but its settings will be reset to default."
1370 " Torrent: \"%1\". Category: \"%2\"").arg(torrentID
.toString(), category
), Log::WARNING
);
1374 resumeData
.category
.clear();
1375 LogMsg(tr("Detected inconsistent data: invalid category. Torrent: \"%1\". Category: \"%2\"")
1376 .arg(torrentID
.toString(), category
), Log::WARNING
);
1380 // We should check isCategoryRecovered again since the category
1381 // can be just recovered by the code above
1382 if (isCategoryRecovered
&& resumeData
.useAutoTMM
)
1384 const Path storageLocation
{resumeData
.ltAddTorrentParams
.save_path
};
1385 if ((storageLocation
!= categorySavePath(resumeData
.category
)) && (storageLocation
!= categoryDownloadPath(resumeData
.category
)))
1387 resumeData
.useAutoTMM
= false;
1388 resumeData
.savePath
= storageLocation
;
1389 resumeData
.downloadPath
= {};
1390 LogMsg(tr("Detected mismatch between the save paths of the recovered category and the current save path of the torrent."
1391 " Torrent is now switched to Manual mode."
1392 " Torrent: \"%1\". Category: \"%2\"").arg(torrentID
.toString(), category
), Log::WARNING
);
1397 Algorithm::removeIf(resumeData
.tags
, [this, &torrentID
](const QString
&tag
)
1404 LogMsg(tr("Detected inconsistent data: tag is missing from the configuration file."
1405 " Tag will be recovered."
1406 " Torrent: \"%1\". Tag: \"%2\"").arg(torrentID
.toString(), tag
), Log::WARNING
);
1410 LogMsg(tr("Detected inconsistent data: invalid tag. Torrent: \"%1\". Tag: \"%2\"")
1411 .arg(torrentID
.toString(), tag
), Log::WARNING
);
1415 resumeData
.ltAddTorrentParams
.userdata
= LTClientData(new ExtensionData
);
1416 #ifndef QBT_USES_LIBTORRENT2
1417 resumeData
.ltAddTorrentParams
.storage
= customStorageConstructor
;
1420 qDebug() << "Starting up torrent" << torrentID
.toString() << "...";
1421 m_loadingTorrents
.insert(torrentID
, resumeData
);
1422 #ifdef QBT_USES_LIBTORRENT2
1423 if (infoHash
.isHybrid())
1425 // this allows to know the being added hybrid torrent by its v1 info hash
1426 // without having yet another mapping table
1427 m_hybridTorrentsByAltID
.insert(torrentIDv1
, nullptr);
1430 m_nativeSession
->async_add_torrent(resumeData
.ltAddTorrentParams
);
1431 ++context
->processingResumeDataCount
;
1434 void SessionImpl::endStartup(ResumeSessionContext
*context
)
1436 if (m_resumeDataStorage
!= context
->startupStorage
)
1438 if (isQueueingSystemEnabled())
1439 saveTorrentsQueue();
1441 const Path dbPath
= context
->startupStorage
->path();
1442 context
->startupStorage
->deleteLater();
1444 if (context
->currentStorageType
== ResumeDataStorageType::Legacy
)
1446 connect(context
->startupStorage
, &QObject::destroyed
, [dbPath
]
1448 Utils::Fs::removeFile(dbPath
);
1453 context
->deleteLater();
1454 connect(context
, &QObject::destroyed
, this, [this]
1456 m_nativeSession
->resume();
1457 if (m_refreshEnqueued
)
1458 m_refreshEnqueued
= false;
1462 m_statisticsLastUpdateTimer
.start();
1464 // Regular saving of fastresume data
1465 connect(m_resumeDataTimer
, &QTimer::timeout
, this, &SessionImpl::generateResumeData
);
1466 const int saveInterval
= saveResumeDataInterval();
1467 if (saveInterval
> 0)
1469 m_resumeDataTimer
->setInterval(std::chrono::minutes(saveInterval
));
1470 m_resumeDataTimer
->start();
1473 m_isRestored
= true;
1474 emit
startupProgressUpdated(100);
1479 void SessionImpl::initializeNativeSession()
1481 lt::settings_pack pack
= loadLTSettings();
1483 const std::string peerId
= lt::generate_fingerprint(PEER_ID
, QBT_VERSION_MAJOR
, QBT_VERSION_MINOR
, QBT_VERSION_BUGFIX
, QBT_VERSION_BUILD
);
1484 pack
.set_str(lt::settings_pack::peer_fingerprint
, peerId
);
1486 pack
.set_bool(lt::settings_pack::listen_system_port_fallback
, false);
1487 pack
.set_str(lt::settings_pack::user_agent
, USER_AGENT
.toStdString());
1488 pack
.set_bool(lt::settings_pack::use_dht_as_fallback
, false);
1490 pack
.set_int(lt::settings_pack::auto_scrape_interval
, 1200); // 20 minutes
1491 pack
.set_int(lt::settings_pack::auto_scrape_min_interval
, 900); // 15 minutes
1492 // libtorrent 1.1 enables UPnP & NAT-PMP by default
1493 // turn them off before `lt::session` ctor to avoid split second effects
1494 pack
.set_bool(lt::settings_pack::enable_upnp
, false);
1495 pack
.set_bool(lt::settings_pack::enable_natpmp
, false);
1497 #ifdef QBT_USES_LIBTORRENT2
1498 // preserve the same behavior as in earlier libtorrent versions
1499 pack
.set_bool(lt::settings_pack::enable_set_file_valid_data
, true);
1502 lt::session_params sessionParams
{std::move(pack
), {}};
1503 #ifdef QBT_USES_LIBTORRENT2
1504 switch (diskIOType())
1506 case DiskIOType::Posix
:
1507 sessionParams
.disk_io_constructor
= customPosixDiskIOConstructor
;
1509 case DiskIOType::MMap
:
1510 sessionParams
.disk_io_constructor
= customMMapDiskIOConstructor
;
1513 sessionParams
.disk_io_constructor
= customDiskIOConstructor
;
1518 #if LIBTORRENT_VERSION_NUM < 20100
1519 m_nativeSession
= new lt::session(sessionParams
, lt::session::paused
);
1521 m_nativeSession
= new lt::session(sessionParams
);
1522 m_nativeSession
->pause();
1525 LogMsg(tr("Peer ID: \"%1\"").arg(QString::fromStdString(peerId
)), Log::INFO
);
1526 LogMsg(tr("HTTP User-Agent: \"%1\"").arg(USER_AGENT
), Log::INFO
);
1527 LogMsg(tr("Distributed Hash Table (DHT) support: %1").arg(isDHTEnabled() ? tr("ON") : tr("OFF")), Log::INFO
);
1528 LogMsg(tr("Local Peer Discovery support: %1").arg(isLSDEnabled() ? tr("ON") : tr("OFF")), Log::INFO
);
1529 LogMsg(tr("Peer Exchange (PeX) support: %1").arg(isPeXEnabled() ? tr("ON") : tr("OFF")), Log::INFO
);
1530 LogMsg(tr("Anonymous mode: %1").arg(isAnonymousModeEnabled() ? tr("ON") : tr("OFF")), Log::INFO
);
1531 LogMsg(tr("Encryption support: %1").arg((encryption() == 0) ? tr("ON") : ((encryption() == 1) ? tr("FORCED") : tr("OFF"))), Log::INFO
);
1533 m_nativeSession
->set_alert_notify([this]()
1535 QMetaObject::invokeMethod(this, &SessionImpl::readAlerts
, Qt::QueuedConnection
);
1539 m_nativeSession
->add_extension(<::create_smart_ban_plugin
);
1540 m_nativeSession
->add_extension(<::create_ut_metadata_plugin
);
1542 m_nativeSession
->add_extension(<::create_ut_pex_plugin
);
1544 auto nativeSessionExtension
= std::make_shared
<NativeSessionExtension
>();
1545 m_nativeSession
->add_extension(nativeSessionExtension
);
1546 m_nativeSessionExtension
= nativeSessionExtension
.get();
1549 void SessionImpl::processBannedIPs(lt::ip_filter
&filter
)
1551 // First, import current filter
1552 for (const QString
&ip
: asConst(m_bannedIPs
.get()))
1555 const lt::address addr
= lt::make_address(ip
.toLatin1().constData(), ec
);
1558 filter
.add_rule(addr
, addr
, lt::ip_filter::blocked
);
1562 void SessionImpl::initMetrics()
1564 const auto findMetricIndex
= [](const char *name
) -> int
1566 const int index
= lt::find_metric_idx(name
);
1567 Q_ASSERT(index
>= 0);
1571 // TODO: switch to "designated initializers" in C++20
1572 m_metricIndices
.net
.hasIncomingConnections
= findMetricIndex("net.has_incoming_connections");
1573 m_metricIndices
.net
.sentPayloadBytes
= findMetricIndex("net.sent_payload_bytes");
1574 m_metricIndices
.net
.recvPayloadBytes
= findMetricIndex("net.recv_payload_bytes");
1575 m_metricIndices
.net
.sentBytes
= findMetricIndex("net.sent_bytes");
1576 m_metricIndices
.net
.recvBytes
= findMetricIndex("net.recv_bytes");
1577 m_metricIndices
.net
.sentIPOverheadBytes
= findMetricIndex("net.sent_ip_overhead_bytes");
1578 m_metricIndices
.net
.recvIPOverheadBytes
= findMetricIndex("net.recv_ip_overhead_bytes");
1579 m_metricIndices
.net
.sentTrackerBytes
= findMetricIndex("net.sent_tracker_bytes");
1580 m_metricIndices
.net
.recvTrackerBytes
= findMetricIndex("net.recv_tracker_bytes");
1581 m_metricIndices
.net
.recvRedundantBytes
= findMetricIndex("net.recv_redundant_bytes");
1582 m_metricIndices
.net
.recvFailedBytes
= findMetricIndex("net.recv_failed_bytes");
1584 m_metricIndices
.peer
.numPeersConnected
= findMetricIndex("peer.num_peers_connected");
1585 m_metricIndices
.peer
.numPeersDownDisk
= findMetricIndex("peer.num_peers_down_disk");
1586 m_metricIndices
.peer
.numPeersUpDisk
= findMetricIndex("peer.num_peers_up_disk");
1588 m_metricIndices
.dht
.dhtBytesIn
= findMetricIndex("dht.dht_bytes_in");
1589 m_metricIndices
.dht
.dhtBytesOut
= findMetricIndex("dht.dht_bytes_out");
1590 m_metricIndices
.dht
.dhtNodes
= findMetricIndex("dht.dht_nodes");
1592 m_metricIndices
.disk
.diskBlocksInUse
= findMetricIndex("disk.disk_blocks_in_use");
1593 m_metricIndices
.disk
.numBlocksRead
= findMetricIndex("disk.num_blocks_read");
1594 #ifndef QBT_USES_LIBTORRENT2
1595 m_metricIndices
.disk
.numBlocksCacheHits
= findMetricIndex("disk.num_blocks_cache_hits");
1597 m_metricIndices
.disk
.writeJobs
= findMetricIndex("disk.num_write_ops");
1598 m_metricIndices
.disk
.readJobs
= findMetricIndex("disk.num_read_ops");
1599 m_metricIndices
.disk
.hashJobs
= findMetricIndex("disk.num_blocks_hashed");
1600 m_metricIndices
.disk
.queuedDiskJobs
= findMetricIndex("disk.queued_disk_jobs");
1601 m_metricIndices
.disk
.diskJobTime
= findMetricIndex("disk.disk_job_time");
1604 lt::settings_pack
SessionImpl::loadLTSettings() const
1606 lt::settings_pack settingsPack
;
1608 const lt::alert_category_t alertMask
= lt::alert::error_notification
1609 | lt::alert::file_progress_notification
1610 | lt::alert::ip_block_notification
1611 | lt::alert::peer_notification
1612 | (isPerformanceWarningEnabled() ? lt::alert::performance_warning
: lt::alert_category_t())
1613 | lt::alert::port_mapping_notification
1614 | lt::alert::status_notification
1615 | lt::alert::storage_notification
1616 | lt::alert::tracker_notification
;
1617 settingsPack
.set_int(lt::settings_pack::alert_mask
, alertMask
);
1619 settingsPack
.set_int(lt::settings_pack::connection_speed
, connectionSpeed());
1621 // from libtorrent doc:
1622 // It will not take affect until the listen_interfaces settings is updated
1623 settingsPack
.set_int(lt::settings_pack::send_socket_buffer_size
, socketSendBufferSize());
1624 settingsPack
.set_int(lt::settings_pack::recv_socket_buffer_size
, socketReceiveBufferSize());
1625 settingsPack
.set_int(lt::settings_pack::listen_queue_size
, socketBacklogSize());
1627 applyNetworkInterfacesSettings(settingsPack
);
1629 settingsPack
.set_int(lt::settings_pack::download_rate_limit
, downloadSpeedLimit());
1630 settingsPack
.set_int(lt::settings_pack::upload_rate_limit
, uploadSpeedLimit());
1632 // The most secure, rc4 only so that all streams are encrypted
1633 settingsPack
.set_int(lt::settings_pack::allowed_enc_level
, lt::settings_pack::pe_rc4
);
1634 settingsPack
.set_bool(lt::settings_pack::prefer_rc4
, true);
1635 switch (encryption())
1638 settingsPack
.set_int(lt::settings_pack::out_enc_policy
, lt::settings_pack::pe_enabled
);
1639 settingsPack
.set_int(lt::settings_pack::in_enc_policy
, lt::settings_pack::pe_enabled
);
1642 settingsPack
.set_int(lt::settings_pack::out_enc_policy
, lt::settings_pack::pe_forced
);
1643 settingsPack
.set_int(lt::settings_pack::in_enc_policy
, lt::settings_pack::pe_forced
);
1645 default: // Disabled
1646 settingsPack
.set_int(lt::settings_pack::out_enc_policy
, lt::settings_pack::pe_disabled
);
1647 settingsPack
.set_int(lt::settings_pack::in_enc_policy
, lt::settings_pack::pe_disabled
);
1650 settingsPack
.set_int(lt::settings_pack::active_checking
, maxActiveCheckingTorrents());
1655 settingsPack
.set_str(lt::settings_pack::i2p_hostname
, I2PAddress().toStdString());
1656 settingsPack
.set_int(lt::settings_pack::i2p_port
, I2PPort());
1657 settingsPack
.set_bool(lt::settings_pack::allow_i2p_mixed
, I2PMixedMode());
1661 settingsPack
.set_str(lt::settings_pack::i2p_hostname
, "");
1662 settingsPack
.set_int(lt::settings_pack::i2p_port
, 0);
1663 settingsPack
.set_bool(lt::settings_pack::allow_i2p_mixed
, false);
1667 settingsPack
.set_int(lt::settings_pack::proxy_type
, lt::settings_pack::none
);
1668 if (Preferences::instance()->useProxyForBT())
1670 const auto *proxyManager
= Net::ProxyConfigurationManager::instance();
1671 const Net::ProxyConfiguration proxyConfig
= proxyManager
->proxyConfiguration();
1673 switch (proxyConfig
.type
)
1675 case Net::ProxyType::SOCKS4
:
1676 settingsPack
.set_int(lt::settings_pack::proxy_type
, lt::settings_pack::socks4
);
1679 case Net::ProxyType::HTTP
:
1680 if (proxyConfig
.authEnabled
)
1681 settingsPack
.set_int(lt::settings_pack::proxy_type
, lt::settings_pack::http_pw
);
1683 settingsPack
.set_int(lt::settings_pack::proxy_type
, lt::settings_pack::http
);
1686 case Net::ProxyType::SOCKS5
:
1687 if (proxyConfig
.authEnabled
)
1688 settingsPack
.set_int(lt::settings_pack::proxy_type
, lt::settings_pack::socks5_pw
);
1690 settingsPack
.set_int(lt::settings_pack::proxy_type
, lt::settings_pack::socks5
);
1697 settingsPack
.set_str(lt::settings_pack::proxy_hostname
, proxyConfig
.ip
.toStdString());
1698 settingsPack
.set_int(lt::settings_pack::proxy_port
, proxyConfig
.port
);
1700 if (proxyConfig
.authEnabled
)
1702 settingsPack
.set_str(lt::settings_pack::proxy_username
, proxyConfig
.username
.toStdString());
1703 settingsPack
.set_str(lt::settings_pack::proxy_password
, proxyConfig
.password
.toStdString());
1706 settingsPack
.set_bool(lt::settings_pack::proxy_peer_connections
, isProxyPeerConnectionsEnabled());
1707 settingsPack
.set_bool(lt::settings_pack::proxy_hostnames
, proxyConfig
.hostnameLookupEnabled
);
1710 settingsPack
.set_bool(lt::settings_pack::announce_to_all_trackers
, announceToAllTrackers());
1711 settingsPack
.set_bool(lt::settings_pack::announce_to_all_tiers
, announceToAllTiers());
1713 settingsPack
.set_int(lt::settings_pack::peer_turnover
, peerTurnover());
1714 settingsPack
.set_int(lt::settings_pack::peer_turnover_cutoff
, peerTurnoverCutoff());
1715 settingsPack
.set_int(lt::settings_pack::peer_turnover_interval
, peerTurnoverInterval());
1717 settingsPack
.set_int(lt::settings_pack::max_out_request_queue
, requestQueueSize());
1719 settingsPack
.set_int(lt::settings_pack::aio_threads
, asyncIOThreads());
1720 #ifdef QBT_USES_LIBTORRENT2
1721 settingsPack
.set_int(lt::settings_pack::hashing_threads
, hashingThreads());
1723 settingsPack
.set_int(lt::settings_pack::file_pool_size
, filePoolSize());
1725 const int checkingMemUsageSize
= checkingMemUsage() * 64;
1726 settingsPack
.set_int(lt::settings_pack::checking_mem_usage
, checkingMemUsageSize
);
1728 #ifndef QBT_USES_LIBTORRENT2
1729 const int cacheSize
= (diskCacheSize() > -1) ? (diskCacheSize() * 64) : -1;
1730 settingsPack
.set_int(lt::settings_pack::cache_size
, cacheSize
);
1731 settingsPack
.set_int(lt::settings_pack::cache_expiry
, diskCacheTTL());
1734 settingsPack
.set_int(lt::settings_pack::max_queued_disk_bytes
, diskQueueSize());
1736 switch (diskIOReadMode())
1738 case DiskIOReadMode::DisableOSCache
:
1739 settingsPack
.set_int(lt::settings_pack::disk_io_read_mode
, lt::settings_pack::disable_os_cache
);
1741 case DiskIOReadMode::EnableOSCache
:
1743 settingsPack
.set_int(lt::settings_pack::disk_io_read_mode
, lt::settings_pack::enable_os_cache
);
1747 switch (diskIOWriteMode())
1749 case DiskIOWriteMode::DisableOSCache
:
1750 settingsPack
.set_int(lt::settings_pack::disk_io_write_mode
, lt::settings_pack::disable_os_cache
);
1752 case DiskIOWriteMode::EnableOSCache
:
1754 settingsPack
.set_int(lt::settings_pack::disk_io_write_mode
, lt::settings_pack::enable_os_cache
);
1756 #ifdef QBT_USES_LIBTORRENT2
1757 case DiskIOWriteMode::WriteThrough
:
1758 settingsPack
.set_int(lt::settings_pack::disk_io_write_mode
, lt::settings_pack::write_through
);
1763 #ifndef QBT_USES_LIBTORRENT2
1764 settingsPack
.set_bool(lt::settings_pack::coalesce_reads
, isCoalesceReadWriteEnabled());
1765 settingsPack
.set_bool(lt::settings_pack::coalesce_writes
, isCoalesceReadWriteEnabled());
1768 settingsPack
.set_bool(lt::settings_pack::piece_extent_affinity
, usePieceExtentAffinity());
1770 settingsPack
.set_int(lt::settings_pack::suggest_mode
, isSuggestModeEnabled()
1771 ? lt::settings_pack::suggest_read_cache
: lt::settings_pack::no_piece_suggestions
);
1773 settingsPack
.set_int(lt::settings_pack::send_buffer_watermark
, sendBufferWatermark() * 1024);
1774 settingsPack
.set_int(lt::settings_pack::send_buffer_low_watermark
, sendBufferLowWatermark() * 1024);
1775 settingsPack
.set_int(lt::settings_pack::send_buffer_watermark_factor
, sendBufferWatermarkFactor());
1777 settingsPack
.set_bool(lt::settings_pack::anonymous_mode
, isAnonymousModeEnabled());
1780 if (isQueueingSystemEnabled())
1782 settingsPack
.set_int(lt::settings_pack::active_downloads
, maxActiveDownloads());
1783 settingsPack
.set_int(lt::settings_pack::active_limit
, maxActiveTorrents());
1784 settingsPack
.set_int(lt::settings_pack::active_seeds
, maxActiveUploads());
1785 settingsPack
.set_bool(lt::settings_pack::dont_count_slow_torrents
, ignoreSlowTorrentsForQueueing());
1786 settingsPack
.set_int(lt::settings_pack::inactive_down_rate
, downloadRateForSlowTorrents() * 1024); // KiB to Bytes
1787 settingsPack
.set_int(lt::settings_pack::inactive_up_rate
, uploadRateForSlowTorrents() * 1024); // KiB to Bytes
1788 settingsPack
.set_int(lt::settings_pack::auto_manage_startup
, slowTorrentsInactivityTimer());
1792 settingsPack
.set_int(lt::settings_pack::active_downloads
, -1);
1793 settingsPack
.set_int(lt::settings_pack::active_seeds
, -1);
1794 settingsPack
.set_int(lt::settings_pack::active_limit
, -1);
1796 settingsPack
.set_int(lt::settings_pack::active_tracker_limit
, -1);
1797 settingsPack
.set_int(lt::settings_pack::active_dht_limit
, -1);
1798 settingsPack
.set_int(lt::settings_pack::active_lsd_limit
, -1);
1799 settingsPack
.set_int(lt::settings_pack::alert_queue_size
, std::numeric_limits
<int>::max() / 2);
1802 settingsPack
.set_int(lt::settings_pack::outgoing_port
, outgoingPortsMin());
1803 settingsPack
.set_int(lt::settings_pack::num_outgoing_ports
, (outgoingPortsMax() - outgoingPortsMin()));
1804 // UPnP lease duration
1805 settingsPack
.set_int(lt::settings_pack::upnp_lease_duration
, UPnPLeaseDuration());
1807 settingsPack
.set_int(lt::settings_pack::peer_tos
, peerToS());
1808 // Include overhead in transfer limits
1809 settingsPack
.set_bool(lt::settings_pack::rate_limit_ip_overhead
, includeOverheadInLimits());
1810 // IP address to announce to trackers
1811 settingsPack
.set_str(lt::settings_pack::announce_ip
, announceIP().toStdString());
1812 // Max concurrent HTTP announces
1813 settingsPack
.set_int(lt::settings_pack::max_concurrent_http_announces
, maxConcurrentHTTPAnnounces());
1814 // Stop tracker timeout
1815 settingsPack
.set_int(lt::settings_pack::stop_tracker_timeout
, stopTrackerTimeout());
1816 // * Max connections limit
1817 settingsPack
.set_int(lt::settings_pack::connections_limit
, maxConnections());
1818 // * Global max upload slots
1819 settingsPack
.set_int(lt::settings_pack::unchoke_slots_limit
, maxUploads());
1821 switch (btProtocol())
1823 case BTProtocol::Both
:
1825 settingsPack
.set_bool(lt::settings_pack::enable_incoming_tcp
, true);
1826 settingsPack
.set_bool(lt::settings_pack::enable_outgoing_tcp
, true);
1827 settingsPack
.set_bool(lt::settings_pack::enable_incoming_utp
, true);
1828 settingsPack
.set_bool(lt::settings_pack::enable_outgoing_utp
, true);
1831 case BTProtocol::TCP
:
1832 settingsPack
.set_bool(lt::settings_pack::enable_incoming_tcp
, true);
1833 settingsPack
.set_bool(lt::settings_pack::enable_outgoing_tcp
, true);
1834 settingsPack
.set_bool(lt::settings_pack::enable_incoming_utp
, false);
1835 settingsPack
.set_bool(lt::settings_pack::enable_outgoing_utp
, false);
1838 case BTProtocol::UTP
:
1839 settingsPack
.set_bool(lt::settings_pack::enable_incoming_tcp
, false);
1840 settingsPack
.set_bool(lt::settings_pack::enable_outgoing_tcp
, false);
1841 settingsPack
.set_bool(lt::settings_pack::enable_incoming_utp
, true);
1842 settingsPack
.set_bool(lt::settings_pack::enable_outgoing_utp
, true);
1846 switch (utpMixedMode())
1848 case MixedModeAlgorithm::TCP
:
1850 settingsPack
.set_int(lt::settings_pack::mixed_mode_algorithm
, lt::settings_pack::prefer_tcp
);
1852 case MixedModeAlgorithm::Proportional
:
1853 settingsPack
.set_int(lt::settings_pack::mixed_mode_algorithm
, lt::settings_pack::peer_proportional
);
1857 settingsPack
.set_bool(lt::settings_pack::allow_idna
, isIDNSupportEnabled());
1859 settingsPack
.set_bool(lt::settings_pack::allow_multiple_connections_per_ip
, multiConnectionsPerIpEnabled());
1861 settingsPack
.set_bool(lt::settings_pack::validate_https_trackers
, validateHTTPSTrackerCertificate());
1863 settingsPack
.set_bool(lt::settings_pack::ssrf_mitigation
, isSSRFMitigationEnabled());
1865 settingsPack
.set_bool(lt::settings_pack::no_connect_privileged_ports
, blockPeersOnPrivilegedPorts());
1867 settingsPack
.set_bool(lt::settings_pack::apply_ip_filter_to_trackers
, isTrackerFilteringEnabled());
1869 settingsPack
.set_bool(lt::settings_pack::enable_dht
, isDHTEnabled());
1871 settingsPack
.set_str(lt::settings_pack::dht_bootstrap_nodes
, "dht.libtorrent.org:25401,router.bittorrent.com:6881,router.utorrent.com:6881,dht.transmissionbt.com:6881,dht.aelitis.com:6881");
1872 settingsPack
.set_bool(lt::settings_pack::enable_lsd
, isLSDEnabled());
1874 switch (chokingAlgorithm())
1876 case ChokingAlgorithm::FixedSlots
:
1878 settingsPack
.set_int(lt::settings_pack::choking_algorithm
, lt::settings_pack::fixed_slots_choker
);
1880 case ChokingAlgorithm::RateBased
:
1881 settingsPack
.set_int(lt::settings_pack::choking_algorithm
, lt::settings_pack::rate_based_choker
);
1885 switch (seedChokingAlgorithm())
1887 case SeedChokingAlgorithm::RoundRobin
:
1888 settingsPack
.set_int(lt::settings_pack::seed_choking_algorithm
, lt::settings_pack::round_robin
);
1890 case SeedChokingAlgorithm::FastestUpload
:
1892 settingsPack
.set_int(lt::settings_pack::seed_choking_algorithm
, lt::settings_pack::fastest_upload
);
1894 case SeedChokingAlgorithm::AntiLeech
:
1895 settingsPack
.set_int(lt::settings_pack::seed_choking_algorithm
, lt::settings_pack::anti_leech
);
1899 return settingsPack
;
1902 void SessionImpl::applyNetworkInterfacesSettings(lt::settings_pack
&settingsPack
) const
1904 if (m_listenInterfaceConfigured
)
1907 if (port() > 0) // user has specified port number
1908 settingsPack
.set_int(lt::settings_pack::max_retry_port_bind
, 0);
1910 QStringList endpoints
;
1911 QStringList outgoingInterfaces
;
1912 const QString portString
= u
':' + QString::number(port());
1914 for (const QString
&ip
: asConst(getListeningIPs()))
1916 const QHostAddress addr
{ip
};
1919 const bool isIPv6
= (addr
.protocol() == QAbstractSocket::IPv6Protocol
);
1920 const QString ip
= isIPv6
1921 ? Utils::Net::canonicalIPv6Addr(addr
).toString()
1924 endpoints
<< ((isIPv6
? (u
'[' + ip
+ u
']') : ip
) + portString
);
1926 if ((ip
!= u
"0.0.0.0") && (ip
!= u
"::"))
1927 outgoingInterfaces
<< ip
;
1931 // ip holds an interface name
1933 // On Vista+ versions and after Qt 5.5 QNetworkInterface::name() returns
1934 // the interface's LUID and not the GUID.
1935 // Libtorrent expects GUIDs for the 'listen_interfaces' setting.
1936 const QString guid
= convertIfaceNameToGuid(ip
);
1937 if (!guid
.isEmpty())
1939 endpoints
<< (guid
+ portString
);
1940 outgoingInterfaces
<< guid
;
1944 LogMsg(tr("Could not find GUID of network interface. Interface: \"%1\"").arg(ip
), Log::WARNING
);
1945 // Since we can't get the GUID, we'll pass the interface name instead.
1946 // Otherwise an empty string will be passed to outgoing_interface which will cause IP leak.
1947 endpoints
<< (ip
+ portString
);
1948 outgoingInterfaces
<< ip
;
1951 endpoints
<< (ip
+ portString
);
1952 outgoingInterfaces
<< ip
;
1957 const QString finalEndpoints
= endpoints
.join(u
',');
1958 settingsPack
.set_str(lt::settings_pack::listen_interfaces
, finalEndpoints
.toStdString());
1959 LogMsg(tr("Trying to listen on the following list of IP addresses: \"%1\"").arg(finalEndpoints
));
1961 settingsPack
.set_str(lt::settings_pack::outgoing_interfaces
, outgoingInterfaces
.join(u
',').toStdString());
1962 m_listenInterfaceConfigured
= true;
1965 void SessionImpl::configurePeerClasses()
1968 // lt::make_address("255.255.255.255") crashes on some people's systems
1969 // so instead we use address_v4::broadcast()
1970 // Proactively do the same for 0.0.0.0 and address_v4::any()
1971 f
.add_rule(lt::address_v4::any()
1972 , lt::address_v4::broadcast()
1973 , 1 << LT::toUnderlyingType(lt::session::global_peer_class_id
));
1975 // IPv6 may not be available on OS and the parsing
1976 // would result in an exception -> abnormal program termination
1977 // Affects Windows XP
1980 f
.add_rule(lt::address_v6::any()
1981 , lt::make_address("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff")
1982 , 1 << LT::toUnderlyingType(lt::session::global_peer_class_id
));
1984 catch (const std::exception
&) {}
1986 if (ignoreLimitsOnLAN())
1989 f
.add_rule(lt::make_address("10.0.0.0")
1990 , lt::make_address("10.255.255.255")
1991 , 1 << LT::toUnderlyingType(lt::session::local_peer_class_id
));
1992 f
.add_rule(lt::make_address("172.16.0.0")
1993 , lt::make_address("172.31.255.255")
1994 , 1 << LT::toUnderlyingType(lt::session::local_peer_class_id
));
1995 f
.add_rule(lt::make_address("192.168.0.0")
1996 , lt::make_address("192.168.255.255")
1997 , 1 << LT::toUnderlyingType(lt::session::local_peer_class_id
));
1999 f
.add_rule(lt::make_address("169.254.0.0")
2000 , lt::make_address("169.254.255.255")
2001 , 1 << LT::toUnderlyingType(lt::session::local_peer_class_id
));
2003 f
.add_rule(lt::make_address("127.0.0.0")
2004 , lt::make_address("127.255.255.255")
2005 , 1 << LT::toUnderlyingType(lt::session::local_peer_class_id
));
2007 // IPv6 may not be available on OS and the parsing
2008 // would result in an exception -> abnormal program termination
2009 // Affects Windows XP
2013 f
.add_rule(lt::make_address("fe80::")
2014 , lt::make_address("febf:ffff:ffff:ffff:ffff:ffff:ffff:ffff")
2015 , 1 << LT::toUnderlyingType(lt::session::local_peer_class_id
));
2016 // unique local addresses
2017 f
.add_rule(lt::make_address("fc00::")
2018 , lt::make_address("fdff:ffff:ffff:ffff:ffff:ffff:ffff:ffff")
2019 , 1 << LT::toUnderlyingType(lt::session::local_peer_class_id
));
2021 f
.add_rule(lt::address_v6::loopback()
2022 , lt::address_v6::loopback()
2023 , 1 << LT::toUnderlyingType(lt::session::local_peer_class_id
));
2025 catch (const std::exception
&) {}
2027 m_nativeSession
->set_peer_class_filter(f
);
2029 lt::peer_class_type_filter peerClassTypeFilter
;
2030 peerClassTypeFilter
.add(lt::peer_class_type_filter::tcp_socket
, lt::session::tcp_peer_class_id
);
2031 peerClassTypeFilter
.add(lt::peer_class_type_filter::ssl_tcp_socket
, lt::session::tcp_peer_class_id
);
2032 peerClassTypeFilter
.add(lt::peer_class_type_filter::i2p_socket
, lt::session::tcp_peer_class_id
);
2033 if (!isUTPRateLimited())
2035 peerClassTypeFilter
.disallow(lt::peer_class_type_filter::utp_socket
2036 , lt::session::global_peer_class_id
);
2037 peerClassTypeFilter
.disallow(lt::peer_class_type_filter::ssl_utp_socket
2038 , lt::session::global_peer_class_id
);
2040 m_nativeSession
->set_peer_class_type_filter(peerClassTypeFilter
);
2043 void SessionImpl::enableTracker(const bool enable
)
2045 const QString profile
= u
"embeddedTracker"_qs
;
2046 auto *portForwarder
= Net::PortForwarder::instance();
2051 m_tracker
= new Tracker(this);
2055 const auto *pref
= Preferences::instance();
2056 if (pref
->isTrackerPortForwardingEnabled())
2057 portForwarder
->setPorts(profile
, {static_cast<quint16
>(pref
->getTrackerPort())});
2059 portForwarder
->removePorts(profile
);
2065 portForwarder
->removePorts(profile
);
2069 void SessionImpl::enableBandwidthScheduler()
2073 m_bwScheduler
= new BandwidthScheduler(this);
2074 connect(m_bwScheduler
.data(), &BandwidthScheduler::bandwidthLimitRequested
2075 , this, &SessionImpl::setAltGlobalSpeedLimitEnabled
);
2077 m_bwScheduler
->start();
2080 void SessionImpl::populateAdditionalTrackers()
2082 m_additionalTrackerList
.clear();
2084 const QString trackers
= additionalTrackers();
2085 for (QStringView tracker
: asConst(QStringView(trackers
).split(u
'\n')))
2087 tracker
= tracker
.trimmed();
2088 if (!tracker
.isEmpty())
2089 m_additionalTrackerList
.append({tracker
.toString()});
2093 void SessionImpl::processShareLimits()
2095 qDebug("Processing share limits...");
2097 // We shouldn't iterate over `m_torrents` in the loop below
2098 // since `deleteTorrent()` modifies it indirectly
2099 const QHash
<TorrentID
, TorrentImpl
*> torrents
{m_torrents
};
2100 for (TorrentImpl
*const torrent
: torrents
)
2102 if (torrent
->isFinished() && !torrent
->isForced())
2104 if (torrent
->ratioLimit() != Torrent::NO_RATIO_LIMIT
)
2106 const qreal ratio
= torrent
->realRatio();
2107 qreal ratioLimit
= torrent
->ratioLimit();
2108 if (ratioLimit
== Torrent::USE_GLOBAL_RATIO
)
2109 // If Global Max Ratio is really set...
2110 ratioLimit
= globalMaxRatio();
2112 if (ratioLimit
>= 0)
2114 qDebug("Ratio: %f (limit: %f)", ratio
, ratioLimit
);
2116 if ((ratio
<= Torrent::MAX_RATIO
) && (ratio
>= ratioLimit
))
2118 const QString description
= tr("Torrent reached the share ratio limit.");
2119 const QString torrentName
= tr("Torrent: \"%1\".").arg(torrent
->name());
2121 if (m_maxRatioAction
== Remove
)
2123 LogMsg(u
"%1 %2 %3"_qs
.arg(description
, tr("Removed torrent."), torrentName
));
2124 deleteTorrent(torrent
->id());
2126 else if (m_maxRatioAction
== DeleteFiles
)
2128 LogMsg(u
"%1 %2 %3"_qs
.arg(description
, tr("Removed torrent and deleted its content."), torrentName
));
2129 deleteTorrent(torrent
->id(), DeleteTorrentAndFiles
);
2131 else if ((m_maxRatioAction
== Pause
) && !torrent
->isPaused())
2134 LogMsg(u
"%1 %2 %3"_qs
.arg(description
, tr("Torrent paused."), torrentName
));
2136 else if ((m_maxRatioAction
== EnableSuperSeeding
) && !torrent
->isPaused() && !torrent
->superSeeding())
2138 torrent
->setSuperSeeding(true);
2139 LogMsg(u
"%1 %2 %3"_qs
.arg(description
, tr("Super seeding enabled."), torrentName
));
2147 if (torrent
->seedingTimeLimit() != Torrent::NO_SEEDING_TIME_LIMIT
)
2149 const qlonglong seedingTimeInMinutes
= torrent
->finishedTime() / 60;
2150 int seedingTimeLimit
= torrent
->seedingTimeLimit();
2151 if (seedingTimeLimit
== Torrent::USE_GLOBAL_SEEDING_TIME
)
2153 // If Global Seeding Time Limit is really set...
2154 seedingTimeLimit
= globalMaxSeedingMinutes();
2157 if (seedingTimeLimit
>= 0)
2159 if ((seedingTimeInMinutes
<= Torrent::MAX_SEEDING_TIME
) && (seedingTimeInMinutes
>= seedingTimeLimit
))
2161 const QString description
= tr("Torrent reached the seeding time limit.");
2162 const QString torrentName
= tr("Torrent: \"%1\".").arg(torrent
->name());
2164 if (m_maxRatioAction
== Remove
)
2166 LogMsg(u
"%1 %2 %3"_qs
.arg(description
, tr("Removed torrent."), torrentName
));
2167 deleteTorrent(torrent
->id());
2169 else if (m_maxRatioAction
== DeleteFiles
)
2171 LogMsg(u
"%1 %2 %3"_qs
.arg(description
, tr("Removed torrent and deleted its content."), torrentName
));
2172 deleteTorrent(torrent
->id(), DeleteTorrentAndFiles
);
2174 else if ((m_maxRatioAction
== Pause
) && !torrent
->isPaused())
2177 LogMsg(u
"%1 %2 %3"_qs
.arg(description
, tr("Torrent paused."), torrentName
));
2179 else if ((m_maxRatioAction
== EnableSuperSeeding
) && !torrent
->isPaused() && !torrent
->superSeeding())
2181 torrent
->setSuperSeeding(true);
2182 LogMsg(u
"%1 %2 %3"_qs
.arg(description
, tr("Super seeding enabled."), torrentName
));
2191 // Add to BitTorrent session the downloaded torrent file
2192 void SessionImpl::handleDownloadFinished(const Net::DownloadResult
&result
)
2194 switch (result
.status
)
2196 case Net::DownloadStatus::Success
:
2197 emit
downloadFromUrlFinished(result
.url
);
2198 if (const nonstd::expected
<TorrentInfo
, QString
> loadResult
= TorrentInfo::load(result
.data
); loadResult
)
2199 addTorrent(loadResult
.value(), m_downloadedTorrents
.take(result
.url
));
2201 LogMsg(tr("Failed to load torrent. Reason: \"%1\"").arg(loadResult
.error()), Log::WARNING
);
2203 case Net::DownloadStatus::RedirectedToMagnet
:
2204 emit
downloadFromUrlFinished(result
.url
);
2205 addTorrent(MagnetUri(result
.magnet
), m_downloadedTorrents
.take(result
.url
));
2208 emit
downloadFromUrlFailed(result
.url
, result
.errorString
);
2212 void SessionImpl::fileSearchFinished(const TorrentID
&id
, const Path
&savePath
, const PathList
&fileNames
)
2214 TorrentImpl
*torrent
= m_torrents
.value(id
);
2217 torrent
->fileSearchFinished(savePath
, fileNames
);
2221 const auto loadingTorrentsIter
= m_loadingTorrents
.find(id
);
2222 if (loadingTorrentsIter
!= m_loadingTorrents
.end())
2224 LoadTorrentParams
¶ms
= loadingTorrentsIter
.value();
2225 lt::add_torrent_params
&p
= params
.ltAddTorrentParams
;
2227 p
.save_path
= savePath
.toString().toStdString();
2228 const TorrentInfo torrentInfo
{*p
.ti
};
2229 const auto nativeIndexes
= torrentInfo
.nativeIndexes();
2230 for (int i
= 0; i
< fileNames
.size(); ++i
)
2231 p
.renamed_files
[nativeIndexes
[i
]] = fileNames
[i
].toString().toStdString();
2233 m_nativeSession
->async_add_torrent(p
);
2237 Torrent
*SessionImpl::getTorrent(const TorrentID
&id
) const
2239 return m_torrents
.value(id
);
2242 Torrent
*SessionImpl::findTorrent(const InfoHash
&infoHash
) const
2244 const auto id
= TorrentID::fromInfoHash(infoHash
);
2245 if (Torrent
*torrent
= m_torrents
.value(id
); torrent
)
2248 if (!infoHash
.isHybrid())
2249 return m_hybridTorrentsByAltID
.value(id
);
2251 // alternative ID can be useful to find existing torrent
2252 // in case if hybrid torrent was added by v1 info hash
2253 const auto altID
= TorrentID::fromSHA1Hash(infoHash
.v1());
2254 return m_torrents
.value(altID
);
2257 void SessionImpl::banIP(const QString
&ip
)
2259 if (m_bannedIPs
.get().contains(ip
))
2263 const lt::address addr
= lt::make_address(ip
.toLatin1().constData(), ec
);
2268 invokeAsync([session
= m_nativeSession
, addr
]
2270 lt::ip_filter filter
= session
->get_ip_filter();
2271 filter
.add_rule(addr
, addr
, lt::ip_filter::blocked
);
2272 session
->set_ip_filter(std::move(filter
));
2275 QStringList bannedIPs
= m_bannedIPs
;
2276 bannedIPs
.append(ip
);
2278 m_bannedIPs
= bannedIPs
;
2281 // Delete a torrent from the session, given its hash
2282 // and from the disk, if the corresponding deleteOption is chosen
2283 bool SessionImpl::deleteTorrent(const TorrentID
&id
, const DeleteOption deleteOption
)
2285 TorrentImpl
*const torrent
= m_torrents
.take(id
);
2286 if (!torrent
) return false;
2288 qDebug("Deleting torrent with ID: %s", qUtf8Printable(torrent
->id().toString()));
2289 emit
torrentAboutToBeRemoved(torrent
);
2291 if (const InfoHash infoHash
= torrent
->infoHash(); infoHash
.isHybrid())
2292 m_hybridTorrentsByAltID
.remove(TorrentID::fromSHA1Hash(infoHash
.v1()));
2294 // Remove it from session
2295 if (deleteOption
== DeleteTorrent
)
2297 m_removingTorrents
[torrent
->id()] = {torrent
->name(), {}, deleteOption
};
2299 const lt::torrent_handle nativeHandle
{torrent
->nativeHandle()};
2300 const auto iter
= std::find_if(m_moveStorageQueue
.begin(), m_moveStorageQueue
.end()
2301 , [&nativeHandle
](const MoveStorageJob
&job
)
2303 return job
.torrentHandle
== nativeHandle
;
2305 if (iter
!= m_moveStorageQueue
.end())
2307 // We shouldn't actually remove torrent until existing "move storage jobs" are done
2308 torrentQueuePositionBottom(nativeHandle
);
2309 nativeHandle
.unset_flags(lt::torrent_flags::auto_managed
);
2310 nativeHandle
.pause();
2314 m_nativeSession
->remove_torrent(nativeHandle
, lt::session::delete_partfile
);
2319 m_removingTorrents
[torrent
->id()] = {torrent
->name(), torrent
->rootPath(), deleteOption
};
2321 if (m_moveStorageQueue
.size() > 1)
2323 // Delete "move storage job" for the deleted torrent
2324 // (note: we shouldn't delete active job)
2325 const auto iter
= std::find_if((m_moveStorageQueue
.begin() + 1), m_moveStorageQueue
.end()
2326 , [torrent
](const MoveStorageJob
&job
)
2328 return job
.torrentHandle
== torrent
->nativeHandle();
2330 if (iter
!= m_moveStorageQueue
.end())
2331 m_moveStorageQueue
.erase(iter
);
2334 m_nativeSession
->remove_torrent(torrent
->nativeHandle(), lt::session::delete_files
);
2337 // Remove it from torrent resume directory
2338 m_resumeDataStorage
->remove(torrent
->id());
2344 bool SessionImpl::cancelDownloadMetadata(const TorrentID
&id
)
2346 const auto downloadedMetadataIter
= m_downloadedMetadata
.find(id
);
2347 if (downloadedMetadataIter
== m_downloadedMetadata
.end())
2350 const lt::torrent_handle nativeHandle
= downloadedMetadataIter
.value();
2351 #ifdef QBT_USES_LIBTORRENT2
2352 const InfoHash infoHash
{nativeHandle
.info_hashes()};
2353 if (infoHash
.isHybrid())
2355 // if magnet link was hybrid initially then it is indexed also by v1 info hash
2356 // so we need to remove both entries
2357 const auto altID
= TorrentID::fromSHA1Hash(infoHash
.v1());
2358 m_downloadedMetadata
.remove((altID
== downloadedMetadataIter
.key()) ? id
: altID
);
2361 m_downloadedMetadata
.erase(downloadedMetadataIter
);
2362 m_nativeSession
->remove_torrent(nativeHandle
, lt::session::delete_files
);
2366 void SessionImpl::increaseTorrentsQueuePos(const QVector
<TorrentID
> &ids
)
2368 using ElementType
= std::pair
<int, const TorrentImpl
*>;
2369 std::priority_queue
<ElementType
2370 , std::vector
<ElementType
>
2371 , std::greater
<ElementType
>> torrentQueue
;
2373 // Sort torrents by queue position
2374 for (const TorrentID
&id
: ids
)
2376 const TorrentImpl
*torrent
= m_torrents
.value(id
);
2377 if (!torrent
) continue;
2378 if (const int position
= torrent
->queuePosition(); position
>= 0)
2379 torrentQueue
.emplace(position
, torrent
);
2382 // Increase torrents queue position (starting with the one in the highest queue position)
2383 while (!torrentQueue
.empty())
2385 const TorrentImpl
*torrent
= torrentQueue
.top().second
;
2386 torrentQueuePositionUp(torrent
->nativeHandle());
2390 m_torrentsQueueChanged
= true;
2393 void SessionImpl::decreaseTorrentsQueuePos(const QVector
<TorrentID
> &ids
)
2395 using ElementType
= std::pair
<int, const TorrentImpl
*>;
2396 std::priority_queue
<ElementType
> torrentQueue
;
2398 // Sort torrents by queue position
2399 for (const TorrentID
&id
: ids
)
2401 const TorrentImpl
*torrent
= m_torrents
.value(id
);
2402 if (!torrent
) continue;
2403 if (const int position
= torrent
->queuePosition(); position
>= 0)
2404 torrentQueue
.emplace(position
, torrent
);
2407 // Decrease torrents queue position (starting with the one in the lowest queue position)
2408 while (!torrentQueue
.empty())
2410 const TorrentImpl
*torrent
= torrentQueue
.top().second
;
2411 torrentQueuePositionDown(torrent
->nativeHandle());
2415 for (const lt::torrent_handle
&torrentHandle
: asConst(m_downloadedMetadata
))
2416 torrentQueuePositionBottom(torrentHandle
);
2418 m_torrentsQueueChanged
= true;
2421 void SessionImpl::topTorrentsQueuePos(const QVector
<TorrentID
> &ids
)
2423 using ElementType
= std::pair
<int, const TorrentImpl
*>;
2424 std::priority_queue
<ElementType
> torrentQueue
;
2426 // Sort torrents by queue position
2427 for (const TorrentID
&id
: ids
)
2429 const TorrentImpl
*torrent
= m_torrents
.value(id
);
2430 if (!torrent
) continue;
2431 if (const int position
= torrent
->queuePosition(); position
>= 0)
2432 torrentQueue
.emplace(position
, torrent
);
2435 // Top torrents queue position (starting with the one in the lowest queue position)
2436 while (!torrentQueue
.empty())
2438 const TorrentImpl
*torrent
= torrentQueue
.top().second
;
2439 torrentQueuePositionTop(torrent
->nativeHandle());
2443 m_torrentsQueueChanged
= true;
2446 void SessionImpl::bottomTorrentsQueuePos(const QVector
<TorrentID
> &ids
)
2448 using ElementType
= std::pair
<int, const TorrentImpl
*>;
2449 std::priority_queue
<ElementType
2450 , std::vector
<ElementType
>
2451 , std::greater
<ElementType
>> torrentQueue
;
2453 // Sort torrents by queue position
2454 for (const TorrentID
&id
: ids
)
2456 const TorrentImpl
*torrent
= m_torrents
.value(id
);
2457 if (!torrent
) continue;
2458 if (const int position
= torrent
->queuePosition(); position
>= 0)
2459 torrentQueue
.emplace(position
, torrent
);
2462 // Bottom torrents queue position (starting with the one in the highest queue position)
2463 while (!torrentQueue
.empty())
2465 const TorrentImpl
*torrent
= torrentQueue
.top().second
;
2466 torrentQueuePositionBottom(torrent
->nativeHandle());
2470 for (const lt::torrent_handle
&torrentHandle
: asConst(m_downloadedMetadata
))
2471 torrentQueuePositionBottom(torrentHandle
);
2473 m_torrentsQueueChanged
= true;
2476 void SessionImpl::handleTorrentNeedSaveResumeData(const TorrentImpl
*torrent
)
2478 if (m_needSaveResumeDataTorrents
.empty())
2480 QMetaObject::invokeMethod(this, [this]()
2482 for (const TorrentID
&torrentID
: asConst(m_needSaveResumeDataTorrents
))
2484 TorrentImpl
*torrent
= m_torrents
.value(torrentID
);
2486 torrent
->saveResumeData();
2488 m_needSaveResumeDataTorrents
.clear();
2489 }, Qt::QueuedConnection
);
2492 m_needSaveResumeDataTorrents
.insert(torrent
->id());
2495 void SessionImpl::handleTorrentSaveResumeDataRequested(const TorrentImpl
*torrent
)
2497 qDebug("Saving resume data is requested for torrent '%s'...", qUtf8Printable(torrent
->name()));
2501 void SessionImpl::handleTorrentSaveResumeDataFailed(const TorrentImpl
*torrent
)
2507 QVector
<Torrent
*> SessionImpl::torrents() const
2509 QVector
<Torrent
*> result
;
2510 result
.reserve(m_torrents
.size());
2511 for (TorrentImpl
*torrent
: asConst(m_torrents
))
2517 qsizetype
SessionImpl::torrentsCount() const
2519 return m_torrents
.size();
2522 bool SessionImpl::addTorrent(const QString
&source
, const AddTorrentParams
¶ms
)
2524 // `source`: .torrent file path/url or magnet uri
2529 if (Net::DownloadManager::hasSupportedScheme(source
))
2531 LogMsg(tr("Downloading torrent, please wait... Source: \"%1\"").arg(source
));
2532 // Launch downloader
2533 Net::DownloadManager::instance()->download(Net::DownloadRequest(source
).limit(MAX_TORRENT_SIZE
)
2534 , Preferences::instance()->useProxyForGeneralPurposes(), this, &SessionImpl::handleDownloadFinished
);
2535 m_downloadedTorrents
[source
] = params
;
2539 const MagnetUri magnetUri
{source
};
2540 if (magnetUri
.isValid())
2541 return addTorrent(magnetUri
, params
);
2543 const Path path
{source
};
2544 TorrentFileGuard guard
{path
};
2545 const nonstd::expected
<TorrentInfo
, QString
> loadResult
= TorrentInfo::loadFromFile(path
);
2548 LogMsg(tr("Failed to load torrent. Source: \"%1\". Reason: \"%2\"").arg(source
, loadResult
.error()), Log::WARNING
);
2552 guard
.markAsAddedToSession();
2553 return addTorrent(loadResult
.value(), params
);
2556 bool SessionImpl::addTorrent(const MagnetUri
&magnetUri
, const AddTorrentParams
¶ms
)
2561 if (!magnetUri
.isValid())
2564 return addTorrent_impl(magnetUri
, params
);
2567 bool SessionImpl::addTorrent(const TorrentInfo
&torrentInfo
, const AddTorrentParams
¶ms
)
2572 return addTorrent_impl(torrentInfo
, params
);
2575 LoadTorrentParams
SessionImpl::initLoadTorrentParams(const AddTorrentParams
&addTorrentParams
)
2577 LoadTorrentParams loadTorrentParams
;
2579 loadTorrentParams
.name
= addTorrentParams
.name
;
2580 loadTorrentParams
.firstLastPiecePriority
= addTorrentParams
.firstLastPiecePriority
;
2581 loadTorrentParams
.hasFinishedStatus
= addTorrentParams
.skipChecking
; // do not react on 'torrent_finished_alert' when skipping
2582 loadTorrentParams
.contentLayout
= addTorrentParams
.contentLayout
.value_or(torrentContentLayout());
2583 loadTorrentParams
.operatingMode
= (addTorrentParams
.addForced
? TorrentOperatingMode::Forced
: TorrentOperatingMode::AutoManaged
);
2584 loadTorrentParams
.stopped
= addTorrentParams
.addPaused
.value_or(isAddTorrentPaused());
2585 loadTorrentParams
.stopCondition
= addTorrentParams
.stopCondition
.value_or(torrentStopCondition());
2586 loadTorrentParams
.addToQueueTop
= addTorrentParams
.addToQueueTop
.value_or(isAddTorrentToQueueTop());
2587 loadTorrentParams
.ratioLimit
= addTorrentParams
.ratioLimit
;
2588 loadTorrentParams
.seedingTimeLimit
= addTorrentParams
.seedingTimeLimit
;
2590 const QString category
= addTorrentParams
.category
;
2591 if (!category
.isEmpty() && !m_categories
.contains(category
) && !addCategory(category
))
2592 loadTorrentParams
.category
= u
""_qs
;
2594 loadTorrentParams
.category
= category
;
2596 const auto defaultSavePath
= suggestedSavePath(loadTorrentParams
.category
, addTorrentParams
.useAutoTMM
);
2597 const auto defaultDownloadPath
= suggestedDownloadPath(loadTorrentParams
.category
, addTorrentParams
.useAutoTMM
);
2599 loadTorrentParams
.useAutoTMM
= addTorrentParams
.useAutoTMM
.value_or(!isAutoTMMDisabledByDefault());
2601 if (!addTorrentParams
.useAutoTMM
.has_value())
2603 // Default TMM settings
2605 if (!loadTorrentParams
.useAutoTMM
)
2607 loadTorrentParams
.savePath
= defaultSavePath
;
2608 if (isDownloadPathEnabled())
2609 loadTorrentParams
.downloadPath
= (!defaultDownloadPath
.isEmpty() ? defaultDownloadPath
: downloadPath());
2614 // Overridden TMM settings
2616 if (!loadTorrentParams
.useAutoTMM
)
2618 if (addTorrentParams
.savePath
.isAbsolute())
2619 loadTorrentParams
.savePath
= addTorrentParams
.savePath
;
2621 loadTorrentParams
.savePath
= defaultSavePath
/ addTorrentParams
.savePath
;
2623 if (!addTorrentParams
.useDownloadPath
.has_value())
2625 // Default "Download path" settings
2627 if (isDownloadPathEnabled())
2628 loadTorrentParams
.downloadPath
= (!defaultDownloadPath
.isEmpty() ? defaultDownloadPath
: downloadPath());
2630 else if (addTorrentParams
.useDownloadPath
.value())
2632 // Overridden "Download path" settings
2634 if (addTorrentParams
.downloadPath
.isAbsolute())
2636 loadTorrentParams
.downloadPath
= addTorrentParams
.downloadPath
;
2640 const Path basePath
= (!defaultDownloadPath
.isEmpty() ? defaultDownloadPath
: downloadPath());
2641 loadTorrentParams
.downloadPath
= basePath
/ addTorrentParams
.downloadPath
;
2647 for (const QString
&tag
: addTorrentParams
.tags
)
2649 if (hasTag(tag
) || addTag(tag
))
2650 loadTorrentParams
.tags
.insert(tag
);
2653 return loadTorrentParams
;
2656 // Add a torrent to the BitTorrent session
2657 bool SessionImpl::addTorrent_impl(const std::variant
<MagnetUri
, TorrentInfo
> &source
, const AddTorrentParams
&addTorrentParams
)
2659 Q_ASSERT(isRestored());
2661 const bool hasMetadata
= std::holds_alternative
<TorrentInfo
>(source
);
2662 const auto infoHash
= (hasMetadata
? std::get
<TorrentInfo
>(source
).infoHash() : std::get
<MagnetUri
>(source
).infoHash());
2663 const auto id
= TorrentID::fromInfoHash(infoHash
);
2665 // alternative ID can be useful to find existing torrent in case if hybrid torrent was added by v1 info hash
2666 const auto altID
= (infoHash
.isHybrid() ? TorrentID::fromSHA1Hash(infoHash
.v1()) : TorrentID());
2668 // We should not add the torrent if it is already
2669 // processed or is pending to add to session
2670 if (m_loadingTorrents
.contains(id
) || (infoHash
.isHybrid() && m_loadingTorrents
.contains(altID
)))
2673 if (Torrent
*torrent
= findTorrent(infoHash
); torrent
)
2677 // Trying to set metadata to existing torrent in case if it has none
2678 torrent
->setMetadata(std::get
<TorrentInfo
>(source
));
2684 // It looks illogical that we don't just use an existing handle,
2685 // but as previous experience has shown, it actually creates unnecessary
2686 // problems and unwanted behavior due to the fact that it was originally
2687 // added with parameters other than those provided by the user.
2688 cancelDownloadMetadata(id
);
2689 if (infoHash
.isHybrid())
2690 cancelDownloadMetadata(altID
);
2692 LoadTorrentParams loadTorrentParams
= initLoadTorrentParams(addTorrentParams
);
2693 lt::add_torrent_params
&p
= loadTorrentParams
.ltAddTorrentParams
;
2695 bool isFindingIncompleteFiles
= false;
2697 const bool useAutoTMM
= loadTorrentParams
.useAutoTMM
;
2698 const Path actualSavePath
= useAutoTMM
? categorySavePath(loadTorrentParams
.category
) : loadTorrentParams
.savePath
;
2702 const TorrentInfo
&torrentInfo
= std::get
<TorrentInfo
>(source
);
2704 Q_ASSERT(addTorrentParams
.filePaths
.isEmpty() || (addTorrentParams
.filePaths
.size() == torrentInfo
.filesCount()));
2706 PathList filePaths
= addTorrentParams
.filePaths
;
2707 if (filePaths
.isEmpty())
2709 filePaths
= torrentInfo
.filePaths();
2710 if (loadTorrentParams
.contentLayout
!= TorrentContentLayout::Original
)
2712 const Path originalRootFolder
= Path::findRootFolder(filePaths
);
2713 const auto originalContentLayout
= (originalRootFolder
.isEmpty()
2714 ? TorrentContentLayout::NoSubfolder
2715 : TorrentContentLayout::Subfolder
);
2716 if (loadTorrentParams
.contentLayout
!= originalContentLayout
)
2718 if (loadTorrentParams
.contentLayout
== TorrentContentLayout::NoSubfolder
)
2719 Path::stripRootFolder(filePaths
);
2721 Path::addRootFolder(filePaths
, filePaths
.at(0).removedExtension());
2726 // if torrent name wasn't explicitly set we handle the case of
2727 // initial renaming of torrent content and rename torrent accordingly
2728 if (loadTorrentParams
.name
.isEmpty())
2730 QString contentName
= Path::findRootFolder(filePaths
).toString();
2731 if (contentName
.isEmpty() && (filePaths
.size() == 1))
2732 contentName
= filePaths
.at(0).filename();
2734 if (!contentName
.isEmpty() && (contentName
!= torrentInfo
.name()))
2735 loadTorrentParams
.name
= contentName
;
2738 if (!loadTorrentParams
.hasFinishedStatus
)
2740 const Path actualDownloadPath
= useAutoTMM
2741 ? categoryDownloadPath(loadTorrentParams
.category
) : loadTorrentParams
.downloadPath
;
2742 findIncompleteFiles(torrentInfo
, actualSavePath
, actualDownloadPath
, filePaths
);
2743 isFindingIncompleteFiles
= true;
2746 const auto nativeIndexes
= torrentInfo
.nativeIndexes();
2747 if (!isFindingIncompleteFiles
)
2749 for (int index
= 0; index
< filePaths
.size(); ++index
)
2750 p
.renamed_files
[nativeIndexes
[index
]] = filePaths
.at(index
).toString().toStdString();
2753 Q_ASSERT(p
.file_priorities
.empty());
2754 Q_ASSERT(addTorrentParams
.filePriorities
.isEmpty() || (addTorrentParams
.filePriorities
.size() == nativeIndexes
.size()));
2756 const int internalFilesCount
= torrentInfo
.nativeInfo()->files().num_files(); // including .pad files
2757 // Use qBittorrent default priority rather than libtorrent's (4)
2758 p
.file_priorities
= std::vector(internalFilesCount
, LT::toNative(DownloadPriority::Normal
));
2760 if (addTorrentParams
.filePriorities
.isEmpty())
2762 if (isExcludedFileNamesEnabled())
2764 // Check file name blacklist when priorities are not explicitly set
2765 for (int i
= 0; i
< filePaths
.size(); ++i
)
2767 if (isFilenameExcluded(filePaths
.at(i
).filename()))
2768 p
.file_priorities
[LT::toUnderlyingType(nativeIndexes
[i
])] = lt::dont_download
;
2774 for (int i
= 0; i
< addTorrentParams
.filePriorities
.size(); ++i
)
2775 p
.file_priorities
[LT::toUnderlyingType(nativeIndexes
[i
])] = LT::toNative(addTorrentParams
.filePriorities
[i
]);
2778 p
.ti
= torrentInfo
.nativeInfo();
2782 const MagnetUri
&magnetUri
= std::get
<MagnetUri
>(source
);
2783 p
= magnetUri
.addTorrentParams();
2785 if (loadTorrentParams
.name
.isEmpty() && !p
.name
.empty())
2786 loadTorrentParams
.name
= QString::fromStdString(p
.name
);
2789 p
.save_path
= actualSavePath
.toString().toStdString();
2791 if (isAddTrackersEnabled() && !(hasMetadata
&& p
.ti
->priv()))
2793 p
.trackers
.reserve(p
.trackers
.size() + static_cast<std::size_t>(m_additionalTrackerList
.size()));
2794 p
.tracker_tiers
.reserve(p
.trackers
.size() + static_cast<std::size_t>(m_additionalTrackerList
.size()));
2795 p
.tracker_tiers
.resize(p
.trackers
.size(), 0);
2796 for (const TrackerEntry
&trackerEntry
: asConst(m_additionalTrackerList
))
2798 p
.trackers
.push_back(trackerEntry
.url
.toStdString());
2799 p
.tracker_tiers
.push_back(trackerEntry
.tier
);
2803 p
.upload_limit
= addTorrentParams
.uploadLimit
;
2804 p
.download_limit
= addTorrentParams
.downloadLimit
;
2806 // Preallocation mode
2807 p
.storage_mode
= isPreallocationEnabled() ? lt::storage_mode_allocate
: lt::storage_mode_sparse
;
2809 if (addTorrentParams
.sequential
)
2810 p
.flags
|= lt::torrent_flags::sequential_download
;
2812 p
.flags
&= ~lt::torrent_flags::sequential_download
;
2815 // Skip checking and directly start seeding
2816 if (addTorrentParams
.skipChecking
)
2817 p
.flags
|= lt::torrent_flags::seed_mode
;
2819 p
.flags
&= ~lt::torrent_flags::seed_mode
;
2821 if (loadTorrentParams
.stopped
|| (loadTorrentParams
.operatingMode
== TorrentOperatingMode::AutoManaged
))
2822 p
.flags
|= lt::torrent_flags::paused
;
2824 p
.flags
&= ~lt::torrent_flags::paused
;
2825 if (loadTorrentParams
.stopped
|| (loadTorrentParams
.operatingMode
== TorrentOperatingMode::Forced
))
2826 p
.flags
&= ~lt::torrent_flags::auto_managed
;
2828 p
.flags
|= lt::torrent_flags::auto_managed
;
2830 p
.flags
|= lt::torrent_flags::duplicate_is_error
;
2832 p
.added_time
= std::time(nullptr);
2835 p
.max_connections
= maxConnectionsPerTorrent();
2836 p
.max_uploads
= maxUploadsPerTorrent();
2838 p
.userdata
= LTClientData(new ExtensionData
);
2839 #ifndef QBT_USES_LIBTORRENT2
2840 p
.storage
= customStorageConstructor
;
2843 m_loadingTorrents
.insert(id
, loadTorrentParams
);
2844 if (infoHash
.isHybrid())
2845 m_hybridTorrentsByAltID
.insert(altID
, nullptr);
2846 if (!isFindingIncompleteFiles
)
2847 m_nativeSession
->async_add_torrent(p
);
2852 void SessionImpl::findIncompleteFiles(const TorrentInfo
&torrentInfo
, const Path
&savePath
2853 , const Path
&downloadPath
, const PathList
&filePaths
) const
2855 Q_ASSERT(filePaths
.isEmpty() || (filePaths
.size() == torrentInfo
.filesCount()));
2857 const auto searchId
= TorrentID::fromInfoHash(torrentInfo
.infoHash());
2858 const PathList originalFileNames
= (filePaths
.isEmpty() ? torrentInfo
.filePaths() : filePaths
);
2859 QMetaObject::invokeMethod(m_fileSearcher
, [=]()
2861 m_fileSearcher
->search(searchId
, originalFileNames
, savePath
, downloadPath
, isAppendExtensionEnabled());
2865 void SessionImpl::enablePortMapping()
2869 if (m_isPortMappingEnabled
)
2872 lt::settings_pack settingsPack
;
2873 settingsPack
.set_bool(lt::settings_pack::enable_upnp
, true);
2874 settingsPack
.set_bool(lt::settings_pack::enable_natpmp
, true);
2875 m_nativeSession
->apply_settings(std::move(settingsPack
));
2877 m_isPortMappingEnabled
= true;
2879 LogMsg(tr("UPnP/NAT-PMP support: ON"), Log::INFO
);
2883 void SessionImpl::disablePortMapping()
2887 if (!m_isPortMappingEnabled
)
2890 lt::settings_pack settingsPack
;
2891 settingsPack
.set_bool(lt::settings_pack::enable_upnp
, false);
2892 settingsPack
.set_bool(lt::settings_pack::enable_natpmp
, false);
2893 m_nativeSession
->apply_settings(std::move(settingsPack
));
2895 m_mappedPorts
.clear();
2896 m_isPortMappingEnabled
= false;
2898 LogMsg(tr("UPnP/NAT-PMP support: OFF"), Log::INFO
);
2902 void SessionImpl::addMappedPorts(const QSet
<quint16
> &ports
)
2904 invokeAsync([this, ports
]
2906 if (!m_isPortMappingEnabled
)
2909 for (const quint16 port
: ports
)
2911 if (!m_mappedPorts
.contains(port
))
2912 m_mappedPorts
.insert(port
, m_nativeSession
->add_port_mapping(lt::session::tcp
, port
, port
));
2917 void SessionImpl::removeMappedPorts(const QSet
<quint16
> &ports
)
2919 invokeAsync([this, ports
]
2921 if (!m_isPortMappingEnabled
)
2924 Algorithm::removeIf(m_mappedPorts
, [this, ports
](const quint16 port
, const std::vector
<lt::port_mapping_t
> &handles
)
2926 if (!ports
.contains(port
))
2929 for (const lt::port_mapping_t
&handle
: handles
)
2930 m_nativeSession
->delete_port_mapping(handle
);
2937 void SessionImpl::invokeAsync(std::function
<void ()> func
)
2939 m_asyncWorker
->start(std::move(func
));
2942 // Add a torrent to libtorrent session in hidden mode
2943 // and force it to download its metadata
2944 bool SessionImpl::downloadMetadata(const MagnetUri
&magnetUri
)
2946 if (!magnetUri
.isValid())
2949 const InfoHash infoHash
= magnetUri
.infoHash();
2951 // We should not add torrent if it's already
2952 // processed or adding to session
2953 if (isKnownTorrent(infoHash
))
2956 lt::add_torrent_params p
= magnetUri
.addTorrentParams();
2958 if (isAddTrackersEnabled())
2960 // Use "additional trackers" when metadata retrieving (this can help when the DHT nodes are few)
2961 p
.trackers
.reserve(p
.trackers
.size() + static_cast<std::size_t>(m_additionalTrackerList
.size()));
2962 p
.tracker_tiers
.reserve(p
.trackers
.size() + static_cast<std::size_t>(m_additionalTrackerList
.size()));
2963 p
.tracker_tiers
.resize(p
.trackers
.size(), 0);
2964 for (const TrackerEntry
&trackerEntry
: asConst(m_additionalTrackerList
))
2966 p
.trackers
.push_back(trackerEntry
.url
.toStdString());
2967 p
.tracker_tiers
.push_back(trackerEntry
.tier
);
2972 // Preallocation mode
2973 if (isPreallocationEnabled())
2974 p
.storage_mode
= lt::storage_mode_allocate
;
2976 p
.storage_mode
= lt::storage_mode_sparse
;
2979 p
.max_connections
= maxConnectionsPerTorrent();
2980 p
.max_uploads
= maxUploadsPerTorrent();
2982 const auto id
= TorrentID::fromInfoHash(infoHash
);
2983 const Path savePath
= Utils::Fs::tempPath() / Path(id
.toString());
2984 p
.save_path
= savePath
.toString().toStdString();
2987 p
.flags
&= ~lt::torrent_flags::paused
;
2988 p
.flags
&= ~lt::torrent_flags::auto_managed
;
2990 // Solution to avoid accidental file writes
2991 p
.flags
|= lt::torrent_flags::upload_mode
;
2993 #ifndef QBT_USES_LIBTORRENT2
2994 p
.storage
= customStorageConstructor
;
2997 // Adding torrent to libtorrent session
2998 m_nativeSession
->async_add_torrent(p
);
2999 m_downloadedMetadata
.insert(id
, {});
3004 void SessionImpl::exportTorrentFile(const Torrent
*torrent
, const Path
&folderPath
)
3006 if (!folderPath
.exists() && !Utils::Fs::mkpath(folderPath
))
3009 const QString validName
= Utils::Fs::toValidFileName(torrent
->name());
3010 QString torrentExportFilename
= u
"%1.torrent"_qs
.arg(validName
);
3011 Path newTorrentPath
= folderPath
/ Path(torrentExportFilename
);
3013 while (newTorrentPath
.exists())
3015 // Append number to torrent name to make it unique
3016 torrentExportFilename
= u
"%1 %2.torrent"_qs
.arg(validName
).arg(++counter
);
3017 newTorrentPath
= folderPath
/ Path(torrentExportFilename
);
3020 const nonstd::expected
<void, QString
> result
= torrent
->exportToFile(newTorrentPath
);
3023 LogMsg(tr("Failed to export torrent. Torrent: \"%1\". Destination: \"%2\". Reason: \"%3\"")
3024 .arg(torrent
->name(), newTorrentPath
.toString(), result
.error()), Log::WARNING
);
3028 void SessionImpl::generateResumeData()
3030 for (TorrentImpl
*const torrent
: asConst(m_torrents
))
3032 if (!torrent
->isValid()) continue;
3034 if (torrent
->needSaveResumeData())
3036 torrent
->saveResumeData();
3037 m_needSaveResumeDataTorrents
.remove(torrent
->id());
3043 void SessionImpl::saveResumeData()
3045 for (const TorrentImpl
*torrent
: asConst(m_torrents
))
3046 torrent
->nativeHandle().save_resume_data(lt::torrent_handle::only_if_modified
);
3047 m_numResumeData
+= m_torrents
.size();
3049 // clear queued storage move jobs except the current ongoing one
3050 if (m_moveStorageQueue
.size() > 1)
3052 #if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0))
3053 m_moveStorageQueue
= m_moveStorageQueue
.mid(0, 1);
3055 m_moveStorageQueue
.resize(1);
3059 QElapsedTimer timer
;
3062 while ((m_numResumeData
> 0) || !m_moveStorageQueue
.isEmpty() || m_needSaveTorrentsQueue
)
3064 const lt::seconds waitTime
{5};
3065 const lt::seconds expireTime
{30};
3067 // only terminate when no storage is moving
3068 if (timer
.hasExpired(lt::total_milliseconds(expireTime
)) && m_moveStorageQueue
.isEmpty())
3070 LogMsg(tr("Aborted saving resume data. Number of outstanding torrents: %1").arg(QString::number(m_numResumeData
))
3075 const std::vector
<lt::alert
*> alerts
= getPendingAlerts(waitTime
);
3077 bool hasWantedAlert
= false;
3078 for (const lt::alert
*a
: alerts
)
3080 if (const int alertType
= a
->type();
3081 (alertType
== lt::save_resume_data_alert::alert_type
) || (alertType
== lt::save_resume_data_failed_alert::alert_type
)
3082 || (alertType
== lt::storage_moved_alert::alert_type
) || (alertType
== lt::storage_moved_failed_alert::alert_type
)
3083 || (alertType
== lt::state_update_alert::alert_type
))
3085 hasWantedAlert
= true;
3096 void SessionImpl::saveTorrentsQueue()
3098 QVector
<TorrentID
> queue
;
3099 for (const TorrentImpl
*torrent
: asConst(m_torrents
))
3101 if (const int queuePos
= torrent
->queuePosition(); queuePos
>= 0)
3103 if (queuePos
>= queue
.size())
3104 queue
.resize(queuePos
+ 1);
3105 queue
[queuePos
] = torrent
->id();
3109 m_resumeDataStorage
->storeQueue(queue
);
3110 m_needSaveTorrentsQueue
= false;
3113 void SessionImpl::removeTorrentsQueue()
3115 m_resumeDataStorage
->storeQueue({});
3116 m_torrentsQueueChanged
= false;
3117 m_needSaveTorrentsQueue
= false;
3120 void SessionImpl::setSavePath(const Path
&path
)
3122 const auto newPath
= (path
.isAbsolute() ? path
: (specialFolderLocation(SpecialFolder::Downloads
) / path
));
3123 if (newPath
== m_savePath
)
3126 if (isDisableAutoTMMWhenDefaultSavePathChanged())
3128 QSet
<QString
> affectedCatogories
{{}}; // includes default (unnamed) category
3129 for (auto it
= m_categories
.cbegin(); it
!= m_categories
.cend(); ++it
)
3131 const QString
&categoryName
= it
.key();
3132 const CategoryOptions
&categoryOptions
= it
.value();
3133 if (categoryOptions
.savePath
.isRelative())
3134 affectedCatogories
.insert(categoryName
);
3137 for (TorrentImpl
*const torrent
: asConst(m_torrents
))
3139 if (affectedCatogories
.contains(torrent
->category()))
3140 torrent
->setAutoTMMEnabled(false);
3144 m_savePath
= newPath
;
3145 for (TorrentImpl
*const torrent
: asConst(m_torrents
))
3146 torrent
->handleCategoryOptionsChanged();
3149 void SessionImpl::setDownloadPath(const Path
&path
)
3151 const Path newPath
= (path
.isAbsolute() ? path
: (savePath() / Path(u
"temp"_qs
) / path
));
3152 if (newPath
== m_downloadPath
)
3155 if (isDisableAutoTMMWhenDefaultSavePathChanged())
3157 QSet
<QString
> affectedCatogories
{{}}; // includes default (unnamed) category
3158 for (auto it
= m_categories
.cbegin(); it
!= m_categories
.cend(); ++it
)
3160 const QString
&categoryName
= it
.key();
3161 const CategoryOptions
&categoryOptions
= it
.value();
3162 const CategoryOptions::DownloadPathOption downloadPathOption
=
3163 categoryOptions
.downloadPath
.value_or(CategoryOptions::DownloadPathOption
{isDownloadPathEnabled(), downloadPath()});
3164 if (downloadPathOption
.enabled
&& downloadPathOption
.path
.isRelative())
3165 affectedCatogories
.insert(categoryName
);
3168 for (TorrentImpl
*const torrent
: asConst(m_torrents
))
3170 if (affectedCatogories
.contains(torrent
->category()))
3171 torrent
->setAutoTMMEnabled(false);
3175 m_downloadPath
= newPath
;
3176 for (TorrentImpl
*const torrent
: asConst(m_torrents
))
3177 torrent
->handleCategoryOptionsChanged();
3180 #if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0))
3181 void SessionImpl::networkOnlineStateChanged(const bool online
)
3183 LogMsg(tr("System network status changed to %1", "e.g: System network status changed to ONLINE").arg(online
? tr("ONLINE") : tr("OFFLINE")), Log::INFO
);
3186 void SessionImpl::networkConfigurationChange(const QNetworkConfiguration
&cfg
)
3188 const QString configuredInterfaceName
= networkInterface();
3189 // Empty means "Any Interface". In this case libtorrent has binded to 0.0.0.0 so any change to any interface will
3190 // be automatically picked up. Otherwise we would rebinding here to 0.0.0.0 again.
3191 if (configuredInterfaceName
.isEmpty()) return;
3193 const QString changedInterface
= cfg
.name();
3195 if (configuredInterfaceName
== changedInterface
)
3197 LogMsg(tr("Network configuration of %1 has changed, refreshing session binding", "e.g: Network configuration of tun0 has changed, refreshing session binding").arg(changedInterface
), Log::INFO
);
3198 configureListeningInterface();
3203 QStringList
SessionImpl::getListeningIPs() const
3207 const QString ifaceName
= networkInterface();
3208 const QString ifaceAddr
= networkInterfaceAddress();
3209 const QHostAddress
configuredAddr(ifaceAddr
);
3210 const bool allIPv4
= (ifaceAddr
== u
"0.0.0.0"); // Means All IPv4 addresses
3211 const bool allIPv6
= (ifaceAddr
== u
"::"); // Means All IPv6 addresses
3213 if (!ifaceAddr
.isEmpty() && !allIPv4
&& !allIPv6
&& configuredAddr
.isNull())
3215 LogMsg(tr("The configured network address is invalid. Address: \"%1\"").arg(ifaceAddr
), Log::CRITICAL
);
3216 // Pass the invalid user configured interface name/address to libtorrent
3217 // in hopes that it will come online later.
3218 // This will not cause IP leak but allow user to reconnect the interface
3219 // and re-establish connection without restarting the client.
3220 IPs
.append(ifaceAddr
);
3224 if (ifaceName
.isEmpty())
3226 if (ifaceAddr
.isEmpty())
3227 return {u
"0.0.0.0"_qs
, u
"::"_qs
}; // Indicates all interfaces + all addresses (aka default)
3230 return {u
"0.0.0.0"_qs
};
3236 const auto checkAndAddIP
= [allIPv4
, allIPv6
, &IPs
](const QHostAddress
&addr
, const QHostAddress
&match
)
3238 if ((allIPv4
&& (addr
.protocol() != QAbstractSocket::IPv4Protocol
))
3239 || (allIPv6
&& (addr
.protocol() != QAbstractSocket::IPv6Protocol
)))
3242 if ((match
== addr
) || allIPv4
|| allIPv6
)
3243 IPs
.append(addr
.toString());
3246 if (ifaceName
.isEmpty())
3248 const QList
<QHostAddress
> addresses
= QNetworkInterface::allAddresses();
3249 for (const auto &addr
: addresses
)
3250 checkAndAddIP(addr
, configuredAddr
);
3252 // At this point ifaceAddr was non-empty
3253 // If IPs.isEmpty() it means the configured Address was not found
3256 LogMsg(tr("Failed to find the configured network address to listen on. Address: \"%1\"")
3257 .arg(ifaceAddr
), Log::CRITICAL
);
3258 IPs
.append(ifaceAddr
);
3264 // Attempt to listen on provided interface
3265 const QNetworkInterface networkIFace
= QNetworkInterface::interfaceFromName(ifaceName
);
3266 if (!networkIFace
.isValid())
3268 qDebug("Invalid network interface: %s", qUtf8Printable(ifaceName
));
3269 LogMsg(tr("The configured network interface is invalid. Interface: \"%1\"").arg(ifaceName
), Log::CRITICAL
);
3270 IPs
.append(ifaceName
);
3274 if (ifaceAddr
.isEmpty())
3276 IPs
.append(ifaceName
);
3277 return IPs
; // On Windows calling code converts it to GUID
3280 const QList
<QNetworkAddressEntry
> addresses
= networkIFace
.addressEntries();
3281 qDebug() << "This network interface has " << addresses
.size() << " IP addresses";
3282 for (const QNetworkAddressEntry
&entry
: addresses
)
3283 checkAndAddIP(entry
.ip(), configuredAddr
);
3285 // Make sure there is at least one IP
3286 // At this point there was an explicit interface and an explicit address set
3287 // and the address should have been found
3290 LogMsg(tr("Failed to find the configured network address to listen on. Address: \"%1\"")
3291 .arg(ifaceAddr
), Log::CRITICAL
);
3292 IPs
.append(ifaceAddr
);
3298 // Set the ports range in which is chosen the port
3299 // the BitTorrent session will listen to
3300 void SessionImpl::configureListeningInterface()
3302 m_listenInterfaceConfigured
= false;
3303 configureDeferred();
3306 int SessionImpl::globalDownloadSpeedLimit() const
3308 // Unfortunately the value was saved as KiB instead of B.
3309 // But it is better to pass it around internally(+ webui) as Bytes.
3310 return m_globalDownloadSpeedLimit
* 1024;
3313 void SessionImpl::setGlobalDownloadSpeedLimit(const int limit
)
3315 // Unfortunately the value was saved as KiB instead of B.
3316 // But it is better to pass it around internally(+ webui) as Bytes.
3317 if (limit
== globalDownloadSpeedLimit())
3321 m_globalDownloadSpeedLimit
= 0;
3322 else if (limit
<= 1024)
3323 m_globalDownloadSpeedLimit
= 1;
3325 m_globalDownloadSpeedLimit
= (limit
/ 1024);
3327 if (!isAltGlobalSpeedLimitEnabled())
3328 configureDeferred();
3331 int SessionImpl::globalUploadSpeedLimit() const
3333 // Unfortunately the value was saved as KiB instead of B.
3334 // But it is better to pass it around internally(+ webui) as Bytes.
3335 return m_globalUploadSpeedLimit
* 1024;
3338 void SessionImpl::setGlobalUploadSpeedLimit(const int limit
)
3340 // Unfortunately the value was saved as KiB instead of B.
3341 // But it is better to pass it around internally(+ webui) as Bytes.
3342 if (limit
== globalUploadSpeedLimit())
3346 m_globalUploadSpeedLimit
= 0;
3347 else if (limit
<= 1024)
3348 m_globalUploadSpeedLimit
= 1;
3350 m_globalUploadSpeedLimit
= (limit
/ 1024);
3352 if (!isAltGlobalSpeedLimitEnabled())
3353 configureDeferred();
3356 int SessionImpl::altGlobalDownloadSpeedLimit() const
3358 // Unfortunately the value was saved as KiB instead of B.
3359 // But it is better to pass it around internally(+ webui) as Bytes.
3360 return m_altGlobalDownloadSpeedLimit
* 1024;
3363 void SessionImpl::setAltGlobalDownloadSpeedLimit(const int limit
)
3365 // Unfortunately the value was saved as KiB instead of B.
3366 // But it is better to pass it around internally(+ webui) as Bytes.
3367 if (limit
== altGlobalDownloadSpeedLimit())
3371 m_altGlobalDownloadSpeedLimit
= 0;
3372 else if (limit
<= 1024)
3373 m_altGlobalDownloadSpeedLimit
= 1;
3375 m_altGlobalDownloadSpeedLimit
= (limit
/ 1024);
3377 if (isAltGlobalSpeedLimitEnabled())
3378 configureDeferred();
3381 int SessionImpl::altGlobalUploadSpeedLimit() const
3383 // Unfortunately the value was saved as KiB instead of B.
3384 // But it is better to pass it around internally(+ webui) as Bytes.
3385 return m_altGlobalUploadSpeedLimit
* 1024;
3388 void SessionImpl::setAltGlobalUploadSpeedLimit(const int limit
)
3390 // Unfortunately the value was saved as KiB instead of B.
3391 // But it is better to pass it around internally(+ webui) as Bytes.
3392 if (limit
== altGlobalUploadSpeedLimit())
3396 m_altGlobalUploadSpeedLimit
= 0;
3397 else if (limit
<= 1024)
3398 m_altGlobalUploadSpeedLimit
= 1;
3400 m_altGlobalUploadSpeedLimit
= (limit
/ 1024);
3402 if (isAltGlobalSpeedLimitEnabled())
3403 configureDeferred();
3406 int SessionImpl::downloadSpeedLimit() const
3408 return isAltGlobalSpeedLimitEnabled()
3409 ? altGlobalDownloadSpeedLimit()
3410 : globalDownloadSpeedLimit();
3413 void SessionImpl::setDownloadSpeedLimit(const int limit
)
3415 if (isAltGlobalSpeedLimitEnabled())
3416 setAltGlobalDownloadSpeedLimit(limit
);
3418 setGlobalDownloadSpeedLimit(limit
);
3421 int SessionImpl::uploadSpeedLimit() const
3423 return isAltGlobalSpeedLimitEnabled()
3424 ? altGlobalUploadSpeedLimit()
3425 : globalUploadSpeedLimit();
3428 void SessionImpl::setUploadSpeedLimit(const int limit
)
3430 if (isAltGlobalSpeedLimitEnabled())
3431 setAltGlobalUploadSpeedLimit(limit
);
3433 setGlobalUploadSpeedLimit(limit
);
3436 bool SessionImpl::isAltGlobalSpeedLimitEnabled() const
3438 return m_isAltGlobalSpeedLimitEnabled
;
3441 void SessionImpl::setAltGlobalSpeedLimitEnabled(const bool enabled
)
3443 if (enabled
== isAltGlobalSpeedLimitEnabled()) return;
3445 // Save new state to remember it on startup
3446 m_isAltGlobalSpeedLimitEnabled
= enabled
;
3447 applyBandwidthLimits();
3449 emit
speedLimitModeChanged(m_isAltGlobalSpeedLimitEnabled
);
3452 bool SessionImpl::isBandwidthSchedulerEnabled() const
3454 return m_isBandwidthSchedulerEnabled
;
3457 void SessionImpl::setBandwidthSchedulerEnabled(const bool enabled
)
3459 if (enabled
!= isBandwidthSchedulerEnabled())
3461 m_isBandwidthSchedulerEnabled
= enabled
;
3463 enableBandwidthScheduler();
3465 delete m_bwScheduler
;
3469 bool SessionImpl::isPerformanceWarningEnabled() const
3471 return m_isPerformanceWarningEnabled
;
3474 void SessionImpl::setPerformanceWarningEnabled(const bool enable
)
3476 if (enable
== m_isPerformanceWarningEnabled
)
3479 m_isPerformanceWarningEnabled
= enable
;
3480 configureDeferred();
3483 int SessionImpl::saveResumeDataInterval() const
3485 return m_saveResumeDataInterval
;
3488 void SessionImpl::setSaveResumeDataInterval(const int value
)
3490 if (value
== m_saveResumeDataInterval
)
3493 m_saveResumeDataInterval
= value
;
3497 m_resumeDataTimer
->setInterval(std::chrono::minutes(value
));
3498 m_resumeDataTimer
->start();
3502 m_resumeDataTimer
->stop();
3506 int SessionImpl::port() const
3511 void SessionImpl::setPort(const int port
)
3516 configureListeningInterface();
3518 if (isReannounceWhenAddressChangedEnabled())
3519 reannounceToAllTrackers();
3523 QString
SessionImpl::networkInterface() const
3525 return m_networkInterface
;
3528 void SessionImpl::setNetworkInterface(const QString
&iface
)
3530 if (iface
!= networkInterface())
3532 m_networkInterface
= iface
;
3533 configureListeningInterface();
3537 QString
SessionImpl::networkInterfaceName() const
3539 return m_networkInterfaceName
;
3542 void SessionImpl::setNetworkInterfaceName(const QString
&name
)
3544 m_networkInterfaceName
= name
;
3547 QString
SessionImpl::networkInterfaceAddress() const
3549 return m_networkInterfaceAddress
;
3552 void SessionImpl::setNetworkInterfaceAddress(const QString
&address
)
3554 if (address
!= networkInterfaceAddress())
3556 m_networkInterfaceAddress
= address
;
3557 configureListeningInterface();
3561 int SessionImpl::encryption() const
3563 return m_encryption
;
3566 void SessionImpl::setEncryption(const int state
)
3568 if (state
!= encryption())
3570 m_encryption
= state
;
3571 configureDeferred();
3572 LogMsg(tr("Encryption support: %1").arg(
3573 state
== 0 ? tr("ON") : ((state
== 1) ? tr("FORCED") : tr("OFF")))
3578 int SessionImpl::maxActiveCheckingTorrents() const
3580 return m_maxActiveCheckingTorrents
;
3583 void SessionImpl::setMaxActiveCheckingTorrents(const int val
)
3585 if (val
== m_maxActiveCheckingTorrents
)
3588 m_maxActiveCheckingTorrents
= val
;
3589 configureDeferred();
3592 bool SessionImpl::isI2PEnabled() const
3594 return m_isI2PEnabled
;
3597 void SessionImpl::setI2PEnabled(const bool enabled
)
3599 if (m_isI2PEnabled
!= enabled
)
3601 m_isI2PEnabled
= enabled
;
3602 configureDeferred();
3606 QString
SessionImpl::I2PAddress() const
3608 return m_I2PAddress
;
3611 void SessionImpl::setI2PAddress(const QString
&address
)
3613 if (m_I2PAddress
!= address
)
3615 m_I2PAddress
= address
;
3616 configureDeferred();
3620 int SessionImpl::I2PPort() const
3625 void SessionImpl::setI2PPort(int port
)
3627 if (m_I2PPort
!= port
)
3630 configureDeferred();
3634 bool SessionImpl::I2PMixedMode() const
3636 return m_I2PMixedMode
;
3639 void SessionImpl::setI2PMixedMode(const bool enabled
)
3641 if (m_I2PMixedMode
!= enabled
)
3643 m_I2PMixedMode
= enabled
;
3644 configureDeferred();
3648 bool SessionImpl::isProxyPeerConnectionsEnabled() const
3650 return m_isProxyPeerConnectionsEnabled
;
3653 void SessionImpl::setProxyPeerConnectionsEnabled(const bool enabled
)
3655 if (enabled
!= isProxyPeerConnectionsEnabled())
3657 m_isProxyPeerConnectionsEnabled
= enabled
;
3658 configureDeferred();
3662 ChokingAlgorithm
SessionImpl::chokingAlgorithm() const
3664 return m_chokingAlgorithm
;
3667 void SessionImpl::setChokingAlgorithm(const ChokingAlgorithm mode
)
3669 if (mode
== m_chokingAlgorithm
) return;
3671 m_chokingAlgorithm
= mode
;
3672 configureDeferred();
3675 SeedChokingAlgorithm
SessionImpl::seedChokingAlgorithm() const
3677 return m_seedChokingAlgorithm
;
3680 void SessionImpl::setSeedChokingAlgorithm(const SeedChokingAlgorithm mode
)
3682 if (mode
== m_seedChokingAlgorithm
) return;
3684 m_seedChokingAlgorithm
= mode
;
3685 configureDeferred();
3688 bool SessionImpl::isAddTrackersEnabled() const
3690 return m_isAddTrackersEnabled
;
3693 void SessionImpl::setAddTrackersEnabled(const bool enabled
)
3695 m_isAddTrackersEnabled
= enabled
;
3698 QString
SessionImpl::additionalTrackers() const
3700 return m_additionalTrackers
;
3703 void SessionImpl::setAdditionalTrackers(const QString
&trackers
)
3705 if (trackers
!= additionalTrackers())
3707 m_additionalTrackers
= trackers
;
3708 populateAdditionalTrackers();
3712 bool SessionImpl::isIPFilteringEnabled() const
3714 return m_isIPFilteringEnabled
;
3717 void SessionImpl::setIPFilteringEnabled(const bool enabled
)
3719 if (enabled
!= m_isIPFilteringEnabled
)
3721 m_isIPFilteringEnabled
= enabled
;
3722 m_IPFilteringConfigured
= false;
3723 configureDeferred();
3727 Path
SessionImpl::IPFilterFile() const
3729 return m_IPFilterFile
;
3732 void SessionImpl::setIPFilterFile(const Path
&path
)
3734 if (path
!= IPFilterFile())
3736 m_IPFilterFile
= path
;
3737 m_IPFilteringConfigured
= false;
3738 configureDeferred();
3742 bool SessionImpl::isExcludedFileNamesEnabled() const
3744 return m_isExcludedFileNamesEnabled
;
3747 void SessionImpl::setExcludedFileNamesEnabled(const bool enabled
)
3749 if (m_isExcludedFileNamesEnabled
== enabled
)
3752 m_isExcludedFileNamesEnabled
= enabled
;
3755 populateExcludedFileNamesRegExpList();
3757 m_excludedFileNamesRegExpList
.clear();
3760 QStringList
SessionImpl::excludedFileNames() const
3762 return m_excludedFileNames
;
3765 void SessionImpl::setExcludedFileNames(const QStringList
&excludedFileNames
)
3767 if (excludedFileNames
!= m_excludedFileNames
)
3769 m_excludedFileNames
= excludedFileNames
;
3770 populateExcludedFileNamesRegExpList();
3774 void SessionImpl::populateExcludedFileNamesRegExpList()
3776 const QStringList excludedNames
= excludedFileNames();
3778 m_excludedFileNamesRegExpList
.clear();
3779 m_excludedFileNamesRegExpList
.reserve(excludedNames
.size());
3781 for (const QString
&str
: excludedNames
)
3783 const QString pattern
= QRegularExpression::anchoredPattern(QRegularExpression::wildcardToRegularExpression(str
));
3784 const QRegularExpression re
{pattern
, QRegularExpression::CaseInsensitiveOption
};
3785 m_excludedFileNamesRegExpList
.append(re
);
3789 bool SessionImpl::isFilenameExcluded(const QString
&fileName
) const
3791 if (!isExcludedFileNamesEnabled())
3794 return std::any_of(m_excludedFileNamesRegExpList
.begin(), m_excludedFileNamesRegExpList
.end(), [&fileName
](const QRegularExpression
&re
)
3796 return re
.match(fileName
).hasMatch();
3800 void SessionImpl::setBannedIPs(const QStringList
&newList
)
3802 if (newList
== m_bannedIPs
)
3803 return; // do nothing
3804 // here filter out incorrect IP
3805 QStringList filteredList
;
3806 for (const QString
&ip
: newList
)
3808 if (Utils::Net::isValidIP(ip
))
3810 // the same IPv6 addresses could be written in different forms;
3811 // QHostAddress::toString() result format follows RFC5952;
3812 // thus we avoid duplicate entries pointing to the same address
3813 filteredList
<< QHostAddress(ip
).toString();
3817 LogMsg(tr("Rejected invalid IP address while applying the list of banned IP addresses. IP: \"%1\"")
3822 // now we have to sort IPs and make them unique
3823 filteredList
.sort();
3824 filteredList
.removeDuplicates();
3825 // Again ensure that the new list is different from the stored one.
3826 if (filteredList
== m_bannedIPs
)
3827 return; // do nothing
3828 // store to session settings
3829 // also here we have to recreate filter list including 3rd party ban file
3830 // and install it again into m_session
3831 m_bannedIPs
= filteredList
;
3832 m_IPFilteringConfigured
= false;
3833 configureDeferred();
3836 ResumeDataStorageType
SessionImpl::resumeDataStorageType() const
3838 return m_resumeDataStorageType
;
3841 void SessionImpl::setResumeDataStorageType(const ResumeDataStorageType type
)
3843 m_resumeDataStorageType
= type
;
3846 QStringList
SessionImpl::bannedIPs() const
3851 bool SessionImpl::isRestored() const
3853 return m_isRestored
;
3856 int SessionImpl::maxConnectionsPerTorrent() const
3858 return m_maxConnectionsPerTorrent
;
3861 void SessionImpl::setMaxConnectionsPerTorrent(int max
)
3863 max
= (max
> 0) ? max
: -1;
3864 if (max
!= maxConnectionsPerTorrent())
3866 m_maxConnectionsPerTorrent
= max
;
3868 for (const TorrentImpl
*torrent
: asConst(m_torrents
))
3872 torrent
->nativeHandle().set_max_connections(max
);
3874 catch (const std::exception
&) {}
3879 int SessionImpl::maxUploadsPerTorrent() const
3881 return m_maxUploadsPerTorrent
;
3884 void SessionImpl::setMaxUploadsPerTorrent(int max
)
3886 max
= (max
> 0) ? max
: -1;
3887 if (max
!= maxUploadsPerTorrent())
3889 m_maxUploadsPerTorrent
= max
;
3891 for (const TorrentImpl
*torrent
: asConst(m_torrents
))
3895 torrent
->nativeHandle().set_max_uploads(max
);
3897 catch (const std::exception
&) {}
3902 bool SessionImpl::announceToAllTrackers() const
3904 return m_announceToAllTrackers
;
3907 void SessionImpl::setAnnounceToAllTrackers(const bool val
)
3909 if (val
!= m_announceToAllTrackers
)
3911 m_announceToAllTrackers
= val
;
3912 configureDeferred();
3916 bool SessionImpl::announceToAllTiers() const
3918 return m_announceToAllTiers
;
3921 void SessionImpl::setAnnounceToAllTiers(const bool val
)
3923 if (val
!= m_announceToAllTiers
)
3925 m_announceToAllTiers
= val
;
3926 configureDeferred();
3930 int SessionImpl::peerTurnover() const
3932 return m_peerTurnover
;
3935 void SessionImpl::setPeerTurnover(const int val
)
3937 if (val
== m_peerTurnover
)
3940 m_peerTurnover
= val
;
3941 configureDeferred();
3944 int SessionImpl::peerTurnoverCutoff() const
3946 return m_peerTurnoverCutoff
;
3949 void SessionImpl::setPeerTurnoverCutoff(const int val
)
3951 if (val
== m_peerTurnoverCutoff
)
3954 m_peerTurnoverCutoff
= val
;
3955 configureDeferred();
3958 int SessionImpl::peerTurnoverInterval() const
3960 return m_peerTurnoverInterval
;
3963 void SessionImpl::setPeerTurnoverInterval(const int val
)
3965 if (val
== m_peerTurnoverInterval
)
3968 m_peerTurnoverInterval
= val
;
3969 configureDeferred();
3972 DiskIOType
SessionImpl::diskIOType() const
3974 return m_diskIOType
;
3977 void SessionImpl::setDiskIOType(const DiskIOType type
)
3979 if (type
!= m_diskIOType
)
3981 m_diskIOType
= type
;
3985 int SessionImpl::requestQueueSize() const
3987 return m_requestQueueSize
;
3990 void SessionImpl::setRequestQueueSize(const int val
)
3992 if (val
== m_requestQueueSize
)
3995 m_requestQueueSize
= val
;
3996 configureDeferred();
3999 int SessionImpl::asyncIOThreads() const
4001 return std::clamp(m_asyncIOThreads
.get(), 1, 1024);
4004 void SessionImpl::setAsyncIOThreads(const int num
)
4006 if (num
== m_asyncIOThreads
)
4009 m_asyncIOThreads
= num
;
4010 configureDeferred();
4013 int SessionImpl::hashingThreads() const
4015 return std::clamp(m_hashingThreads
.get(), 1, 1024);
4018 void SessionImpl::setHashingThreads(const int num
)
4020 if (num
== m_hashingThreads
)
4023 m_hashingThreads
= num
;
4024 configureDeferred();
4027 int SessionImpl::filePoolSize() const
4029 return m_filePoolSize
;
4032 void SessionImpl::setFilePoolSize(const int size
)
4034 if (size
== m_filePoolSize
)
4037 m_filePoolSize
= size
;
4038 configureDeferred();
4041 int SessionImpl::checkingMemUsage() const
4043 return std::max(1, m_checkingMemUsage
.get());
4046 void SessionImpl::setCheckingMemUsage(int size
)
4048 size
= std::max(size
, 1);
4050 if (size
== m_checkingMemUsage
)
4053 m_checkingMemUsage
= size
;
4054 configureDeferred();
4057 int SessionImpl::diskCacheSize() const
4059 #ifdef QBT_APP_64BIT
4060 return std::min(m_diskCacheSize
.get(), 33554431); // 32768GiB
4062 // When build as 32bit binary, set the maximum at less than 2GB to prevent crashes
4063 // allocate 1536MiB and leave 512MiB to the rest of program data in RAM
4064 return std::min(m_diskCacheSize
.get(), 1536);
4068 void SessionImpl::setDiskCacheSize(int size
)
4070 #ifdef QBT_APP_64BIT
4071 size
= std::min(size
, 33554431); // 32768GiB
4073 // allocate 1536MiB and leave 512MiB to the rest of program data in RAM
4074 size
= std::min(size
, 1536);
4076 if (size
!= m_diskCacheSize
)
4078 m_diskCacheSize
= size
;
4079 configureDeferred();
4083 int SessionImpl::diskCacheTTL() const
4085 return m_diskCacheTTL
;
4088 void SessionImpl::setDiskCacheTTL(const int ttl
)
4090 if (ttl
!= m_diskCacheTTL
)
4092 m_diskCacheTTL
= ttl
;
4093 configureDeferred();
4097 qint64
SessionImpl::diskQueueSize() const
4099 return m_diskQueueSize
;
4102 void SessionImpl::setDiskQueueSize(const qint64 size
)
4104 if (size
== m_diskQueueSize
)
4107 m_diskQueueSize
= size
;
4108 configureDeferred();
4111 DiskIOReadMode
SessionImpl::diskIOReadMode() const
4113 return m_diskIOReadMode
;
4116 void SessionImpl::setDiskIOReadMode(const DiskIOReadMode mode
)
4118 if (mode
== m_diskIOReadMode
)
4121 m_diskIOReadMode
= mode
;
4122 configureDeferred();
4125 DiskIOWriteMode
SessionImpl::diskIOWriteMode() const
4127 return m_diskIOWriteMode
;
4130 void SessionImpl::setDiskIOWriteMode(const DiskIOWriteMode mode
)
4132 if (mode
== m_diskIOWriteMode
)
4135 m_diskIOWriteMode
= mode
;
4136 configureDeferred();
4139 bool SessionImpl::isCoalesceReadWriteEnabled() const
4141 return m_coalesceReadWriteEnabled
;
4144 void SessionImpl::setCoalesceReadWriteEnabled(const bool enabled
)
4146 if (enabled
== m_coalesceReadWriteEnabled
) return;
4148 m_coalesceReadWriteEnabled
= enabled
;
4149 configureDeferred();
4152 bool SessionImpl::isSuggestModeEnabled() const
4154 return m_isSuggestMode
;
4157 bool SessionImpl::usePieceExtentAffinity() const
4159 return m_usePieceExtentAffinity
;
4162 void SessionImpl::setPieceExtentAffinity(const bool enabled
)
4164 if (enabled
== m_usePieceExtentAffinity
) return;
4166 m_usePieceExtentAffinity
= enabled
;
4167 configureDeferred();
4170 void SessionImpl::setSuggestMode(const bool mode
)
4172 if (mode
== m_isSuggestMode
) return;
4174 m_isSuggestMode
= mode
;
4175 configureDeferred();
4178 int SessionImpl::sendBufferWatermark() const
4180 return m_sendBufferWatermark
;
4183 void SessionImpl::setSendBufferWatermark(const int value
)
4185 if (value
== m_sendBufferWatermark
) return;
4187 m_sendBufferWatermark
= value
;
4188 configureDeferred();
4191 int SessionImpl::sendBufferLowWatermark() const
4193 return m_sendBufferLowWatermark
;
4196 void SessionImpl::setSendBufferLowWatermark(const int value
)
4198 if (value
== m_sendBufferLowWatermark
) return;
4200 m_sendBufferLowWatermark
= value
;
4201 configureDeferred();
4204 int SessionImpl::sendBufferWatermarkFactor() const
4206 return m_sendBufferWatermarkFactor
;
4209 void SessionImpl::setSendBufferWatermarkFactor(const int value
)
4211 if (value
== m_sendBufferWatermarkFactor
) return;
4213 m_sendBufferWatermarkFactor
= value
;
4214 configureDeferred();
4217 int SessionImpl::connectionSpeed() const
4219 return m_connectionSpeed
;
4222 void SessionImpl::setConnectionSpeed(const int value
)
4224 if (value
== m_connectionSpeed
) return;
4226 m_connectionSpeed
= value
;
4227 configureDeferred();
4230 int SessionImpl::socketSendBufferSize() const
4232 return m_socketSendBufferSize
;
4235 void SessionImpl::setSocketSendBufferSize(const int value
)
4237 if (value
== m_socketSendBufferSize
)
4240 m_socketSendBufferSize
= value
;
4241 configureDeferred();
4244 int SessionImpl::socketReceiveBufferSize() const
4246 return m_socketReceiveBufferSize
;
4249 void SessionImpl::setSocketReceiveBufferSize(const int value
)
4251 if (value
== m_socketReceiveBufferSize
)
4254 m_socketReceiveBufferSize
= value
;
4255 configureDeferred();
4258 int SessionImpl::socketBacklogSize() const
4260 return m_socketBacklogSize
;
4263 void SessionImpl::setSocketBacklogSize(const int value
)
4265 if (value
== m_socketBacklogSize
) return;
4267 m_socketBacklogSize
= value
;
4268 configureDeferred();
4271 bool SessionImpl::isAnonymousModeEnabled() const
4273 return m_isAnonymousModeEnabled
;
4276 void SessionImpl::setAnonymousModeEnabled(const bool enabled
)
4278 if (enabled
!= m_isAnonymousModeEnabled
)
4280 m_isAnonymousModeEnabled
= enabled
;
4281 configureDeferred();
4282 LogMsg(tr("Anonymous mode: %1").arg(isAnonymousModeEnabled() ? tr("ON") : tr("OFF"))
4287 bool SessionImpl::isQueueingSystemEnabled() const
4289 return m_isQueueingEnabled
;
4292 void SessionImpl::setQueueingSystemEnabled(const bool enabled
)
4294 if (enabled
!= m_isQueueingEnabled
)
4296 m_isQueueingEnabled
= enabled
;
4297 configureDeferred();
4300 m_torrentsQueueChanged
= true;
4302 removeTorrentsQueue();
4306 int SessionImpl::maxActiveDownloads() const
4308 return m_maxActiveDownloads
;
4311 void SessionImpl::setMaxActiveDownloads(int max
)
4313 max
= std::max(max
, -1);
4314 if (max
!= m_maxActiveDownloads
)
4316 m_maxActiveDownloads
= max
;
4317 configureDeferred();
4321 int SessionImpl::maxActiveUploads() const
4323 return m_maxActiveUploads
;
4326 void SessionImpl::setMaxActiveUploads(int max
)
4328 max
= std::max(max
, -1);
4329 if (max
!= m_maxActiveUploads
)
4331 m_maxActiveUploads
= max
;
4332 configureDeferred();
4336 int SessionImpl::maxActiveTorrents() const
4338 return m_maxActiveTorrents
;
4341 void SessionImpl::setMaxActiveTorrents(int max
)
4343 max
= std::max(max
, -1);
4344 if (max
!= m_maxActiveTorrents
)
4346 m_maxActiveTorrents
= max
;
4347 configureDeferred();
4351 bool SessionImpl::ignoreSlowTorrentsForQueueing() const
4353 return m_ignoreSlowTorrentsForQueueing
;
4356 void SessionImpl::setIgnoreSlowTorrentsForQueueing(const bool ignore
)
4358 if (ignore
!= m_ignoreSlowTorrentsForQueueing
)
4360 m_ignoreSlowTorrentsForQueueing
= ignore
;
4361 configureDeferred();
4365 int SessionImpl::downloadRateForSlowTorrents() const
4367 return m_downloadRateForSlowTorrents
;
4370 void SessionImpl::setDownloadRateForSlowTorrents(const int rateInKibiBytes
)
4372 if (rateInKibiBytes
== m_downloadRateForSlowTorrents
)
4375 m_downloadRateForSlowTorrents
= rateInKibiBytes
;
4376 configureDeferred();
4379 int SessionImpl::uploadRateForSlowTorrents() const
4381 return m_uploadRateForSlowTorrents
;
4384 void SessionImpl::setUploadRateForSlowTorrents(const int rateInKibiBytes
)
4386 if (rateInKibiBytes
== m_uploadRateForSlowTorrents
)
4389 m_uploadRateForSlowTorrents
= rateInKibiBytes
;
4390 configureDeferred();
4393 int SessionImpl::slowTorrentsInactivityTimer() const
4395 return m_slowTorrentsInactivityTimer
;
4398 void SessionImpl::setSlowTorrentsInactivityTimer(const int timeInSeconds
)
4400 if (timeInSeconds
== m_slowTorrentsInactivityTimer
)
4403 m_slowTorrentsInactivityTimer
= timeInSeconds
;
4404 configureDeferred();
4407 int SessionImpl::outgoingPortsMin() const
4409 return m_outgoingPortsMin
;
4412 void SessionImpl::setOutgoingPortsMin(const int min
)
4414 if (min
!= m_outgoingPortsMin
)
4416 m_outgoingPortsMin
= min
;
4417 configureDeferred();
4421 int SessionImpl::outgoingPortsMax() const
4423 return m_outgoingPortsMax
;
4426 void SessionImpl::setOutgoingPortsMax(const int max
)
4428 if (max
!= m_outgoingPortsMax
)
4430 m_outgoingPortsMax
= max
;
4431 configureDeferred();
4435 int SessionImpl::UPnPLeaseDuration() const
4437 return m_UPnPLeaseDuration
;
4440 void SessionImpl::setUPnPLeaseDuration(const int duration
)
4442 if (duration
!= m_UPnPLeaseDuration
)
4444 m_UPnPLeaseDuration
= duration
;
4445 configureDeferred();
4449 int SessionImpl::peerToS() const
4454 void SessionImpl::setPeerToS(const int value
)
4456 if (value
== m_peerToS
)
4460 configureDeferred();
4463 bool SessionImpl::ignoreLimitsOnLAN() const
4465 return m_ignoreLimitsOnLAN
;
4468 void SessionImpl::setIgnoreLimitsOnLAN(const bool ignore
)
4470 if (ignore
!= m_ignoreLimitsOnLAN
)
4472 m_ignoreLimitsOnLAN
= ignore
;
4473 configureDeferred();
4477 bool SessionImpl::includeOverheadInLimits() const
4479 return m_includeOverheadInLimits
;
4482 void SessionImpl::setIncludeOverheadInLimits(const bool include
)
4484 if (include
!= m_includeOverheadInLimits
)
4486 m_includeOverheadInLimits
= include
;
4487 configureDeferred();
4491 QString
SessionImpl::announceIP() const
4493 return m_announceIP
;
4496 void SessionImpl::setAnnounceIP(const QString
&ip
)
4498 if (ip
!= m_announceIP
)
4501 configureDeferred();
4505 int SessionImpl::maxConcurrentHTTPAnnounces() const
4507 return m_maxConcurrentHTTPAnnounces
;
4510 void SessionImpl::setMaxConcurrentHTTPAnnounces(const int value
)
4512 if (value
== m_maxConcurrentHTTPAnnounces
)
4515 m_maxConcurrentHTTPAnnounces
= value
;
4516 configureDeferred();
4519 bool SessionImpl::isReannounceWhenAddressChangedEnabled() const
4521 return m_isReannounceWhenAddressChangedEnabled
;
4524 void SessionImpl::setReannounceWhenAddressChangedEnabled(const bool enabled
)
4526 if (enabled
== m_isReannounceWhenAddressChangedEnabled
)
4529 m_isReannounceWhenAddressChangedEnabled
= enabled
;
4532 void SessionImpl::reannounceToAllTrackers() const
4534 for (const TorrentImpl
*torrent
: asConst(m_torrents
))
4538 torrent
->nativeHandle().force_reannounce(0, -1, lt::torrent_handle::ignore_min_interval
);
4540 catch (const std::exception
&) {}
4544 int SessionImpl::stopTrackerTimeout() const
4546 return m_stopTrackerTimeout
;
4549 void SessionImpl::setStopTrackerTimeout(const int value
)
4551 if (value
== m_stopTrackerTimeout
)
4554 m_stopTrackerTimeout
= value
;
4555 configureDeferred();
4558 int SessionImpl::maxConnections() const
4560 return m_maxConnections
;
4563 void SessionImpl::setMaxConnections(int max
)
4565 max
= (max
> 0) ? max
: -1;
4566 if (max
!= m_maxConnections
)
4568 m_maxConnections
= max
;
4569 configureDeferred();
4573 int SessionImpl::maxUploads() const
4575 return m_maxUploads
;
4578 void SessionImpl::setMaxUploads(int max
)
4580 max
= (max
> 0) ? max
: -1;
4581 if (max
!= m_maxUploads
)
4584 configureDeferred();
4588 BTProtocol
SessionImpl::btProtocol() const
4590 return m_btProtocol
;
4593 void SessionImpl::setBTProtocol(const BTProtocol protocol
)
4595 if ((protocol
< BTProtocol::Both
) || (BTProtocol::UTP
< protocol
))
4598 if (protocol
== m_btProtocol
) return;
4600 m_btProtocol
= protocol
;
4601 configureDeferred();
4604 bool SessionImpl::isUTPRateLimited() const
4606 return m_isUTPRateLimited
;
4609 void SessionImpl::setUTPRateLimited(const bool limited
)
4611 if (limited
!= m_isUTPRateLimited
)
4613 m_isUTPRateLimited
= limited
;
4614 configureDeferred();
4618 MixedModeAlgorithm
SessionImpl::utpMixedMode() const
4620 return m_utpMixedMode
;
4623 void SessionImpl::setUtpMixedMode(const MixedModeAlgorithm mode
)
4625 if (mode
== m_utpMixedMode
) return;
4627 m_utpMixedMode
= mode
;
4628 configureDeferred();
4631 bool SessionImpl::isIDNSupportEnabled() const
4633 return m_IDNSupportEnabled
;
4636 void SessionImpl::setIDNSupportEnabled(const bool enabled
)
4638 if (enabled
== m_IDNSupportEnabled
) return;
4640 m_IDNSupportEnabled
= enabled
;
4641 configureDeferred();
4644 bool SessionImpl::multiConnectionsPerIpEnabled() const
4646 return m_multiConnectionsPerIpEnabled
;
4649 void SessionImpl::setMultiConnectionsPerIpEnabled(const bool enabled
)
4651 if (enabled
== m_multiConnectionsPerIpEnabled
) return;
4653 m_multiConnectionsPerIpEnabled
= enabled
;
4654 configureDeferred();
4657 bool SessionImpl::validateHTTPSTrackerCertificate() const
4659 return m_validateHTTPSTrackerCertificate
;
4662 void SessionImpl::setValidateHTTPSTrackerCertificate(const bool enabled
)
4664 if (enabled
== m_validateHTTPSTrackerCertificate
) return;
4666 m_validateHTTPSTrackerCertificate
= enabled
;
4667 configureDeferred();
4670 bool SessionImpl::isSSRFMitigationEnabled() const
4672 return m_SSRFMitigationEnabled
;
4675 void SessionImpl::setSSRFMitigationEnabled(const bool enabled
)
4677 if (enabled
== m_SSRFMitigationEnabled
) return;
4679 m_SSRFMitigationEnabled
= enabled
;
4680 configureDeferred();
4683 bool SessionImpl::blockPeersOnPrivilegedPorts() const
4685 return m_blockPeersOnPrivilegedPorts
;
4688 void SessionImpl::setBlockPeersOnPrivilegedPorts(const bool enabled
)
4690 if (enabled
== m_blockPeersOnPrivilegedPorts
) return;
4692 m_blockPeersOnPrivilegedPorts
= enabled
;
4693 configureDeferred();
4696 bool SessionImpl::isTrackerFilteringEnabled() const
4698 return m_isTrackerFilteringEnabled
;
4701 void SessionImpl::setTrackerFilteringEnabled(const bool enabled
)
4703 if (enabled
!= m_isTrackerFilteringEnabled
)
4705 m_isTrackerFilteringEnabled
= enabled
;
4706 configureDeferred();
4710 bool SessionImpl::isListening() const
4712 return m_nativeSessionExtension
->isSessionListening();
4715 MaxRatioAction
SessionImpl::maxRatioAction() const
4717 return static_cast<MaxRatioAction
>(m_maxRatioAction
.get());
4720 void SessionImpl::setMaxRatioAction(const MaxRatioAction act
)
4722 m_maxRatioAction
= static_cast<int>(act
);
4725 bool SessionImpl::isKnownTorrent(const InfoHash
&infoHash
) const
4727 const bool isHybrid
= infoHash
.isHybrid();
4728 const auto id
= TorrentID::fromInfoHash(infoHash
);
4729 // alternative ID can be useful to find existing torrent
4730 // in case if hybrid torrent was added by v1 info hash
4731 const auto altID
= (isHybrid
? TorrentID::fromSHA1Hash(infoHash
.v1()) : TorrentID());
4733 if (m_loadingTorrents
.contains(id
) || (isHybrid
&& m_loadingTorrents
.contains(altID
)))
4735 if (m_downloadedMetadata
.contains(id
) || (isHybrid
&& m_downloadedMetadata
.contains(altID
)))
4737 return findTorrent(infoHash
);
4740 void SessionImpl::updateSeedingLimitTimer()
4742 if ((globalMaxRatio() == Torrent::NO_RATIO_LIMIT
) && !hasPerTorrentRatioLimit()
4743 && (globalMaxSeedingMinutes() == Torrent::NO_SEEDING_TIME_LIMIT
) && !hasPerTorrentSeedingTimeLimit())
4745 if (m_seedingLimitTimer
->isActive())
4746 m_seedingLimitTimer
->stop();
4748 else if (!m_seedingLimitTimer
->isActive())
4750 m_seedingLimitTimer
->start();
4754 void SessionImpl::handleTorrentShareLimitChanged(TorrentImpl
*const)
4756 updateSeedingLimitTimer();
4759 void SessionImpl::handleTorrentNameChanged(TorrentImpl
*const)
4763 void SessionImpl::handleTorrentSavePathChanged(TorrentImpl
*const torrent
)
4765 emit
torrentSavePathChanged(torrent
);
4768 void SessionImpl::handleTorrentCategoryChanged(TorrentImpl
*const torrent
, const QString
&oldCategory
)
4770 emit
torrentCategoryChanged(torrent
, oldCategory
);
4773 void SessionImpl::handleTorrentTagAdded(TorrentImpl
*const torrent
, const QString
&tag
)
4775 emit
torrentTagAdded(torrent
, tag
);
4778 void SessionImpl::handleTorrentTagRemoved(TorrentImpl
*const torrent
, const QString
&tag
)
4780 emit
torrentTagRemoved(torrent
, tag
);
4783 void SessionImpl::handleTorrentSavingModeChanged(TorrentImpl
*const torrent
)
4785 emit
torrentSavingModeChanged(torrent
);
4788 void SessionImpl::handleTorrentTrackersAdded(TorrentImpl
*const torrent
, const QVector
<TrackerEntry
> &newTrackers
)
4790 for (const TrackerEntry
&newTracker
: newTrackers
)
4791 LogMsg(tr("Added tracker to torrent. Torrent: \"%1\". Tracker: \"%2\"").arg(torrent
->name(), newTracker
.url
));
4792 emit
trackersAdded(torrent
, newTrackers
);
4793 if (torrent
->trackers().size() == newTrackers
.size())
4794 emit
trackerlessStateChanged(torrent
, false);
4795 emit
trackersChanged(torrent
);
4798 void SessionImpl::handleTorrentTrackersRemoved(TorrentImpl
*const torrent
, const QStringList
&deletedTrackers
)
4800 for (const QString
&deletedTracker
: deletedTrackers
)
4801 LogMsg(tr("Removed tracker from torrent. Torrent: \"%1\". Tracker: \"%2\"").arg(torrent
->name(), deletedTracker
));
4802 emit
trackersRemoved(torrent
, deletedTrackers
);
4803 if (torrent
->trackers().isEmpty())
4804 emit
trackerlessStateChanged(torrent
, true);
4805 emit
trackersChanged(torrent
);
4808 void SessionImpl::handleTorrentTrackersChanged(TorrentImpl
*const torrent
)
4810 emit
trackersChanged(torrent
);
4813 void SessionImpl::handleTorrentUrlSeedsAdded(TorrentImpl
*const torrent
, const QVector
<QUrl
> &newUrlSeeds
)
4815 for (const QUrl
&newUrlSeed
: newUrlSeeds
)
4816 LogMsg(tr("Added URL seed to torrent. Torrent: \"%1\". URL: \"%2\"").arg(torrent
->name(), newUrlSeed
.toString()));
4819 void SessionImpl::handleTorrentUrlSeedsRemoved(TorrentImpl
*const torrent
, const QVector
<QUrl
> &urlSeeds
)
4821 for (const QUrl
&urlSeed
: urlSeeds
)
4822 LogMsg(tr("Removed URL seed from torrent. Torrent: \"%1\". URL: \"%2\"").arg(torrent
->name(), urlSeed
.toString()));
4825 void SessionImpl::handleTorrentMetadataReceived(TorrentImpl
*const torrent
)
4827 if (!torrentExportDirectory().isEmpty())
4828 exportTorrentFile(torrent
, torrentExportDirectory());
4830 emit
torrentMetadataReceived(torrent
);
4833 void SessionImpl::handleTorrentPaused(TorrentImpl
*const torrent
)
4835 LogMsg(tr("Torrent paused. Torrent: \"%1\"").arg(torrent
->name()));
4836 emit
torrentPaused(torrent
);
4839 void SessionImpl::handleTorrentResumed(TorrentImpl
*const torrent
)
4841 LogMsg(tr("Torrent resumed. Torrent: \"%1\"").arg(torrent
->name()));
4842 emit
torrentResumed(torrent
);
4845 void SessionImpl::handleTorrentChecked(TorrentImpl
*const torrent
)
4847 emit
torrentFinishedChecking(torrent
);
4850 void SessionImpl::handleTorrentFinished(TorrentImpl
*const torrent
)
4852 LogMsg(tr("Torrent download finished. Torrent: \"%1\"").arg(torrent
->name()));
4853 emit
torrentFinished(torrent
);
4855 if (const Path exportPath
= finishedTorrentExportDirectory(); !exportPath
.isEmpty())
4856 exportTorrentFile(torrent
, exportPath
);
4858 // Check whether it contains .torrent files
4859 for (const Path
&torrentRelpath
: asConst(torrent
->filePaths()))
4861 if (torrentRelpath
.hasExtension(u
".torrent"_qs
))
4863 emit
recursiveTorrentDownloadPossible(torrent
);
4868 const bool hasUnfinishedTorrents
= std::any_of(m_torrents
.cbegin(), m_torrents
.cend(), [](const TorrentImpl
*torrent
)
4870 return !(torrent
->isFinished() || torrent
->isPaused() || torrent
->isErrored());
4872 if (!hasUnfinishedTorrents
)
4873 emit
allTorrentsFinished();
4876 void SessionImpl::handleTorrentResumeDataReady(TorrentImpl
*const torrent
, const LoadTorrentParams
&data
)
4880 m_resumeDataStorage
->store(torrent
->id(), data
);
4881 const auto iter
= m_changedTorrentIDs
.find(torrent
->id());
4882 if (iter
!= m_changedTorrentIDs
.end())
4884 m_resumeDataStorage
->remove(iter
.value());
4885 m_changedTorrentIDs
.erase(iter
);
4889 void SessionImpl::handleTorrentInfoHashChanged(TorrentImpl
*torrent
, const InfoHash
&prevInfoHash
)
4891 Q_ASSERT(torrent
->infoHash().isHybrid());
4893 m_hybridTorrentsByAltID
.insert(TorrentID::fromSHA1Hash(torrent
->infoHash().v1()), torrent
);
4895 const auto prevID
= TorrentID::fromInfoHash(prevInfoHash
);
4896 const TorrentID currentID
= torrent
->id();
4897 if (currentID
!= prevID
)
4899 m_torrents
[torrent
->id()] = m_torrents
.take(prevID
);
4900 m_changedTorrentIDs
[torrent
->id()] = prevID
;
4904 bool SessionImpl::addMoveTorrentStorageJob(TorrentImpl
*torrent
, const Path
&newPath
, const MoveStorageMode mode
, const MoveStorageContext context
)
4908 const lt::torrent_handle torrentHandle
= torrent
->nativeHandle();
4909 const Path currentLocation
= torrent
->actualStorageLocation();
4910 const bool torrentHasActiveJob
= !m_moveStorageQueue
.isEmpty() && (m_moveStorageQueue
.first().torrentHandle
== torrentHandle
);
4912 if (m_moveStorageQueue
.size() > 1)
4914 auto iter
= std::find_if((m_moveStorageQueue
.begin() + 1), m_moveStorageQueue
.end()
4915 , [&torrentHandle
](const MoveStorageJob
&job
)
4917 return job
.torrentHandle
== torrentHandle
;
4920 if (iter
!= m_moveStorageQueue
.end())
4922 // remove existing inactive job
4923 torrent
->handleMoveStorageJobFinished(currentLocation
, iter
->context
, torrentHasActiveJob
);
4924 LogMsg(tr("Torrent move canceled. Torrent: \"%1\". Source: \"%2\". Destination: \"%3\"").arg(torrent
->name(), currentLocation
.toString(), iter
->path
.toString()));
4925 m_moveStorageQueue
.erase(iter
);
4929 if (torrentHasActiveJob
)
4931 // if there is active job for this torrent prevent creating meaningless
4932 // job that will move torrent to the same location as current one
4933 if (m_moveStorageQueue
.first().path
== newPath
)
4935 LogMsg(tr("Failed to enqueue torrent move. Torrent: \"%1\". Source: \"%2\". Destination: \"%3\". Reason: torrent is currently moving to the destination")
4936 .arg(torrent
->name(), currentLocation
.toString(), newPath
.toString()));
4942 if (currentLocation
== newPath
)
4944 LogMsg(tr("Failed to enqueue torrent move. Torrent: \"%1\". Source: \"%2\" Destination: \"%3\". Reason: both paths point to the same location")
4945 .arg(torrent
->name(), currentLocation
.toString(), newPath
.toString()));
4950 const MoveStorageJob moveStorageJob
{torrentHandle
, newPath
, mode
, context
};
4951 m_moveStorageQueue
<< moveStorageJob
;
4952 LogMsg(tr("Enqueued torrent move. Torrent: \"%1\". Source: \"%2\". Destination: \"%3\"").arg(torrent
->name(), currentLocation
.toString(), newPath
.toString()));
4954 if (m_moveStorageQueue
.size() == 1)
4955 moveTorrentStorage(moveStorageJob
);
4960 void SessionImpl::moveTorrentStorage(const MoveStorageJob
&job
) const
4962 #ifdef QBT_USES_LIBTORRENT2
4963 const auto id
= TorrentID::fromInfoHash(job
.torrentHandle
.info_hashes());
4965 const auto id
= TorrentID::fromInfoHash(job
.torrentHandle
.info_hash());
4967 const TorrentImpl
*torrent
= m_torrents
.value(id
);
4968 const QString torrentName
= (torrent
? torrent
->name() : id
.toString());
4969 LogMsg(tr("Start moving torrent. Torrent: \"%1\". Destination: \"%2\"").arg(torrentName
, job
.path
.toString()));
4971 job
.torrentHandle
.move_storage(job
.path
.toString().toStdString(), toNative(job
.mode
));
4974 void SessionImpl::handleMoveTorrentStorageJobFinished(const Path
&newPath
)
4976 const MoveStorageJob finishedJob
= m_moveStorageQueue
.takeFirst();
4977 if (!m_moveStorageQueue
.isEmpty())
4978 moveTorrentStorage(m_moveStorageQueue
.first());
4980 const auto iter
= std::find_if(m_moveStorageQueue
.cbegin(), m_moveStorageQueue
.cend()
4981 , [&finishedJob
](const MoveStorageJob
&job
)
4983 return job
.torrentHandle
== finishedJob
.torrentHandle
;
4986 const bool torrentHasOutstandingJob
= (iter
!= m_moveStorageQueue
.cend());
4988 TorrentImpl
*torrent
= m_torrents
.value(finishedJob
.torrentHandle
.info_hash());
4991 torrent
->handleMoveStorageJobFinished(newPath
, finishedJob
.context
, torrentHasOutstandingJob
);
4993 else if (!torrentHasOutstandingJob
)
4995 // Last job is completed for torrent that being removing, so actually remove it
4996 const lt::torrent_handle nativeHandle
{finishedJob
.torrentHandle
};
4997 const RemovingTorrentData
&removingTorrentData
= m_removingTorrents
[nativeHandle
.info_hash()];
4998 if (removingTorrentData
.deleteOption
== DeleteTorrent
)
4999 m_nativeSession
->remove_torrent(nativeHandle
, lt::session::delete_partfile
);
5003 void SessionImpl::storeCategories() const
5005 QJsonObject jsonObj
;
5006 for (auto it
= m_categories
.cbegin(); it
!= m_categories
.cend(); ++it
)
5008 const QString
&categoryName
= it
.key();
5009 const CategoryOptions
&categoryOptions
= it
.value();
5010 jsonObj
[categoryName
] = categoryOptions
.toJSON();
5013 const Path path
= specialFolderLocation(SpecialFolder::Config
) / CATEGORIES_FILE_NAME
;
5014 const QByteArray data
= QJsonDocument(jsonObj
).toJson();
5015 const nonstd::expected
<void, QString
> result
= Utils::IO::saveToFile(path
, data
);
5018 LogMsg(tr("Failed to save Categories configuration. File: \"%1\". Error: \"%2\"")
5019 .arg(path
.toString(), result
.error()), Log::WARNING
);
5023 void SessionImpl::upgradeCategories()
5025 const auto legacyCategories
= SettingValue
<QVariantMap
>(u
"BitTorrent/Session/Categories"_qs
).get();
5026 for (auto it
= legacyCategories
.cbegin(); it
!= legacyCategories
.cend(); ++it
)
5028 const QString
&categoryName
= it
.key();
5029 CategoryOptions categoryOptions
;
5030 categoryOptions
.savePath
= Path(it
.value().toString());
5031 m_categories
[categoryName
] = categoryOptions
;
5037 void SessionImpl::loadCategories()
5039 m_categories
.clear();
5041 QFile confFile
{(specialFolderLocation(SpecialFolder::Config
) / CATEGORIES_FILE_NAME
).data()};
5042 if (!confFile
.exists())
5044 // TODO: Remove the following upgrade code in v4.5
5045 // == BEGIN UPGRADE CODE ==
5046 upgradeCategories();
5047 m_needUpgradeDownloadPath
= true;
5048 // == END UPGRADE CODE ==
5053 if (!confFile
.open(QFile::ReadOnly
))
5055 LogMsg(tr("Failed to load Categories. File: \"%1\". Error: \"%2\"")
5056 .arg(confFile
.fileName(), confFile
.errorString()), Log::CRITICAL
);
5060 QJsonParseError jsonError
;
5061 const QJsonDocument jsonDoc
= QJsonDocument::fromJson(confFile
.readAll(), &jsonError
);
5062 if (jsonError
.error
!= QJsonParseError::NoError
)
5064 LogMsg(tr("Failed to parse Categories configuration. File: \"%1\". Error: \"%2\"")
5065 .arg(confFile
.fileName(), jsonError
.errorString()), Log::WARNING
);
5069 if (!jsonDoc
.isObject())
5071 LogMsg(tr("Failed to load Categories configuration. File: \"%1\". Reason: invalid data format")
5072 .arg(confFile
.fileName()), Log::WARNING
);
5076 const QJsonObject jsonObj
= jsonDoc
.object();
5077 for (auto it
= jsonObj
.constBegin(); it
!= jsonObj
.constEnd(); ++it
)
5079 const QString
&categoryName
= it
.key();
5080 const auto categoryOptions
= CategoryOptions::fromJSON(it
.value().toObject());
5081 m_categories
[categoryName
] = categoryOptions
;
5085 bool SessionImpl::hasPerTorrentRatioLimit() const
5087 return std::any_of(m_torrents
.cbegin(), m_torrents
.cend(), [](const TorrentImpl
*torrent
)
5089 return (torrent
->ratioLimit() >= 0);
5093 bool SessionImpl::hasPerTorrentSeedingTimeLimit() const
5095 return std::any_of(m_torrents
.cbegin(), m_torrents
.cend(), [](const TorrentImpl
*torrent
)
5097 return (torrent
->seedingTimeLimit() >= 0);
5101 void SessionImpl::configureDeferred()
5103 if (m_deferredConfigureScheduled
)
5106 m_deferredConfigureScheduled
= true;
5107 QMetaObject::invokeMethod(this, qOverload
<>(&SessionImpl::configure
), Qt::QueuedConnection
);
5110 // Enable IP Filtering
5111 // this method creates ban list from scratch combining user ban list and 3rd party ban list file
5112 void SessionImpl::enableIPFilter()
5114 qDebug("Enabling IPFilter");
5115 // 1. Parse the IP filter
5116 // 2. In the slot add the manually banned IPs to the provided lt::ip_filter
5117 // 3. Set the ip_filter in one go so there isn't a time window where there isn't an ip_filter
5118 // set between clearing the old one and setting the new one.
5119 if (!m_filterParser
)
5121 m_filterParser
= new FilterParserThread(this);
5122 connect(m_filterParser
.data(), &FilterParserThread::IPFilterParsed
, this, &SessionImpl::handleIPFilterParsed
);
5123 connect(m_filterParser
.data(), &FilterParserThread::IPFilterError
, this, &SessionImpl::handleIPFilterError
);
5125 m_filterParser
->processFilterFile(IPFilterFile());
5128 // Disable IP Filtering
5129 void SessionImpl::disableIPFilter()
5131 qDebug("Disabling IPFilter");
5134 disconnect(m_filterParser
.data(), nullptr, this, nullptr);
5135 delete m_filterParser
;
5138 // Add the banned IPs after the IPFilter disabling
5139 // which creates an empty filter and overrides all previously
5141 lt::ip_filter filter
;
5142 processBannedIPs(filter
);
5143 m_nativeSession
->set_ip_filter(filter
);
5146 void SessionImpl::recursiveTorrentDownload(const TorrentID
&id
)
5148 const TorrentImpl
*torrent
= m_torrents
.value(id
);
5152 for (const Path
&torrentRelpath
: asConst(torrent
->filePaths()))
5154 if (torrentRelpath
.hasExtension(u
".torrent"_qs
))
5156 const Path torrentFullpath
= torrent
->savePath() / torrentRelpath
;
5158 LogMsg(tr("Recursive download .torrent file within torrent. Source torrent: \"%1\". File: \"%2\"")
5159 .arg(torrent
->name(), torrentFullpath
.toString()));
5161 AddTorrentParams params
;
5162 // Passing the save path along to the sub torrent file
5163 params
.savePath
= torrent
->savePath();
5164 const nonstd::expected
<TorrentInfo
, QString
> loadResult
= TorrentInfo::loadFromFile(torrentFullpath
);
5167 addTorrent(loadResult
.value(), params
);
5171 LogMsg(tr("Failed to load .torrent file within torrent. Source torrent: \"%1\". File: \"%2\". Error: \"%3\"")
5172 .arg(torrent
->name(), torrentFullpath
.toString(), loadResult
.error()), Log::WARNING
);
5178 const SessionStatus
&SessionImpl::status() const
5183 const CacheStatus
&SessionImpl::cacheStatus() const
5185 return m_cacheStatus
;
5188 void SessionImpl::enqueueRefresh()
5190 Q_ASSERT(!m_refreshEnqueued
);
5192 QTimer::singleShot(refreshInterval(), Qt::CoarseTimer
, this, [this]
5194 m_nativeSession
->post_torrent_updates();
5195 m_nativeSession
->post_session_stats();
5197 if (m_torrentsQueueChanged
)
5199 m_torrentsQueueChanged
= false;
5200 m_needSaveTorrentsQueue
= true;
5204 m_refreshEnqueued
= true;
5207 void SessionImpl::handleIPFilterParsed(const int ruleCount
)
5211 lt::ip_filter filter
= m_filterParser
->IPfilter();
5212 processBannedIPs(filter
);
5213 m_nativeSession
->set_ip_filter(filter
);
5215 LogMsg(tr("Successfully parsed the IP filter file. Number of rules applied: %1").arg(ruleCount
));
5216 emit
IPFilterParsed(false, ruleCount
);
5219 void SessionImpl::handleIPFilterError()
5221 lt::ip_filter filter
;
5222 processBannedIPs(filter
);
5223 m_nativeSession
->set_ip_filter(filter
);
5225 LogMsg(tr("Failed to parse the IP filter file"), Log::WARNING
);
5226 emit
IPFilterParsed(true, 0);
5229 std::vector
<lt::alert
*> SessionImpl::getPendingAlerts(const lt::time_duration time
) const
5231 if (time
> lt::time_duration::zero())
5232 m_nativeSession
->wait_for_alert(time
);
5234 std::vector
<lt::alert
*> alerts
;
5235 m_nativeSession
->pop_alerts(&alerts
);
5239 TorrentContentLayout
SessionImpl::torrentContentLayout() const
5241 return m_torrentContentLayout
;
5244 void SessionImpl::setTorrentContentLayout(const TorrentContentLayout value
)
5246 m_torrentContentLayout
= value
;
5249 // Read alerts sent by the BitTorrent session
5250 void SessionImpl::readAlerts()
5252 const std::vector
<lt::alert
*> alerts
= getPendingAlerts();
5253 handleAddTorrentAlerts(alerts
);
5254 for (const lt::alert
*a
: alerts
)
5257 processTrackerStatuses();
5260 void SessionImpl::handleAddTorrentAlerts(const std::vector
<lt::alert
*> &alerts
)
5262 QVector
<Torrent
*> loadedTorrents
;
5264 loadedTorrents
.reserve(MAX_PROCESSING_RESUMEDATA_COUNT
);
5266 for (const lt::alert
*a
: alerts
)
5268 if (a
->type() != lt::add_torrent_alert::alert_type
)
5271 const auto *alert
= static_cast<const lt::add_torrent_alert
*>(a
);
5274 const QString msg
= QString::fromStdString(alert
->message());
5275 LogMsg(tr("Failed to load torrent. Reason: \"%1\"").arg(msg
), Log::WARNING
);
5276 emit
loadTorrentFailed(msg
);
5278 const lt::add_torrent_params
¶ms
= alert
->params
;
5279 const bool hasMetadata
= (params
.ti
&& params
.ti
->is_valid());
5280 #ifdef QBT_USES_LIBTORRENT2
5281 const InfoHash infoHash
{(hasMetadata
? params
.ti
->info_hashes() : params
.info_hashes
)};
5282 if (infoHash
.isHybrid())
5283 m_hybridTorrentsByAltID
.remove(TorrentID::fromSHA1Hash(infoHash
.v1()));
5285 const InfoHash infoHash
{(hasMetadata
? params
.ti
->info_hash() : params
.info_hash
)};
5287 if (const auto loadingTorrentsIter
= m_loadingTorrents
.find(TorrentID::fromInfoHash(infoHash
))
5288 ; loadingTorrentsIter
!= m_loadingTorrents
.end())
5290 m_loadingTorrents
.erase(loadingTorrentsIter
);
5292 else if (const auto downloadedMetadataIter
= m_downloadedMetadata
.find(TorrentID::fromInfoHash(infoHash
))
5293 ; downloadedMetadataIter
!= m_downloadedMetadata
.end())
5295 m_downloadedMetadata
.erase(downloadedMetadataIter
);
5296 if (infoHash
.isHybrid())
5298 // index hybrid magnet links by both v1 and v2 info hashes
5299 const auto altID
= TorrentID::fromSHA1Hash(infoHash
.v1());
5300 m_downloadedMetadata
.remove(altID
);
5308 #ifdef QBT_USES_LIBTORRENT2
5309 const InfoHash infoHash
{alert
->handle
.info_hashes()};
5311 const InfoHash infoHash
{alert
->handle
.info_hash()};
5313 const auto torrentID
= TorrentID::fromInfoHash(infoHash
);
5315 if (const auto loadingTorrentsIter
= m_loadingTorrents
.find(torrentID
)
5316 ; loadingTorrentsIter
!= m_loadingTorrents
.end())
5318 const LoadTorrentParams params
= loadingTorrentsIter
.value();
5319 m_loadingTorrents
.erase(loadingTorrentsIter
);
5321 Torrent
*torrent
= createTorrent(alert
->handle
, params
);
5322 loadedTorrents
.append(torrent
);
5324 else if (const auto downloadedMetadataIter
= m_downloadedMetadata
.find(torrentID
)
5325 ; downloadedMetadataIter
!= m_downloadedMetadata
.end())
5327 downloadedMetadataIter
.value() = alert
->handle
;
5328 if (infoHash
.isHybrid())
5330 // index hybrid magnet links by both v1 and v2 info hashes
5331 const auto altID
= TorrentID::fromSHA1Hash(infoHash
.v1());
5332 m_downloadedMetadata
[altID
] = alert
->handle
;
5337 if (!loadedTorrents
.isEmpty())
5340 m_torrentsQueueChanged
= true;
5341 emit
torrentsLoaded(loadedTorrents
);
5345 void SessionImpl::handleAlert(const lt::alert
*a
)
5351 #ifdef QBT_USES_LIBTORRENT2
5352 case lt::file_prio_alert::alert_type
:
5354 case lt::file_renamed_alert::alert_type
:
5355 case lt::file_rename_failed_alert::alert_type
:
5356 case lt::file_completed_alert::alert_type
:
5357 case lt::torrent_finished_alert::alert_type
:
5358 case lt::save_resume_data_alert::alert_type
:
5359 case lt::save_resume_data_failed_alert::alert_type
:
5360 case lt::torrent_paused_alert::alert_type
:
5361 case lt::torrent_resumed_alert::alert_type
:
5362 case lt::fastresume_rejected_alert::alert_type
:
5363 case lt::torrent_checked_alert::alert_type
:
5364 case lt::metadata_received_alert::alert_type
:
5365 case lt::performance_alert::alert_type
:
5366 dispatchTorrentAlert(static_cast<const lt::torrent_alert
*>(a
));
5368 case lt::state_update_alert::alert_type
:
5369 handleStateUpdateAlert(static_cast<const lt::state_update_alert
*>(a
));
5371 case lt::session_stats_alert::alert_type
:
5372 handleSessionStatsAlert(static_cast<const lt::session_stats_alert
*>(a
));
5374 case lt::tracker_announce_alert::alert_type
:
5375 case lt::tracker_error_alert::alert_type
:
5376 case lt::tracker_reply_alert::alert_type
:
5377 case lt::tracker_warning_alert::alert_type
:
5378 handleTrackerAlert(static_cast<const lt::tracker_alert
*>(a
));
5380 case lt::file_error_alert::alert_type
:
5381 handleFileErrorAlert(static_cast<const lt::file_error_alert
*>(a
));
5383 case lt::add_torrent_alert::alert_type
:
5384 // handled separately
5386 case lt::torrent_removed_alert::alert_type
:
5387 handleTorrentRemovedAlert(static_cast<const lt::torrent_removed_alert
*>(a
));
5389 case lt::torrent_deleted_alert::alert_type
:
5390 handleTorrentDeletedAlert(static_cast<const lt::torrent_deleted_alert
*>(a
));
5392 case lt::torrent_delete_failed_alert::alert_type
:
5393 handleTorrentDeleteFailedAlert(static_cast<const lt::torrent_delete_failed_alert
*>(a
));
5395 case lt::portmap_error_alert::alert_type
:
5396 handlePortmapWarningAlert(static_cast<const lt::portmap_error_alert
*>(a
));
5398 case lt::portmap_alert::alert_type
:
5399 handlePortmapAlert(static_cast<const lt::portmap_alert
*>(a
));
5401 case lt::peer_blocked_alert::alert_type
:
5402 handlePeerBlockedAlert(static_cast<const lt::peer_blocked_alert
*>(a
));
5404 case lt::peer_ban_alert::alert_type
:
5405 handlePeerBanAlert(static_cast<const lt::peer_ban_alert
*>(a
));
5407 case lt::url_seed_alert::alert_type
:
5408 handleUrlSeedAlert(static_cast<const lt::url_seed_alert
*>(a
));
5410 case lt::listen_succeeded_alert::alert_type
:
5411 handleListenSucceededAlert(static_cast<const lt::listen_succeeded_alert
*>(a
));
5413 case lt::listen_failed_alert::alert_type
:
5414 handleListenFailedAlert(static_cast<const lt::listen_failed_alert
*>(a
));
5416 case lt::external_ip_alert::alert_type
:
5417 handleExternalIPAlert(static_cast<const lt::external_ip_alert
*>(a
));
5419 case lt::alerts_dropped_alert::alert_type
:
5420 handleAlertsDroppedAlert(static_cast<const lt::alerts_dropped_alert
*>(a
));
5422 case lt::storage_moved_alert::alert_type
:
5423 handleStorageMovedAlert(static_cast<const lt::storage_moved_alert
*>(a
));
5425 case lt::storage_moved_failed_alert::alert_type
:
5426 handleStorageMovedFailedAlert(static_cast<const lt::storage_moved_failed_alert
*>(a
));
5428 case lt::socks5_alert::alert_type
:
5429 handleSocks5Alert(static_cast<const lt::socks5_alert
*>(a
));
5431 #ifdef QBT_USES_LIBTORRENT2
5432 case lt::torrent_conflict_alert::alert_type
:
5433 handleTorrentConflictAlert(static_cast<const lt::torrent_conflict_alert
*>(a
));
5438 catch (const std::exception
&exc
)
5440 qWarning() << "Caught exception in " << Q_FUNC_INFO
<< ": " << QString::fromStdString(exc
.what());
5444 void SessionImpl::dispatchTorrentAlert(const lt::torrent_alert
*a
)
5446 const TorrentID torrentID
{a
->handle
.info_hash()};
5447 TorrentImpl
*torrent
= m_torrents
.value(torrentID
);
5448 #ifdef QBT_USES_LIBTORRENT2
5449 if (!torrent
&& (a
->type() == lt::metadata_received_alert::alert_type
))
5451 const InfoHash infoHash
{a
->handle
.info_hashes()};
5452 if (infoHash
.isHybrid())
5453 torrent
= m_torrents
.value(TorrentID::fromSHA1Hash(infoHash
.v1()));
5459 torrent
->handleAlert(a
);
5465 case lt::metadata_received_alert::alert_type
:
5466 handleMetadataReceivedAlert(static_cast<const lt::metadata_received_alert
*>(a
));
5471 TorrentImpl
*SessionImpl::createTorrent(const lt::torrent_handle
&nativeHandle
, const LoadTorrentParams
¶ms
)
5473 auto *const torrent
= new TorrentImpl(this, m_nativeSession
, nativeHandle
, params
);
5474 m_torrents
.insert(torrent
->id(), torrent
);
5475 if (const InfoHash infoHash
= torrent
->infoHash(); infoHash
.isHybrid())
5476 m_hybridTorrentsByAltID
.insert(TorrentID::fromSHA1Hash(infoHash
.v1()), torrent
);
5480 if (params
.addToQueueTop
)
5481 nativeHandle
.queue_position_top();
5483 torrent
->saveResumeData(lt::torrent_handle::save_info_dict
);
5485 // The following is useless for newly added magnet
5486 if (torrent
->hasMetadata())
5488 if (!torrentExportDirectory().isEmpty())
5489 exportTorrentFile(torrent
, torrentExportDirectory());
5493 if (((torrent
->ratioLimit() >= 0) || (torrent
->seedingTimeLimit() >= 0))
5494 && !m_seedingLimitTimer
->isActive())
5496 m_seedingLimitTimer
->start();
5501 LogMsg(tr("Restored torrent. Torrent: \"%1\"").arg(torrent
->name()));
5505 LogMsg(tr("Added new torrent. Torrent: \"%1\"").arg(torrent
->name()));
5506 emit
torrentAdded(torrent
);
5509 // Torrent could have error just after adding to libtorrent
5510 if (torrent
->hasError())
5511 LogMsg(tr("Torrent errored. Torrent: \"%1\". Error: \"%2\"").arg(torrent
->name(), torrent
->error()), Log::WARNING
);
5516 void SessionImpl::handleTorrentRemovedAlert(const lt::torrent_removed_alert
*p
)
5518 #ifdef QBT_USES_LIBTORRENT2
5519 const auto id
= TorrentID::fromInfoHash(p
->info_hashes
);
5521 const auto id
= TorrentID::fromInfoHash(p
->info_hash
);
5524 const auto removingTorrentDataIter
= m_removingTorrents
.find(id
);
5525 if (removingTorrentDataIter
!= m_removingTorrents
.end())
5527 if (removingTorrentDataIter
->deleteOption
== DeleteTorrent
)
5529 LogMsg(tr("Removed torrent. Torrent: \"%1\"").arg(removingTorrentDataIter
->name
));
5530 m_removingTorrents
.erase(removingTorrentDataIter
);
5535 void SessionImpl::handleTorrentDeletedAlert(const lt::torrent_deleted_alert
*p
)
5537 #ifdef QBT_USES_LIBTORRENT2
5538 const auto id
= TorrentID::fromInfoHash(p
->info_hashes
);
5540 const auto id
= TorrentID::fromInfoHash(p
->info_hash
);
5543 const auto removingTorrentDataIter
= m_removingTorrents
.find(id
);
5544 if (removingTorrentDataIter
== m_removingTorrents
.end())
5547 // torrent_deleted_alert can also be posted due to deletion of partfile. Ignore it in such a case.
5548 if (removingTorrentDataIter
->deleteOption
== DeleteTorrent
)
5551 Utils::Fs::smartRemoveEmptyFolderTree(removingTorrentDataIter
->pathToRemove
);
5552 LogMsg(tr("Removed torrent and deleted its content. Torrent: \"%1\"").arg(removingTorrentDataIter
->name
));
5553 m_removingTorrents
.erase(removingTorrentDataIter
);
5556 void SessionImpl::handleTorrentDeleteFailedAlert(const lt::torrent_delete_failed_alert
*p
)
5558 #ifdef QBT_USES_LIBTORRENT2
5559 const auto id
= TorrentID::fromInfoHash(p
->info_hashes
);
5561 const auto id
= TorrentID::fromInfoHash(p
->info_hash
);
5564 const auto removingTorrentDataIter
= m_removingTorrents
.find(id
);
5565 if (removingTorrentDataIter
== m_removingTorrents
.end())
5570 // libtorrent won't delete the directory if it contains files not listed in the torrent,
5571 // so we remove the directory ourselves
5572 Utils::Fs::smartRemoveEmptyFolderTree(removingTorrentDataIter
->pathToRemove
);
5574 LogMsg(tr("Removed torrent but failed to delete its content and/or partfile. Torrent: \"%1\". Error: \"%2\"")
5575 .arg(removingTorrentDataIter
->name
, QString::fromLocal8Bit(p
->error
.message().c_str()))
5578 else // torrent without metadata, hence no files on disk
5580 LogMsg(tr("Removed torrent. Torrent: \"%1\"").arg(removingTorrentDataIter
->name
));
5583 m_removingTorrents
.erase(removingTorrentDataIter
);
5586 void SessionImpl::handleMetadataReceivedAlert(const lt::metadata_received_alert
*p
)
5588 const TorrentID torrentID
{p
->handle
.info_hash()};
5591 if (const auto iter
= m_downloadedMetadata
.find(torrentID
); iter
!= m_downloadedMetadata
.end())
5594 m_downloadedMetadata
.erase(iter
);
5596 #ifdef QBT_USES_LIBTORRENT2
5597 const InfoHash infoHash
{p
->handle
.info_hashes()};
5598 if (infoHash
.isHybrid())
5600 const auto altID
= TorrentID::fromSHA1Hash(infoHash
.v1());
5601 if (const auto iter
= m_downloadedMetadata
.find(altID
); iter
!= m_downloadedMetadata
.end())
5604 m_downloadedMetadata
.erase(iter
);
5610 const TorrentInfo metadata
{*p
->handle
.torrent_file()};
5611 m_nativeSession
->remove_torrent(p
->handle
, lt::session::delete_files
);
5613 emit
metadataDownloaded(metadata
);
5617 void SessionImpl::handleFileErrorAlert(const lt::file_error_alert
*p
)
5619 TorrentImpl
*const torrent
= m_torrents
.value(p
->handle
.info_hash());
5623 torrent
->handleAlert(p
);
5625 const TorrentID id
= torrent
->id();
5626 if (!m_recentErroredTorrents
.contains(id
))
5628 m_recentErroredTorrents
.insert(id
);
5630 const QString msg
= QString::fromStdString(p
->message());
5631 LogMsg(tr("File error alert. Torrent: \"%1\". File: \"%2\". Reason: \"%3\"")
5632 .arg(torrent
->name(), QString::fromLocal8Bit(p
->filename()), msg
)
5634 emit
fullDiskError(torrent
, msg
);
5637 m_recentErroredTorrentsTimer
->start();
5640 void SessionImpl::handlePortmapWarningAlert(const lt::portmap_error_alert
*p
)
5642 LogMsg(tr("UPnP/NAT-PMP port mapping failed. Message: \"%1\"").arg(QString::fromStdString(p
->message())), Log::WARNING
);
5645 void SessionImpl::handlePortmapAlert(const lt::portmap_alert
*p
)
5647 qDebug("UPnP Success, msg: %s", p
->message().c_str());
5648 LogMsg(tr("UPnP/NAT-PMP port mapping succeeded. Message: \"%1\"").arg(QString::fromStdString(p
->message())), Log::INFO
);
5651 void SessionImpl::handlePeerBlockedAlert(const lt::peer_blocked_alert
*p
)
5656 case lt::peer_blocked_alert::ip_filter
:
5657 reason
= tr("IP filter", "this peer was blocked. Reason: IP filter.");
5659 case lt::peer_blocked_alert::port_filter
:
5660 reason
= tr("filtered port (%1)", "this peer was blocked. Reason: filtered port (8899).").arg(QString::number(p
->endpoint
.port()));
5662 case lt::peer_blocked_alert::i2p_mixed
:
5663 reason
= tr("%1 mixed mode restrictions", "this peer was blocked. Reason: I2P mixed mode restrictions.").arg(u
"I2P"_qs
); // don't translate I2P
5665 case lt::peer_blocked_alert::privileged_ports
:
5666 reason
= tr("privileged port (%1)", "this peer was blocked. Reason: privileged port (80).").arg(QString::number(p
->endpoint
.port()));
5668 case lt::peer_blocked_alert::utp_disabled
:
5669 reason
= tr("%1 is disabled", "this peer was blocked. Reason: uTP is disabled.").arg(C_UTP
); // don't translate μTP
5671 case lt::peer_blocked_alert::tcp_disabled
:
5672 reason
= tr("%1 is disabled", "this peer was blocked. Reason: TCP is disabled.").arg(u
"TCP"_qs
); // don't translate TCP
5676 const QString ip
{toString(p
->endpoint
.address())};
5678 Logger::instance()->addPeer(ip
, true, reason
);
5681 void SessionImpl::handlePeerBanAlert(const lt::peer_ban_alert
*p
)
5683 const QString ip
{toString(p
->endpoint
.address())};
5685 Logger::instance()->addPeer(ip
, false);
5688 void SessionImpl::handleUrlSeedAlert(const lt::url_seed_alert
*p
)
5690 const TorrentImpl
*torrent
= m_torrents
.value(p
->handle
.info_hash());
5696 LogMsg(tr("URL seed DNS lookup failed. Torrent: \"%1\". URL: \"%2\". Error: \"%3\"")
5697 .arg(torrent
->name(), QString::fromUtf8(p
->server_url()), QString::fromStdString(p
->message()))
5702 LogMsg(tr("Received error message from URL seed. Torrent: \"%1\". URL: \"%2\". Message: \"%3\"")
5703 .arg(torrent
->name(), QString::fromUtf8(p
->server_url()), QString::fromUtf8(p
->error_message()))
5708 void SessionImpl::handleListenSucceededAlert(const lt::listen_succeeded_alert
*p
)
5710 const QString proto
{toString(p
->socket_type
)};
5711 LogMsg(tr("Successfully listening on IP. IP: \"%1\". Port: \"%2/%3\"")
5712 .arg(toString(p
->address
), proto
, QString::number(p
->port
)), Log::INFO
);
5715 void SessionImpl::handleListenFailedAlert(const lt::listen_failed_alert
*p
)
5717 const QString proto
{toString(p
->socket_type
)};
5718 LogMsg(tr("Failed to listen on IP. IP: \"%1\". Port: \"%2/%3\". Reason: \"%4\"")
5719 .arg(toString(p
->address
), proto
, QString::number(p
->port
)
5720 , QString::fromLocal8Bit(p
->error
.message().c_str())), Log::CRITICAL
);
5723 void SessionImpl::handleExternalIPAlert(const lt::external_ip_alert
*p
)
5725 const QString externalIP
{toString(p
->external_address
)};
5726 LogMsg(tr("Detected external IP. IP: \"%1\"")
5727 .arg(externalIP
), Log::INFO
);
5729 if (m_lastExternalIP
!= externalIP
)
5731 if (isReannounceWhenAddressChangedEnabled() && !m_lastExternalIP
.isEmpty())
5732 reannounceToAllTrackers();
5733 m_lastExternalIP
= externalIP
;
5737 void SessionImpl::handleSessionStatsAlert(const lt::session_stats_alert
*p
)
5739 if (m_refreshEnqueued
)
5740 m_refreshEnqueued
= false;
5744 const int64_t interval
= lt::total_microseconds(p
->timestamp() - m_statsLastTimestamp
);
5748 m_statsLastTimestamp
= p
->timestamp();
5750 const auto stats
= p
->counters();
5752 m_status
.hasIncomingConnections
= static_cast<bool>(stats
[m_metricIndices
.net
.hasIncomingConnections
]);
5754 const int64_t ipOverheadDownload
= stats
[m_metricIndices
.net
.recvIPOverheadBytes
];
5755 const int64_t ipOverheadUpload
= stats
[m_metricIndices
.net
.sentIPOverheadBytes
];
5756 const int64_t totalDownload
= stats
[m_metricIndices
.net
.recvBytes
] + ipOverheadDownload
;
5757 const int64_t totalUpload
= stats
[m_metricIndices
.net
.sentBytes
] + ipOverheadUpload
;
5758 const int64_t totalPayloadDownload
= stats
[m_metricIndices
.net
.recvPayloadBytes
];
5759 const int64_t totalPayloadUpload
= stats
[m_metricIndices
.net
.sentPayloadBytes
];
5760 const int64_t trackerDownload
= stats
[m_metricIndices
.net
.recvTrackerBytes
];
5761 const int64_t trackerUpload
= stats
[m_metricIndices
.net
.sentTrackerBytes
];
5762 const int64_t dhtDownload
= stats
[m_metricIndices
.dht
.dhtBytesIn
];
5763 const int64_t dhtUpload
= stats
[m_metricIndices
.dht
.dhtBytesOut
];
5765 const auto calcRate
= [interval
](const qint64 previous
, const qint64 current
) -> qint64
5767 Q_ASSERT(current
>= previous
);
5768 Q_ASSERT(interval
>= 0);
5769 return (((current
- previous
) * lt::microseconds(1s
).count()) / interval
);
5772 m_status
.payloadDownloadRate
= calcRate(m_status
.totalPayloadDownload
, totalPayloadDownload
);
5773 m_status
.payloadUploadRate
= calcRate(m_status
.totalPayloadUpload
, totalPayloadUpload
);
5774 m_status
.downloadRate
= calcRate(m_status
.totalDownload
, totalDownload
);
5775 m_status
.uploadRate
= calcRate(m_status
.totalUpload
, totalUpload
);
5776 m_status
.ipOverheadDownloadRate
= calcRate(m_status
.ipOverheadDownload
, ipOverheadDownload
);
5777 m_status
.ipOverheadUploadRate
= calcRate(m_status
.ipOverheadUpload
, ipOverheadUpload
);
5778 m_status
.dhtDownloadRate
= calcRate(m_status
.dhtDownload
, dhtDownload
);
5779 m_status
.dhtUploadRate
= calcRate(m_status
.dhtUpload
, dhtUpload
);
5780 m_status
.trackerDownloadRate
= calcRate(m_status
.trackerDownload
, trackerDownload
);
5781 m_status
.trackerUploadRate
= calcRate(m_status
.trackerUpload
, trackerUpload
);
5783 m_status
.totalPayloadDownload
= totalPayloadDownload
;
5784 m_status
.totalPayloadUpload
= totalPayloadUpload
;
5785 m_status
.ipOverheadDownload
= ipOverheadDownload
;
5786 m_status
.ipOverheadUpload
= ipOverheadUpload
;
5787 m_status
.trackerDownload
= trackerDownload
;
5788 m_status
.trackerUpload
= trackerUpload
;
5789 m_status
.dhtDownload
= dhtDownload
;
5790 m_status
.dhtUpload
= dhtUpload
;
5791 m_status
.totalWasted
= stats
[m_metricIndices
.net
.recvRedundantBytes
]
5792 + stats
[m_metricIndices
.net
.recvFailedBytes
];
5793 m_status
.dhtNodes
= stats
[m_metricIndices
.dht
.dhtNodes
];
5794 m_status
.diskReadQueue
= stats
[m_metricIndices
.peer
.numPeersUpDisk
];
5795 m_status
.diskWriteQueue
= stats
[m_metricIndices
.peer
.numPeersDownDisk
];
5796 m_status
.peersCount
= stats
[m_metricIndices
.peer
.numPeersConnected
];
5798 if (totalDownload
> m_status
.totalDownload
)
5800 m_status
.totalDownload
= totalDownload
;
5801 m_isStatisticsDirty
= true;
5804 if (totalUpload
> m_status
.totalUpload
)
5806 m_status
.totalUpload
= totalUpload
;
5807 m_isStatisticsDirty
= true;
5810 m_status
.allTimeDownload
= m_previouslyDownloaded
+ m_status
.totalDownload
;
5811 m_status
.allTimeUpload
= m_previouslyUploaded
+ m_status
.totalUpload
;
5813 if (m_statisticsLastUpdateTimer
.hasExpired(STATISTICS_SAVE_INTERVAL
))
5816 m_cacheStatus
.totalUsedBuffers
= stats
[m_metricIndices
.disk
.diskBlocksInUse
];
5817 m_cacheStatus
.jobQueueLength
= stats
[m_metricIndices
.disk
.queuedDiskJobs
];
5819 #ifndef QBT_USES_LIBTORRENT2
5820 const int64_t numBlocksRead
= stats
[m_metricIndices
.disk
.numBlocksRead
];
5821 const int64_t numBlocksCacheHits
= stats
[m_metricIndices
.disk
.numBlocksCacheHits
];
5822 m_cacheStatus
.readRatio
= static_cast<qreal
>(numBlocksCacheHits
) / std::max
<int64_t>((numBlocksCacheHits
+ numBlocksRead
), 1);
5825 const int64_t totalJobs
= stats
[m_metricIndices
.disk
.writeJobs
] + stats
[m_metricIndices
.disk
.readJobs
]
5826 + stats
[m_metricIndices
.disk
.hashJobs
];
5827 m_cacheStatus
.averageJobTime
= (totalJobs
> 0)
5828 ? (stats
[m_metricIndices
.disk
.diskJobTime
] / totalJobs
) : 0;
5830 emit
statsUpdated();
5833 void SessionImpl::handleAlertsDroppedAlert(const lt::alerts_dropped_alert
*p
) const
5835 LogMsg(tr("Error: Internal alert queue is full and alerts are dropped, you might see degraded performance. Dropped alert type: \"%1\". Message: \"%2\"")
5836 .arg(QString::fromStdString(p
->dropped_alerts
.to_string()), QString::fromStdString(p
->message())), Log::CRITICAL
);
5839 void SessionImpl::handleStorageMovedAlert(const lt::storage_moved_alert
*p
)
5841 Q_ASSERT(!m_moveStorageQueue
.isEmpty());
5843 const MoveStorageJob
¤tJob
= m_moveStorageQueue
.first();
5844 Q_ASSERT(currentJob
.torrentHandle
== p
->handle
);
5846 const Path newPath
{QString::fromUtf8(p
->storage_path())};
5847 Q_ASSERT(newPath
== currentJob
.path
);
5849 #ifdef QBT_USES_LIBTORRENT2
5850 const auto id
= TorrentID::fromInfoHash(currentJob
.torrentHandle
.info_hashes());
5852 const auto id
= TorrentID::fromInfoHash(currentJob
.torrentHandle
.info_hash());
5855 TorrentImpl
*torrent
= m_torrents
.value(id
);
5856 const QString torrentName
= (torrent
? torrent
->name() : id
.toString());
5857 LogMsg(tr("Moved torrent successfully. Torrent: \"%1\". Destination: \"%2\"").arg(torrentName
, newPath
.toString()));
5859 handleMoveTorrentStorageJobFinished(newPath
);
5862 void SessionImpl::handleStorageMovedFailedAlert(const lt::storage_moved_failed_alert
*p
)
5864 Q_ASSERT(!m_moveStorageQueue
.isEmpty());
5866 const MoveStorageJob
¤tJob
= m_moveStorageQueue
.first();
5867 Q_ASSERT(currentJob
.torrentHandle
== p
->handle
);
5869 #ifdef QBT_USES_LIBTORRENT2
5870 const auto id
= TorrentID::fromInfoHash(currentJob
.torrentHandle
.info_hashes());
5872 const auto id
= TorrentID::fromInfoHash(currentJob
.torrentHandle
.info_hash());
5875 TorrentImpl
*torrent
= m_torrents
.value(id
);
5876 const QString torrentName
= (torrent
? torrent
->name() : id
.toString());
5877 const Path currentLocation
= (torrent
? torrent
->actualStorageLocation()
5878 : Path(p
->handle
.status(lt::torrent_handle::query_save_path
).save_path
));
5879 const QString errorMessage
= QString::fromStdString(p
->message());
5880 LogMsg(tr("Failed to move torrent. Torrent: \"%1\". Source: \"%2\". Destination: \"%3\". Reason: \"%4\"")
5881 .arg(torrentName
, currentLocation
.toString(), currentJob
.path
.toString(), errorMessage
), Log::WARNING
);
5883 handleMoveTorrentStorageJobFinished(currentLocation
);
5886 void SessionImpl::handleStateUpdateAlert(const lt::state_update_alert
*p
)
5888 QVector
<Torrent
*> updatedTorrents
;
5889 updatedTorrents
.reserve(static_cast<decltype(updatedTorrents
)::size_type
>(p
->status
.size()));
5891 for (const lt::torrent_status
&status
: p
->status
)
5893 #ifdef QBT_USES_LIBTORRENT2
5894 const auto id
= TorrentID::fromInfoHash(status
.info_hashes
);
5896 const auto id
= TorrentID::fromInfoHash(status
.info_hash
);
5898 TorrentImpl
*const torrent
= m_torrents
.value(id
);
5902 torrent
->handleStateUpdate(status
);
5903 updatedTorrents
.push_back(torrent
);
5906 if (!updatedTorrents
.isEmpty())
5907 emit
torrentsUpdated(updatedTorrents
);
5909 if (m_needSaveTorrentsQueue
)
5910 saveTorrentsQueue();
5912 if (m_refreshEnqueued
)
5913 m_refreshEnqueued
= false;
5918 void SessionImpl::handleSocks5Alert(const lt::socks5_alert
*p
) const
5922 const auto addr
= p
->ip
.address();
5923 const QString endpoint
= (addr
.is_v6() ? u
"[%1]:%2"_qs
: u
"%1:%2"_qs
)
5924 .arg(QString::fromStdString(addr
.to_string()), QString::number(p
->ip
.port()));
5925 LogMsg(tr("SOCKS5 proxy error. Address: %1. Message: \"%2\".")
5926 .arg(endpoint
, QString::fromLocal8Bit(p
->error
.message().c_str()))
5931 void SessionImpl::handleTrackerAlert(const lt::tracker_alert
*a
)
5933 TorrentImpl
*torrent
= m_torrents
.value(a
->handle
.info_hash());
5937 QMap
<TrackerEntry::Endpoint
, int> &updateInfo
= m_updatedTrackerEntries
[torrent
->nativeHandle()][std::string(a
->tracker_url())];
5939 if (a
->type() == lt::tracker_reply_alert::alert_type
)
5941 const int numPeers
= static_cast<const lt::tracker_reply_alert
*>(a
)->num_peers
;
5942 updateInfo
.insert(a
->local_endpoint
, numPeers
);
5946 #ifdef QBT_USES_LIBTORRENT2
5947 void SessionImpl::handleTorrentConflictAlert(const lt::torrent_conflict_alert
*a
)
5949 const auto torrentIDv1
= TorrentID::fromSHA1Hash(a
->metadata
->info_hashes().v1
);
5950 const auto torrentIDv2
= TorrentID::fromSHA256Hash(a
->metadata
->info_hashes().v2
);
5951 TorrentImpl
*torrent1
= m_torrents
.value(torrentIDv1
);
5952 TorrentImpl
*torrent2
= m_torrents
.value(torrentIDv2
);
5956 deleteTorrent(torrentIDv1
);
5958 cancelDownloadMetadata(torrentIDv1
);
5960 invokeAsync([torrentHandle
= torrent2
->nativeHandle(), metadata
= a
->metadata
]
5964 torrentHandle
.set_metadata(metadata
->info_section());
5966 catch (const std::exception
&) {}
5972 cancelDownloadMetadata(torrentIDv2
);
5974 invokeAsync([torrentHandle
= torrent1
->nativeHandle(), metadata
= a
->metadata
]
5978 torrentHandle
.set_metadata(metadata
->info_section());
5980 catch (const std::exception
&) {}
5985 cancelDownloadMetadata(torrentIDv1
);
5986 cancelDownloadMetadata(torrentIDv2
);
5989 if (!torrent1
|| !torrent2
)
5990 emit
metadataDownloaded(TorrentInfo(*a
->metadata
));
5994 void SessionImpl::processTrackerStatuses()
5996 if (m_updatedTrackerEntries
.isEmpty())
5999 for (auto it
= m_updatedTrackerEntries
.cbegin(); it
!= m_updatedTrackerEntries
.cend(); ++it
)
6001 invokeAsync([this, torrentHandle
= it
.key(), updatedTrackers
= it
.value()]() mutable
6005 std::vector
<lt::announce_entry
> nativeTrackers
= torrentHandle
.trackers();
6006 invoke([this, torrentHandle
, nativeTrackers
= std::move(nativeTrackers
)
6007 , updatedTrackers
= std::move(updatedTrackers
)]
6009 TorrentImpl
*torrent
= m_torrents
.value(torrentHandle
.info_hash());
6013 QHash
<QString
, TrackerEntry
> updatedTrackerEntries
;
6014 updatedTrackerEntries
.reserve(updatedTrackers
.size());
6015 for (const lt::announce_entry
&announceEntry
: nativeTrackers
)
6017 const auto updatedTrackersIter
= updatedTrackers
.find(announceEntry
.url
);
6018 if (updatedTrackersIter
== updatedTrackers
.end())
6021 const QMap
<TrackerEntry::Endpoint
, int> &updateInfo
= updatedTrackersIter
.value();
6022 TrackerEntry trackerEntry
= torrent
->updateTrackerEntry(announceEntry
, updateInfo
);
6023 #if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0))
6024 updatedTrackerEntries
[trackerEntry
.url
] = std::move(trackerEntry
);
6026 updatedTrackerEntries
.emplace(trackerEntry
.url
, std::move(trackerEntry
));
6030 emit
trackerEntriesUpdated(torrent
, updatedTrackerEntries
);
6033 catch (const std::exception
&)
6039 m_updatedTrackerEntries
.clear();
6042 void SessionImpl::saveStatistics() const
6044 if (!m_isStatisticsDirty
)
6047 const QVariantHash stats
{
6048 {u
"AlltimeDL"_qs
, m_status
.allTimeDownload
},
6049 {u
"AlltimeUL"_qs
, m_status
.allTimeUpload
}};
6050 std::unique_ptr
<QSettings
> settings
= Profile::instance()->applicationSettings(u
"qBittorrent-data"_qs
);
6051 settings
->setValue(u
"Stats/AllStats"_qs
, stats
);
6053 m_statisticsLastUpdateTimer
.start();
6054 m_isStatisticsDirty
= false;
6057 void SessionImpl::loadStatistics()
6059 const std::unique_ptr
<QSettings
> settings
= Profile::instance()->applicationSettings(u
"qBittorrent-data"_qs
);
6060 const QVariantHash value
= settings
->value(u
"Stats/AllStats"_qs
).toHash();
6062 m_previouslyDownloaded
= value
[u
"AlltimeDL"_qs
].toLongLong();
6063 m_previouslyUploaded
= value
[u
"AlltimeUL"_qs
].toLongLong();