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