WebUI: Provide 'Merge trackers to existing torrent' option
[qBittorrent.git] / src / base / bittorrent / sessionimpl.h
blobe9124de1ff97b7cf5f45b18e1c78064f37ea8b1a
1 /*
2 * Bittorrent Client using Qt and libtorrent.
3 * Copyright (C) 2015-2024 Vladimir Golovnev <glassez@yandex.ru>
4 * Copyright (C) 2006 Christophe Dumez <chris@qbittorrent.org>
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License
8 * as published by the Free Software Foundation; either version 2
9 * of the License, or (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20 * In addition, as a special exception, the copyright holders give permission to
21 * link this program with the OpenSSL project's "OpenSSL" library (or with
22 * modified versions of it that use the same license as the "OpenSSL" library),
23 * and distribute the linked executables. You must obey the GNU General Public
24 * License in all respects for all of the code used other than "OpenSSL". If you
25 * modify file(s), you may extend this exception to your version of the file(s),
26 * but you are not obligated to do so. If you do not wish to do so, delete this
27 * exception statement from your version.
30 #pragma once
32 #include <utility>
33 #include <vector>
35 #include <libtorrent/fwd.hpp>
36 #include <libtorrent/portmap.hpp>
37 #include <libtorrent/torrent_handle.hpp>
39 #include <QtContainerFwd>
40 #include <QDateTime>
41 #include <QElapsedTimer>
42 #include <QHash>
43 #include <QList>
44 #include <QMap>
45 #include <QPointer>
46 #include <QSet>
48 #include "base/path.h"
49 #include "base/settingvalue.h"
50 #include "base/utils/thread.h"
51 #include "addtorrentparams.h"
52 #include "cachestatus.h"
53 #include "categoryoptions.h"
54 #include "session.h"
55 #include "sessionstatus.h"
56 #include "torrentinfo.h"
57 #include "trackerentrystatus.h"
59 class QString;
60 class QThread;
61 class QThreadPool;
62 class QTimer;
63 class QUrl;
65 class BandwidthScheduler;
66 class FileSearcher;
67 class FilterParserThread;
68 class NativeSessionExtension;
70 namespace BitTorrent
72 enum class MoveStorageMode;
73 enum class MoveStorageContext;
75 class InfoHash;
76 class ResumeDataStorage;
77 class Torrent;
78 class TorrentContentRemover;
79 class TorrentDescriptor;
80 class TorrentImpl;
81 class Tracker;
83 struct LoadTorrentParams;
84 struct TrackerEntry;
86 struct SessionMetricIndices
88 struct
90 int hasIncomingConnections = -1;
91 int sentPayloadBytes = -1;
92 int recvPayloadBytes = -1;
93 int sentBytes = -1;
94 int recvBytes = -1;
95 int sentIPOverheadBytes = -1;
96 int recvIPOverheadBytes = -1;
97 int sentTrackerBytes = -1;
98 int recvTrackerBytes = -1;
99 int recvRedundantBytes = -1;
100 int recvFailedBytes = -1;
101 } net;
103 struct
105 int numPeersConnected = -1;
106 int numPeersUpDisk = -1;
107 int numPeersDownDisk = -1;
108 } peer;
110 struct
112 int dhtBytesIn = -1;
113 int dhtBytesOut = -1;
114 int dhtNodes = -1;
115 } dht;
117 struct
119 int diskBlocksInUse = -1;
120 int numBlocksRead = -1;
121 #ifndef QBT_USES_LIBTORRENT2
122 int numBlocksCacheHits = -1;
123 #endif
124 int writeJobs = -1;
125 int readJobs = -1;
126 int hashJobs = -1;
127 int queuedDiskJobs = -1;
128 int diskJobTime = -1;
129 } disk;
132 class SessionImpl final : public Session
134 Q_OBJECT
135 Q_DISABLE_COPY_MOVE(SessionImpl)
137 public:
138 Path savePath() const override;
139 void setSavePath(const Path &path) override;
140 Path downloadPath() const override;
141 void setDownloadPath(const Path &path) override;
142 bool isDownloadPathEnabled() const override;
143 void setDownloadPathEnabled(bool enabled) override;
145 QStringList categories() const override;
146 CategoryOptions categoryOptions(const QString &categoryName) const override;
147 Path categorySavePath(const QString &categoryName) const override;
148 Path categorySavePath(const QString &categoryName, const CategoryOptions &options) const override;
149 Path categoryDownloadPath(const QString &categoryName) const override;
150 Path categoryDownloadPath(const QString &categoryName, const CategoryOptions &options) const override;
151 bool addCategory(const QString &name, const CategoryOptions &options = {}) override;
152 bool editCategory(const QString &name, const CategoryOptions &options) override;
153 bool removeCategory(const QString &name) override;
154 bool isSubcategoriesEnabled() const override;
155 void setSubcategoriesEnabled(bool value) override;
156 bool useCategoryPathsInManualMode() const override;
157 void setUseCategoryPathsInManualMode(bool value) override;
159 Path suggestedSavePath(const QString &categoryName, std::optional<bool> useAutoTMM) const override;
160 Path suggestedDownloadPath(const QString &categoryName, std::optional<bool> useAutoTMM) const override;
162 TagSet tags() const override;
163 bool hasTag(const Tag &tag) const override;
164 bool addTag(const Tag &tag) override;
165 bool removeTag(const Tag &tag) override;
167 bool isAutoTMMDisabledByDefault() const override;
168 void setAutoTMMDisabledByDefault(bool value) override;
169 bool isDisableAutoTMMWhenCategoryChanged() const override;
170 void setDisableAutoTMMWhenCategoryChanged(bool value) override;
171 bool isDisableAutoTMMWhenDefaultSavePathChanged() const override;
172 void setDisableAutoTMMWhenDefaultSavePathChanged(bool value) override;
173 bool isDisableAutoTMMWhenCategorySavePathChanged() const override;
174 void setDisableAutoTMMWhenCategorySavePathChanged(bool value) override;
176 qreal globalMaxRatio() const override;
177 void setGlobalMaxRatio(qreal ratio) override;
178 int globalMaxSeedingMinutes() const override;
179 void setGlobalMaxSeedingMinutes(int minutes) override;
180 int globalMaxInactiveSeedingMinutes() const override;
181 void setGlobalMaxInactiveSeedingMinutes(int minutes) override;
182 ShareLimitAction shareLimitAction() const override;
183 void setShareLimitAction(ShareLimitAction act) override;
185 QString getDHTBootstrapNodes() const override;
186 void setDHTBootstrapNodes(const QString &nodes) override;
187 bool isDHTEnabled() const override;
188 void setDHTEnabled(bool enabled) override;
189 bool isLSDEnabled() const override;
190 void setLSDEnabled(bool enabled) override;
191 bool isPeXEnabled() const override;
192 void setPeXEnabled(bool enabled) override;
193 bool isAddTorrentToQueueTop() const override;
194 void setAddTorrentToQueueTop(bool value) override;
195 bool isAddTorrentStopped() const override;
196 void setAddTorrentStopped(bool value) override;
197 Torrent::StopCondition torrentStopCondition() const override;
198 void setTorrentStopCondition(Torrent::StopCondition stopCondition) override;
199 TorrentContentLayout torrentContentLayout() const override;
200 void setTorrentContentLayout(TorrentContentLayout value) override;
201 bool isTrackerEnabled() const override;
202 void setTrackerEnabled(bool enabled) override;
203 bool isAppendExtensionEnabled() const override;
204 void setAppendExtensionEnabled(bool enabled) override;
205 bool isUnwantedFolderEnabled() const override;
206 void setUnwantedFolderEnabled(bool enabled) override;
207 int refreshInterval() const override;
208 void setRefreshInterval(int value) override;
209 bool isPreallocationEnabled() const override;
210 void setPreallocationEnabled(bool enabled) override;
211 Path torrentExportDirectory() const override;
212 void setTorrentExportDirectory(const Path &path) override;
213 Path finishedTorrentExportDirectory() const override;
214 void setFinishedTorrentExportDirectory(const Path &path) override;
216 int globalDownloadSpeedLimit() const override;
217 void setGlobalDownloadSpeedLimit(int limit) override;
218 int globalUploadSpeedLimit() const override;
219 void setGlobalUploadSpeedLimit(int limit) override;
220 int altGlobalDownloadSpeedLimit() const override;
221 void setAltGlobalDownloadSpeedLimit(int limit) override;
222 int altGlobalUploadSpeedLimit() const override;
223 void setAltGlobalUploadSpeedLimit(int limit) override;
224 int downloadSpeedLimit() const override;
225 void setDownloadSpeedLimit(int limit) override;
226 int uploadSpeedLimit() const override;
227 void setUploadSpeedLimit(int limit) override;
228 bool isAltGlobalSpeedLimitEnabled() const override;
229 void setAltGlobalSpeedLimitEnabled(bool enabled) override;
230 bool isBandwidthSchedulerEnabled() const override;
231 void setBandwidthSchedulerEnabled(bool enabled) override;
233 bool isPerformanceWarningEnabled() const override;
234 void setPerformanceWarningEnabled(bool enable) override;
235 int saveResumeDataInterval() const override;
236 void setSaveResumeDataInterval(int value) override;
237 int shutdownTimeout() const override;
238 void setShutdownTimeout(int value) override;
239 int port() const override;
240 void setPort(int port) override;
241 bool isSSLEnabled() const override;
242 void setSSLEnabled(bool enabled) override;
243 int sslPort() const override;
244 void setSSLPort(int port) override;
245 QString networkInterface() const override;
246 void setNetworkInterface(const QString &iface) override;
247 QString networkInterfaceName() const override;
248 void setNetworkInterfaceName(const QString &name) override;
249 QString networkInterfaceAddress() const override;
250 void setNetworkInterfaceAddress(const QString &address) override;
251 int encryption() const override;
252 void setEncryption(int state) override;
253 int maxActiveCheckingTorrents() const override;
254 void setMaxActiveCheckingTorrents(int val) override;
255 bool isI2PEnabled() const override;
256 void setI2PEnabled(bool enabled) override;
257 QString I2PAddress() const override;
258 void setI2PAddress(const QString &address) override;
259 int I2PPort() const override;
260 void setI2PPort(int port) override;
261 bool I2PMixedMode() const override;
262 void setI2PMixedMode(bool enabled) override;
263 int I2PInboundQuantity() const override;
264 void setI2PInboundQuantity(int value) override;
265 int I2POutboundQuantity() const override;
266 void setI2POutboundQuantity(int value) override;
267 int I2PInboundLength() const override;
268 void setI2PInboundLength(int value) override;
269 int I2POutboundLength() const override;
270 void setI2POutboundLength(int value) override;
271 bool isProxyPeerConnectionsEnabled() const override;
272 void setProxyPeerConnectionsEnabled(bool enabled) override;
273 ChokingAlgorithm chokingAlgorithm() const override;
274 void setChokingAlgorithm(ChokingAlgorithm mode) override;
275 SeedChokingAlgorithm seedChokingAlgorithm() const override;
276 void setSeedChokingAlgorithm(SeedChokingAlgorithm mode) override;
277 bool isAddTrackersEnabled() const override;
278 void setAddTrackersEnabled(bool enabled) override;
279 QString additionalTrackers() const override;
280 void setAdditionalTrackers(const QString &trackers) override;
281 bool isIPFilteringEnabled() const override;
282 void setIPFilteringEnabled(bool enabled) override;
283 Path IPFilterFile() const override;
284 void setIPFilterFile(const Path &path) override;
285 bool announceToAllTrackers() const override;
286 void setAnnounceToAllTrackers(bool val) override;
287 bool announceToAllTiers() const override;
288 void setAnnounceToAllTiers(bool val) override;
289 int peerTurnover() const override;
290 void setPeerTurnover(int val) override;
291 int peerTurnoverCutoff() const override;
292 void setPeerTurnoverCutoff(int val) override;
293 int peerTurnoverInterval() const override;
294 void setPeerTurnoverInterval(int val) override;
295 int requestQueueSize() const override;
296 void setRequestQueueSize(int val) override;
297 int asyncIOThreads() const override;
298 void setAsyncIOThreads(int num) override;
299 int hashingThreads() const override;
300 void setHashingThreads(int num) override;
301 int filePoolSize() const override;
302 void setFilePoolSize(int size) override;
303 int checkingMemUsage() const override;
304 void setCheckingMemUsage(int size) override;
305 int diskCacheSize() const override;
306 void setDiskCacheSize(int size) override;
307 int diskCacheTTL() const override;
308 void setDiskCacheTTL(int ttl) override;
309 qint64 diskQueueSize() const override;
310 void setDiskQueueSize(qint64 size) override;
311 DiskIOType diskIOType() const override;
312 void setDiskIOType(DiskIOType type) override;
313 DiskIOReadMode diskIOReadMode() const override;
314 void setDiskIOReadMode(DiskIOReadMode mode) override;
315 DiskIOWriteMode diskIOWriteMode() const override;
316 void setDiskIOWriteMode(DiskIOWriteMode mode) override;
317 bool isCoalesceReadWriteEnabled() const override;
318 void setCoalesceReadWriteEnabled(bool enabled) override;
319 bool usePieceExtentAffinity() const override;
320 void setPieceExtentAffinity(bool enabled) override;
321 bool isSuggestModeEnabled() const override;
322 void setSuggestMode(bool mode) override;
323 int sendBufferWatermark() const override;
324 void setSendBufferWatermark(int value) override;
325 int sendBufferLowWatermark() const override;
326 void setSendBufferLowWatermark(int value) override;
327 int sendBufferWatermarkFactor() const override;
328 void setSendBufferWatermarkFactor(int value) override;
329 int connectionSpeed() const override;
330 void setConnectionSpeed(int value) override;
331 int socketSendBufferSize() const override;
332 void setSocketSendBufferSize(int value) override;
333 int socketReceiveBufferSize() const override;
334 void setSocketReceiveBufferSize(int value) override;
335 int socketBacklogSize() const override;
336 void setSocketBacklogSize(int value) override;
337 bool isAnonymousModeEnabled() const override;
338 void setAnonymousModeEnabled(bool enabled) override;
339 bool isQueueingSystemEnabled() const override;
340 void setQueueingSystemEnabled(bool enabled) override;
341 bool ignoreSlowTorrentsForQueueing() const override;
342 void setIgnoreSlowTorrentsForQueueing(bool ignore) override;
343 int downloadRateForSlowTorrents() const override;
344 void setDownloadRateForSlowTorrents(int rateInKibiBytes) override;
345 int uploadRateForSlowTorrents() const override;
346 void setUploadRateForSlowTorrents(int rateInKibiBytes) override;
347 int slowTorrentsInactivityTimer() const override;
348 void setSlowTorrentsInactivityTimer(int timeInSeconds) override;
349 int outgoingPortsMin() const override;
350 void setOutgoingPortsMin(int min) override;
351 int outgoingPortsMax() const override;
352 void setOutgoingPortsMax(int max) override;
353 int UPnPLeaseDuration() const override;
354 void setUPnPLeaseDuration(int duration) override;
355 int peerToS() const override;
356 void setPeerToS(int value) override;
357 bool ignoreLimitsOnLAN() const override;
358 void setIgnoreLimitsOnLAN(bool ignore) override;
359 bool includeOverheadInLimits() const override;
360 void setIncludeOverheadInLimits(bool include) override;
361 QString announceIP() const override;
362 void setAnnounceIP(const QString &ip) override;
363 int maxConcurrentHTTPAnnounces() const override;
364 void setMaxConcurrentHTTPAnnounces(int value) override;
365 bool isReannounceWhenAddressChangedEnabled() const override;
366 void setReannounceWhenAddressChangedEnabled(bool enabled) override;
367 void reannounceToAllTrackers() const override;
368 int stopTrackerTimeout() const override;
369 void setStopTrackerTimeout(int value) override;
370 int maxConnections() const override;
371 void setMaxConnections(int max) override;
372 int maxConnectionsPerTorrent() const override;
373 void setMaxConnectionsPerTorrent(int max) override;
374 int maxUploads() const override;
375 void setMaxUploads(int max) override;
376 int maxUploadsPerTorrent() const override;
377 void setMaxUploadsPerTorrent(int max) override;
378 int maxActiveDownloads() const override;
379 void setMaxActiveDownloads(int max) override;
380 int maxActiveUploads() const override;
381 void setMaxActiveUploads(int max) override;
382 int maxActiveTorrents() const override;
383 void setMaxActiveTorrents(int max) override;
384 BTProtocol btProtocol() const override;
385 void setBTProtocol(BTProtocol protocol) override;
386 bool isUTPRateLimited() const override;
387 void setUTPRateLimited(bool limited) override;
388 MixedModeAlgorithm utpMixedMode() const override;
389 void setUtpMixedMode(MixedModeAlgorithm mode) override;
390 bool isIDNSupportEnabled() const override;
391 void setIDNSupportEnabled(bool enabled) override;
392 bool multiConnectionsPerIpEnabled() const override;
393 void setMultiConnectionsPerIpEnabled(bool enabled) override;
394 bool validateHTTPSTrackerCertificate() const override;
395 void setValidateHTTPSTrackerCertificate(bool enabled) override;
396 bool isSSRFMitigationEnabled() const override;
397 void setSSRFMitigationEnabled(bool enabled) override;
398 bool blockPeersOnPrivilegedPorts() const override;
399 void setBlockPeersOnPrivilegedPorts(bool enabled) override;
400 bool isTrackerFilteringEnabled() const override;
401 void setTrackerFilteringEnabled(bool enabled) override;
402 bool isExcludedFileNamesEnabled() const override;
403 void setExcludedFileNamesEnabled(bool enabled) override;
404 QStringList excludedFileNames() const override;
405 void setExcludedFileNames(const QStringList &excludedFileNames) override;
406 void applyFilenameFilter(const PathList &files, QList<BitTorrent::DownloadPriority> &priorities) override;
407 QStringList bannedIPs() const override;
408 void setBannedIPs(const QStringList &newList) override;
409 ResumeDataStorageType resumeDataStorageType() const override;
410 void setResumeDataStorageType(ResumeDataStorageType type) override;
411 bool isMergeTrackersEnabled() const override;
412 void setMergeTrackersEnabled(bool enabled) override;
413 bool isStartPaused() const override;
414 void setStartPaused(bool value) override;
415 TorrentContentRemoveOption torrentContentRemoveOption() const override;
416 void setTorrentContentRemoveOption(TorrentContentRemoveOption option) override;
418 bool isRestored() const override;
420 bool isPaused() const override;
421 void pause() override;
422 void resume() override;
424 Torrent *getTorrent(const TorrentID &id) const override;
425 Torrent *findTorrent(const InfoHash &infoHash) const override;
426 QList<Torrent *> torrents() const override;
427 qsizetype torrentsCount() const override;
428 const SessionStatus &status() const override;
429 const CacheStatus &cacheStatus() const override;
430 bool isListening() const override;
432 void banIP(const QString &ip) override;
434 bool isKnownTorrent(const InfoHash &infoHash) const override;
435 bool addTorrent(const TorrentDescriptor &torrentDescr, const AddTorrentParams &params = {}) override;
436 bool removeTorrent(const TorrentID &id, TorrentRemoveOption deleteOption = TorrentRemoveOption::KeepContent) override;
437 bool downloadMetadata(const TorrentDescriptor &torrentDescr) override;
438 bool cancelDownloadMetadata(const TorrentID &id) override;
440 void increaseTorrentsQueuePos(const QList<TorrentID> &ids) override;
441 void decreaseTorrentsQueuePos(const QList<TorrentID> &ids) override;
442 void topTorrentsQueuePos(const QList<TorrentID> &ids) override;
443 void bottomTorrentsQueuePos(const QList<TorrentID> &ids) override;
445 // Torrent interface
446 void handleTorrentResumeDataRequested(const TorrentImpl *torrent);
447 void handleTorrentShareLimitChanged(TorrentImpl *torrent);
448 void handleTorrentNameChanged(TorrentImpl *torrent);
449 void handleTorrentSavePathChanged(TorrentImpl *torrent);
450 void handleTorrentCategoryChanged(TorrentImpl *torrent, const QString &oldCategory);
451 void handleTorrentTagAdded(TorrentImpl *torrent, const Tag &tag);
452 void handleTorrentTagRemoved(TorrentImpl *torrent, const Tag &tag);
453 void handleTorrentSavingModeChanged(TorrentImpl *torrent);
454 void handleTorrentMetadataReceived(TorrentImpl *torrent);
455 void handleTorrentStopped(TorrentImpl *torrent);
456 void handleTorrentStarted(TorrentImpl *torrent);
457 void handleTorrentChecked(TorrentImpl *torrent);
458 void handleTorrentFinished(TorrentImpl *torrent);
459 void handleTorrentTrackersAdded(TorrentImpl *torrent, const QList<TrackerEntry> &newTrackers);
460 void handleTorrentTrackersRemoved(TorrentImpl *torrent, const QStringList &deletedTrackers);
461 void handleTorrentTrackersChanged(TorrentImpl *torrent);
462 void handleTorrentUrlSeedsAdded(TorrentImpl *torrent, const QList<QUrl> &newUrlSeeds);
463 void handleTorrentUrlSeedsRemoved(TorrentImpl *torrent, const QList<QUrl> &urlSeeds);
464 void handleTorrentResumeDataReady(TorrentImpl *torrent, const LoadTorrentParams &data);
465 void handleTorrentInfoHashChanged(TorrentImpl *torrent, const InfoHash &prevInfoHash);
466 void handleTorrentStorageMovingStateChanged(TorrentImpl *torrent);
468 bool addMoveTorrentStorageJob(TorrentImpl *torrent, const Path &newPath, MoveStorageMode mode, MoveStorageContext context);
470 void findIncompleteFiles(const TorrentInfo &torrentInfo, const Path &savePath
471 , const Path &downloadPath, const PathList &filePaths = {}) const;
473 void enablePortMapping();
474 void disablePortMapping();
475 void addMappedPorts(const QSet<quint16> &ports);
476 void removeMappedPorts(const QSet<quint16> &ports);
478 template <typename Func>
479 void invoke(Func &&func)
481 QMetaObject::invokeMethod(this, std::forward<Func>(func), Qt::QueuedConnection);
484 void invokeAsync(std::function<void ()> func);
486 signals:
487 void addTorrentAlertsReceived(qsizetype count);
489 private slots:
490 void configureDeferred();
491 void readAlerts();
492 void enqueueRefresh();
493 void generateResumeData();
494 void handleIPFilterParsed(int ruleCount);
495 void handleIPFilterError();
496 void fileSearchFinished(const TorrentID &id, const Path &savePath, const PathList &fileNames);
497 void torrentContentRemovingFinished(const QString &torrentName, const QString &errorMessage);
499 private:
500 struct ResumeSessionContext;
502 struct MoveStorageJob
504 lt::torrent_handle torrentHandle;
505 Path path;
506 MoveStorageMode mode {};
507 MoveStorageContext context {};
510 struct RemovingTorrentData
512 QString name;
513 Path contentStoragePath;
514 PathList fileNames;
515 TorrentRemoveOption removeOption {};
518 explicit SessionImpl(QObject *parent = nullptr);
519 ~SessionImpl();
521 bool hasPerTorrentRatioLimit() const;
522 bool hasPerTorrentSeedingTimeLimit() const;
523 bool hasPerTorrentInactiveSeedingTimeLimit() const;
525 // Session configuration
526 Q_INVOKABLE void configure();
527 void configureComponents();
528 void initializeNativeSession();
529 lt::settings_pack loadLTSettings() const;
530 void applyNetworkInterfacesSettings(lt::settings_pack &settingsPack) const;
531 void configurePeerClasses();
532 void initMetrics();
533 void applyBandwidthLimits();
534 void processBannedIPs(lt::ip_filter &filter);
535 QStringList getListeningIPs() const;
536 void configureListeningInterface();
537 void enableTracker(bool enable);
538 void enableBandwidthScheduler();
539 void populateAdditionalTrackers();
540 void enableIPFilter();
541 void disableIPFilter();
542 void processTrackerStatuses();
543 void processTorrentShareLimits(TorrentImpl *torrent);
544 void populateExcludedFileNamesRegExpList();
545 void prepareStartup();
546 void handleLoadedResumeData(ResumeSessionContext *context);
547 void processNextResumeData(ResumeSessionContext *context);
548 void endStartup(ResumeSessionContext *context);
550 LoadTorrentParams initLoadTorrentParams(const AddTorrentParams &addTorrentParams);
551 bool addTorrent_impl(const TorrentDescriptor &source, const AddTorrentParams &addTorrentParams);
553 void updateSeedingLimitTimer();
554 void exportTorrentFile(const Torrent *torrent, const Path &folderPath);
556 void handleAlert(const lt::alert *alert);
557 void dispatchTorrentAlert(const lt::torrent_alert *alert);
558 void handleAddTorrentAlert(const lt::add_torrent_alert *alert);
559 void handleStateUpdateAlert(const lt::state_update_alert *alert);
560 void handleMetadataReceivedAlert(const lt::metadata_received_alert *alert);
561 void handleFileErrorAlert(const lt::file_error_alert *alert);
562 void handleTorrentRemovedAlert(const lt::torrent_removed_alert *alert);
563 void handleTorrentDeletedAlert(const lt::torrent_deleted_alert *alert);
564 void handleTorrentDeleteFailedAlert(const lt::torrent_delete_failed_alert *alert);
565 void handleTorrentNeedCertAlert(const lt::torrent_need_cert_alert *alert);
566 void handlePortmapWarningAlert(const lt::portmap_error_alert *alert);
567 void handlePortmapAlert(const lt::portmap_alert *alert);
568 void handlePeerBlockedAlert(const lt::peer_blocked_alert *alert);
569 void handlePeerBanAlert(const lt::peer_ban_alert *alert);
570 void handleUrlSeedAlert(const lt::url_seed_alert *alert);
571 void handleListenSucceededAlert(const lt::listen_succeeded_alert *alert);
572 void handleListenFailedAlert(const lt::listen_failed_alert *alert);
573 void handleExternalIPAlert(const lt::external_ip_alert *alert);
574 void handleSessionErrorAlert(const lt::session_error_alert *alert) const;
575 void handleSessionStatsAlert(const lt::session_stats_alert *alert);
576 void handleAlertsDroppedAlert(const lt::alerts_dropped_alert *alert) const;
577 void handleStorageMovedAlert(const lt::storage_moved_alert *alert);
578 void handleStorageMovedFailedAlert(const lt::storage_moved_failed_alert *alert);
579 void handleSocks5Alert(const lt::socks5_alert *alert) const;
580 void handleI2PAlert(const lt::i2p_alert *alert) const;
581 void handleTrackerAlert(const lt::tracker_alert *alert);
582 #ifdef QBT_USES_LIBTORRENT2
583 void handleTorrentConflictAlert(const lt::torrent_conflict_alert *alert);
584 #endif
586 TorrentImpl *createTorrent(const lt::torrent_handle &nativeHandle, const LoadTorrentParams &params);
588 void saveResumeData();
589 void saveTorrentsQueue();
590 void removeTorrentsQueue();
592 std::vector<lt::alert *> getPendingAlerts(lt::time_duration time = lt::time_duration::zero()) const;
594 void moveTorrentStorage(const MoveStorageJob &job) const;
595 void handleMoveTorrentStorageJobFinished(const Path &newPath);
597 void loadCategories();
598 void storeCategories() const;
599 void upgradeCategories();
600 DownloadPathOption resolveCategoryDownloadPathOption(const QString &categoryName, const std::optional<DownloadPathOption> &option) const;
602 void saveStatistics() const;
603 void loadStatistics();
605 void updateTrackerEntryStatuses(lt::torrent_handle torrentHandle, QHash<std::string, QHash<lt::tcp::endpoint, QMap<int, int>>> updatedTrackers);
607 void handleRemovedTorrent(const TorrentID &torrentID, const QString &partfileRemoveError = {});
609 CachedSettingValue<QString> m_DHTBootstrapNodes;
610 CachedSettingValue<bool> m_isDHTEnabled;
611 CachedSettingValue<bool> m_isLSDEnabled;
612 CachedSettingValue<bool> m_isPeXEnabled;
613 CachedSettingValue<bool> m_isIPFilteringEnabled;
614 CachedSettingValue<bool> m_isTrackerFilteringEnabled;
615 CachedSettingValue<Path> m_IPFilterFile;
616 CachedSettingValue<bool> m_announceToAllTrackers;
617 CachedSettingValue<bool> m_announceToAllTiers;
618 CachedSettingValue<int> m_asyncIOThreads;
619 CachedSettingValue<int> m_hashingThreads;
620 CachedSettingValue<int> m_filePoolSize;
621 CachedSettingValue<int> m_checkingMemUsage;
622 CachedSettingValue<int> m_diskCacheSize;
623 CachedSettingValue<int> m_diskCacheTTL;
624 CachedSettingValue<qint64> m_diskQueueSize;
625 CachedSettingValue<DiskIOType> m_diskIOType;
626 CachedSettingValue<DiskIOReadMode> m_diskIOReadMode;
627 CachedSettingValue<DiskIOWriteMode> m_diskIOWriteMode;
628 CachedSettingValue<bool> m_coalesceReadWriteEnabled;
629 CachedSettingValue<bool> m_usePieceExtentAffinity;
630 CachedSettingValue<bool> m_isSuggestMode;
631 CachedSettingValue<int> m_sendBufferWatermark;
632 CachedSettingValue<int> m_sendBufferLowWatermark;
633 CachedSettingValue<int> m_sendBufferWatermarkFactor;
634 CachedSettingValue<int> m_connectionSpeed;
635 CachedSettingValue<int> m_socketSendBufferSize;
636 CachedSettingValue<int> m_socketReceiveBufferSize;
637 CachedSettingValue<int> m_socketBacklogSize;
638 CachedSettingValue<bool> m_isAnonymousModeEnabled;
639 CachedSettingValue<bool> m_isQueueingEnabled;
640 CachedSettingValue<int> m_maxActiveDownloads;
641 CachedSettingValue<int> m_maxActiveUploads;
642 CachedSettingValue<int> m_maxActiveTorrents;
643 CachedSettingValue<bool> m_ignoreSlowTorrentsForQueueing;
644 CachedSettingValue<int> m_downloadRateForSlowTorrents;
645 CachedSettingValue<int> m_uploadRateForSlowTorrents;
646 CachedSettingValue<int> m_slowTorrentsInactivityTimer;
647 CachedSettingValue<int> m_outgoingPortsMin;
648 CachedSettingValue<int> m_outgoingPortsMax;
649 CachedSettingValue<int> m_UPnPLeaseDuration;
650 CachedSettingValue<int> m_peerToS;
651 CachedSettingValue<bool> m_ignoreLimitsOnLAN;
652 CachedSettingValue<bool> m_includeOverheadInLimits;
653 CachedSettingValue<QString> m_announceIP;
654 CachedSettingValue<int> m_maxConcurrentHTTPAnnounces;
655 CachedSettingValue<bool> m_isReannounceWhenAddressChangedEnabled;
656 CachedSettingValue<int> m_stopTrackerTimeout;
657 CachedSettingValue<int> m_maxConnections;
658 CachedSettingValue<int> m_maxUploads;
659 CachedSettingValue<int> m_maxConnectionsPerTorrent;
660 CachedSettingValue<int> m_maxUploadsPerTorrent;
661 CachedSettingValue<BTProtocol> m_btProtocol;
662 CachedSettingValue<bool> m_isUTPRateLimited;
663 CachedSettingValue<MixedModeAlgorithm> m_utpMixedMode;
664 CachedSettingValue<bool> m_IDNSupportEnabled;
665 CachedSettingValue<bool> m_multiConnectionsPerIpEnabled;
666 CachedSettingValue<bool> m_validateHTTPSTrackerCertificate;
667 CachedSettingValue<bool> m_SSRFMitigationEnabled;
668 CachedSettingValue<bool> m_blockPeersOnPrivilegedPorts;
669 CachedSettingValue<bool> m_isAddTrackersEnabled;
670 CachedSettingValue<QString> m_additionalTrackers;
671 CachedSettingValue<qreal> m_globalMaxRatio;
672 CachedSettingValue<int> m_globalMaxSeedingMinutes;
673 CachedSettingValue<int> m_globalMaxInactiveSeedingMinutes;
674 CachedSettingValue<bool> m_isAddTorrentToQueueTop;
675 CachedSettingValue<bool> m_isAddTorrentStopped;
676 CachedSettingValue<Torrent::StopCondition> m_torrentStopCondition;
677 CachedSettingValue<TorrentContentLayout> m_torrentContentLayout;
678 CachedSettingValue<bool> m_isAppendExtensionEnabled;
679 CachedSettingValue<bool> m_isUnwantedFolderEnabled;
680 CachedSettingValue<int> m_refreshInterval;
681 CachedSettingValue<bool> m_isPreallocationEnabled;
682 CachedSettingValue<Path> m_torrentExportDirectory;
683 CachedSettingValue<Path> m_finishedTorrentExportDirectory;
684 CachedSettingValue<int> m_globalDownloadSpeedLimit;
685 CachedSettingValue<int> m_globalUploadSpeedLimit;
686 CachedSettingValue<int> m_altGlobalDownloadSpeedLimit;
687 CachedSettingValue<int> m_altGlobalUploadSpeedLimit;
688 CachedSettingValue<bool> m_isAltGlobalSpeedLimitEnabled;
689 CachedSettingValue<bool> m_isBandwidthSchedulerEnabled;
690 CachedSettingValue<bool> m_isPerformanceWarningEnabled;
691 CachedSettingValue<int> m_saveResumeDataInterval;
692 CachedSettingValue<int> m_shutdownTimeout;
693 CachedSettingValue<int> m_port;
694 CachedSettingValue<bool> m_sslEnabled;
695 CachedSettingValue<int> m_sslPort;
696 CachedSettingValue<QString> m_networkInterface;
697 CachedSettingValue<QString> m_networkInterfaceName;
698 CachedSettingValue<QString> m_networkInterfaceAddress;
699 CachedSettingValue<int> m_encryption;
700 CachedSettingValue<int> m_maxActiveCheckingTorrents;
701 CachedSettingValue<bool> m_isProxyPeerConnectionsEnabled;
702 CachedSettingValue<ChokingAlgorithm> m_chokingAlgorithm;
703 CachedSettingValue<SeedChokingAlgorithm> m_seedChokingAlgorithm;
704 CachedSettingValue<QStringList> m_storedTags;
705 CachedSettingValue<ShareLimitAction> m_shareLimitAction;
706 CachedSettingValue<Path> m_savePath;
707 CachedSettingValue<Path> m_downloadPath;
708 CachedSettingValue<bool> m_isDownloadPathEnabled;
709 CachedSettingValue<bool> m_isSubcategoriesEnabled;
710 CachedSettingValue<bool> m_useCategoryPathsInManualMode;
711 CachedSettingValue<bool> m_isAutoTMMDisabledByDefault;
712 CachedSettingValue<bool> m_isDisableAutoTMMWhenCategoryChanged;
713 CachedSettingValue<bool> m_isDisableAutoTMMWhenDefaultSavePathChanged;
714 CachedSettingValue<bool> m_isDisableAutoTMMWhenCategorySavePathChanged;
715 CachedSettingValue<bool> m_isTrackerEnabled;
716 CachedSettingValue<int> m_peerTurnover;
717 CachedSettingValue<int> m_peerTurnoverCutoff;
718 CachedSettingValue<int> m_peerTurnoverInterval;
719 CachedSettingValue<int> m_requestQueueSize;
720 CachedSettingValue<bool> m_isExcludedFileNamesEnabled;
721 CachedSettingValue<QStringList> m_excludedFileNames;
722 CachedSettingValue<QStringList> m_bannedIPs;
723 CachedSettingValue<ResumeDataStorageType> m_resumeDataStorageType;
724 CachedSettingValue<bool> m_isMergeTrackersEnabled;
725 CachedSettingValue<bool> m_isI2PEnabled;
726 CachedSettingValue<QString> m_I2PAddress;
727 CachedSettingValue<int> m_I2PPort;
728 CachedSettingValue<bool> m_I2PMixedMode;
729 CachedSettingValue<int> m_I2PInboundQuantity;
730 CachedSettingValue<int> m_I2POutboundQuantity;
731 CachedSettingValue<int> m_I2PInboundLength;
732 CachedSettingValue<int> m_I2POutboundLength;
733 CachedSettingValue<TorrentContentRemoveOption> m_torrentContentRemoveOption;
734 SettingValue<bool> m_startPaused;
736 lt::session *m_nativeSession = nullptr;
737 NativeSessionExtension *m_nativeSessionExtension = nullptr;
739 bool m_deferredConfigureScheduled = false;
740 bool m_IPFilteringConfigured = false;
741 mutable bool m_listenInterfaceConfigured = false;
743 bool m_isRestored = false;
744 bool m_isPaused = isStartPaused();
746 // Order is important. This needs to be declared after its CachedSettingsValue
747 // counterpart, because it uses it for initialization in the constructor
748 // initialization list.
749 const bool m_wasPexEnabled = m_isPeXEnabled;
751 int m_numResumeData = 0;
752 QList<TrackerEntry> m_additionalTrackerEntries;
753 QList<QRegularExpression> m_excludedFileNamesRegExpList;
755 // Statistics
756 mutable QElapsedTimer m_statisticsLastUpdateTimer;
757 mutable bool m_isStatisticsDirty = false;
758 qint64 m_previouslyUploaded = 0;
759 qint64 m_previouslyDownloaded = 0;
761 bool m_torrentsQueueChanged = false;
762 bool m_needSaveTorrentsQueue = false;
763 bool m_refreshEnqueued = false;
764 QTimer *m_seedingLimitTimer = nullptr;
765 QTimer *m_resumeDataTimer = nullptr;
766 // IP filtering
767 QPointer<FilterParserThread> m_filterParser;
768 QPointer<BandwidthScheduler> m_bwScheduler;
769 // Tracker
770 QPointer<Tracker> m_tracker;
772 Utils::Thread::UniquePtr m_ioThread;
773 QThreadPool *m_asyncWorker = nullptr;
774 ResumeDataStorage *m_resumeDataStorage = nullptr;
775 FileSearcher *m_fileSearcher = nullptr;
776 TorrentContentRemover *m_torrentContentRemover = nullptr;
778 QHash<TorrentID, lt::torrent_handle> m_downloadedMetadata;
780 QHash<TorrentID, TorrentImpl *> m_torrents;
781 QHash<TorrentID, TorrentImpl *> m_hybridTorrentsByAltID;
782 QHash<TorrentID, LoadTorrentParams> m_loadingTorrents;
783 QHash<TorrentID, RemovingTorrentData> m_removingTorrents;
784 QHash<TorrentID, TorrentID> m_changedTorrentIDs;
785 QMap<QString, CategoryOptions> m_categories;
786 TagSet m_tags;
788 qsizetype m_receivedAddTorrentAlertsCount = 0;
789 QList<Torrent *> m_loadedTorrents;
791 // This field holds amounts of peers reported by trackers in their responses to announces
792 // (torrent.tracker_name.tracker_local_endpoint.protocol_version.num_peers)
793 QHash<lt::torrent_handle, QHash<std::string, QHash<lt::tcp::endpoint, QMap<int, int>>>> m_updatedTrackerStatuses;
795 // I/O errored torrents
796 QSet<TorrentID> m_recentErroredTorrents;
797 QTimer *m_recentErroredTorrentsTimer = nullptr;
799 SessionMetricIndices m_metricIndices;
800 lt::time_point m_statsLastTimestamp = lt::clock_type::now();
802 SessionStatus m_status;
803 CacheStatus m_cacheStatus;
805 QList<MoveStorageJob> m_moveStorageQueue;
807 QString m_lastExternalIP;
809 bool m_needUpgradeDownloadPath = false;
811 // All port mapping related routines are invoked from working thread
812 // so there are no synchronization used. If multithreaded access is
813 // ever required, synchronization should also be provided.
814 bool m_isPortMappingEnabled = false;
815 QHash<quint16, std::vector<lt::port_mapping_t>> m_mappedPorts;
817 QTimer *m_wakeupCheckTimer = nullptr;
818 QDateTime m_wakeupCheckTimestamp;
820 QList<TorrentImpl *> m_pendingFinishedTorrents;
822 friend void Session::initInstance();
823 friend void Session::freeInstance();
824 friend Session *Session::instance();
825 static Session *m_instance;