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