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