8000 [feat] librqbit: support ephemeral ports when listening. by ikatson · Pull Request #455 · ikatson/rqbit · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

[feat] librqbit: support ephemeral ports when listening. #455

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jul 10, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
67 changes: 38 additions & 29 deletions crates/librqbit/src/listen.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use std::{
net::{Ipv4Addr, SocketAddr},
net::{Ipv6Addr, SocketAddr},
sync::Arc,
};

Expand Down Expand Up @@ -58,7 +58,7 @@ impl Default for ListenerOptions {
Self {
// TODO: once uTP is stable upgrade default to both
mode: ListenerMode::TcpOnly,
listen_addr: (Ipv4Addr::LOCALHOST, 0).into(),
listen_addr: (Ipv6Addr::UNSPECIFIED, 0).into(),
enable_upnp_port_forwarding: false,
utp_opts: None,
}
Expand All @@ -72,63 +72,72 @@ impl ListenerOptions {
cancellation_token: CancellationToken,
bind_device: Option<&BindDevice>,
) -> anyhow::Result<ListenResult> {
if self.listen_addr.port() == 0 {
anyhow::bail!("you must set the listen port explicitly")
}
let mut utp_opts = self.utp_opts.take().unwrap_or_default();
utp_opts.cancellation_token = cancellation_token.clone();
utp_opts.parent_span = parent_span;
utp_opts.dont_wait_for_lastack = true;

let tcp = async {
if !self.mode.tcp_enabled() {
return Ok::<_, anyhow::Error>(None);
}
let mut listen_addr = self.listen_addr;

let tcp_socket = if self.mode.tcp_enabled() {
let listener = TcpListener::bind_tcp(
self.listen_addr,
BindOpts {
request_dualstack: true,
reuseport: true,
reuseport: false,
device: bind_device,
},
)
.context("error starting TCP listener")?;
listen_addr = listener.bind_addr();
info!(
"Listening on TCP {:?} for incoming peer connections",
self.listen_addr
listen_addr
);
Ok(Some(listener))
Some(listener)
} else {
None
};

let utp = async {
if !self.mode.utp_enabled() {
return Ok::<_, anyhow::Error>(None);
}
let socket = UtpSocketUdp::new_udp_with_opts(
self.listen_addr,
let utp_socket = if self.mode.utp_enabled() {
let bind_result = UtpSocketUdp::new_udp_with_opts(
listen_addr,
utp_opts,
UtpSocketUdpOpts { bind_device },
)
.await
.context("error starting uTP listener")?;
info!(
"Listening on UDP {:?} for incoming uTP peer connections",
self.listen_addr
);
Ok(Some(socket))
.await;
match bind_result {
Ok(sock) => {
listen_addr = sock.bind_addr();
info!(
"Listening on UDP {:?} for incoming uTP peer connections",
listen_addr
);
Some(sock)
}
Err(e) if tcp_socket.is_some() => {
// If we listen over TCP, it's not a fatal error if we can't listen over uTP.
tracing::error!("Error listening on UDP {listen_addr:?}: {e:#}");
None
}
Err(e) => {
return Err(e.into());
}
}
} else {
None
};

let announce_port = if self.listen_addr.ip().is_loopback() {
let announce_port = if listen_addr.ip().is_loopback() {
None
} else {
Some(self.listen_addr.port())
Some(listen_addr.port())
};
let (tcp_socket, utp_socket) = tokio::try_join!(tcp, utp)?;
Ok(ListenResult {
tcp_socket,
utp_socket,
announce_port,
addr: self.listen_addr,
addr: listen_addr,
enable_upnp_port_forwarding: self.enable_upnp_port_forwarding,
})
}
Expand Down
35 changes: 10 additions & 25 deletions crates/rqbit/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -528,7 +528,7 @@ async fn async_main(mut opts: Opts, cancel: CancellationToken) -> anyhow::Result
};
let listen = listen_mode.map(|mode| ListenerOptions {
mode,
listen_addr: (opts.listen_ip, opts.listen_port.unwrap_or(4240)).into(),
listen_addr: (opts.listen_ip, opts.listen_port.unwrap_or(0)).into(),
enable_upnp_port_forwarding: !opts.disable_upnp_port_forward,
..Default::default()
});
Expand Down Expand Up @@ -618,6 +618,13 @@ async fn async_main(mut opts: Opts, cancel: CancellationToken) -> anyhow::Result
match &opts.subcommand {
SubCommand::Server(server_opts) => match &server_opts.subcommand {
ServerSubcommand::Start(start_opts) => {
// If the listen port wasn't set, default to 4240
if let Some(l) = sopts.listen.as_mut() {
if l.listen_addr.port() == 0 {
l.listen_addr.set_port(4240);
}
}

if !start_opts.disable_persistence {
if let Some(p) = start_opts.persistence_location.as_ref() {
if p.starts_with("postgres://") {
Expand Down Expand Up @@ -685,9 +692,8 @@ async fn async_main(mut opts: Opts, cancel: CancellationToken) -> anyhow::Result
}

if let Some(listen) = sopts.listen.as_mut() {
// We are creating ephemeral ports, no point in port forwarding.
// We are creating an ephemeral download, no point in port forwarding.
listen.enable_upnp_port_forwarding = false;
maybe_set_ephemeral_port(&opts.listen_port, listen)?;
}

let torrent_opts = || AddTorrentOptions {
Expand Down Expand Up @@ -822,9 +828,7 @@ async fn async_main(mut opts: Opts, cancel: CancellationToken) -> anyhow::Result
sopts.disable_dht_persistence = true;
sopts.persistence = None;

if let Some(listen) = sopts.listen.as_mut() {
maybe_set_ephemeral_port(&opts.listen_port, listen)?;
} else {
if sopts.listen.is_none() {
anyhow::bail!("you disabled all listeners, can't share");
}

Expand Down Expand Up @@ -875,25 +879,6 @@ async fn async_main(mut opts: Opts, cancel: CancellationToken) -> anyhow::Result
}
}

fn maybe_set_ephemeral_port(
forced_listen_port: &Option<u16>,
listen: &mut ListenerOptions,
) -> anyhow::Result<()> {
// If the user hasn't specified a specific port, find a free random port.
// It needs to be the same for TCP and UDP, as we announce that port
// to trackers and DHT.
if forced_listen_port.is_none() {
let mut addr = listen.listen_addr;
addr.set_port(0);
let ephemeral_port = std::net::TcpListener::bind(addr)
.and_then(|l| l.local_addr())
.context("failed finding an ephemeral TCP/UDP listen port to use")?
.port();
listen.listen_addr.set_port(ephemeral_port);
}
Ok(())
}

async fn start_http_api(
cancel: CancellationToken,
session: Arc<Session>,
Expand Down
0