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