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