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