Skip to content

misterdownloadmanager: The ultimate open-source, clean-room download manager written from scratch in pure Rust for Windows, Mac, and Linux

Torrents: the DHT joins through four public routers, and the port picked is kept (#650) (#664)

Ahmed Nefzaoui69aeb6db1484
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 52491060..db9b191e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -17,6 +17,8 @@ Each release's notes on GitHub come from its section here (`## [X.Y.Z]`, see
### Fixed
+- Torrents: magnet links without trackers find peers through the DHT again where its first nodes didn't answer. MDM asked only two public routers to join the DHT; where neither answered (one name pointing at an old address, or a network blocking one), the DHT stayed empty and the log said "error in bootstrap" every minute or two. It now asks four together (`dht.libtorrent.org`, `dht.transmissionbt.com`, `router.bittorrent.com`, `router.utorrent.com`), any one that answers is enough, and the others are asked no more once one has. The nodes it knows are kept for the next start, the IPv6 ones too ([#650](https://github.com/anefzaoui/misterdownloadmanager/issues/650)).
+- Torrents: with the **Port** box empty in Torrent settings, MDM keeps the port it picked and listens on it again at the next start (another one if a program has taken it), so peers that learned it, and a router's or firewall's rule for it, still reach MDM; it was a new port at each start. MDM's log says where it listens: one socket for IPv4 and IPv6, which Windows' `netstat -p tcp` (IPv4 only) doesn't list ([#650](https://github.com/anefzaoui/misterdownloadmanager/issues/650)).
- macOS: YouTube videos that need yt-dlp's JavaScript runtime load when MDM is opened from Finder or the Dock. MDM found Homebrew's yt-dlp, but the helpers it started didn't get Homebrew's folders on their PATH, so yt-dlp found neither Deno nor ffmpeg ("Requested format is not available"); they now look there too, after the folders of their own PATH ([#659](https://github.com/anefzaoui/misterdownloadmanager/issues/659)).
- A download handed over by the browser whose link the site refuses to MDM before sending anything (FileHippo's links answered **412 Precondition Failed**; a one-time link the browser has already used, or one tied to its session, answers 403, 404 or 410) goes on from the address the browser's own download of it had reached, once; if that is refused too, the link's own answer is the error shown. Its cookies go there only when it is the same site ([#630](https://github.com/anefzaoui/misterdownloadmanager/issues/630)).
- Raising a speed limit, or turning it off, applies at once: to a download's own limit (its progress window's **Speed Limiter** tab), the limit for one file and the limit for all downloads together. A connection already waiting its turn under the old limit sat out the wait the old limit gave it, many seconds at a low limit, before the new speed showed; it now counts what is left at the new limit, and ends its wait as soon as there is no limit ([#621](https://github.com/anefzaoui/misterdownloadmanager/issues/621)).
diff --git a/Cargo.lock b/Cargo.lock
index 4ff494ad..76129acf 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -3975,7 +3975,7 @@ dependencies = [
[[package]]
name = "librqbit"
version = "9.1.0"
-source = "git+https://github.com/anefzaoui/rqbit.git?rev=ef50d87f4a9d5be9e3951b74f722433f9b46bd76#ef50d87f4a9d5be9e3951b74f722433f9b46bd76"
+source = "git+https://github.com/anefzaoui/rqbit.git?rev=ac7fa6e06b1a95956c63e1f5fd1cd795985967e1#ac7fa6e06b1a95956c63e1f5fd1cd795985967e1"
dependencies = [
"anyhow",
"arc-swap",
@@ -4038,7 +4038,7 @@ dependencies = [
[[package]]
name = "librqbit-bencode"
version = "9.1.0"
-source = "git+https://github.com/anefzaoui/rqbit.git?rev=ef50d87f4a9d5be9e3951b74f722433f9b46bd76#ef50d87f4a9d5be9e3951b74f722433f9b46bd76"
+source = "git+https://github.com/anefzaoui/rqbit.git?rev=ac7fa6e06b1a95956c63e1f5fd1cd795985967e1#ac7fa6e06b1a95956c63e1f5fd1cd795985967e1"
dependencies = [
"anyhow",
"arrayvec",
@@ -4054,7 +4054,7 @@ dependencies = [
[[package]]
name = "librqbit-buffers"
version = "9.1.0"
-source = "git+https://github.com/anefzaoui/rqbit.git?rev=ef50d87f4a9d5be9e3951b74f722433f9b46bd76#ef50d87f4a9d5be9e3951b74f722433f9b46bd76"
+source = "git+https://github.com/anefzaoui/rqbit.git?rev=ac7fa6e06b1a95956c63e1f5fd1cd795985967e1#ac7fa6e06b1a95956c63e1f5fd1cd795985967e1"
dependencies = [
"bytes",
"librqbit-clone-to-owned",
@@ -4065,7 +4065,7 @@ dependencies = [
[[package]]
name = "librqbit-clone-to-owned"
version = "9.1.0"
-source = "git+https://github.com/anefzaoui/rqbit.git?rev=ef50d87f4a9d5be9e3951b74f722433f9b46bd76#ef50d87f4a9d5be9e3951b74f722433f9b46bd76"
+source = "git+https://github.com/anefzaoui/rqbit.git?rev=ac7fa6e06b1a95956c63e1f5fd1cd795985967e1#ac7fa6e06b1a95956c63e1f5fd1cd795985967e1"
dependencies = [
"bytes",
]
@@ -4073,7 +4073,7 @@ dependencies = [
[[package]]
name = "librqbit-core"
version = "9.1.0"
-source = "git+https://github.com/anefzaoui/rqbit.git?rev=ef50d87f4a9d5be9e3951b74f722433f9b46bd76#ef50d87f4a9d5be9e3951b74f722433f9b46bd76"
+source = "git+https://github.com/anefzaoui/rqbit.git?rev=ac7fa6e06b1a95956c63e1f5fd1cd795985967e1#ac7fa6e06b1a95956c63e1f5fd1cd795985967e1"
dependencies = [
"anyhow",
"bytes",
@@ -4102,7 +4102,7 @@ dependencies = [
[[package]]
name = "librqbit-dht"
version = "9.1.0"
-source = "git+https://github.com/anefzaoui/rqbit.git?rev=ef50d87f4a9d5be9e3951b74f722433f9b46bd76#ef50d87f4a9d5be9e3951b74f722433f9b46bd76"
+source = "git+https://github.com/anefzaoui/rqbit.git?rev=ac7fa6e06b1a95956c63e1f5fd1cd795985967e1#ac7fa6e06b1a95956c63e1f5fd1cd795985967e1"
dependencies = [
"anyhow",
"backon",
@@ -4149,7 +4149,7 @@ dependencies = [
[[package]]
name = "librqbit-lsd"
version = "9.1.0"
-source = "git+https://github.com/anefzaoui/rqbit.git?rev=ef50d87f4a9d5be9e3951b74f722433f9b46bd76#ef50d87f4a9d5be9e3951b74f722433f9b46bd76"
+source = "git+https://github.com/anefzaoui/rqbit.git?rev=ac7fa6e06b1a95956c63e1f5fd1cd795985967e1#ac7fa6e06b1a95956c63e1f5fd1cd795985967e1"
dependencies = [
"anyhow",
"atoi",
@@ -4168,7 +4168,7 @@ dependencies = [
[[package]]
name = "librqbit-peer-protocol"
version = "9.1.0"
-source = "git+https://github.com/anefzaoui/rqbit.git?rev=ef50d87f4a9d5be9e3951b74f722433f9b46bd76#ef50d87f4a9d5be9e3951b74f722433f9b46bd76"
+source = "git+https://github.com/anefzaoui/rqbit.git?rev=ac7fa6e06b1a95956c63e1f5fd1cd795985967e1#ac7fa6e06b1a95956c63e1f5fd1cd795985967e1"
dependencies = [
"anyhow",
"bitvec",
@@ -4188,7 +4188,7 @@ dependencies = [
[[package]]
name = "librqbit-sha1-wrapper"
version = "9.1.0"
-source = "git+https://github.com/anefzaoui/rqbit.git?rev=ef50d87f4a9d5be9e3951b74f722433f9b46bd76#ef50d87f4a9d5be9e3951b74f722433f9b46bd76"
+source = "git+https://github.com/anefzaoui/rqbit.git?rev=ac7fa6e06b1a95956c63e1f5fd1cd795985967e1#ac7fa6e06b1a95956c63e1f5fd1cd795985967e1"
dependencies = [
"assert_cfg",
"aws-lc-rs",
@@ -4197,7 +4197,7 @@ dependencies = [
[[package]]
name = "librqbit-tracker-comms"
version = "9.1.0"
-source = "git+https://github.com/anefzaoui/rqbit.git?rev=ef50d87f4a9d5be9e3951b74f722433f9b46bd76#ef50d87f4a9d5be9e3951b74f722433f9b46bd76"
+source = "git+https://github.com/anefzaoui/rqbit.git?rev=ac7fa6e06b1a95956c63e1f5fd1cd795985967e1#ac7fa6e06b1a95956c63e1f5fd1cd795985967e1"
dependencies = [
"anyhow",
"async-stream",
@@ -4225,7 +4225,7 @@ dependencies = [
[[package]]
name = "librqbit-upnp"
version = "9.1.0"
-source = "git+https://github.com/anefzaoui/rqbit.git?rev=ef50d87f4a9d5be9e3951b74f722433f9b46bd76#ef50d87f4a9d5be9e3951b74f722433f9b46bd76"
+source = "git+https://github.com/anefzaoui/rqbit.git?rev=ac7fa6e06b1a95956c63e1f5fd1cd795985967e1#ac7fa6e06b1a95956c63e1f5fd1cd795985967e1"
dependencies = [
"anyhow",
"bstr",
@@ -4735,6 +4735,7 @@ dependencies = [
"tempfile",
"thiserror 2.0.21",
"tokio",
+ "tracing",
"tracing-subscriber",
"url",
]
diff --git a/Cargo.toml b/Cargo.toml
index 0b51c03e..ad55749c 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -195,19 +195,20 @@ debug = "line-tables-only"
# librqbit 9.1.0 with per-torrent rate limits that change while a torrent runs (#39), and a
# magnet lookup's progress counted (#92), and every socket bound to one address (`bind_ip`,
# #143), and every HTTP client of a session built through MDM's TLS setup (`configure_http_client`:
-# a system without CA certificates), until upstream has them (ikatson/rqbit); every crate of that
-# repository from the same commit.
-librqbit = { git = "https://github.com/anefzaoui/rqbit.git", rev = "ef50d87f4a9d5be9e3951b74f722433f9b46bd76" }
-librqbit-bencode = { git = "https://github.com/anefzaoui/rqbit.git", rev = "ef50d87f4a9d5be9e3951b74f722433f9b46bd76" }
-librqbit-buffers = { git = "https://github.com/anefzaoui/rqbit.git", rev = "ef50d87f4a9d5be9e3951b74f722433f9b46bd76" }
-librqbit-clone-to-owned = { git = "https://github.com/anefzaoui/rqbit.git", rev = "ef50d87f4a9d5be9e3951b74f722433f9b46bd76" }
-librqbit-core = { git = "https://github.com/anefzaoui/rqbit.git", rev = "ef50d87f4a9d5be9e3951b74f722433f9b46bd76" }
-librqbit-dht = { git = "https://github.com/anefzaoui/rqbit.git", rev = "ef50d87f4a9d5be9e3951b74f722433f9b46bd76" }
-librqbit-lsd = { git = "https://github.com/anefzaoui/rqbit.git", rev = "ef50d87f4a9d5be9e3951b74f722433f9b46bd76" }
-librqbit-peer-protocol = { git = "https://github.com/anefzaoui/rqbit.git", rev = "ef50d87f4a9d5be9e3951b74f722433f9b46bd76" }
-librqbit-sha1-wrapper = { git = "https://github.com/anefzaoui/rqbit.git", rev = "ef50d87f4a9d5be9e3951b74f722433f9b46bd76" }
-librqbit-tracker-comms = { git = "https://github.com/anefzaoui/rqbit.git", rev = "ef50d87f4a9d5be9e3951b74f722433f9b46bd76" }
-librqbit-upnp = { git = "https://github.com/anefzaoui/rqbit.git", rev = "ef50d87f4a9d5be9e3951b74f722433f9b46bd76" }
+# a system without CA certificates), and a DHT that stops asking a bootstrap node that never
+# answers once another one has, and loads its saved IPv6 nodes (#650), until upstream has them
+# (ikatson/rqbit); every crate of that repository from the same commit.
+librqbit = { git = "https://github.com/anefzaoui/rqbit.git", rev = "ac7fa6e06b1a95956c63e1f5fd1cd795985967e1" }
+librqbit-bencode = { git = "https://github.com/anefzaoui/rqbit.git", rev = "ac7fa6e06b1a95956c63e1f5fd1cd795985967e1" }
+librqbit-buffers = { git = "https://github.com/anefzaoui/rqbit.git", rev = "ac7fa6e06b1a95956c63e1f5fd1cd795985967e1" }
+librqbit-clone-to-owned = { git = "https://github.com/anefzaoui/rqbit.git", rev = "ac7fa6e06b1a95956c63e1f5fd1cd795985967e1" }
+librqbit-core = { git = "https://github.com/anefzaoui/rqbit.git", rev = "ac7fa6e06b1a95956c63e1f5fd1cd795985967e1" }
+librqbit-dht = { git = "https://github.com/anefzaoui/rqbit.git", rev = "ac7fa6e06b1a95956c63e1f5fd1cd795985967e1" }
+librqbit-lsd = { git = "https://github.com/anefzaoui/rqbit.git", rev = "ac7fa6e06b1a95956c63e1f5fd1cd795985967e1" }
+librqbit-peer-protocol = { git = "https://github.com/anefzaoui/rqbit.git", rev = "ac7fa6e06b1a95956c63e1f5fd1cd795985967e1" }
+librqbit-sha1-wrapper = { git = "https://github.com/anefzaoui/rqbit.git", rev = "ac7fa6e06b1a95956c63e1f5fd1cd795985967e1" }
+librqbit-tracker-comms = { git = "https://github.com/anefzaoui/rqbit.git", rev = "ac7fa6e06b1a95956c63e1f5fd1cd795985967e1" }
+librqbit-upnp = { git = "https://github.com/anefzaoui/rqbit.git", rev = "ac7fa6e06b1a95956c63e1f5fd1cd795985967e1" }
ecolor = { git = "https://github.com/anefzaoui/egui.git", rev = "4ad60e5365470a6d12166a8075478f8aea44c9f8" }
emath = { git = "https://github.com/anefzaoui/egui.git", rev = "4ad60e5365470a6d12166a8075478f8aea44c9f8" }
epaint = { git = "https://github.com/anefzaoui/egui.git", rev = "4ad60e5365470a6d12166a8075478f8aea44c9f8" }
diff --git a/ROADMAP.md b/ROADMAP.md
index a2d0b883..b4eef43d 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -565,6 +565,10 @@ These ship in a later version, when they're ready.
### Bugs being looked into
+- πŸ”„ Torrents: magnet links without trackers finding no peers where the DHT's first nodes didn't
+ answer ([#650](https://github.com/anefzaoui/misterdownloadmanager/issues/650)): four public
+ routers asked together, the ones that never answer left alone once one has, the IPv6 nodes kept
+ for the next start too, and the port picked kept from one start to the next; fix in review
- πŸ”„ Windows: the window stopping on a stalled system while it checked its title bar's colours
([#633](https://github.com/anefzaoui/misterdownloadmanager/issues/633),
[#583](https://github.com/anefzaoui/misterdownloadmanager/issues/583)): the colours are now set
diff --git a/crates/torrent/Cargo.toml b/crates/torrent/Cargo.toml
index 8f18795d..3a0211f5 100644
--- a/crates/torrent/Cargo.toml
+++ b/crates/torrent/Cargo.toml
@@ -18,6 +18,8 @@ flate2.workspace = true
# Reading librqbit's saved session (session.json) before it starts (lib.rs).
serde_json.workspace = true
thiserror.workspace = true
+# MDM's log: where the session listens (lib.rs).
+tracing.workspace = true
tokio.workspace = true
# The blocklist file's URL, and trackers' hosts (lib.rs, trackers.rs).
url.workspace = true
diff --git a/crates/torrent/examples/metadata_probe.rs b/crates/torrent/examples/metadata_probe.rs
index 78de5034..4a6e1f33 100644
--- a/crates/torrent/examples/metadata_probe.rs
+++ b/crates/torrent/examples/metadata_probe.rs
@@ -8,7 +8,12 @@
//!
//! SOURCE: a magnet link, or a .torrent file (looked up as its magnet link, with its trackers).
//! Options: `--no-trackers` (the DHT alone), `--no-dht` (the trackers alone), `--runs N` (each
-//! source N times), `--wait S` (give up after S seconds, 180 by default, as the app).
+//! source N times), `--wait S` (give up after S seconds, 180 by default, as the app),
+//! `--state DIR` (the session's folder, kept: a later run starts with the DHT nodes and the port
+//! of the one before, as the app's next session does), `--bootstrap HOST:PORT,...` (the DHT's
+//! first nodes instead of MDM's public routers, #650), `--listen-ip ADDR` (listen there only:
+//! 127.0.0.1 or ::1 keeps Windows Firewall out of it; the DHT then stays on it too, and local
+//! peer discovery is off).
//! Prints a Markdown table, a row a run; times in seconds from the session's start. RUST_LOG
//! (`librqbit_dht=debug`, ...) adds librqbit's log on stderr.
@@ -50,12 +55,28 @@ async fn main() {
};
let runs = value("--runs", 1);
let wait = Duration::from_secs(value("--wait", 180));
+ let mut text = |name: &str| {
+ let i = args.iter().position(|a| a == name)?;
+ args.remove(i);
+ Some(args.remove(i))
+ };
+ let state = text("--state").map(std::path::PathBuf::from);
+ let listen_ip = text("--listen-ip").map(|a| a.parse().expect("an IP address"));
+ let bootstrap = text("--bootstrap").map(|b| b.split(',').map(str::to_owned).collect());
if args.is_empty() {
eprintln!(
- "usage: metadata_probe [--no-trackers] [--no-dht] [--runs N] [--wait S] SOURCE..."
+ "usage: metadata_probe [--no-trackers] [--no-dht] [--runs N] [--wait S] \
+ [--state DIR] [--bootstrap HOST:PORT,...] [--listen-ip ADDR] SOURCE..."
);
std::process::exit(2);
}
+ let setup = Setup {
+ dht: !no_dht,
+ wait,
+ state,
+ bootstrap,
+ listen_ip,
+ };
println!(
"| source | trackers | DHT | session | DHT β‰₯ 8 nodes | 1st tracker peer | 1st DHT peer | 1st answer | file list | peers asked / answered |"
@@ -64,7 +85,7 @@ async fn main() {
for source in &args {
let (name, magnet) = magnet_of(source, no_trackers);
for _ in 0..runs {
- let row = run(&name, &magnet, !no_dht, wait).await;
+ let row = run(&name, &magnet, &setup).await;
println!("{row}");
}
}
@@ -98,15 +119,30 @@ fn magnet_of(source: &str, no_trackers: bool) -> (String, String) {
(name, magnet)
}
-async fn run(name: &str, magnet: &str, dht: bool, wait: Duration) -> String {
- let dir = tempfile::tempdir().expect("a temporary folder");
+struct Setup {
+ dht: bool,
+ wait: Duration,
+ state: Option<std::path::PathBuf>,
+ bootstrap: Option<Vec<String>>,
+ listen_ip: Option<std::net::IpAddr>,
+}
+
+async fn run(name: &str, magnet: &str, setup: &Setup) -> String {
+ let tmp = tempfile::tempdir().expect("a temporary folder");
+ let dir = setup.state.clone().unwrap_or_else(|| tmp.path().to_owned());
let t0 = Instant::now();
let t = Torrents::start(Config {
- dht,
- ..Config::new(dir.path().to_owned())
+ dht: setup.dht,
+ dht_bootstrap: setup.bootstrap.clone(),
+ listen_ip: setup.listen_ip,
+ // Local peer discovery listens on every address (UDP 6771): not with one address.
+ lsd: setup.listen_ip.is_none(),
+ ..Config::new(dir)
})
.await
.expect("session started");
+ let wait = setup.wait;
+ eprintln!("probe: listening on {:?}", t.listen_addr());
let started = t0.elapsed().as_secs_f64();
let lookup = std::sync::Arc::new(Lookup::default());
let marks = std::sync::Arc::new(std::sync::Mutex::new(Marks::default()));
diff --git a/crates/torrent/src/lib.rs b/crates/torrent/src/lib.rs
index fca53c67..e42e6d6d 100644
--- a/crates/torrent/src/lib.rs
+++ b/crates/torrent/src/lib.rs
@@ -485,6 +485,64 @@ fn id(hash: &str) -> Result<TorrentIdOrHash, TorrentError> {
TorrentIdOrHash::parse(hash).map_err(|_| TorrentError::Unknown)
}
+/// The DHT's first nodes on the internet (#650): the public routers BitTorrent clients use. Any
+/// one that answers is enough; they are asked together, and the rest no more once one has
+/// answered. librqbit's own two alone left the DHT empty where neither answered (a name
+/// resolving to an old address, a network blocking one), and magnet links without trackers
+/// then found no peer. Later starts begin with the nodes saved in `dht.json`.
+pub const DHT_BOOTSTRAP: &[&str] = &[
+ "dht.libtorrent.org:25401",
+ "dht.transmissionbt.com:6881",
+ "router.bittorrent.com:6881",
+ "router.utorrent.com:6881",
+];
+
+/// The DHT's first nodes: the ones a test names, else [`DHT_BOOTSTRAP`].
+fn bootstrap_nodes(cfg: &Config) -> Vec<String> {
+ cfg.dht_bootstrap
+ .clone()
+ .unwrap_or_else(|| DHT_BOOTSTRAP.iter().map(|a| (*a).to_owned()).collect())
+}
+
+/// The file in the state folder that keeps the port picked when Torrent settings name none
+/// (#650): the next session listens on it again, so peers that learned it, and a router's or
+/// firewall's rule for it, still reach MDM.
+const PORT_FILE: &str = "listen-port";
+
+fn saved_port(state_dir: &Path) -> Option<u16> {
+ std::fs::read_to_string(state_dir.join(PORT_FILE))
+ .ok()?
+ .trim()
+ .parse()
+ .ok()
+ .filter(|p| *p != 0)
+}
+
+/// Where the session listens, in MDM's log (#650): a listener on every address is one IPv6
+/// socket that takes IPv4 too, which Windows' `netstat -p tcp` (IPv4 only) doesn't list.
+/// `saved_nodes`: the DHT started from the nodes the last session saved (`dht.json`).
+fn log_network(session: &Session, saved_nodes: bool) {
+ match session.listen_addr() {
+ Some(a) if a.ip().is_unspecified() && a.is_ipv6() => tracing::info!(
+ "torrents: listening for peers on TCP port {} (every address, IPv4 and IPv6: {a})",
+ a.port()
+ ),
+ Some(a) => tracing::info!("torrents: listening for peers on TCP {a}"),
+ None => tracing::info!("torrents: not listening for peers (Torrent settings or a proxy)"),
+ }
+ if let Some(dht) = session.get_dht() {
+ tracing::info!(
+ "torrents: DHT on UDP {}, starting from {}",
+ dht.listen_addr(),
+ if saved_nodes {
+ "the nodes the last session saved, and the bootstrap nodes"
+ } else {
+ "the bootstrap nodes"
+ }
+ );
+ }
+}
+
impl Torrents {
pub async fn start(cfg: Config) -> Result<Torrents, TorrentError> {
std::fs::create_dir_all(&cfg.state_dir).map_err(engine)?;
@@ -496,25 +554,34 @@ impl Torrents {
};
// Offline only without one named: a test's DHT on loopback is still on.
let dht_on = cfg.dht && !proxied && (!cfg.offline || cfg.dht_bootstrap.is_some());
- let dht = dht_on.then(|| librqbit::DhtSessionConfig {
- bootstrap_addrs: cfg.dht_bootstrap.clone(),
- persistence: Some(librqbit::dht::DhtPersistenceConfig {
- dump_interval: None,
- config_filename: Some(cfg.state_dir.join("dht.json")),
- }),
- ..Default::default()
- });
+ let dht = || {
+ dht_on.then(|| librqbit::DhtSessionConfig {
+ bootstrap_addrs: Some(bootstrap_nodes(&cfg)),
+ persistence: Some(librqbit::dht::DhtPersistenceConfig {
+ dump_interval: None,
+ config_filename: Some(cfg.state_dir.join("dht.json")),
+ }),
+ ..Default::default()
+ })
+ };
// Offline (tests): loopback only. A set address: that one (with the port asked for).
// Bound to an address: on it.
let ip = cfg.listen_ip.or(bind_ip).or(cfg
.offline
.then_some(std::net::IpAddr::V4(Ipv4Addr::LOCALHOST)));
- let listen = (cfg.listen && !proxied).then(|| ListenerOptions {
+ let listening = cfg.listen && !proxied;
+ // No port in Torrent settings: the one the last session listened on, when there was one.
+ let saved = if listening && cfg.port.is_none() {
+ saved_port(&cfg.state_dir)
+ } else {
+ None
+ };
+ let listen = |port: u16| ListenerOptions {
listen_addr: match ip {
- Some(ip) => (ip, cfg.port.unwrap_or(0)).into(),
+ Some(ip) => (ip, port).into(),
None => {
let mut any = ListenerOptions::default().listen_addr;
- any.set_port(cfg.port.unwrap_or(0));
+ any.set_port(port);
any
}
},
@@ -526,7 +593,7 @@ impl Torrents {
&& ip.is_none_or(|i| !i.is_loopback()),
ipv4_only: cfg.offline || v4_only || ip.is_some_and(|i| i.is_ipv4()),
..Default::default()
- });
+ };
// A list librqbit can't read would stop the session from starting: only a file there.
let blocklist_url = cfg
.blocklist
@@ -534,14 +601,14 @@ impl Torrents {
.filter(|p| p.is_file())
.and_then(|p| url::Url::from_file_path(p).ok())
.map(|u| u.to_string());
- let opts = SessionOptions {
- dht,
- listen,
+ let opts = |port: u16| SessionOptions {
+ dht: dht(),
+ listen: listening.then(|| listen(port)),
connect: cfg.proxy.clone().map(|proxy| ConnectionOptions {
proxy_url: Some(proxy),
..Default::default()
}),
- blocklist_url,
+ blocklist_url: blocklist_url.clone(),
disable_trackers: cfg.offline,
// Behind a proxy, UDP trackers are dropped (they would go around it): their client
// sends from loopback, so no UDP can leave. A set listen address: that one (tests,
@@ -579,11 +646,29 @@ impl Torrents {
..Default::default()
};
prepare_saved(&cfg.state_dir.join("session"), proxied);
+ let saved_nodes = dht_on && cfg.state_dir.join("dht.json").is_file();
+ let output = cfg.state_dir.join("unsorted");
+ let port = cfg.port.or(saved).unwrap_or(0);
+ let session = match Session::new_with_opts(output.clone(), opts(port)).await {
+ // The saved port taken (another program has it now): any other one. A port set in
+ // Torrent settings is kept, and its error says why.
+ Err(e) if saved.is_some() => {
+ tracing::warn!(
+ "torrents: can't listen on port {port} again ({e:#}); taking another one"
+ );
+ Session::new_with_opts(output, opts(0)).await
+ }
+ started => started,
+ }
// With its causes: "error starting listeners: error binding: …" says why (an adapter's
// address gone, #143).
- let session = Session::new_with_opts(cfg.state_dir.join("unsorted"), opts)
- .await
- .map_err(|e| engine(format!("{e:#}")))?;
+ .map_err(|e| engine(format!("{e:#}")))?;
+ log_network(&session, saved_nodes);
+ if let (true, None, Some(addr)) = (listening, cfg.port, session.listen_addr())
+ && saved != Some(addr.port())
+ {
+ let _ = std::fs::write(cfg.state_dir.join(PORT_FILE), addr.port().to_string());
+ }
let api = Api::new(session.clone(), None);
Ok(Torrents {
session,
@@ -1487,6 +1572,77 @@ mod tests {
t.stop().await;
}
+ /// #650: with no port in Torrent settings, the one picked is kept: the next session
+ /// listens on it again. When another program has it by then, another one is taken, and kept
+ /// from then on. A port set in Torrent settings isn't saved.
+ #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
+ async fn the_picked_port_is_kept() {
+ let tmp = tempfile::tempdir().unwrap();
+ // On loopback: a listener on every address makes Windows Firewall ask about each new
+ // test build.
+ let cfg = |dir: &str| Config {
+ upnp: false,
+ dht: false,
+ lsd: false,
+ listen_ip: Some(std::net::IpAddr::V4(Ipv4Addr::LOCALHOST)),
+ ..Config::new(tmp.path().join(dir))
+ };
+ let port = |t: &Torrents| t.listen_addr().expect("listens").port();
+ let saved = || saved_port(&tmp.path().join("auto"));
+
+ let t = Torrents::start(cfg("auto")).await.unwrap();
+ let first = port(&t);
+ assert_eq!(saved(), Some(first));
+ t.stop().await;
+ let t = Torrents::start(cfg("auto")).await.unwrap();
+ assert_eq!(port(&t), first, "the same port again");
+ t.stop().await;
+
+ let other = std::net::TcpListener::bind((Ipv4Addr::LOCALHOST, first)).unwrap();
+ let t = Torrents::start(cfg("auto")).await.unwrap();
+ let second = port(&t);
+ assert_ne!(second, first, "another program has it");
+ assert_eq!(saved(), Some(second));
+ t.stop().await;
+ drop(other);
+
+ let free = std::net::TcpListener::bind((Ipv4Addr::LOCALHOST, 0))
+ .unwrap()
+ .local_addr()
+ .unwrap()
+ .port();
+ let t = Torrents::start(Config {
+ port: Some(free),
+ ..cfg("fixed")
+ })
+ .await
+ .unwrap();
+ assert_eq!(port(&t), free);
+ assert_eq!(saved_port(&tmp.path().join("fixed")), None);
+ t.stop().await;
+ }
+
+ /// #650: the DHT starts from several public routers, not librqbit's two alone; a test's
+ /// own nodes replace them.
+ #[test]
+ fn the_dht_has_fallback_routers() {
+ let cfg = Config::new(PathBuf::from("state"));
+ let nodes = bootstrap_nodes(&cfg);
+ for router in [
+ "dht.libtorrent.org:25401",
+ "dht.transmissionbt.com:6881",
+ "router.bittorrent.com:6881",
+ "router.utorrent.com:6881",
+ ] {
+ assert!(nodes.iter().any(|n| n == router), "{router} in {nodes:?}");
+ }
+ let own = Config {
+ dht_bootstrap: Some(vec!["127.0.0.1:6881".into()]),
+ ..cfg
+ };
+ assert_eq!(bootstrap_nodes(&own), ["127.0.0.1:6881"]);
+ }
+
#[test]
fn torrent_files_are_read_up_to_their_cap() {
let dir = tempfile::tempdir().unwrap();
diff --git a/docs/torrent-security.md b/docs/torrent-security.md
index be1615ee..498fe705 100644
--- a/docs/torrent-security.md
+++ b/docs/torrent-security.md
@@ -18,7 +18,7 @@ MDM starts its torrent engine the first time a torrent needs it. With **Stop the
This is the only part of MDM that waits for connections from outside. Downloads, MDM's DNS choice (Options β†’ Connection β†’ DNS), its updates and its helpers only connect out, so they never need a firewall exception; the browser extension and the automation API reach MDM on this computer only (127.0.0.1).
-In Torrent settings you can turn off **Accept incoming connections** and **Map the port on the router (UPnP)**, or the DHT. Downloads still work, sometimes more slowly. A fixed **Port** keeps firewall and router rules working. These changes apply the next time the engine starts, so when no torrent is running.
+In Torrent settings you can turn off **Accept incoming connections** and **Map the port on the router (UPnP)**, or the DHT. Downloads still work, sometimes more slowly. With the **Port** box empty, MDM picks a port the first time and keeps it (another one if a program has taken it since), so firewall and router rules keep working; a port typed there is always the one used. These changes apply the next time the engine starts, so when no torrent is running.
The torrent engine is written in Rust, which rules out many memory bugs, and MDM checks every piece against the torrent's fingerprint, so a peer can't slip in altered data. MDM keeps the engine up to date with the fixes its authors publish.
diff --git a/docs/torrents.md b/docs/torrents.md
index 060c9473..4fb279e4 100644
--- a/docs/torrents.md
+++ b/docs/torrents.md
@@ -115,6 +115,10 @@ The same window has the network switches (incoming connections, the port, UPnP,
MDM starts its torrent engine the first time you add a torrent. If you never use torrents, it never listens for peers.
+To find peers without trackers, MDM joins the DHT through four public routers (`dht.libtorrent.org`, `dht.transmissionbt.com`, `router.bittorrent.com` and `router.utorrent.com`); any one that answers is enough. It keeps the DHT nodes it found for the next start, so later starts don't depend on those routers.
+
+MDM's log (`logs\mdm.log` in [MDM's data folder](crash-reports.md#where-reports-are-kept)) says where it listens, for example `torrents: listening for peers on TCP port 51413 (every address, IPv4 and IPv6: [::]:51413)`. That is one socket for IPv4 and IPv6, so on Windows `netstat -ano -p tcp` (IPv4 only) doesn't list it; `netstat -ano` or `Get-NetTCPConnection -State Listen` does, under `[::]` or `::`.
+
On a Linux system without CA certificates (a minimal install without the `ca-certificates` package), torrents still work: peers, the DHT and `http://` trackers. An `https://` tracker can't be checked there, so MDM skips it; install that package to use those too.
With a debrid account, torrents and magnet links can go to the service instead of to peers, and MDM downloads the files from it over HTTP: see [Torrents through the service](debrid.md#torrents-through-the-service).