Don't overwrite tracker entry of unrelated protocol
[qBittorrent.git] / src / base / bittorrent / sessionimpl.h
blobbd6f730ca02a41dee2ccac1593845440d49ca328
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 bool isDHTEnabled() const override;
178 void setDHTEnabled(bool enabled) override;
179 bool isLSDEnabled() const override;
180 void setLSDEnabled(bool enabled) override;
181 bool isPeXEnabled() const override;
182 void setPeXEnabled(bool enabled) override;
183 bool isAddTorrentToQueueTop() const override;
184 void setAddTorrentToQueueTop(bool value) override;
185 bool isAddTorrentPaused() const override;
186 void setAddTorrentPaused(bool value) override;
187 Torrent::StopCondition torrentStopCondition() const override;
188 void setTorrentStopCondition(Torrent::StopCondition stopCondition) override;
189 TorrentContentLayout torrentContentLayout() const override;
190 void setTorrentContentLayout(TorrentContentLayout value) override;
191 bool isTrackerEnabled() const override;
192 void setTrackerEnabled(bool enabled) override;
193 bool isAppendExtensionEnabled() const override;
194 void setAppendExtensionEnabled(bool enabled) override;
195 int refreshInterval() const override;
196 void setRefreshInterval(int value) override;
197 bool isPreallocationEnabled() const override;
198 void setPreallocationEnabled(bool enabled) override;
199 Path torrentExportDirectory() const override;
200 void setTorrentExportDirectory(const Path &path) override;
201 Path finishedTorrentExportDirectory() const override;
202 void setFinishedTorrentExportDirectory(const Path &path) override;
204 int globalDownloadSpeedLimit() const override;
205 void setGlobalDownloadSpeedLimit(int limit) override;
206 int globalUploadSpeedLimit() const override;
207 void setGlobalUploadSpeedLimit(int limit) override;
208 int altGlobalDownloadSpeedLimit() const override;
209 void setAltGlobalDownloadSpeedLimit(int limit) override;
210 int altGlobalUploadSpeedLimit() const override;
211 void setAltGlobalUploadSpeedLimit(int limit) override;
212 int downloadSpeedLimit() const override;
213 void setDownloadSpeedLimit(int limit) override;
214 int uploadSpeedLimit() const override;
215 void setUploadSpeedLimit(int limit) override;
216 bool isAltGlobalSpeedLimitEnabled() const override;
217 void setAltGlobalSpeedLimitEnabled(bool enabled) override;
218 bool isBandwidthSchedulerEnabled() const override;
219 void setBandwidthSchedulerEnabled(bool enabled) override;
221 bool isPerformanceWarningEnabled() const override;
222 void setPerformanceWarningEnabled(bool enable) override;
223 int saveResumeDataInterval() const override;
224 void setSaveResumeDataInterval(int value) override;
225 int port() const override;
226 void setPort(int port) override;
227 QString networkInterface() const override;
228 void setNetworkInterface(const QString &iface) override;
229 QString networkInterfaceName() const override;
230 void setNetworkInterfaceName(const QString &name) override;
231 QString networkInterfaceAddress() const override;
232 void setNetworkInterfaceAddress(const QString &address) override;
233 int encryption() const override;
234 void setEncryption(int state) override;
235 int maxActiveCheckingTorrents() const override;
236 void setMaxActiveCheckingTorrents(int val) override;
237 bool isI2PEnabled() const override;
238 void setI2PEnabled(bool enabled) override;
239 QString I2PAddress() const override;
240 void setI2PAddress(const QString &address) override;
241 int I2PPort() const override;
242 void setI2PPort(int port) override;
243 bool I2PMixedMode() const override;
244 void setI2PMixedMode(bool enabled) override;
245 int I2PInboundQuantity() const override;
246 void setI2PInboundQuantity(int value) override;
247 int I2POutboundQuantity() const override;
248 void setI2POutboundQuantity(int value) override;
249 int I2PInboundLength() const override;
250 void setI2PInboundLength(int value) override;
251 int I2POutboundLength() const override;
252 void setI2POutboundLength(int value) 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;
393 bool isMergeTrackersEnabled() const override;
394 void setMergeTrackersEnabled(bool enabled) override;
396 bool isRestored() const override;
398 Torrent *getTorrent(const TorrentID &id) const override;
399 Torrent *findTorrent(const InfoHash &infoHash) const override;
400 QVector<Torrent *> torrents() const override;
401 qsizetype torrentsCount() const override;
402 const SessionStatus &status() const override;
403 const CacheStatus &cacheStatus() const override;
404 bool isListening() const override;
406 MaxRatioAction maxRatioAction() const override;
407 void setMaxRatioAction(MaxRatioAction act) override;
409 void banIP(const QString &ip) override;
411 bool isKnownTorrent(const InfoHash &infoHash) const override;
412 bool addTorrent(const TorrentDescriptor &torrentDescr, const AddTorrentParams &params = {}) override;
413 bool deleteTorrent(const TorrentID &id, DeleteOption deleteOption = DeleteTorrent) override;
414 bool downloadMetadata(const TorrentDescriptor &torrentDescr) override;
415 bool cancelDownloadMetadata(const TorrentID &id) override;
417 void increaseTorrentsQueuePos(const QVector<TorrentID> &ids) override;
418 void decreaseTorrentsQueuePos(const QVector<TorrentID> &ids) override;
419 void topTorrentsQueuePos(const QVector<TorrentID> &ids) override;
420 void bottomTorrentsQueuePos(const QVector<TorrentID> &ids) override;
422 // Torrent interface
423 void handleTorrentNeedSaveResumeData(const TorrentImpl *torrent);
424 void handleTorrentSaveResumeDataRequested(const TorrentImpl *torrent);
425 void handleTorrentSaveResumeDataFailed(const TorrentImpl *torrent);
426 void handleTorrentShareLimitChanged(TorrentImpl *torrent);
427 void handleTorrentNameChanged(TorrentImpl *torrent);
428 void handleTorrentSavePathChanged(TorrentImpl *torrent);
429 void handleTorrentCategoryChanged(TorrentImpl *torrent, const QString &oldCategory);
430 void handleTorrentTagAdded(TorrentImpl *torrent, const QString &tag);
431 void handleTorrentTagRemoved(TorrentImpl *torrent, const QString &tag);
432 void handleTorrentSavingModeChanged(TorrentImpl *torrent);
433 void handleTorrentMetadataReceived(TorrentImpl *torrent);
434 void handleTorrentPaused(TorrentImpl *torrent);
435 void handleTorrentResumed(TorrentImpl *torrent);
436 void handleTorrentChecked(TorrentImpl *torrent);
437 void handleTorrentFinished(TorrentImpl *torrent);
438 void handleTorrentTrackersAdded(TorrentImpl *torrent, const QVector<TrackerEntry> &newTrackers);
439 void handleTorrentTrackersRemoved(TorrentImpl *torrent, const QStringList &deletedTrackers);
440 void handleTorrentTrackersChanged(TorrentImpl *torrent);
441 void handleTorrentUrlSeedsAdded(TorrentImpl *torrent, const QVector<QUrl> &newUrlSeeds);
442 void handleTorrentUrlSeedsRemoved(TorrentImpl *torrent, const QVector<QUrl> &urlSeeds);
443 void handleTorrentResumeDataReady(TorrentImpl *torrent, const LoadTorrentParams &data);
444 void handleTorrentInfoHashChanged(TorrentImpl *torrent, const InfoHash &prevInfoHash);
445 void handleTorrentStorageMovingStateChanged(TorrentImpl *torrent);
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 fileSearchFinished(const TorrentID &id, const Path &savePath, const PathList &fileNames);
475 private:
476 struct ResumeSessionContext;
478 struct MoveStorageJob
480 lt::torrent_handle torrentHandle;
481 Path path;
482 MoveStorageMode mode {};
483 MoveStorageContext context {};
486 struct RemovingTorrentData
488 QString name;
489 Path pathToRemove;
490 DeleteOption deleteOption {};
493 explicit SessionImpl(QObject *parent = nullptr);
494 ~SessionImpl();
496 bool hasPerTorrentRatioLimit() const;
497 bool hasPerTorrentSeedingTimeLimit() const;
498 bool hasPerTorrentInactiveSeedingTimeLimit() const;
500 // Session configuration
501 Q_INVOKABLE void configure();
502 void configureComponents();
503 void initializeNativeSession();
504 lt::settings_pack loadLTSettings() const;
505 void applyNetworkInterfacesSettings(lt::settings_pack &settingsPack) const;
506 void configurePeerClasses();
507 void initMetrics();
508 void applyBandwidthLimits();
509 void processBannedIPs(lt::ip_filter &filter);
510 QStringList getListeningIPs() const;
511 void configureListeningInterface();
512 void enableTracker(bool enable);
513 void enableBandwidthScheduler();
514 void populateAdditionalTrackers();
515 void enableIPFilter();
516 void disableIPFilter();
517 void processTrackerStatuses();
518 void populateExcludedFileNamesRegExpList();
519 void prepareStartup();
520 void handleLoadedResumeData(ResumeSessionContext *context);
521 void processNextResumeData(ResumeSessionContext *context);
522 void endStartup(ResumeSessionContext *context);
524 LoadTorrentParams initLoadTorrentParams(const AddTorrentParams &addTorrentParams);
525 bool addTorrent_impl(const TorrentDescriptor &source, const AddTorrentParams &addTorrentParams);
527 void updateSeedingLimitTimer();
528 void exportTorrentFile(const Torrent *torrent, const Path &folderPath);
530 void handleAlert(const lt::alert *a);
531 void handleAddTorrentAlerts(const std::vector<lt::alert *> &alerts);
532 void dispatchTorrentAlert(const lt::torrent_alert *a);
533 void handleStateUpdateAlert(const lt::state_update_alert *p);
534 void handleMetadataReceivedAlert(const lt::metadata_received_alert *p);
535 void handleFileErrorAlert(const lt::file_error_alert *p);
536 void handleTorrentRemovedAlert(const lt::torrent_removed_alert *p);
537 void handleTorrentDeletedAlert(const lt::torrent_deleted_alert *p);
538 void handleTorrentDeleteFailedAlert(const lt::torrent_delete_failed_alert *p);
539 void handlePortmapWarningAlert(const lt::portmap_error_alert *p);
540 void handlePortmapAlert(const lt::portmap_alert *p);
541 void handlePeerBlockedAlert(const lt::peer_blocked_alert *p);
542 void handlePeerBanAlert(const lt::peer_ban_alert *p);
543 void handleUrlSeedAlert(const lt::url_seed_alert *p);
544 void handleListenSucceededAlert(const lt::listen_succeeded_alert *p);
545 void handleListenFailedAlert(const lt::listen_failed_alert *p);
546 void handleExternalIPAlert(const lt::external_ip_alert *p);
547 void handleSessionStatsAlert(const lt::session_stats_alert *p);
548 void handleAlertsDroppedAlert(const lt::alerts_dropped_alert *p) const;
549 void handleStorageMovedAlert(const lt::storage_moved_alert *p);
550 void handleStorageMovedFailedAlert(const lt::storage_moved_failed_alert *p);
551 void handleSocks5Alert(const lt::socks5_alert *p) const;
552 void handleTrackerAlert(const lt::tracker_alert *a);
553 #ifdef QBT_USES_LIBTORRENT2
554 void handleTorrentConflictAlert(const lt::torrent_conflict_alert *a);
555 #endif
557 TorrentImpl *createTorrent(const lt::torrent_handle &nativeHandle, const LoadTorrentParams &params);
559 void saveResumeData();
560 void saveTorrentsQueue();
561 void removeTorrentsQueue();
563 std::vector<lt::alert *> getPendingAlerts(lt::time_duration time = lt::time_duration::zero()) const;
565 void moveTorrentStorage(const MoveStorageJob &job) const;
566 void handleMoveTorrentStorageJobFinished(const Path &newPath);
568 void loadCategories();
569 void storeCategories() const;
570 void upgradeCategories();
572 void saveStatistics() const;
573 void loadStatistics();
575 // BitTorrent
576 lt::session *m_nativeSession = nullptr;
577 NativeSessionExtension *m_nativeSessionExtension = nullptr;
579 bool m_deferredConfigureScheduled = false;
580 bool m_IPFilteringConfigured = false;
581 mutable bool m_listenInterfaceConfigured = false;
583 CachedSettingValue<bool> m_isDHTEnabled;
584 CachedSettingValue<bool> m_isLSDEnabled;
585 CachedSettingValue<bool> m_isPeXEnabled;
586 CachedSettingValue<bool> m_isIPFilteringEnabled;
587 CachedSettingValue<bool> m_isTrackerFilteringEnabled;
588 CachedSettingValue<Path> m_IPFilterFile;
589 CachedSettingValue<bool> m_announceToAllTrackers;
590 CachedSettingValue<bool> m_announceToAllTiers;
591 CachedSettingValue<int> m_asyncIOThreads;
592 CachedSettingValue<int> m_hashingThreads;
593 CachedSettingValue<int> m_filePoolSize;
594 CachedSettingValue<int> m_checkingMemUsage;
595 CachedSettingValue<int> m_diskCacheSize;
596 CachedSettingValue<int> m_diskCacheTTL;
597 CachedSettingValue<qint64> m_diskQueueSize;
598 CachedSettingValue<DiskIOType> m_diskIOType;
599 CachedSettingValue<DiskIOReadMode> m_diskIOReadMode;
600 CachedSettingValue<DiskIOWriteMode> m_diskIOWriteMode;
601 CachedSettingValue<bool> m_coalesceReadWriteEnabled;
602 CachedSettingValue<bool> m_usePieceExtentAffinity;
603 CachedSettingValue<bool> m_isSuggestMode;
604 CachedSettingValue<int> m_sendBufferWatermark;
605 CachedSettingValue<int> m_sendBufferLowWatermark;
606 CachedSettingValue<int> m_sendBufferWatermarkFactor;
607 CachedSettingValue<int> m_connectionSpeed;
608 CachedSettingValue<int> m_socketSendBufferSize;
609 CachedSettingValue<int> m_socketReceiveBufferSize;
610 CachedSettingValue<int> m_socketBacklogSize;
611 CachedSettingValue<bool> m_isAnonymousModeEnabled;
612 CachedSettingValue<bool> m_isQueueingEnabled;
613 CachedSettingValue<int> m_maxActiveDownloads;
614 CachedSettingValue<int> m_maxActiveUploads;
615 CachedSettingValue<int> m_maxActiveTorrents;
616 CachedSettingValue<bool> m_ignoreSlowTorrentsForQueueing;
617 CachedSettingValue<int> m_downloadRateForSlowTorrents;
618 CachedSettingValue<int> m_uploadRateForSlowTorrents;
619 CachedSettingValue<int> m_slowTorrentsInactivityTimer;
620 CachedSettingValue<int> m_outgoingPortsMin;
621 CachedSettingValue<int> m_outgoingPortsMax;
622 CachedSettingValue<int> m_UPnPLeaseDuration;
623 CachedSettingValue<int> m_peerToS;
624 CachedSettingValue<bool> m_ignoreLimitsOnLAN;
625 CachedSettingValue<bool> m_includeOverheadInLimits;
626 CachedSettingValue<QString> m_announceIP;
627 CachedSettingValue<int> m_maxConcurrentHTTPAnnounces;
628 CachedSettingValue<bool> m_isReannounceWhenAddressChangedEnabled;
629 CachedSettingValue<int> m_stopTrackerTimeout;
630 CachedSettingValue<int> m_maxConnections;
631 CachedSettingValue<int> m_maxUploads;
632 CachedSettingValue<int> m_maxConnectionsPerTorrent;
633 CachedSettingValue<int> m_maxUploadsPerTorrent;
634 CachedSettingValue<BTProtocol> m_btProtocol;
635 CachedSettingValue<bool> m_isUTPRateLimited;
636 CachedSettingValue<MixedModeAlgorithm> m_utpMixedMode;
637 CachedSettingValue<bool> m_IDNSupportEnabled;
638 CachedSettingValue<bool> m_multiConnectionsPerIpEnabled;
639 CachedSettingValue<bool> m_validateHTTPSTrackerCertificate;
640 CachedSettingValue<bool> m_SSRFMitigationEnabled;
641 CachedSettingValue<bool> m_blockPeersOnPrivilegedPorts;
642 CachedSettingValue<bool> m_isAddTrackersEnabled;
643 CachedSettingValue<QString> m_additionalTrackers;
644 CachedSettingValue<qreal> m_globalMaxRatio;
645 CachedSettingValue<int> m_globalMaxSeedingMinutes;
646 CachedSettingValue<int> m_globalMaxInactiveSeedingMinutes;
647 CachedSettingValue<bool> m_isAddTorrentToQueueTop;
648 CachedSettingValue<bool> m_isAddTorrentPaused;
649 CachedSettingValue<Torrent::StopCondition> m_torrentStopCondition;
650 CachedSettingValue<TorrentContentLayout> m_torrentContentLayout;
651 CachedSettingValue<bool> m_isAppendExtensionEnabled;
652 CachedSettingValue<int> m_refreshInterval;
653 CachedSettingValue<bool> m_isPreallocationEnabled;
654 CachedSettingValue<Path> m_torrentExportDirectory;
655 CachedSettingValue<Path> m_finishedTorrentExportDirectory;
656 CachedSettingValue<int> m_globalDownloadSpeedLimit;
657 CachedSettingValue<int> m_globalUploadSpeedLimit;
658 CachedSettingValue<int> m_altGlobalDownloadSpeedLimit;
659 CachedSettingValue<int> m_altGlobalUploadSpeedLimit;
660 CachedSettingValue<bool> m_isAltGlobalSpeedLimitEnabled;
661 CachedSettingValue<bool> m_isBandwidthSchedulerEnabled;
662 CachedSettingValue<bool> m_isPerformanceWarningEnabled;
663 CachedSettingValue<int> m_saveResumeDataInterval;
664 CachedSettingValue<int> m_port;
665 CachedSettingValue<QString> m_networkInterface;
666 CachedSettingValue<QString> m_networkInterfaceName;
667 CachedSettingValue<QString> m_networkInterfaceAddress;
668 CachedSettingValue<int> m_encryption;
669 CachedSettingValue<int> m_maxActiveCheckingTorrents;
670 CachedSettingValue<bool> m_isProxyPeerConnectionsEnabled;
671 CachedSettingValue<ChokingAlgorithm> m_chokingAlgorithm;
672 CachedSettingValue<SeedChokingAlgorithm> m_seedChokingAlgorithm;
673 CachedSettingValue<QStringList> m_storedTags;
674 CachedSettingValue<int> m_maxRatioAction;
675 CachedSettingValue<Path> m_savePath;
676 CachedSettingValue<Path> m_downloadPath;
677 CachedSettingValue<bool> m_isDownloadPathEnabled;
678 CachedSettingValue<bool> m_isSubcategoriesEnabled;
679 CachedSettingValue<bool> m_useCategoryPathsInManualMode;
680 CachedSettingValue<bool> m_isAutoTMMDisabledByDefault;
681 CachedSettingValue<bool> m_isDisableAutoTMMWhenCategoryChanged;
682 CachedSettingValue<bool> m_isDisableAutoTMMWhenDefaultSavePathChanged;
683 CachedSettingValue<bool> m_isDisableAutoTMMWhenCategorySavePathChanged;
684 CachedSettingValue<bool> m_isTrackerEnabled;
685 CachedSettingValue<int> m_peerTurnover;
686 CachedSettingValue<int> m_peerTurnoverCutoff;
687 CachedSettingValue<int> m_peerTurnoverInterval;
688 CachedSettingValue<int> m_requestQueueSize;
689 CachedSettingValue<bool> m_isExcludedFileNamesEnabled;
690 CachedSettingValue<QStringList> m_excludedFileNames;
691 CachedSettingValue<QStringList> m_bannedIPs;
692 CachedSettingValue<ResumeDataStorageType> m_resumeDataStorageType;
693 CachedSettingValue<bool> m_isMergeTrackersEnabled;
694 CachedSettingValue<bool> m_isI2PEnabled;
695 CachedSettingValue<QString> m_I2PAddress;
696 CachedSettingValue<int> m_I2PPort;
697 CachedSettingValue<bool> m_I2PMixedMode;
698 CachedSettingValue<int> m_I2PInboundQuantity;
699 CachedSettingValue<int> m_I2POutboundQuantity;
700 CachedSettingValue<int> m_I2PInboundLength;
701 CachedSettingValue<int> m_I2POutboundLength;
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<TorrentID, RemovingTorrentData> m_removingTorrents;
742 QSet<TorrentID> m_needSaveResumeDataTorrents;
743 QHash<TorrentID, TorrentID> m_changedTorrentIDs;
744 QMap<QString, CategoryOptions> m_categories;
745 QSet<QString> m_tags;
747 // This field holds amounts of peers reported by trackers in their responses to announces
748 // (torrent.tracker_name.tracker_local_endpoint.protocol_version.num_peers)
749 QHash<lt::torrent_handle, QHash<std::string, QHash<TrackerEntry::Endpoint, QMap<int, int>>>> m_updatedTrackerEntries;
751 // I/O errored torrents
752 QSet<TorrentID> m_recentErroredTorrents;
753 QTimer *m_recentErroredTorrentsTimer = nullptr;
755 SessionMetricIndices m_metricIndices;
756 lt::time_point m_statsLastTimestamp = lt::clock_type::now();
758 SessionStatus m_status;
759 CacheStatus m_cacheStatus;
761 QList<MoveStorageJob> m_moveStorageQueue;
763 QString m_lastExternalIP;
765 bool m_needUpgradeDownloadPath = false;
767 // All port mapping related routines are invoked from working thread
768 // so there are no synchronization used. If multithreaded access is
769 // ever required, synchronization should also be provided.
770 bool m_isPortMappingEnabled = false;
771 QHash<quint16, std::vector<lt::port_mapping_t>> m_mappedPorts;
773 QTimer *m_wakeupCheckTimer = nullptr;
774 QDateTime m_wakeupCheckTimestamp;
776 friend void Session::initInstance();
777 friend void Session::freeInstance();
778 friend Session *Session::instance();
779 static Session *m_instance;