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