Enable customizing the save statistics time interval
[qBittorrent.git] / src / base / bittorrent / sessionimpl.h
blobb1fe4efe0d946d695f005c4490495a4521ab6aeb
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 std::chrono::minutes saveStatisticsInterval() const override;
238 void setSaveStatisticsInterval(std::chrono::minutes value) override;
239 int shutdownTimeout() const override;
240 void setShutdownTimeout(int value) override;
241 int port() const override;
242 void setPort(int port) override;
243 bool isSSLEnabled() const override;
244 void setSSLEnabled(bool enabled) override;
245 int sslPort() const override;
246 void setSSLPort(int port) override;
247 QString networkInterface() const override;
248 void setNetworkInterface(const QString &iface) override;
249 QString networkInterfaceName() const override;
250 void setNetworkInterfaceName(const QString &name) override;
251 QString networkInterfaceAddress() const override;
252 void setNetworkInterfaceAddress(const QString &address) override;
253 int encryption() const override;
254 void setEncryption(int state) override;
255 int maxActiveCheckingTorrents() const override;
256 void setMaxActiveCheckingTorrents(int val) override;
257 bool isI2PEnabled() const override;
258 void setI2PEnabled(bool enabled) override;
259 QString I2PAddress() const override;
260 void setI2PAddress(const QString &address) override;
261 int I2PPort() const override;
262 void setI2PPort(int port) override;
263 bool I2PMixedMode() const override;
264 void setI2PMixedMode(bool enabled) override;
265 int I2PInboundQuantity() const override;
266 void setI2PInboundQuantity(int value) override;
267 int I2POutboundQuantity() const override;
268 void setI2POutboundQuantity(int value) override;
269 int I2PInboundLength() const override;
270 void setI2PInboundLength(int value) override;
271 int I2POutboundLength() const override;
272 void setI2POutboundLength(int value) override;
273 bool isProxyPeerConnectionsEnabled() const override;
274 void setProxyPeerConnectionsEnabled(bool enabled) override;
275 ChokingAlgorithm chokingAlgorithm() const override;
276 void setChokingAlgorithm(ChokingAlgorithm mode) override;
277 SeedChokingAlgorithm seedChokingAlgorithm() const override;
278 void setSeedChokingAlgorithm(SeedChokingAlgorithm mode) override;
279 bool isAddTrackersEnabled() const override;
280 void setAddTrackersEnabled(bool enabled) override;
281 QString additionalTrackers() const override;
282 void setAdditionalTrackers(const QString &trackers) override;
283 bool isIPFilteringEnabled() const override;
284 void setIPFilteringEnabled(bool enabled) override;
285 Path IPFilterFile() const override;
286 void setIPFilterFile(const Path &path) override;
287 bool announceToAllTrackers() const override;
288 void setAnnounceToAllTrackers(bool val) override;
289 bool announceToAllTiers() const override;
290 void setAnnounceToAllTiers(bool val) override;
291 int peerTurnover() const override;
292 void setPeerTurnover(int val) override;
293 int peerTurnoverCutoff() const override;
294 void setPeerTurnoverCutoff(int val) override;
295 int peerTurnoverInterval() const override;
296 void setPeerTurnoverInterval(int val) override;
297 int requestQueueSize() const override;
298 void setRequestQueueSize(int val) override;
299 int asyncIOThreads() const override;
300 void setAsyncIOThreads(int num) override;
301 int hashingThreads() const override;
302 void setHashingThreads(int num) override;
303 int filePoolSize() const override;
304 void setFilePoolSize(int size) override;
305 int checkingMemUsage() const override;
306 void setCheckingMemUsage(int size) override;
307 int diskCacheSize() const override;
308 void setDiskCacheSize(int size) override;
309 int diskCacheTTL() const override;
310 void setDiskCacheTTL(int ttl) override;
311 qint64 diskQueueSize() const override;
312 void setDiskQueueSize(qint64 size) override;
313 DiskIOType diskIOType() const override;
314 void setDiskIOType(DiskIOType type) override;
315 DiskIOReadMode diskIOReadMode() const override;
316 void setDiskIOReadMode(DiskIOReadMode mode) override;
317 DiskIOWriteMode diskIOWriteMode() const override;
318 void setDiskIOWriteMode(DiskIOWriteMode mode) override;
319 bool isCoalesceReadWriteEnabled() const override;
320 void setCoalesceReadWriteEnabled(bool enabled) override;
321 bool usePieceExtentAffinity() const override;
322 void setPieceExtentAffinity(bool enabled) override;
323 bool isSuggestModeEnabled() const override;
324 void setSuggestMode(bool mode) override;
325 int sendBufferWatermark() const override;
326 void setSendBufferWatermark(int value) override;
327 int sendBufferLowWatermark() const override;
328 void setSendBufferLowWatermark(int value) override;
329 int sendBufferWatermarkFactor() const override;
330 void setSendBufferWatermarkFactor(int value) override;
331 int connectionSpeed() const override;
332 void setConnectionSpeed(int value) override;
333 int socketSendBufferSize() const override;
334 void setSocketSendBufferSize(int value) override;
335 int socketReceiveBufferSize() const override;
336 void setSocketReceiveBufferSize(int value) override;
337 int socketBacklogSize() const override;
338 void setSocketBacklogSize(int value) override;
339 bool isAnonymousModeEnabled() const override;
340 void setAnonymousModeEnabled(bool enabled) override;
341 bool isQueueingSystemEnabled() const override;
342 void setQueueingSystemEnabled(bool enabled) override;
343 bool ignoreSlowTorrentsForQueueing() const override;
344 void setIgnoreSlowTorrentsForQueueing(bool ignore) override;
345 int downloadRateForSlowTorrents() const override;
346 void setDownloadRateForSlowTorrents(int rateInKibiBytes) override;
347 int uploadRateForSlowTorrents() const override;
348 void setUploadRateForSlowTorrents(int rateInKibiBytes) override;
349 int slowTorrentsInactivityTimer() const override;
350 void setSlowTorrentsInactivityTimer(int timeInSeconds) override;
351 int outgoingPortsMin() const override;
352 void setOutgoingPortsMin(int min) override;
353 int outgoingPortsMax() const override;
354 void setOutgoingPortsMax(int max) override;
355 int UPnPLeaseDuration() const override;
356 void setUPnPLeaseDuration(int duration) override;
357 int peerToS() const override;
358 void setPeerToS(int value) override;
359 bool ignoreLimitsOnLAN() const override;
360 void setIgnoreLimitsOnLAN(bool ignore) override;
361 bool includeOverheadInLimits() const override;
362 void setIncludeOverheadInLimits(bool include) override;
363 QString announceIP() const override;
364 void setAnnounceIP(const QString &ip) override;
365 int maxConcurrentHTTPAnnounces() const override;
366 void setMaxConcurrentHTTPAnnounces(int value) override;
367 bool isReannounceWhenAddressChangedEnabled() const override;
368 void setReannounceWhenAddressChangedEnabled(bool enabled) override;
369 void reannounceToAllTrackers() const override;
370 int stopTrackerTimeout() const override;
371 void setStopTrackerTimeout(int value) override;
372 int maxConnections() const override;
373 void setMaxConnections(int max) override;
374 int maxConnectionsPerTorrent() const override;
375 void setMaxConnectionsPerTorrent(int max) override;
376 int maxUploads() const override;
377 void setMaxUploads(int max) override;
378 int maxUploadsPerTorrent() const override;
379 void setMaxUploadsPerTorrent(int max) override;
380 int maxActiveDownloads() const override;
381 void setMaxActiveDownloads(int max) override;
382 int maxActiveUploads() const override;
383 void setMaxActiveUploads(int max) override;
384 int maxActiveTorrents() const override;
385 void setMaxActiveTorrents(int max) override;
386 BTProtocol btProtocol() const override;
387 void setBTProtocol(BTProtocol protocol) override;
388 bool isUTPRateLimited() const override;
389 void setUTPRateLimited(bool limited) override;
390 MixedModeAlgorithm utpMixedMode() const override;
391 void setUtpMixedMode(MixedModeAlgorithm mode) override;
392 bool isIDNSupportEnabled() const override;
393 void setIDNSupportEnabled(bool enabled) override;
394 bool multiConnectionsPerIpEnabled() const override;
395 void setMultiConnectionsPerIpEnabled(bool enabled) override;
396 bool validateHTTPSTrackerCertificate() const override;
397 void setValidateHTTPSTrackerCertificate(bool enabled) override;
398 bool isSSRFMitigationEnabled() const override;
399 void setSSRFMitigationEnabled(bool enabled) override;
400 bool blockPeersOnPrivilegedPorts() const override;
401 void setBlockPeersOnPrivilegedPorts(bool enabled) override;
402 bool isTrackerFilteringEnabled() const override;
403 void setTrackerFilteringEnabled(bool enabled) override;
404 bool isExcludedFileNamesEnabled() const override;
405 void setExcludedFileNamesEnabled(bool enabled) override;
406 QStringList excludedFileNames() const override;
407 void setExcludedFileNames(const QStringList &excludedFileNames) override;
408 void applyFilenameFilter(const PathList &files, QList<BitTorrent::DownloadPriority> &priorities) override;
409 QStringList bannedIPs() const override;
410 void setBannedIPs(const QStringList &newList) override;
411 ResumeDataStorageType resumeDataStorageType() const override;
412 void setResumeDataStorageType(ResumeDataStorageType type) override;
413 bool isMergeTrackersEnabled() const override;
414 void setMergeTrackersEnabled(bool enabled) override;
415 bool isStartPaused() const override;
416 void setStartPaused(bool value) override;
417 TorrentContentRemoveOption torrentContentRemoveOption() const override;
418 void setTorrentContentRemoveOption(TorrentContentRemoveOption option) override;
420 bool isRestored() const override;
422 bool isPaused() const override;
423 void pause() override;
424 void resume() override;
426 Torrent *getTorrent(const TorrentID &id) const override;
427 Torrent *findTorrent(const InfoHash &infoHash) const override;
428 QList<Torrent *> torrents() const override;
429 qsizetype torrentsCount() const override;
430 const SessionStatus &status() const override;
431 const CacheStatus &cacheStatus() const override;
432 bool isListening() const override;
434 void banIP(const QString &ip) override;
436 bool isKnownTorrent(const InfoHash &infoHash) const override;
437 bool addTorrent(const TorrentDescriptor &torrentDescr, const AddTorrentParams &params = {}) override;
438 bool removeTorrent(const TorrentID &id, TorrentRemoveOption deleteOption = TorrentRemoveOption::KeepContent) override;
439 bool downloadMetadata(const TorrentDescriptor &torrentDescr) override;
440 bool cancelDownloadMetadata(const TorrentID &id) override;
442 void increaseTorrentsQueuePos(const QList<TorrentID> &ids) override;
443 void decreaseTorrentsQueuePos(const QList<TorrentID> &ids) override;
444 void topTorrentsQueuePos(const QList<TorrentID> &ids) override;
445 void bottomTorrentsQueuePos(const QList<TorrentID> &ids) override;
447 // Torrent interface
448 void handleTorrentResumeDataRequested(const TorrentImpl *torrent);
449 void handleTorrentShareLimitChanged(TorrentImpl *torrent);
450 void handleTorrentNameChanged(TorrentImpl *torrent);
451 void handleTorrentSavePathChanged(TorrentImpl *torrent);
452 void handleTorrentCategoryChanged(TorrentImpl *torrent, const QString &oldCategory);
453 void handleTorrentTagAdded(TorrentImpl *torrent, const Tag &tag);
454 void handleTorrentTagRemoved(TorrentImpl *torrent, const Tag &tag);
455 void handleTorrentSavingModeChanged(TorrentImpl *torrent);
456 void handleTorrentMetadataReceived(TorrentImpl *torrent);
457 void handleTorrentStopped(TorrentImpl *torrent);
458 void handleTorrentStarted(TorrentImpl *torrent);
459 void handleTorrentChecked(TorrentImpl *torrent);
460 void handleTorrentFinished(TorrentImpl *torrent);
461 void handleTorrentTrackersAdded(TorrentImpl *torrent, const QList<TrackerEntry> &newTrackers);
462 void handleTorrentTrackersRemoved(TorrentImpl *torrent, const QStringList &deletedTrackers);
463 void handleTorrentTrackersChanged(TorrentImpl *torrent);
464 void handleTorrentUrlSeedsAdded(TorrentImpl *torrent, const QList<QUrl> &newUrlSeeds);
465 void handleTorrentUrlSeedsRemoved(TorrentImpl *torrent, const QList<QUrl> &urlSeeds);
466 void handleTorrentResumeDataReady(TorrentImpl *torrent, const LoadTorrentParams &data);
467 void handleTorrentInfoHashChanged(TorrentImpl *torrent, const InfoHash &prevInfoHash);
468 void handleTorrentStorageMovingStateChanged(TorrentImpl *torrent);
470 bool addMoveTorrentStorageJob(TorrentImpl *torrent, const Path &newPath, MoveStorageMode mode, MoveStorageContext context);
472 void findIncompleteFiles(const TorrentInfo &torrentInfo, const Path &savePath
473 , const Path &downloadPath, const PathList &filePaths = {}) const;
475 void enablePortMapping();
476 void disablePortMapping();
477 void addMappedPorts(const QSet<quint16> &ports);
478 void removeMappedPorts(const QSet<quint16> &ports);
480 template <typename Func>
481 void invoke(Func &&func)
483 QMetaObject::invokeMethod(this, std::forward<Func>(func), Qt::QueuedConnection);
486 void invokeAsync(std::function<void ()> func);
488 signals:
489 void addTorrentAlertsReceived(qsizetype count);
491 private slots:
492 void configureDeferred();
493 void readAlerts();
494 void enqueueRefresh();
495 void generateResumeData();
496 void handleIPFilterParsed(int ruleCount);
497 void handleIPFilterError();
498 void fileSearchFinished(const TorrentID &id, const Path &savePath, const PathList &fileNames);
499 void torrentContentRemovingFinished(const QString &torrentName, const QString &errorMessage);
501 private:
502 struct ResumeSessionContext;
504 struct MoveStorageJob
506 lt::torrent_handle torrentHandle;
507 Path path;
508 MoveStorageMode mode {};
509 MoveStorageContext context {};
512 struct RemovingTorrentData
514 QString name;
515 Path contentStoragePath;
516 PathList fileNames;
517 TorrentRemoveOption removeOption {};
520 explicit SessionImpl(QObject *parent = nullptr);
521 ~SessionImpl();
523 bool hasPerTorrentRatioLimit() const;
524 bool hasPerTorrentSeedingTimeLimit() const;
525 bool hasPerTorrentInactiveSeedingTimeLimit() const;
527 // Session configuration
528 Q_INVOKABLE void configure();
529 void configureComponents();
530 void initializeNativeSession();
531 lt::settings_pack loadLTSettings() const;
532 void applyNetworkInterfacesSettings(lt::settings_pack &settingsPack) const;
533 void configurePeerClasses();
534 void initMetrics();
535 void applyBandwidthLimits();
536 void processBannedIPs(lt::ip_filter &filter);
537 QStringList getListeningIPs() const;
538 void configureListeningInterface();
539 void enableTracker(bool enable);
540 void enableBandwidthScheduler();
541 void populateAdditionalTrackers();
542 void enableIPFilter();
543 void disableIPFilter();
544 void processTrackerStatuses();
545 void processTorrentShareLimits(TorrentImpl *torrent);
546 void populateExcludedFileNamesRegExpList();
547 void prepareStartup();
548 void handleLoadedResumeData(ResumeSessionContext *context);
549 void processNextResumeData(ResumeSessionContext *context);
550 void endStartup(ResumeSessionContext *context);
552 LoadTorrentParams initLoadTorrentParams(const AddTorrentParams &addTorrentParams);
553 bool addTorrent_impl(const TorrentDescriptor &source, const AddTorrentParams &addTorrentParams);
555 void updateSeedingLimitTimer();
556 void exportTorrentFile(const Torrent *torrent, const Path &folderPath);
558 void handleAlert(const lt::alert *alert);
559 void dispatchTorrentAlert(const lt::torrent_alert *alert);
560 void handleAddTorrentAlert(const lt::add_torrent_alert *alert);
561 void handleStateUpdateAlert(const lt::state_update_alert *alert);
562 void handleMetadataReceivedAlert(const lt::metadata_received_alert *alert);
563 void handleFileErrorAlert(const lt::file_error_alert *alert);
564 void handleTorrentRemovedAlert(const lt::torrent_removed_alert *alert);
565 void handleTorrentDeletedAlert(const lt::torrent_deleted_alert *alert);
566 void handleTorrentDeleteFailedAlert(const lt::torrent_delete_failed_alert *alert);
567 void handleTorrentNeedCertAlert(const lt::torrent_need_cert_alert *alert);
568 void handlePortmapWarningAlert(const lt::portmap_error_alert *alert);
569 void handlePortmapAlert(const lt::portmap_alert *alert);
570 void handlePeerBlockedAlert(const lt::peer_blocked_alert *alert);
571 void handlePeerBanAlert(const lt::peer_ban_alert *alert);
572 void handleUrlSeedAlert(const lt::url_seed_alert *alert);
573 void handleListenSucceededAlert(const lt::listen_succeeded_alert *alert);
574 void handleListenFailedAlert(const lt::listen_failed_alert *alert);
575 void handleExternalIPAlert(const lt::external_ip_alert *alert);
576 void handleSessionErrorAlert(const lt::session_error_alert *alert) const;
577 void handleSessionStatsAlert(const lt::session_stats_alert *alert);
578 void handleAlertsDroppedAlert(const lt::alerts_dropped_alert *alert) const;
579 void handleStorageMovedAlert(const lt::storage_moved_alert *alert);
580 void handleStorageMovedFailedAlert(const lt::storage_moved_failed_alert *alert);
581 void handleSocks5Alert(const lt::socks5_alert *alert) const;
582 void handleI2PAlert(const lt::i2p_alert *alert) const;
583 void handleTrackerAlert(const lt::tracker_alert *alert);
584 #ifdef QBT_USES_LIBTORRENT2
585 void handleTorrentConflictAlert(const lt::torrent_conflict_alert *alert);
586 #endif
588 TorrentImpl *createTorrent(const lt::torrent_handle &nativeHandle, const LoadTorrentParams &params);
590 void saveResumeData();
591 void saveTorrentsQueue();
592 void removeTorrentsQueue();
594 std::vector<lt::alert *> getPendingAlerts(lt::time_duration time = lt::time_duration::zero()) const;
596 void moveTorrentStorage(const MoveStorageJob &job) const;
597 void handleMoveTorrentStorageJobFinished(const Path &newPath);
599 void loadCategories();
600 void storeCategories() const;
601 void upgradeCategories();
602 DownloadPathOption resolveCategoryDownloadPathOption(const QString &categoryName, const std::optional<DownloadPathOption> &option) const;
604 void saveStatistics() const;
605 void loadStatistics();
607 void updateTrackerEntryStatuses(lt::torrent_handle torrentHandle, QHash<std::string, QHash<lt::tcp::endpoint, QMap<int, int>>> updatedTrackers);
609 void handleRemovedTorrent(const TorrentID &torrentID, const QString &partfileRemoveError = {});
611 CachedSettingValue<QString> m_DHTBootstrapNodes;
612 CachedSettingValue<bool> m_isDHTEnabled;
613 CachedSettingValue<bool> m_isLSDEnabled;
614 CachedSettingValue<bool> m_isPeXEnabled;
615 CachedSettingValue<bool> m_isIPFilteringEnabled;
616 CachedSettingValue<bool> m_isTrackerFilteringEnabled;
617 CachedSettingValue<Path> m_IPFilterFile;
618 CachedSettingValue<bool> m_announceToAllTrackers;
619 CachedSettingValue<bool> m_announceToAllTiers;
620 CachedSettingValue<int> m_asyncIOThreads;
621 CachedSettingValue<int> m_hashingThreads;
622 CachedSettingValue<int> m_filePoolSize;
623 CachedSettingValue<int> m_checkingMemUsage;
624 CachedSettingValue<int> m_diskCacheSize;
625 CachedSettingValue<int> m_diskCacheTTL;
626 CachedSettingValue<qint64> m_diskQueueSize;
627 CachedSettingValue<DiskIOType> m_diskIOType;
628 CachedSettingValue<DiskIOReadMode> m_diskIOReadMode;
629 CachedSettingValue<DiskIOWriteMode> m_diskIOWriteMode;
630 CachedSettingValue<bool> m_coalesceReadWriteEnabled;
631 CachedSettingValue<bool> m_usePieceExtentAffinity;
632 CachedSettingValue<bool> m_isSuggestMode;
633 CachedSettingValue<int> m_sendBufferWatermark;
634 CachedSettingValue<int> m_sendBufferLowWatermark;
635 CachedSettingValue<int> m_sendBufferWatermarkFactor;
636 CachedSettingValue<int> m_connectionSpeed;
637 CachedSettingValue<int> m_socketSendBufferSize;
638 CachedSettingValue<int> m_socketReceiveBufferSize;
639 CachedSettingValue<int> m_socketBacklogSize;
640 CachedSettingValue<bool> m_isAnonymousModeEnabled;
641 CachedSettingValue<bool> m_isQueueingEnabled;
642 CachedSettingValue<int> m_maxActiveDownloads;
643 CachedSettingValue<int> m_maxActiveUploads;
644 CachedSettingValue<int> m_maxActiveTorrents;
645 CachedSettingValue<bool> m_ignoreSlowTorrentsForQueueing;
646 CachedSettingValue<int> m_downloadRateForSlowTorrents;
647 CachedSettingValue<int> m_uploadRateForSlowTorrents;
648 CachedSettingValue<int> m_slowTorrentsInactivityTimer;
649 CachedSettingValue<int> m_outgoingPortsMin;
650 CachedSettingValue<int> m_outgoingPortsMax;
651 CachedSettingValue<int> m_UPnPLeaseDuration;
652 CachedSettingValue<int> m_peerToS;
653 CachedSettingValue<bool> m_ignoreLimitsOnLAN;
654 CachedSettingValue<bool> m_includeOverheadInLimits;
655 CachedSettingValue<QString> m_announceIP;
656 CachedSettingValue<int> m_maxConcurrentHTTPAnnounces;
657 CachedSettingValue<bool> m_isReannounceWhenAddressChangedEnabled;
658 CachedSettingValue<int> m_stopTrackerTimeout;
659 CachedSettingValue<int> m_maxConnections;
660 CachedSettingValue<int> m_maxUploads;
661 CachedSettingValue<int> m_maxConnectionsPerTorrent;
662 CachedSettingValue<int> m_maxUploadsPerTorrent;
663 CachedSettingValue<BTProtocol> m_btProtocol;
664 CachedSettingValue<bool> m_isUTPRateLimited;
665 CachedSettingValue<MixedModeAlgorithm> m_utpMixedMode;
666 CachedSettingValue<bool> m_IDNSupportEnabled;
667 CachedSettingValue<bool> m_multiConnectionsPerIpEnabled;
668 CachedSettingValue<bool> m_validateHTTPSTrackerCertificate;
669 CachedSettingValue<bool> m_SSRFMitigationEnabled;
670 CachedSettingValue<bool> m_blockPeersOnPrivilegedPorts;
671 CachedSettingValue<bool> m_isAddTrackersEnabled;
672 CachedSettingValue<QString> m_additionalTrackers;
673 CachedSettingValue<qreal> m_globalMaxRatio;
674 CachedSettingValue<int> m_globalMaxSeedingMinutes;
675 CachedSettingValue<int> m_globalMaxInactiveSeedingMinutes;
676 CachedSettingValue<bool> m_isAddTorrentToQueueTop;
677 CachedSettingValue<bool> m_isAddTorrentStopped;
678 CachedSettingValue<Torrent::StopCondition> m_torrentStopCondition;
679 CachedSettingValue<TorrentContentLayout> m_torrentContentLayout;
680 CachedSettingValue<bool> m_isAppendExtensionEnabled;
681 CachedSettingValue<bool> m_isUnwantedFolderEnabled;
682 CachedSettingValue<int> m_refreshInterval;
683 CachedSettingValue<bool> m_isPreallocationEnabled;
684 CachedSettingValue<Path> m_torrentExportDirectory;
685 CachedSettingValue<Path> m_finishedTorrentExportDirectory;
686 CachedSettingValue<int> m_globalDownloadSpeedLimit;
687 CachedSettingValue<int> m_globalUploadSpeedLimit;
688 CachedSettingValue<int> m_altGlobalDownloadSpeedLimit;
689 CachedSettingValue<int> m_altGlobalUploadSpeedLimit;
690 CachedSettingValue<bool> m_isAltGlobalSpeedLimitEnabled;
691 CachedSettingValue<bool> m_isBandwidthSchedulerEnabled;
692 CachedSettingValue<bool> m_isPerformanceWarningEnabled;
693 CachedSettingValue<int> m_saveResumeDataInterval;
694 CachedSettingValue<int> m_saveStatisticsInterval;
695 CachedSettingValue<int> m_shutdownTimeout;
696 CachedSettingValue<int> m_port;
697 CachedSettingValue<bool> m_sslEnabled;
698 CachedSettingValue<int> m_sslPort;
699 CachedSettingValue<QString> m_networkInterface;
700 CachedSettingValue<QString> m_networkInterfaceName;
701 CachedSettingValue<QString> m_networkInterfaceAddress;
702 CachedSettingValue<int> m_encryption;
703 CachedSettingValue<int> m_maxActiveCheckingTorrents;
704 CachedSettingValue<bool> m_isProxyPeerConnectionsEnabled;
705 CachedSettingValue<ChokingAlgorithm> m_chokingAlgorithm;
706 CachedSettingValue<SeedChokingAlgorithm> m_seedChokingAlgorithm;
707 CachedSettingValue<QStringList> m_storedTags;
708 CachedSettingValue<ShareLimitAction> m_shareLimitAction;
709 CachedSettingValue<Path> m_savePath;
710 CachedSettingValue<Path> m_downloadPath;
711 CachedSettingValue<bool> m_isDownloadPathEnabled;
712 CachedSettingValue<bool> m_isSubcategoriesEnabled;
713 CachedSettingValue<bool> m_useCategoryPathsInManualMode;
714 CachedSettingValue<bool> m_isAutoTMMDisabledByDefault;
715 CachedSettingValue<bool> m_isDisableAutoTMMWhenCategoryChanged;
716 CachedSettingValue<bool> m_isDisableAutoTMMWhenDefaultSavePathChanged;
717 CachedSettingValue<bool> m_isDisableAutoTMMWhenCategorySavePathChanged;
718 CachedSettingValue<bool> m_isTrackerEnabled;
719 CachedSettingValue<int> m_peerTurnover;
720 CachedSettingValue<int> m_peerTurnoverCutoff;
721 CachedSettingValue<int> m_peerTurnoverInterval;
722 CachedSettingValue<int> m_requestQueueSize;
723 CachedSettingValue<bool> m_isExcludedFileNamesEnabled;
724 CachedSettingValue<QStringList> m_excludedFileNames;
725 CachedSettingValue<QStringList> m_bannedIPs;
726 CachedSettingValue<ResumeDataStorageType> m_resumeDataStorageType;
727 CachedSettingValue<bool> m_isMergeTrackersEnabled;
728 CachedSettingValue<bool> m_isI2PEnabled;
729 CachedSettingValue<QString> m_I2PAddress;
730 CachedSettingValue<int> m_I2PPort;
731 CachedSettingValue<bool> m_I2PMixedMode;
732 CachedSettingValue<int> m_I2PInboundQuantity;
733 CachedSettingValue<int> m_I2POutboundQuantity;
734 CachedSettingValue<int> m_I2PInboundLength;
735 CachedSettingValue<int> m_I2POutboundLength;
736 CachedSettingValue<TorrentContentRemoveOption> m_torrentContentRemoveOption;
737 SettingValue<bool> m_startPaused;
739 lt::session *m_nativeSession = nullptr;
740 NativeSessionExtension *m_nativeSessionExtension = nullptr;
742 bool m_deferredConfigureScheduled = false;
743 bool m_IPFilteringConfigured = false;
744 mutable bool m_listenInterfaceConfigured = false;
746 bool m_isRestored = false;
747 bool m_isPaused = isStartPaused();
749 // Order is important. This needs to be declared after its CachedSettingsValue
750 // counterpart, because it uses it for initialization in the constructor
751 // initialization list.
752 const bool m_wasPexEnabled = m_isPeXEnabled;
754 int m_numResumeData = 0;
755 QList<TrackerEntry> m_additionalTrackerEntries;
756 QList<QRegularExpression> m_excludedFileNamesRegExpList;
758 // Statistics
759 mutable QElapsedTimer m_statisticsLastUpdateTimer;
760 mutable bool m_isStatisticsDirty = false;
761 qint64 m_previouslyUploaded = 0;
762 qint64 m_previouslyDownloaded = 0;
764 bool m_torrentsQueueChanged = false;
765 bool m_needSaveTorrentsQueue = false;
766 bool m_refreshEnqueued = false;
767 QTimer *m_seedingLimitTimer = nullptr;
768 QTimer *m_resumeDataTimer = nullptr;
769 // IP filtering
770 QPointer<FilterParserThread> m_filterParser;
771 QPointer<BandwidthScheduler> m_bwScheduler;
772 // Tracker
773 QPointer<Tracker> m_tracker;
775 Utils::Thread::UniquePtr m_ioThread;
776 QThreadPool *m_asyncWorker = nullptr;
777 ResumeDataStorage *m_resumeDataStorage = nullptr;
778 FileSearcher *m_fileSearcher = nullptr;
779 TorrentContentRemover *m_torrentContentRemover = nullptr;
781 QHash<TorrentID, lt::torrent_handle> m_downloadedMetadata;
783 QHash<TorrentID, TorrentImpl *> m_torrents;
784 QHash<TorrentID, TorrentImpl *> m_hybridTorrentsByAltID;
785 QHash<TorrentID, LoadTorrentParams> m_loadingTorrents;
786 QHash<TorrentID, RemovingTorrentData> m_removingTorrents;
787 QHash<TorrentID, TorrentID> m_changedTorrentIDs;
788 QMap<QString, CategoryOptions> m_categories;
789 TagSet m_tags;
791 qsizetype m_receivedAddTorrentAlertsCount = 0;
792 QList<Torrent *> m_loadedTorrents;
794 // This field holds amounts of peers reported by trackers in their responses to announces
795 // (torrent.tracker_name.tracker_local_endpoint.protocol_version.num_peers)
796 QHash<lt::torrent_handle, QHash<std::string, QHash<lt::tcp::endpoint, QMap<int, int>>>> m_updatedTrackerStatuses;
798 // I/O errored torrents
799 QSet<TorrentID> m_recentErroredTorrents;
800 QTimer *m_recentErroredTorrentsTimer = nullptr;
802 SessionMetricIndices m_metricIndices;
803 lt::time_point m_statsLastTimestamp = lt::clock_type::now();
805 SessionStatus m_status;
806 CacheStatus m_cacheStatus;
808 QList<MoveStorageJob> m_moveStorageQueue;
810 QString m_lastExternalIP;
812 bool m_needUpgradeDownloadPath = false;
814 // All port mapping related routines are invoked from working thread
815 // so there are no synchronization used. If multithreaded access is
816 // ever required, synchronization should also be provided.
817 bool m_isPortMappingEnabled = false;
818 QHash<quint16, std::vector<lt::port_mapping_t>> m_mappedPorts;
820 QTimer *m_wakeupCheckTimer = nullptr;
821 QDateTime m_wakeupCheckTimestamp;
823 QList<TorrentImpl *> m_pendingFinishedTorrents;
825 friend void Session::initInstance();
826 friend void Session::freeInstance();
827 friend Session *Session::instance();
828 static Session *m_instance;