Revamp handling of getting resume data from libtorrent
[qBittorrent.git] / src / base / bittorrent / sessionimpl.h
blob1f5dadedb180153b22e6e779af7be550f839e2ec
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 handleTorrentResumeDataRequested(const TorrentImpl *torrent);
430 void handleTorrentShareLimitChanged(TorrentImpl *torrent);
431 void handleTorrentNameChanged(TorrentImpl *torrent);
432 void handleTorrentSavePathChanged(TorrentImpl *torrent);
433 void handleTorrentCategoryChanged(TorrentImpl *torrent, const QString &oldCategory);
434 void handleTorrentTagAdded(TorrentImpl *torrent, const Tag &tag);
435 void handleTorrentTagRemoved(TorrentImpl *torrent, const Tag &tag);
436 void handleTorrentSavingModeChanged(TorrentImpl *torrent);
437 void handleTorrentMetadataReceived(TorrentImpl *torrent);
438 void handleTorrentPaused(TorrentImpl *torrent);
439 void handleTorrentResumed(TorrentImpl *torrent);
440 void handleTorrentChecked(TorrentImpl *torrent);
441 void handleTorrentFinished(TorrentImpl *torrent);
442 void handleTorrentTrackersAdded(TorrentImpl *torrent, const QVector<TrackerEntry> &newTrackers);
443 void handleTorrentTrackersRemoved(TorrentImpl *torrent, const QStringList &deletedTrackers);
444 void handleTorrentTrackersChanged(TorrentImpl *torrent);
445 void handleTorrentUrlSeedsAdded(TorrentImpl *torrent, const QVector<QUrl> &newUrlSeeds);
446 void handleTorrentUrlSeedsRemoved(TorrentImpl *torrent, const QVector<QUrl> &urlSeeds);
447 void handleTorrentResumeDataReady(TorrentImpl *torrent, const LoadTorrentParams &data);
448 void handleTorrentInfoHashChanged(TorrentImpl *torrent, const InfoHash &prevInfoHash);
449 void handleTorrentStorageMovingStateChanged(TorrentImpl *torrent);
451 bool addMoveTorrentStorageJob(TorrentImpl *torrent, const Path &newPath, MoveStorageMode mode, MoveStorageContext context);
453 void findIncompleteFiles(const TorrentInfo &torrentInfo, const Path &savePath
454 , const Path &downloadPath, const PathList &filePaths = {}) const;
456 void enablePortMapping();
457 void disablePortMapping();
458 void addMappedPorts(const QSet<quint16> &ports);
459 void removeMappedPorts(const QSet<quint16> &ports);
461 template <typename Func>
462 void invoke(Func &&func)
464 QMetaObject::invokeMethod(this, std::forward<Func>(func), Qt::QueuedConnection);
467 void invokeAsync(std::function<void ()> func);
469 signals:
470 void addTorrentAlertsReceived(qsizetype count);
472 private slots:
473 void configureDeferred();
474 void readAlerts();
475 void enqueueRefresh();
476 void processShareLimits();
477 void generateResumeData();
478 void handleIPFilterParsed(int ruleCount);
479 void handleIPFilterError();
480 void fileSearchFinished(const TorrentID &id, const Path &savePath, const PathList &fileNames);
482 private:
483 struct ResumeSessionContext;
485 struct MoveStorageJob
487 lt::torrent_handle torrentHandle;
488 Path path;
489 MoveStorageMode mode {};
490 MoveStorageContext context {};
493 struct RemovingTorrentData
495 QString name;
496 Path pathToRemove;
497 DeleteOption deleteOption {};
500 explicit SessionImpl(QObject *parent = nullptr);
501 ~SessionImpl();
503 bool hasPerTorrentRatioLimit() const;
504 bool hasPerTorrentSeedingTimeLimit() const;
505 bool hasPerTorrentInactiveSeedingTimeLimit() const;
507 // Session configuration
508 Q_INVOKABLE void configure();
509 void configureComponents();
510 void initializeNativeSession();
511 lt::settings_pack loadLTSettings() const;
512 void applyNetworkInterfacesSettings(lt::settings_pack &settingsPack) const;
513 void configurePeerClasses();
514 void initMetrics();
515 void applyBandwidthLimits();
516 void processBannedIPs(lt::ip_filter &filter);
517 QStringList getListeningIPs() const;
518 void configureListeningInterface();
519 void enableTracker(bool enable);
520 void enableBandwidthScheduler();
521 void populateAdditionalTrackers();
522 void enableIPFilter();
523 void disableIPFilter();
524 void processTrackerStatuses();
525 void populateExcludedFileNamesRegExpList();
526 void prepareStartup();
527 void handleLoadedResumeData(ResumeSessionContext *context);
528 void processNextResumeData(ResumeSessionContext *context);
529 void endStartup(ResumeSessionContext *context);
531 LoadTorrentParams initLoadTorrentParams(const AddTorrentParams &addTorrentParams);
532 bool addTorrent_impl(const TorrentDescriptor &source, const AddTorrentParams &addTorrentParams);
534 void updateSeedingLimitTimer();
535 void exportTorrentFile(const Torrent *torrent, const Path &folderPath);
537 void handleAlert(const lt::alert *a);
538 void handleAddTorrentAlerts(const std::vector<lt::alert *> &alerts);
539 void dispatchTorrentAlert(const lt::torrent_alert *a);
540 void handleStateUpdateAlert(const lt::state_update_alert *p);
541 void handleMetadataReceivedAlert(const lt::metadata_received_alert *p);
542 void handleFileErrorAlert(const lt::file_error_alert *p);
543 void handleTorrentRemovedAlert(const lt::torrent_removed_alert *p);
544 void handleTorrentDeletedAlert(const lt::torrent_deleted_alert *p);
545 void handleTorrentDeleteFailedAlert(const lt::torrent_delete_failed_alert *p);
546 void handlePortmapWarningAlert(const lt::portmap_error_alert *p);
547 void handlePortmapAlert(const lt::portmap_alert *p);
548 void handlePeerBlockedAlert(const lt::peer_blocked_alert *p);
549 void handlePeerBanAlert(const lt::peer_ban_alert *p);
550 void handleUrlSeedAlert(const lt::url_seed_alert *p);
551 void handleListenSucceededAlert(const lt::listen_succeeded_alert *p);
552 void handleListenFailedAlert(const lt::listen_failed_alert *p);
553 void handleExternalIPAlert(const lt::external_ip_alert *p);
554 void handleSessionErrorAlert(const lt::session_error_alert *p) const;
555 void handleSessionStatsAlert(const lt::session_stats_alert *p);
556 void handleAlertsDroppedAlert(const lt::alerts_dropped_alert *p) const;
557 void handleStorageMovedAlert(const lt::storage_moved_alert *p);
558 void handleStorageMovedFailedAlert(const lt::storage_moved_failed_alert *p);
559 void handleSocks5Alert(const lt::socks5_alert *p) const;
560 void handleI2PAlert(const lt::i2p_alert *p) const;
561 void handleTrackerAlert(const lt::tracker_alert *a);
562 #ifdef QBT_USES_LIBTORRENT2
563 void handleTorrentConflictAlert(const lt::torrent_conflict_alert *a);
564 #endif
566 TorrentImpl *createTorrent(const lt::torrent_handle &nativeHandle, const LoadTorrentParams &params);
568 void saveResumeData();
569 void saveTorrentsQueue();
570 void removeTorrentsQueue();
572 std::vector<lt::alert *> getPendingAlerts(lt::time_duration time = lt::time_duration::zero()) const;
574 void moveTorrentStorage(const MoveStorageJob &job) const;
575 void handleMoveTorrentStorageJobFinished(const Path &newPath);
577 void loadCategories();
578 void storeCategories() const;
579 void upgradeCategories();
580 DownloadPathOption resolveCategoryDownloadPathOption(const QString &categoryName, const std::optional<DownloadPathOption> &option) const;
582 void saveStatistics() const;
583 void loadStatistics();
585 void updateTrackerEntries(lt::torrent_handle torrentHandle, QHash<std::string, QHash<lt::tcp::endpoint, QMap<int, int>>> updatedTrackers);
587 // BitTorrent
588 lt::session *m_nativeSession = nullptr;
589 NativeSessionExtension *m_nativeSessionExtension = nullptr;
591 bool m_deferredConfigureScheduled = false;
592 bool m_IPFilteringConfigured = false;
593 mutable bool m_listenInterfaceConfigured = false;
595 CachedSettingValue<QString> m_DHTBootstrapNodes;
596 CachedSettingValue<bool> m_isDHTEnabled;
597 CachedSettingValue<bool> m_isLSDEnabled;
598 CachedSettingValue<bool> m_isPeXEnabled;
599 CachedSettingValue<bool> m_isIPFilteringEnabled;
600 CachedSettingValue<bool> m_isTrackerFilteringEnabled;
601 CachedSettingValue<Path> m_IPFilterFile;
602 CachedSettingValue<bool> m_announceToAllTrackers;
603 CachedSettingValue<bool> m_announceToAllTiers;
604 CachedSettingValue<int> m_asyncIOThreads;
605 CachedSettingValue<int> m_hashingThreads;
606 CachedSettingValue<int> m_filePoolSize;
607 CachedSettingValue<int> m_checkingMemUsage;
608 CachedSettingValue<int> m_diskCacheSize;
609 CachedSettingValue<int> m_diskCacheTTL;
610 CachedSettingValue<qint64> m_diskQueueSize;
611 CachedSettingValue<DiskIOType> m_diskIOType;
612 CachedSettingValue<DiskIOReadMode> m_diskIOReadMode;
613 CachedSettingValue<DiskIOWriteMode> m_diskIOWriteMode;
614 CachedSettingValue<bool> m_coalesceReadWriteEnabled;
615 CachedSettingValue<bool> m_usePieceExtentAffinity;
616 CachedSettingValue<bool> m_isSuggestMode;
617 CachedSettingValue<int> m_sendBufferWatermark;
618 CachedSettingValue<int> m_sendBufferLowWatermark;
619 CachedSettingValue<int> m_sendBufferWatermarkFactor;
620 CachedSettingValue<int> m_connectionSpeed;
621 CachedSettingValue<int> m_socketSendBufferSize;
622 CachedSettingValue<int> m_socketReceiveBufferSize;
623 CachedSettingValue<int> m_socketBacklogSize;
624 CachedSettingValue<bool> m_isAnonymousModeEnabled;
625 CachedSettingValue<bool> m_isQueueingEnabled;
626 CachedSettingValue<int> m_maxActiveDownloads;
627 CachedSettingValue<int> m_maxActiveUploads;
628 CachedSettingValue<int> m_maxActiveTorrents;
629 CachedSettingValue<bool> m_ignoreSlowTorrentsForQueueing;
630 CachedSettingValue<int> m_downloadRateForSlowTorrents;
631 CachedSettingValue<int> m_uploadRateForSlowTorrents;
632 CachedSettingValue<int> m_slowTorrentsInactivityTimer;
633 CachedSettingValue<int> m_outgoingPortsMin;
634 CachedSettingValue<int> m_outgoingPortsMax;
635 CachedSettingValue<int> m_UPnPLeaseDuration;
636 CachedSettingValue<int> m_peerToS;
637 CachedSettingValue<bool> m_ignoreLimitsOnLAN;
638 CachedSettingValue<bool> m_includeOverheadInLimits;
639 CachedSettingValue<QString> m_announceIP;
640 CachedSettingValue<int> m_maxConcurrentHTTPAnnounces;
641 CachedSettingValue<bool> m_isReannounceWhenAddressChangedEnabled;
642 CachedSettingValue<int> m_stopTrackerTimeout;
643 CachedSettingValue<int> m_maxConnections;
644 CachedSettingValue<int> m_maxUploads;
645 CachedSettingValue<int> m_maxConnectionsPerTorrent;
646 CachedSettingValue<int> m_maxUploadsPerTorrent;
647 CachedSettingValue<BTProtocol> m_btProtocol;
648 CachedSettingValue<bool> m_isUTPRateLimited;
649 CachedSettingValue<MixedModeAlgorithm> m_utpMixedMode;
650 CachedSettingValue<bool> m_IDNSupportEnabled;
651 CachedSettingValue<bool> m_multiConnectionsPerIpEnabled;
652 CachedSettingValue<bool> m_validateHTTPSTrackerCertificate;
653 CachedSettingValue<bool> m_SSRFMitigationEnabled;
654 CachedSettingValue<bool> m_blockPeersOnPrivilegedPorts;
655 CachedSettingValue<bool> m_isAddTrackersEnabled;
656 CachedSettingValue<QString> m_additionalTrackers;
657 CachedSettingValue<qreal> m_globalMaxRatio;
658 CachedSettingValue<int> m_globalMaxSeedingMinutes;
659 CachedSettingValue<int> m_globalMaxInactiveSeedingMinutes;
660 CachedSettingValue<bool> m_isAddTorrentToQueueTop;
661 CachedSettingValue<bool> m_isAddTorrentPaused;
662 CachedSettingValue<Torrent::StopCondition> m_torrentStopCondition;
663 CachedSettingValue<TorrentContentLayout> m_torrentContentLayout;
664 CachedSettingValue<bool> m_isAppendExtensionEnabled;
665 CachedSettingValue<bool> m_isUnwantedFolderEnabled;
666 CachedSettingValue<int> m_refreshInterval;
667 CachedSettingValue<bool> m_isPreallocationEnabled;
668 CachedSettingValue<Path> m_torrentExportDirectory;
669 CachedSettingValue<Path> m_finishedTorrentExportDirectory;
670 CachedSettingValue<int> m_globalDownloadSpeedLimit;
671 CachedSettingValue<int> m_globalUploadSpeedLimit;
672 CachedSettingValue<int> m_altGlobalDownloadSpeedLimit;
673 CachedSettingValue<int> m_altGlobalUploadSpeedLimit;
674 CachedSettingValue<bool> m_isAltGlobalSpeedLimitEnabled;
675 CachedSettingValue<bool> m_isBandwidthSchedulerEnabled;
676 CachedSettingValue<bool> m_isPerformanceWarningEnabled;
677 CachedSettingValue<int> m_saveResumeDataInterval;
678 CachedSettingValue<int> m_port;
679 CachedSettingValue<QString> m_networkInterface;
680 CachedSettingValue<QString> m_networkInterfaceName;
681 CachedSettingValue<QString> m_networkInterfaceAddress;
682 CachedSettingValue<int> m_encryption;
683 CachedSettingValue<int> m_maxActiveCheckingTorrents;
684 CachedSettingValue<bool> m_isProxyPeerConnectionsEnabled;
685 CachedSettingValue<ChokingAlgorithm> m_chokingAlgorithm;
686 CachedSettingValue<SeedChokingAlgorithm> m_seedChokingAlgorithm;
687 CachedSettingValue<QStringList> m_storedTags;
688 CachedSettingValue<int> m_maxRatioAction;
689 CachedSettingValue<Path> m_savePath;
690 CachedSettingValue<Path> m_downloadPath;
691 CachedSettingValue<bool> m_isDownloadPathEnabled;
692 CachedSettingValue<bool> m_isSubcategoriesEnabled;
693 CachedSettingValue<bool> m_useCategoryPathsInManualMode;
694 CachedSettingValue<bool> m_isAutoTMMDisabledByDefault;
695 CachedSettingValue<bool> m_isDisableAutoTMMWhenCategoryChanged;
696 CachedSettingValue<bool> m_isDisableAutoTMMWhenDefaultSavePathChanged;
697 CachedSettingValue<bool> m_isDisableAutoTMMWhenCategorySavePathChanged;
698 CachedSettingValue<bool> m_isTrackerEnabled;
699 CachedSettingValue<int> m_peerTurnover;
700 CachedSettingValue<int> m_peerTurnoverCutoff;
701 CachedSettingValue<int> m_peerTurnoverInterval;
702 CachedSettingValue<int> m_requestQueueSize;
703 CachedSettingValue<bool> m_isExcludedFileNamesEnabled;
704 CachedSettingValue<QStringList> m_excludedFileNames;
705 CachedSettingValue<QStringList> m_bannedIPs;
706 CachedSettingValue<ResumeDataStorageType> m_resumeDataStorageType;
707 CachedSettingValue<bool> m_isMergeTrackersEnabled;
708 CachedSettingValue<bool> m_isI2PEnabled;
709 CachedSettingValue<QString> m_I2PAddress;
710 CachedSettingValue<int> m_I2PPort;
711 CachedSettingValue<bool> m_I2PMixedMode;
712 CachedSettingValue<int> m_I2PInboundQuantity;
713 CachedSettingValue<int> m_I2POutboundQuantity;
714 CachedSettingValue<int> m_I2PInboundLength;
715 CachedSettingValue<int> m_I2POutboundLength;
717 bool m_isRestored = false;
719 // Order is important. This needs to be declared after its CachedSettingsValue
720 // counterpart, because it uses it for initialization in the constructor
721 // initialization list.
722 const bool m_wasPexEnabled = m_isPeXEnabled;
724 int m_numResumeData = 0;
725 QVector<TrackerEntry> m_additionalTrackerList;
726 QVector<QRegularExpression> m_excludedFileNamesRegExpList;
728 // Statistics
729 mutable QElapsedTimer m_statisticsLastUpdateTimer;
730 mutable bool m_isStatisticsDirty = false;
731 qint64 m_previouslyUploaded = 0;
732 qint64 m_previouslyDownloaded = 0;
734 bool m_torrentsQueueChanged = false;
735 bool m_needSaveTorrentsQueue = false;
736 bool m_refreshEnqueued = false;
737 QTimer *m_seedingLimitTimer = nullptr;
738 QTimer *m_resumeDataTimer = nullptr;
739 // IP filtering
740 QPointer<FilterParserThread> m_filterParser;
741 QPointer<BandwidthScheduler> m_bwScheduler;
742 // Tracker
743 QPointer<Tracker> m_tracker;
745 Utils::Thread::UniquePtr m_ioThread;
746 QThreadPool *m_asyncWorker = nullptr;
747 ResumeDataStorage *m_resumeDataStorage = nullptr;
748 FileSearcher *m_fileSearcher = nullptr;
750 QHash<TorrentID, lt::torrent_handle> m_downloadedMetadata;
752 QHash<TorrentID, TorrentImpl *> m_torrents;
753 QHash<TorrentID, TorrentImpl *> m_hybridTorrentsByAltID;
754 QHash<TorrentID, LoadTorrentParams> m_loadingTorrents;
755 QHash<TorrentID, RemovingTorrentData> m_removingTorrents;
756 QHash<TorrentID, TorrentID> m_changedTorrentIDs;
757 QMap<QString, CategoryOptions> m_categories;
758 TagSet m_tags;
760 // This field holds amounts of peers reported by trackers in their responses to announces
761 // (torrent.tracker_name.tracker_local_endpoint.protocol_version.num_peers)
762 QHash<lt::torrent_handle, QHash<std::string, QHash<lt::tcp::endpoint, QMap<int, int>>>> m_updatedTrackerEntries;
764 // I/O errored torrents
765 QSet<TorrentID> m_recentErroredTorrents;
766 QTimer *m_recentErroredTorrentsTimer = nullptr;
768 SessionMetricIndices m_metricIndices;
769 lt::time_point m_statsLastTimestamp = lt::clock_type::now();
771 SessionStatus m_status;
772 CacheStatus m_cacheStatus;
774 QList<MoveStorageJob> m_moveStorageQueue;
776 QString m_lastExternalIP;
778 bool m_needUpgradeDownloadPath = false;
780 // All port mapping related routines are invoked from working thread
781 // so there are no synchronization used. If multithreaded access is
782 // ever required, synchronization should also be provided.
783 bool m_isPortMappingEnabled = false;
784 QHash<quint16, std::vector<lt::port_mapping_t>> m_mappedPorts;
786 QTimer *m_wakeupCheckTimer = nullptr;
787 QDateTime m_wakeupCheckTimestamp;
789 friend void Session::initInstance();
790 friend void Session::freeInstance();
791 friend Session *Session::instance();
792 static Session *m_instance;