Add ability to pause/resume entire BitTorrent session
[qBittorrent.git] / src / base / bittorrent / sessionimpl.h
blob334c0baf9e28d8f27db7e03b7c604f54c7a5dd0f
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 <QMap>
44 #include <QPointer>
45 #include <QSet>
46 #include <QVector>
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 TorrentDescriptor;
79 class TorrentImpl;
80 class Tracker;
82 struct LoadTorrentParams;
83 struct TrackerEntry;
85 struct SessionMetricIndices
87 struct
89 int hasIncomingConnections = -1;
90 int sentPayloadBytes = -1;
91 int recvPayloadBytes = -1;
92 int sentBytes = -1;
93 int recvBytes = -1;
94 int sentIPOverheadBytes = -1;
95 int recvIPOverheadBytes = -1;
96 int sentTrackerBytes = -1;
97 int recvTrackerBytes = -1;
98 int recvRedundantBytes = -1;
99 int recvFailedBytes = -1;
100 } net;
102 struct
104 int numPeersConnected = -1;
105 int numPeersUpDisk = -1;
106 int numPeersDownDisk = -1;
107 } peer;
109 struct
111 int dhtBytesIn = -1;
112 int dhtBytesOut = -1;
113 int dhtNodes = -1;
114 } dht;
116 struct
118 int diskBlocksInUse = -1;
119 int numBlocksRead = -1;
120 #ifndef QBT_USES_LIBTORRENT2
121 int numBlocksCacheHits = -1;
122 #endif
123 int writeJobs = -1;
124 int readJobs = -1;
125 int hashJobs = -1;
126 int queuedDiskJobs = -1;
127 int diskJobTime = -1;
128 } disk;
131 class SessionImpl final : public Session
133 Q_OBJECT
134 Q_DISABLE_COPY_MOVE(SessionImpl)
136 public:
137 Path savePath() const override;
138 void setSavePath(const Path &path) override;
139 Path downloadPath() const override;
140 void setDownloadPath(const Path &path) override;
141 bool isDownloadPathEnabled() const override;
142 void setDownloadPathEnabled(bool enabled) override;
144 QStringList categories() const override;
145 CategoryOptions categoryOptions(const QString &categoryName) const override;
146 Path categorySavePath(const QString &categoryName) const override;
147 Path categorySavePath(const QString &categoryName, const CategoryOptions &options) const override;
148 Path categoryDownloadPath(const QString &categoryName) const override;
149 Path categoryDownloadPath(const QString &categoryName, const CategoryOptions &options) const override;
150 bool addCategory(const QString &name, const CategoryOptions &options = {}) override;
151 bool editCategory(const QString &name, const CategoryOptions &options) override;
152 bool removeCategory(const QString &name) override;
153 bool isSubcategoriesEnabled() const override;
154 void setSubcategoriesEnabled(bool value) override;
155 bool useCategoryPathsInManualMode() const override;
156 void setUseCategoryPathsInManualMode(bool value) override;
158 Path suggestedSavePath(const QString &categoryName, std::optional<bool> useAutoTMM) const override;
159 Path suggestedDownloadPath(const QString &categoryName, std::optional<bool> useAutoTMM) const override;
161 TagSet tags() const override;
162 bool hasTag(const Tag &tag) const override;
163 bool addTag(const Tag &tag) override;
164 bool removeTag(const Tag &tag) override;
166 bool isAutoTMMDisabledByDefault() const override;
167 void setAutoTMMDisabledByDefault(bool value) override;
168 bool isDisableAutoTMMWhenCategoryChanged() const override;
169 void setDisableAutoTMMWhenCategoryChanged(bool value) override;
170 bool isDisableAutoTMMWhenDefaultSavePathChanged() const override;
171 void setDisableAutoTMMWhenDefaultSavePathChanged(bool value) override;
172 bool isDisableAutoTMMWhenCategorySavePathChanged() const override;
173 void setDisableAutoTMMWhenCategorySavePathChanged(bool value) override;
175 qreal globalMaxRatio() const override;
176 void setGlobalMaxRatio(qreal ratio) override;
177 int globalMaxSeedingMinutes() const override;
178 void setGlobalMaxSeedingMinutes(int minutes) override;
179 int globalMaxInactiveSeedingMinutes() const override;
180 void setGlobalMaxInactiveSeedingMinutes(int minutes) override;
181 ShareLimitAction shareLimitAction() const override;
182 void setShareLimitAction(ShareLimitAction act) override;
184 QString getDHTBootstrapNodes() const override;
185 void setDHTBootstrapNodes(const QString &nodes) override;
186 bool isDHTEnabled() const override;
187 void setDHTEnabled(bool enabled) override;
188 bool isLSDEnabled() const override;
189 void setLSDEnabled(bool enabled) override;
190 bool isPeXEnabled() const override;
191 void setPeXEnabled(bool enabled) override;
192 bool isAddTorrentToQueueTop() const override;
193 void setAddTorrentToQueueTop(bool value) override;
194 bool isAddTorrentStopped() const override;
195 void setAddTorrentStopped(bool value) override;
196 Torrent::StopCondition torrentStopCondition() const override;
197 void setTorrentStopCondition(Torrent::StopCondition stopCondition) override;
198 TorrentContentLayout torrentContentLayout() const override;
199 void setTorrentContentLayout(TorrentContentLayout value) override;
200 bool isTrackerEnabled() const override;
201 void setTrackerEnabled(bool enabled) override;
202 bool isAppendExtensionEnabled() const override;
203 void setAppendExtensionEnabled(bool enabled) override;
204 bool isUnwantedFolderEnabled() const override;
205 void setUnwantedFolderEnabled(bool enabled) override;
206 int refreshInterval() const override;
207 void setRefreshInterval(int value) override;
208 bool isPreallocationEnabled() const override;
209 void setPreallocationEnabled(bool enabled) override;
210 Path torrentExportDirectory() const override;
211 void setTorrentExportDirectory(const Path &path) override;
212 Path finishedTorrentExportDirectory() const override;
213 void setFinishedTorrentExportDirectory(const Path &path) override;
215 int globalDownloadSpeedLimit() const override;
216 void setGlobalDownloadSpeedLimit(int limit) override;
217 int globalUploadSpeedLimit() const override;
218 void setGlobalUploadSpeedLimit(int limit) override;
219 int altGlobalDownloadSpeedLimit() const override;
220 void setAltGlobalDownloadSpeedLimit(int limit) override;
221 int altGlobalUploadSpeedLimit() const override;
222 void setAltGlobalUploadSpeedLimit(int limit) override;
223 int downloadSpeedLimit() const override;
224 void setDownloadSpeedLimit(int limit) override;
225 int uploadSpeedLimit() const override;
226 void setUploadSpeedLimit(int limit) override;
227 bool isAltGlobalSpeedLimitEnabled() const override;
228 void setAltGlobalSpeedLimitEnabled(bool enabled) override;
229 bool isBandwidthSchedulerEnabled() const override;
230 void setBandwidthSchedulerEnabled(bool enabled) override;
232 bool isPerformanceWarningEnabled() const override;
233 void setPerformanceWarningEnabled(bool enable) override;
234 int saveResumeDataInterval() const override;
235 void setSaveResumeDataInterval(int value) override;
236 int port() const override;
237 void setPort(int port) override;
238 bool isSSLEnabled() const override;
239 void setSSLEnabled(bool enabled) override;
240 int sslPort() const override;
241 void setSSLPort(int port) override;
242 QString networkInterface() const override;
243 void setNetworkInterface(const QString &iface) override;
244 QString networkInterfaceName() const override;
245 void setNetworkInterfaceName(const QString &name) override;
246 QString networkInterfaceAddress() const override;
247 void setNetworkInterfaceAddress(const QString &address) override;
248 int encryption() const override;
249 void setEncryption(int state) override;
250 int maxActiveCheckingTorrents() const override;
251 void setMaxActiveCheckingTorrents(int val) override;
252 bool isI2PEnabled() const override;
253 void setI2PEnabled(bool enabled) override;
254 QString I2PAddress() const override;
255 void setI2PAddress(const QString &address) override;
256 int I2PPort() const override;
257 void setI2PPort(int port) override;
258 bool I2PMixedMode() const override;
259 void setI2PMixedMode(bool enabled) override;
260 int I2PInboundQuantity() const override;
261 void setI2PInboundQuantity(int value) override;
262 int I2POutboundQuantity() const override;
263 void setI2POutboundQuantity(int value) override;
264 int I2PInboundLength() const override;
265 void setI2PInboundLength(int value) override;
266 int I2POutboundLength() const override;
267 void setI2POutboundLength(int value) override;
268 bool isProxyPeerConnectionsEnabled() const override;
269 void setProxyPeerConnectionsEnabled(bool enabled) override;
270 ChokingAlgorithm chokingAlgorithm() const override;
271 void setChokingAlgorithm(ChokingAlgorithm mode) override;
272 SeedChokingAlgorithm seedChokingAlgorithm() const override;
273 void setSeedChokingAlgorithm(SeedChokingAlgorithm mode) override;
274 bool isAddTrackersEnabled() const override;
275 void setAddTrackersEnabled(bool enabled) override;
276 QString additionalTrackers() const override;
277 void setAdditionalTrackers(const QString &trackers) override;
278 bool isIPFilteringEnabled() const override;
279 void setIPFilteringEnabled(bool enabled) override;
280 Path IPFilterFile() const override;
281 void setIPFilterFile(const Path &path) override;
282 bool announceToAllTrackers() const override;
283 void setAnnounceToAllTrackers(bool val) override;
284 bool announceToAllTiers() const override;
285 void setAnnounceToAllTiers(bool val) override;
286 int peerTurnover() const override;
287 void setPeerTurnover(int val) override;
288 int peerTurnoverCutoff() const override;
289 void setPeerTurnoverCutoff(int val) override;
290 int peerTurnoverInterval() const override;
291 void setPeerTurnoverInterval(int val) override;
292 int requestQueueSize() const override;
293 void setRequestQueueSize(int val) override;
294 int asyncIOThreads() const override;
295 void setAsyncIOThreads(int num) override;
296 int hashingThreads() const override;
297 void setHashingThreads(int num) override;
298 int filePoolSize() const override;
299 void setFilePoolSize(int size) override;
300 int checkingMemUsage() const override;
301 void setCheckingMemUsage(int size) override;
302 int diskCacheSize() const override;
303 void setDiskCacheSize(int size) override;
304 int diskCacheTTL() const override;
305 void setDiskCacheTTL(int ttl) override;
306 qint64 diskQueueSize() const override;
307 void setDiskQueueSize(qint64 size) override;
308 DiskIOType diskIOType() const override;
309 void setDiskIOType(DiskIOType type) override;
310 DiskIOReadMode diskIOReadMode() const override;
311 void setDiskIOReadMode(DiskIOReadMode mode) override;
312 DiskIOWriteMode diskIOWriteMode() const override;
313 void setDiskIOWriteMode(DiskIOWriteMode mode) override;
314 bool isCoalesceReadWriteEnabled() const override;
315 void setCoalesceReadWriteEnabled(bool enabled) override;
316 bool usePieceExtentAffinity() const override;
317 void setPieceExtentAffinity(bool enabled) override;
318 bool isSuggestModeEnabled() const override;
319 void setSuggestMode(bool mode) override;
320 int sendBufferWatermark() const override;
321 void setSendBufferWatermark(int value) override;
322 int sendBufferLowWatermark() const override;
323 void setSendBufferLowWatermark(int value) override;
324 int sendBufferWatermarkFactor() const override;
325 void setSendBufferWatermarkFactor(int value) override;
326 int connectionSpeed() const override;
327 void setConnectionSpeed(int value) override;
328 int socketSendBufferSize() const override;
329 void setSocketSendBufferSize(int value) override;
330 int socketReceiveBufferSize() const override;
331 void setSocketReceiveBufferSize(int value) override;
332 int socketBacklogSize() const override;
333 void setSocketBacklogSize(int value) override;
334 bool isAnonymousModeEnabled() const override;
335 void setAnonymousModeEnabled(bool enabled) override;
336 bool isQueueingSystemEnabled() const override;
337 void setQueueingSystemEnabled(bool enabled) override;
338 bool ignoreSlowTorrentsForQueueing() const override;
339 void setIgnoreSlowTorrentsForQueueing(bool ignore) override;
340 int downloadRateForSlowTorrents() const override;
341 void setDownloadRateForSlowTorrents(int rateInKibiBytes) override;
342 int uploadRateForSlowTorrents() const override;
343 void setUploadRateForSlowTorrents(int rateInKibiBytes) override;
344 int slowTorrentsInactivityTimer() const override;
345 void setSlowTorrentsInactivityTimer(int timeInSeconds) override;
346 int outgoingPortsMin() const override;
347 void setOutgoingPortsMin(int min) override;
348 int outgoingPortsMax() const override;
349 void setOutgoingPortsMax(int max) override;
350 int UPnPLeaseDuration() const override;
351 void setUPnPLeaseDuration(int duration) override;
352 int peerToS() const override;
353 void setPeerToS(int value) override;
354 bool ignoreLimitsOnLAN() const override;
355 void setIgnoreLimitsOnLAN(bool ignore) override;
356 bool includeOverheadInLimits() const override;
357 void setIncludeOverheadInLimits(bool include) override;
358 QString announceIP() const override;
359 void setAnnounceIP(const QString &ip) override;
360 int maxConcurrentHTTPAnnounces() const override;
361 void setMaxConcurrentHTTPAnnounces(int value) override;
362 bool isReannounceWhenAddressChangedEnabled() const override;
363 void setReannounceWhenAddressChangedEnabled(bool enabled) override;
364 void reannounceToAllTrackers() const override;
365 int stopTrackerTimeout() const override;
366 void setStopTrackerTimeout(int value) override;
367 int maxConnections() const override;
368 void setMaxConnections(int max) override;
369 int maxConnectionsPerTorrent() const override;
370 void setMaxConnectionsPerTorrent(int max) override;
371 int maxUploads() const override;
372 void setMaxUploads(int max) override;
373 int maxUploadsPerTorrent() const override;
374 void setMaxUploadsPerTorrent(int max) override;
375 int maxActiveDownloads() const override;
376 void setMaxActiveDownloads(int max) override;
377 int maxActiveUploads() const override;
378 void setMaxActiveUploads(int max) override;
379 int maxActiveTorrents() const override;
380 void setMaxActiveTorrents(int max) override;
381 BTProtocol btProtocol() const override;
382 void setBTProtocol(BTProtocol protocol) override;
383 bool isUTPRateLimited() const override;
384 void setUTPRateLimited(bool limited) override;
385 MixedModeAlgorithm utpMixedMode() const override;
386 void setUtpMixedMode(MixedModeAlgorithm mode) override;
387 bool isIDNSupportEnabled() const override;
388 void setIDNSupportEnabled(bool enabled) override;
389 bool multiConnectionsPerIpEnabled() const override;
390 void setMultiConnectionsPerIpEnabled(bool enabled) override;
391 bool validateHTTPSTrackerCertificate() const override;
392 void setValidateHTTPSTrackerCertificate(bool enabled) override;
393 bool isSSRFMitigationEnabled() const override;
394 void setSSRFMitigationEnabled(bool enabled) override;
395 bool blockPeersOnPrivilegedPorts() const override;
396 void setBlockPeersOnPrivilegedPorts(bool enabled) override;
397 bool isTrackerFilteringEnabled() const override;
398 void setTrackerFilteringEnabled(bool enabled) override;
399 bool isExcludedFileNamesEnabled() const override;
400 void setExcludedFileNamesEnabled(bool enabled) override;
401 QStringList excludedFileNames() const override;
402 void setExcludedFileNames(const QStringList &excludedFileNames) override;
403 bool isFilenameExcluded(const QString &fileName) const override;
404 QStringList bannedIPs() const override;
405 void setBannedIPs(const QStringList &newList) override;
406 ResumeDataStorageType resumeDataStorageType() const override;
407 void setResumeDataStorageType(ResumeDataStorageType type) override;
408 bool isMergeTrackersEnabled() const override;
409 void setMergeTrackersEnabled(bool enabled) override;
410 bool isStartPaused() const override;
411 void setStartPaused(bool value) override;
413 bool isRestored() const override;
415 bool isPaused() const override;
416 void pause() override;
417 void resume() override;
419 Torrent *getTorrent(const TorrentID &id) const override;
420 Torrent *findTorrent(const InfoHash &infoHash) const override;
421 QVector<Torrent *> torrents() const override;
422 qsizetype torrentsCount() const override;
423 const SessionStatus &status() const override;
424 const CacheStatus &cacheStatus() const override;
425 bool isListening() const override;
427 void banIP(const QString &ip) override;
429 bool isKnownTorrent(const InfoHash &infoHash) const override;
430 bool addTorrent(const TorrentDescriptor &torrentDescr, const AddTorrentParams &params = {}) override;
431 bool deleteTorrent(const TorrentID &id, DeleteOption deleteOption = DeleteTorrent) override;
432 bool downloadMetadata(const TorrentDescriptor &torrentDescr) override;
433 bool cancelDownloadMetadata(const TorrentID &id) override;
435 void increaseTorrentsQueuePos(const QVector<TorrentID> &ids) override;
436 void decreaseTorrentsQueuePos(const QVector<TorrentID> &ids) override;
437 void topTorrentsQueuePos(const QVector<TorrentID> &ids) override;
438 void bottomTorrentsQueuePos(const QVector<TorrentID> &ids) override;
440 // Torrent interface
441 void handleTorrentResumeDataRequested(const TorrentImpl *torrent);
442 void handleTorrentShareLimitChanged(TorrentImpl *torrent);
443 void handleTorrentNameChanged(TorrentImpl *torrent);
444 void handleTorrentSavePathChanged(TorrentImpl *torrent);
445 void handleTorrentCategoryChanged(TorrentImpl *torrent, const QString &oldCategory);
446 void handleTorrentTagAdded(TorrentImpl *torrent, const Tag &tag);
447 void handleTorrentTagRemoved(TorrentImpl *torrent, const Tag &tag);
448 void handleTorrentSavingModeChanged(TorrentImpl *torrent);
449 void handleTorrentMetadataReceived(TorrentImpl *torrent);
450 void handleTorrentStopped(TorrentImpl *torrent);
451 void handleTorrentStarted(TorrentImpl *torrent);
452 void handleTorrentChecked(TorrentImpl *torrent);
453 void handleTorrentFinished(TorrentImpl *torrent);
454 void handleTorrentTrackersAdded(TorrentImpl *torrent, const QVector<TrackerEntry> &newTrackers);
455 void handleTorrentTrackersRemoved(TorrentImpl *torrent, const QStringList &deletedTrackers);
456 void handleTorrentTrackersChanged(TorrentImpl *torrent);
457 void handleTorrentUrlSeedsAdded(TorrentImpl *torrent, const QVector<QUrl> &newUrlSeeds);
458 void handleTorrentUrlSeedsRemoved(TorrentImpl *torrent, const QVector<QUrl> &urlSeeds);
459 void handleTorrentResumeDataReady(TorrentImpl *torrent, const LoadTorrentParams &data);
460 void handleTorrentInfoHashChanged(TorrentImpl *torrent, const InfoHash &prevInfoHash);
461 void handleTorrentStorageMovingStateChanged(TorrentImpl *torrent);
463 bool addMoveTorrentStorageJob(TorrentImpl *torrent, const Path &newPath, MoveStorageMode mode, MoveStorageContext context);
465 void findIncompleteFiles(const TorrentInfo &torrentInfo, const Path &savePath
466 , const Path &downloadPath, const PathList &filePaths = {}) const;
468 void enablePortMapping();
469 void disablePortMapping();
470 void addMappedPorts(const QSet<quint16> &ports);
471 void removeMappedPorts(const QSet<quint16> &ports);
473 template <typename Func>
474 void invoke(Func &&func)
476 QMetaObject::invokeMethod(this, std::forward<Func>(func), Qt::QueuedConnection);
479 void invokeAsync(std::function<void ()> func);
481 signals:
482 void addTorrentAlertsReceived(qsizetype count);
484 private slots:
485 void configureDeferred();
486 void readAlerts();
487 void enqueueRefresh();
488 void processShareLimits();
489 void generateResumeData();
490 void handleIPFilterParsed(int ruleCount);
491 void handleIPFilterError();
492 void fileSearchFinished(const TorrentID &id, const Path &savePath, const PathList &fileNames);
494 private:
495 struct ResumeSessionContext;
497 struct MoveStorageJob
499 lt::torrent_handle torrentHandle;
500 Path path;
501 MoveStorageMode mode {};
502 MoveStorageContext context {};
505 struct RemovingTorrentData
507 QString name;
508 Path pathToRemove;
509 DeleteOption deleteOption {};
512 explicit SessionImpl(QObject *parent = nullptr);
513 ~SessionImpl();
515 bool hasPerTorrentRatioLimit() const;
516 bool hasPerTorrentSeedingTimeLimit() const;
517 bool hasPerTorrentInactiveSeedingTimeLimit() const;
519 // Session configuration
520 Q_INVOKABLE void configure();
521 void configureComponents();
522 void initializeNativeSession();
523 lt::settings_pack loadLTSettings() const;
524 void applyNetworkInterfacesSettings(lt::settings_pack &settingsPack) const;
525 void configurePeerClasses();
526 void initMetrics();
527 void applyBandwidthLimits();
528 void processBannedIPs(lt::ip_filter &filter);
529 QStringList getListeningIPs() const;
530 void configureListeningInterface();
531 void enableTracker(bool enable);
532 void enableBandwidthScheduler();
533 void populateAdditionalTrackers();
534 void enableIPFilter();
535 void disableIPFilter();
536 void processTrackerStatuses();
537 void populateExcludedFileNamesRegExpList();
538 void prepareStartup();
539 void handleLoadedResumeData(ResumeSessionContext *context);
540 void processNextResumeData(ResumeSessionContext *context);
541 void endStartup(ResumeSessionContext *context);
543 LoadTorrentParams initLoadTorrentParams(const AddTorrentParams &addTorrentParams);
544 bool addTorrent_impl(const TorrentDescriptor &source, const AddTorrentParams &addTorrentParams);
546 void updateSeedingLimitTimer();
547 void exportTorrentFile(const Torrent *torrent, const Path &folderPath);
549 void handleAlert(const lt::alert *a);
550 void handleAddTorrentAlerts(const std::vector<lt::alert *> &alerts);
551 void dispatchTorrentAlert(const lt::torrent_alert *a);
552 void handleStateUpdateAlert(const lt::state_update_alert *p);
553 void handleMetadataReceivedAlert(const lt::metadata_received_alert *p);
554 void handleFileErrorAlert(const lt::file_error_alert *p);
555 void handleTorrentRemovedAlert(const lt::torrent_removed_alert *p);
556 void handleTorrentDeletedAlert(const lt::torrent_deleted_alert *p);
557 void handleTorrentDeleteFailedAlert(const lt::torrent_delete_failed_alert *p);
558 void handleTorrentNeedCertAlert(const lt::torrent_need_cert_alert *a);
559 void handlePortmapWarningAlert(const lt::portmap_error_alert *p);
560 void handlePortmapAlert(const lt::portmap_alert *p);
561 void handlePeerBlockedAlert(const lt::peer_blocked_alert *p);
562 void handlePeerBanAlert(const lt::peer_ban_alert *p);
563 void handleUrlSeedAlert(const lt::url_seed_alert *p);
564 void handleListenSucceededAlert(const lt::listen_succeeded_alert *p);
565 void handleListenFailedAlert(const lt::listen_failed_alert *p);
566 void handleExternalIPAlert(const lt::external_ip_alert *p);
567 void handleSessionErrorAlert(const lt::session_error_alert *p) const;
568 void handleSessionStatsAlert(const lt::session_stats_alert *p);
569 void handleAlertsDroppedAlert(const lt::alerts_dropped_alert *p) const;
570 void handleStorageMovedAlert(const lt::storage_moved_alert *p);
571 void handleStorageMovedFailedAlert(const lt::storage_moved_failed_alert *p);
572 void handleSocks5Alert(const lt::socks5_alert *p) const;
573 void handleI2PAlert(const lt::i2p_alert *p) const;
574 void handleTrackerAlert(const lt::tracker_alert *a);
575 #ifdef QBT_USES_LIBTORRENT2
576 void handleTorrentConflictAlert(const lt::torrent_conflict_alert *a);
577 #endif
579 TorrentImpl *createTorrent(const lt::torrent_handle &nativeHandle, const LoadTorrentParams &params);
581 void saveResumeData();
582 void saveTorrentsQueue();
583 void removeTorrentsQueue();
585 std::vector<lt::alert *> getPendingAlerts(lt::time_duration time = lt::time_duration::zero()) const;
587 void moveTorrentStorage(const MoveStorageJob &job) const;
588 void handleMoveTorrentStorageJobFinished(const Path &newPath);
590 void loadCategories();
591 void storeCategories() const;
592 void upgradeCategories();
593 DownloadPathOption resolveCategoryDownloadPathOption(const QString &categoryName, const std::optional<DownloadPathOption> &option) const;
595 void saveStatistics() const;
596 void loadStatistics();
598 void updateTrackerEntryStatuses(lt::torrent_handle torrentHandle, QHash<std::string, QHash<lt::tcp::endpoint, QMap<int, int>>> updatedTrackers);
600 // BitTorrent
601 lt::session *m_nativeSession = nullptr;
602 NativeSessionExtension *m_nativeSessionExtension = nullptr;
604 bool m_deferredConfigureScheduled = false;
605 bool m_IPFilteringConfigured = false;
606 mutable bool m_listenInterfaceConfigured = false;
608 CachedSettingValue<QString> m_DHTBootstrapNodes;
609 CachedSettingValue<bool> m_isDHTEnabled;
610 CachedSettingValue<bool> m_isLSDEnabled;
611 CachedSettingValue<bool> m_isPeXEnabled;
612 CachedSettingValue<bool> m_isIPFilteringEnabled;
613 CachedSettingValue<bool> m_isTrackerFilteringEnabled;
614 CachedSettingValue<Path> m_IPFilterFile;
615 CachedSettingValue<bool> m_announceToAllTrackers;
616 CachedSettingValue<bool> m_announceToAllTiers;
617 CachedSettingValue<int> m_asyncIOThreads;
618 CachedSettingValue<int> m_hashingThreads;
619 CachedSettingValue<int> m_filePoolSize;
620 CachedSettingValue<int> m_checkingMemUsage;
621 CachedSettingValue<int> m_diskCacheSize;
622 CachedSettingValue<int> m_diskCacheTTL;
623 CachedSettingValue<qint64> m_diskQueueSize;
624 CachedSettingValue<DiskIOType> m_diskIOType;
625 CachedSettingValue<DiskIOReadMode> m_diskIOReadMode;
626 CachedSettingValue<DiskIOWriteMode> m_diskIOWriteMode;
627 CachedSettingValue<bool> m_coalesceReadWriteEnabled;
628 CachedSettingValue<bool> m_usePieceExtentAffinity;
629 CachedSettingValue<bool> m_isSuggestMode;
630 CachedSettingValue<int> m_sendBufferWatermark;
631 CachedSettingValue<int> m_sendBufferLowWatermark;
632 CachedSettingValue<int> m_sendBufferWatermarkFactor;
633 CachedSettingValue<int> m_connectionSpeed;
634 CachedSettingValue<int> m_socketSendBufferSize;
635 CachedSettingValue<int> m_socketReceiveBufferSize;
636 CachedSettingValue<int> m_socketBacklogSize;
637 CachedSettingValue<bool> m_isAnonymousModeEnabled;
638 CachedSettingValue<bool> m_isQueueingEnabled;
639 CachedSettingValue<int> m_maxActiveDownloads;
640 CachedSettingValue<int> m_maxActiveUploads;
641 CachedSettingValue<int> m_maxActiveTorrents;
642 CachedSettingValue<bool> m_ignoreSlowTorrentsForQueueing;
643 CachedSettingValue<int> m_downloadRateForSlowTorrents;
644 CachedSettingValue<int> m_uploadRateForSlowTorrents;
645 CachedSettingValue<int> m_slowTorrentsInactivityTimer;
646 CachedSettingValue<int> m_outgoingPortsMin;
647 CachedSettingValue<int> m_outgoingPortsMax;
648 CachedSettingValue<int> m_UPnPLeaseDuration;
649 CachedSettingValue<int> m_peerToS;
650 CachedSettingValue<bool> m_ignoreLimitsOnLAN;
651 CachedSettingValue<bool> m_includeOverheadInLimits;
652 CachedSettingValue<QString> m_announceIP;
653 CachedSettingValue<int> m_maxConcurrentHTTPAnnounces;
654 CachedSettingValue<bool> m_isReannounceWhenAddressChangedEnabled;
655 CachedSettingValue<int> m_stopTrackerTimeout;
656 CachedSettingValue<int> m_maxConnections;
657 CachedSettingValue<int> m_maxUploads;
658 CachedSettingValue<int> m_maxConnectionsPerTorrent;
659 CachedSettingValue<int> m_maxUploadsPerTorrent;
660 CachedSettingValue<BTProtocol> m_btProtocol;
661 CachedSettingValue<bool> m_isUTPRateLimited;
662 CachedSettingValue<MixedModeAlgorithm> m_utpMixedMode;
663 CachedSettingValue<bool> m_IDNSupportEnabled;
664 CachedSettingValue<bool> m_multiConnectionsPerIpEnabled;
665 CachedSettingValue<bool> m_validateHTTPSTrackerCertificate;
666 CachedSettingValue<bool> m_SSRFMitigationEnabled;
667 CachedSettingValue<bool> m_blockPeersOnPrivilegedPorts;
668 CachedSettingValue<bool> m_isAddTrackersEnabled;
669 CachedSettingValue<QString> m_additionalTrackers;
670 CachedSettingValue<qreal> m_globalMaxRatio;
671 CachedSettingValue<int> m_globalMaxSeedingMinutes;
672 CachedSettingValue<int> m_globalMaxInactiveSeedingMinutes;
673 CachedSettingValue<bool> m_isAddTorrentToQueueTop;
674 CachedSettingValue<bool> m_isAddTorrentStopped;
675 CachedSettingValue<Torrent::StopCondition> m_torrentStopCondition;
676 CachedSettingValue<TorrentContentLayout> m_torrentContentLayout;
677 CachedSettingValue<bool> m_isAppendExtensionEnabled;
678 CachedSettingValue<bool> m_isUnwantedFolderEnabled;
679 CachedSettingValue<int> m_refreshInterval;
680 CachedSettingValue<bool> m_isPreallocationEnabled;
681 CachedSettingValue<Path> m_torrentExportDirectory;
682 CachedSettingValue<Path> m_finishedTorrentExportDirectory;
683 CachedSettingValue<int> m_globalDownloadSpeedLimit;
684 CachedSettingValue<int> m_globalUploadSpeedLimit;
685 CachedSettingValue<int> m_altGlobalDownloadSpeedLimit;
686 CachedSettingValue<int> m_altGlobalUploadSpeedLimit;
687 CachedSettingValue<bool> m_isAltGlobalSpeedLimitEnabled;
688 CachedSettingValue<bool> m_isBandwidthSchedulerEnabled;
689 CachedSettingValue<bool> m_isPerformanceWarningEnabled;
690 CachedSettingValue<int> m_saveResumeDataInterval;
691 CachedSettingValue<int> m_port;
692 CachedSettingValue<bool> m_sslEnabled;
693 CachedSettingValue<int> m_sslPort;
694 CachedSettingValue<QString> m_networkInterface;
695 CachedSettingValue<QString> m_networkInterfaceName;
696 CachedSettingValue<QString> m_networkInterfaceAddress;
697 CachedSettingValue<int> m_encryption;
698 CachedSettingValue<int> m_maxActiveCheckingTorrents;
699 CachedSettingValue<bool> m_isProxyPeerConnectionsEnabled;
700 CachedSettingValue<ChokingAlgorithm> m_chokingAlgorithm;
701 CachedSettingValue<SeedChokingAlgorithm> m_seedChokingAlgorithm;
702 CachedSettingValue<QStringList> m_storedTags;
703 CachedSettingValue<ShareLimitAction> m_shareLimitAction;
704 CachedSettingValue<Path> m_savePath;
705 CachedSettingValue<Path> m_downloadPath;
706 CachedSettingValue<bool> m_isDownloadPathEnabled;
707 CachedSettingValue<bool> m_isSubcategoriesEnabled;
708 CachedSettingValue<bool> m_useCategoryPathsInManualMode;
709 CachedSettingValue<bool> m_isAutoTMMDisabledByDefault;
710 CachedSettingValue<bool> m_isDisableAutoTMMWhenCategoryChanged;
711 CachedSettingValue<bool> m_isDisableAutoTMMWhenDefaultSavePathChanged;
712 CachedSettingValue<bool> m_isDisableAutoTMMWhenCategorySavePathChanged;
713 CachedSettingValue<bool> m_isTrackerEnabled;
714 CachedSettingValue<int> m_peerTurnover;
715 CachedSettingValue<int> m_peerTurnoverCutoff;
716 CachedSettingValue<int> m_peerTurnoverInterval;
717 CachedSettingValue<int> m_requestQueueSize;
718 CachedSettingValue<bool> m_isExcludedFileNamesEnabled;
719 CachedSettingValue<QStringList> m_excludedFileNames;
720 CachedSettingValue<QStringList> m_bannedIPs;
721 CachedSettingValue<ResumeDataStorageType> m_resumeDataStorageType;
722 CachedSettingValue<bool> m_isMergeTrackersEnabled;
723 CachedSettingValue<bool> m_isI2PEnabled;
724 CachedSettingValue<QString> m_I2PAddress;
725 CachedSettingValue<int> m_I2PPort;
726 CachedSettingValue<bool> m_I2PMixedMode;
727 CachedSettingValue<int> m_I2PInboundQuantity;
728 CachedSettingValue<int> m_I2POutboundQuantity;
729 CachedSettingValue<int> m_I2PInboundLength;
730 CachedSettingValue<int> m_I2POutboundLength;
731 SettingValue<bool> m_startPaused;
733 bool m_isRestored = false;
734 bool m_isPaused = isStartPaused();
736 // Order is important. This needs to be declared after its CachedSettingsValue
737 // counterpart, because it uses it for initialization in the constructor
738 // initialization list.
739 const bool m_wasPexEnabled = m_isPeXEnabled;
741 int m_numResumeData = 0;
742 QVector<TrackerEntry> m_additionalTrackerEntries;
743 QVector<QRegularExpression> m_excludedFileNamesRegExpList;
745 // Statistics
746 mutable QElapsedTimer m_statisticsLastUpdateTimer;
747 mutable bool m_isStatisticsDirty = false;
748 qint64 m_previouslyUploaded = 0;
749 qint64 m_previouslyDownloaded = 0;
751 bool m_torrentsQueueChanged = false;
752 bool m_needSaveTorrentsQueue = false;
753 bool m_refreshEnqueued = false;
754 QTimer *m_seedingLimitTimer = nullptr;
755 QTimer *m_resumeDataTimer = nullptr;
756 // IP filtering
757 QPointer<FilterParserThread> m_filterParser;
758 QPointer<BandwidthScheduler> m_bwScheduler;
759 // Tracker
760 QPointer<Tracker> m_tracker;
762 Utils::Thread::UniquePtr m_ioThread;
763 QThreadPool *m_asyncWorker = nullptr;
764 ResumeDataStorage *m_resumeDataStorage = nullptr;
765 FileSearcher *m_fileSearcher = nullptr;
767 QHash<TorrentID, lt::torrent_handle> m_downloadedMetadata;
769 QHash<TorrentID, TorrentImpl *> m_torrents;
770 QHash<TorrentID, TorrentImpl *> m_hybridTorrentsByAltID;
771 QHash<TorrentID, LoadTorrentParams> m_loadingTorrents;
772 QHash<TorrentID, RemovingTorrentData> m_removingTorrents;
773 QHash<TorrentID, TorrentID> m_changedTorrentIDs;
774 QMap<QString, CategoryOptions> m_categories;
775 TagSet m_tags;
777 // This field holds amounts of peers reported by trackers in their responses to announces
778 // (torrent.tracker_name.tracker_local_endpoint.protocol_version.num_peers)
779 QHash<lt::torrent_handle, QHash<std::string, QHash<lt::tcp::endpoint, QMap<int, int>>>> m_updatedTrackerStatuses;
781 // I/O errored torrents
782 QSet<TorrentID> m_recentErroredTorrents;
783 QTimer *m_recentErroredTorrentsTimer = nullptr;
785 SessionMetricIndices m_metricIndices;
786 lt::time_point m_statsLastTimestamp = lt::clock_type::now();
788 SessionStatus m_status;
789 CacheStatus m_cacheStatus;
791 QList<MoveStorageJob> m_moveStorageQueue;
793 QString m_lastExternalIP;
795 bool m_needUpgradeDownloadPath = false;
797 // All port mapping related routines are invoked from working thread
798 // so there are no synchronization used. If multithreaded access is
799 // ever required, synchronization should also be provided.
800 bool m_isPortMappingEnabled = false;
801 QHash<quint16, std::vector<lt::port_mapping_t>> m_mappedPorts;
803 QTimer *m_wakeupCheckTimer = nullptr;
804 QDateTime m_wakeupCheckTimestamp;
806 friend void Session::initInstance();
807 friend void Session::freeInstance();
808 friend Session *Session::instance();
809 static Session *m_instance;