From 6d9d5fa7a2f3d347ff2da8cc66cdf6a1cd4eb47d Mon Sep 17 00:00:00 2001 From: dignifiedquire Date: Wed, 18 Jun 2025 12:26:18 +0000 Subject: [PATCH] deploy: 06a88c62ec33d0b1f196d776065080f80a13f2e0 --- .../docs/iroh/discovery/pkarr/dht/index.html | 2 +- .../discovery/pkarr/dht/struct.Builder.html | 14 +- .../pkarr/dht/struct.DhtDiscovery.html | 4 +- .../docs/iroh/discovery/trait.Discovery.html | 2 +- pr/3314/docs/iroh/net_report/index.html | 2 +- .../iroh/net_report/struct.QuicConfig.html | 4 +- .../docs/src/iroh/discovery/pkarr/dht.rs.html | 409 ++-- pr/3314/docs/src/iroh/net_report.rs.html | 1791 +++++++++-------- .../src/iroh/net_report/reportgen.rs.html | 1369 +++++++------ pr/3314/docs/src/iroh_relay/quic.rs.html | 2 +- 10 files changed, 1800 insertions(+), 1799 deletions(-) diff --git a/pr/3314/docs/iroh/discovery/pkarr/dht/index.html b/pr/3314/docs/iroh/discovery/pkarr/dht/index.html index df70bf22cc..566a1adb7e 100644 --- a/pr/3314/docs/iroh/discovery/pkarr/dht/index.html +++ b/pr/3314/docs/iroh/discovery/pkarr/dht/index.html @@ -1,4 +1,4 @@ -iroh::discovery::pkarr::dht - Rust

Module dht

Source
Available on crate feature discovery-pkarr-dht only.
Expand description

Pkarr based node discovery for iroh, supporting both relay servers and the DHT.

+iroh::discovery::pkarr::dht - Rust

Module dht

Source
Available on crate feature discovery-pkarr-dht only.
Expand description

Pkarr based node discovery for iroh, supporting both relay servers and the DHT.

This module contains pkarr-based node discovery for iroh which can use both pkarr relay servers as well as the Mainline DHT directly. See the pkarr module for an overview of pkarr.

diff --git a/pr/3314/docs/iroh/discovery/pkarr/dht/struct.Builder.html b/pr/3314/docs/iroh/discovery/pkarr/dht/struct.Builder.html index c1f8ad1a40..f8283300a1 100644 --- a/pr/3314/docs/iroh/discovery/pkarr/dht/struct.Builder.html +++ b/pr/3314/docs/iroh/discovery/pkarr/dht/struct.Builder.html @@ -1,16 +1,16 @@ Builder in iroh::discovery::pkarr::dht - Rust

Struct Builder

Source
pub struct Builder { /* private fields */ }
Available on crate feature discovery-pkarr-dht only.
Expand description

Builder for DhtDiscovery.

By default, publishing to the DHT is enabled, and relay publishing is disabled.

-

Implementations§

Source§

impl Builder

Source

pub fn client(self, client: PkarrClient) -> Self

Explicitly sets the pkarr client to use.

+

Implementations§

Source§

impl Builder

Source

pub fn client(self, client: PkarrClient) -> Self

Explicitly sets the pkarr client to use.

Source

pub fn secret_key(self, secret_key: SecretKey) -> Self

Sets the secret key to use for signing the DNS packets.

Without a secret key, the node will not publish its address to the DHT.

Source

pub fn ttl(self, ttl: u32) -> Self

Sets the time-to-live value for the DNS packets.

Source

pub fn pkarr_relay(self, pkarr_relay: Url) -> Self

Sets the pkarr relay URL to use.

-
Source

pub fn n0_dns_pkarr_relay(self) -> Self

Uses the default number 0 pkarr relay URL.

-
Source

pub fn dht(self, dht: bool) -> Self

Sets whether to publish to the Mainline DHT.

-
Source

pub fn include_direct_addresses(self, include_direct_addresses: bool) -> Self

Sets whether to include the direct addresses in the DNS packet.

-
Source

pub fn initial_publish_delay(self, initial_publish_delay: Duration) -> Self

Sets the initial delay before the first publish.

-
Source

pub fn republish_delay(self, republish_delay: Duration) -> Self

Sets the republish delay for the DHT.

-
Source

pub fn build(self) -> Result<DhtDiscovery, DiscoveryError>

Builds the discovery mechanism.

+
Source

pub fn n0_dns_pkarr_relay(self) -> Self

Uses the default number 0 pkarr relay URL.

+
Source

pub fn dht(self, dht: bool) -> Self

Sets whether to publish to the Mainline DHT.

+
Source

pub fn include_direct_addresses(self, include_direct_addresses: bool) -> Self

Sets whether to include the direct addresses in the DNS packet.

+
Source

pub fn initial_publish_delay(self, initial_publish_delay: Duration) -> Self

Sets the initial delay before the first publish.

+
Source

pub fn republish_delay(self, republish_delay: Duration) -> Self

Sets the republish delay for the DHT.

+
Source

pub fn build(self) -> Result<DhtDiscovery, DiscoveryError>

Builds the discovery mechanism.

Trait Implementations§

Source§

impl Debug for Builder

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for Builder

Source§

fn default() -> Self

Returns the “default value” for a type. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where T: 'a,

§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where diff --git a/pr/3314/docs/iroh/discovery/pkarr/dht/struct.DhtDiscovery.html b/pr/3314/docs/iroh/discovery/pkarr/dht/struct.DhtDiscovery.html index fc3556b48d..66767238d1 100644 --- a/pr/3314/docs/iroh/discovery/pkarr/dht/struct.DhtDiscovery.html +++ b/pr/3314/docs/iroh/discovery/pkarr/dht/struct.DhtDiscovery.html @@ -4,8 +4,8 @@ them to the BitTorrent Mainline DHT. See the Discovery trait to be used as a node discovery service which can be used as both a publisher and resolver. Calling DhtDiscovery::publish will start a background task that periodically publishes the node address.

-

Implementations§

Source§

impl DhtDiscovery

Source

pub fn builder() -> Builder

Creates a new builder for DhtDiscovery.

-

Trait Implementations§

Source§

impl Clone for DhtDiscovery

Source§

fn clone(&self) -> DhtDiscovery

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for DhtDiscovery

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for DhtDiscovery

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl Discovery for DhtDiscovery

Source§

fn publish(&self, data: &NodeData)

Publishes the given NodeData to the discovery mechanism. Read more
Source§

fn resolve( +

Implementations§

Source§

impl DhtDiscovery

Source

pub fn builder() -> Builder

Creates a new builder for DhtDiscovery.

+

Trait Implementations§

Source§

impl Clone for DhtDiscovery

Source§

fn clone(&self) -> DhtDiscovery

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for DhtDiscovery

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for DhtDiscovery

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl Discovery for DhtDiscovery

Source§

fn publish(&self, data: &NodeData)

Publishes the given NodeData to the discovery mechanism. Read more
Source§

fn resolve( &self, _endpoint: Endpoint, node_id: NodeId, diff --git a/pr/3314/docs/iroh/discovery/trait.Discovery.html b/pr/3314/docs/iroh/discovery/trait.Discovery.html index 54cbc9fa33..bcfc9254fd 100644 --- a/pr/3314/docs/iroh/discovery/trait.Discovery.html +++ b/pr/3314/docs/iroh/discovery/trait.Discovery.html @@ -50,4 +50,4 @@ should be sent on all streams.

The crate::endpoint::Endpoint will subscribe to the discovery system and add the discovered addresses to the internal address book as they arrive on this stream.

-

Implementations on Foreign Types§

Source§

impl<T: Discovery> Discovery for Arc<T>

Implementors§

Source§

impl Discovery for DnsDiscovery

Available on non-wasm_browser only.
Source§

impl Discovery for MdnsDiscovery

Available on crate feature discovery-local-network only.
Source§

impl Discovery for DhtDiscovery

Available on crate feature discovery-pkarr-dht only.
Source§

impl Discovery for PkarrPublisher

Source§

impl Discovery for PkarrResolver

Source§

impl Discovery for StaticProvider

Source§

impl Discovery for ConcurrentDiscovery

\ No newline at end of file +

Implementations on Foreign Types§

Source§

impl<T: Discovery> Discovery for Arc<T>

Implementors§

Source§

impl Discovery for DnsDiscovery

Available on non-wasm_browser only.
Source§

impl Discovery for MdnsDiscovery

Available on crate feature discovery-local-network only.
Source§

impl Discovery for DhtDiscovery

Available on crate feature discovery-pkarr-dht only.
Source§

impl Discovery for PkarrPublisher

Source§

impl Discovery for PkarrResolver

Source§

impl Discovery for StaticProvider

Source§

impl Discovery for ConcurrentDiscovery

\ No newline at end of file diff --git a/pr/3314/docs/iroh/net_report/index.html b/pr/3314/docs/iroh/net_report/index.html index a324ba4ee7..813b437adc 100644 --- a/pr/3314/docs/iroh/net_report/index.html +++ b/pr/3314/docs/iroh/net_report/index.html @@ -1,4 +1,4 @@ -iroh::net_report - Rust

Module net_report

Source
Expand description

Checks the network conditions from the current host.

+iroh::net_report - Rust

Module net_report

Source
Expand description

Checks the network conditions from the current host.

NetReport is responsible for finding out the network conditions of the current host, like whether it is connected to the internet via IPv4 and/or IPv6, what the NAT situation is etc and reachability to the configured relays.

diff --git a/pr/3314/docs/iroh/net_report/struct.QuicConfig.html b/pr/3314/docs/iroh/net_report/struct.QuicConfig.html index 207d4bd510..79bcbab067 100644 --- a/pr/3314/docs/iroh/net_report/struct.QuicConfig.html +++ b/pr/3314/docs/iroh/net_report/struct.QuicConfig.html @@ -1,4 +1,4 @@ -QuicConfig in iroh::net_report - Rust

Struct QuicConfig

Source
pub struct QuicConfig {
+QuicConfig in iroh::net_report - Rust

Struct QuicConfig

Source
pub struct QuicConfig {
     pub ep: Endpoint,
     pub client_config: ClientConfig,
     pub ipv4: bool,
@@ -8,7 +8,7 @@
 
§client_config: ClientConfig

A client config.

§ipv4: bool

Enable ipv4 QUIC address discovery probes

§ipv6: bool

Enable ipv6 QUIC address discovery probes

-

Trait Implementations§

Source§

impl Clone for QuicConfig

Source§

fn clone(&self) -> QuicConfig

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for QuicConfig

Source§

fn fmt(&self, __derive_more_f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where +

Trait Implementations§

Source§

impl Clone for QuicConfig

Source§

fn clone(&self) -> QuicConfig

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for QuicConfig

Source§

fn fmt(&self, __derive_more_f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where T: 'a,

§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where T: 'a,

§

fn implicit( diff --git a/pr/3314/docs/src/iroh/discovery/pkarr/dht.rs.html b/pr/3314/docs/src/iroh/discovery/pkarr/dht.rs.html index e79fda46ad..5deda2fd97 100644 --- a/pr/3314/docs/src/iroh/discovery/pkarr/dht.rs.html +++ b/pr/3314/docs/src/iroh/discovery/pkarr/dht.rs.html @@ -19,7 +19,7 @@ 19 20use crate::{ 21 discovery::{ -22 pkarr::{DEFAULT_PKARR_TTL, N0_DNS_PKARR_RELAY_PROD}, +22 pkarr::{DEFAULT_PKARR_TTL, N0_DNS_PKARR_RELAY_PROD, N0_DNS_PKARR_RELAY_STAGING}, 23 Discovery, DiscoveryError, DiscoveryItem, NodeData, 24 }, 25 node_info::NodeInfo, @@ -171,206 +171,211 @@ 171 /// 172 /// [number 0]: https://n0.computer 173 pub fn n0_dns_pkarr_relay(mut self) -> Self { -174 self.pkarr_relay = Some(N0_DNS_PKARR_RELAY_PROD.parse().expect("valid URL")); -175 self -176 } -177 -178 /// Sets whether to publish to the Mainline DHT. -179 pub fn dht(mut self, dht: bool) -> Self { -180 self.dht = dht; -181 self -182 } -183 -184 /// Sets whether to include the direct addresses in the DNS packet. -185 pub fn include_direct_addresses(mut self, include_direct_addresses: bool) -> Self { -186 self.include_direct_addresses = include_direct_addresses; -187 self -188 } -189 -190 /// Sets the initial delay before the first publish. -191 pub fn initial_publish_delay(mut self, initial_publish_delay: Duration) -> Self { -192 self.initial_publish_delay = initial_publish_delay; -193 self -194 } -195 -196 /// Sets the republish delay for the DHT. -197 pub fn republish_delay(mut self, republish_delay: Duration) -> Self { -198 self.republish_delay = republish_delay; -199 self -200 } -201 -202 /// Builds the discovery mechanism. -203 pub fn build(self) -> Result<DhtDiscovery, DiscoveryError> { -204 if !(self.dht || self.pkarr_relay.is_some()) { -205 return Err(DiscoveryError::from_err( -206 "pkarr", -207 std::io::Error::other("at least one of DHT or relay must be enabled"), -208 )); -209 } -210 let pkarr = match self.client { -211 Some(client) => client, -212 None => { -213 let mut builder = PkarrClient::builder(); -214 builder.no_default_network(); -215 if self.dht { -216 builder.dht(|x| x); -217 } -218 if let Some(url) = &self.pkarr_relay { -219 builder -220 .relays(&[url.clone()]) -221 .map_err(|e| DiscoveryError::from_err("pkarr", e))?; +174 let url = if crate::endpoint::force_staging_infra() { +175 N0_DNS_PKARR_RELAY_STAGING +176 } else { +177 N0_DNS_PKARR_RELAY_PROD +178 }; +179 self.pkarr_relay = Some(url.parse().expect("valid URL")); +180 self +181 } +182 +183 /// Sets whether to publish to the Mainline DHT. +184 pub fn dht(mut self, dht: bool) -> Self { +185 self.dht = dht; +186 self +187 } +188 +189 /// Sets whether to include the direct addresses in the DNS packet. +190 pub fn include_direct_addresses(mut self, include_direct_addresses: bool) -> Self { +191 self.include_direct_addresses = include_direct_addresses; +192 self +193 } +194 +195 /// Sets the initial delay before the first publish. +196 pub fn initial_publish_delay(mut self, initial_publish_delay: Duration) -> Self { +197 self.initial_publish_delay = initial_publish_delay; +198 self +199 } +200 +201 /// Sets the republish delay for the DHT. +202 pub fn republish_delay(mut self, republish_delay: Duration) -> Self { +203 self.republish_delay = republish_delay; +204 self +205 } +206 +207 /// Builds the discovery mechanism. +208 pub fn build(self) -> Result<DhtDiscovery, DiscoveryError> { +209 if !(self.dht || self.pkarr_relay.is_some()) { +210 return Err(DiscoveryError::from_err( +211 "pkarr", +212 std::io::Error::other("at least one of DHT or relay must be enabled"), +213 )); +214 } +215 let pkarr = match self.client { +216 Some(client) => client, +217 None => { +218 let mut builder = PkarrClient::builder(); +219 builder.no_default_network(); +220 if self.dht { +221 builder.dht(|x| x); 222 } -223 builder -224 .build() -225 .map_err(|e| DiscoveryError::from_err("pkarr", e))? -226 } -227 }; -228 let ttl = self.ttl.unwrap_or(DEFAULT_PKARR_TTL); -229 let include_direct_addresses = self.include_direct_addresses; -230 -231 Ok(DhtDiscovery(Arc::new(Inner { -232 pkarr, -233 ttl, -234 relay_url: self.pkarr_relay, -235 include_direct_addresses, -236 secret_key: self.secret_key, -237 initial_publish_delay: self.initial_publish_delay, -238 republish_delay: self.republish_delay, -239 task: Default::default(), -240 }))) -241 } -242} -243 -244impl DhtDiscovery { -245 /// Creates a new builder for [`DhtDiscovery`]. -246 pub fn builder() -> Builder { -247 Builder::default() -248 } -249 -250 /// Periodically publishes the node address to the DHT and/or relay. -251 async fn publish_loop(self, keypair: SecretKey, signed_packet: SignedPacket) { -252 let this = self; -253 let z32 = pkarr::PublicKey::try_from(keypair.public().as_bytes()) -254 .expect("valid public key") -255 .to_z32(); -256 // initial delay. If the task gets aborted before this delay is over, -257 // we have not published anything to the DHT yet. -258 time::sleep(this.0.initial_publish_delay).await; -259 loop { -260 // TODO: publish takes a compare-and-swap timestamp, make use of that. -261 let res = this.0.pkarr.publish(&signed_packet, None).await; -262 match res { -263 Ok(()) => { -264 tracing::debug!("pkarr publish success. published under {z32}",); -265 } -266 Err(e) => { -267 // we could do a smaller delay here, but in general DHT publish -268 // not working is due to a network issue, and if the network changes -269 // the task will be restarted anyway. -270 // -271 // Being unable to publish to the DHT is something that is expected -272 // to happen from time to time, so this does not warrant a error log. -273 tracing::warn!("pkarr publish error: {}", e); -274 } -275 } -276 time::sleep(this.0.republish_delay).await; -277 } -278 } -279} -280 -281impl Discovery for DhtDiscovery { -282 fn publish(&self, data: &NodeData) { -283 let Some(keypair) = &self.0.secret_key else { -284 tracing::debug!("no keypair set, not publishing"); -285 return; -286 }; -287 tracing::debug!("publishing {data:?}"); -288 let mut info = NodeInfo::from_parts(keypair.public(), data.clone()); -289 if !self.0.include_direct_addresses { -290 info.clear_direct_addresses(); -291 } -292 let Ok(signed_packet) = info.to_pkarr_signed_packet(keypair, self.0.ttl) else { -293 tracing::warn!("failed to create signed packet"); -294 return; -295 }; -296 let this = self.clone(); -297 let curr = task::spawn(this.publish_loop(keypair.clone(), signed_packet)); -298 let mut task = self.0.task.lock().expect("poisoned"); -299 *task = Some(AbortOnDropHandle::new(curr)); -300 } -301 -302 fn resolve( -303 &self, -304 _endpoint: Endpoint, -305 node_id: NodeId, -306 ) -> Option<BoxStream<Result<DiscoveryItem, DiscoveryError>>> { -307 let pkarr_public_key = -308 pkarr::PublicKey::try_from(node_id.as_bytes()).expect("valid public key"); -309 tracing::info!("resolving {} as {}", node_id, pkarr_public_key.to_z32()); -310 let discovery = self.0.clone(); -311 let stream = n0_future::stream::once_future(async move { -312 discovery.resolve_pkarr(pkarr_public_key).await -313 }) -314 .filter_map(|x| x) -315 .boxed(); -316 Some(stream) -317 } -318} -319 -320#[cfg(test)] -321mod tests { -322 use std::collections::BTreeSet; -323 -324 use iroh_base::RelayUrl; -325 use n0_snafu::{Result, ResultExt}; -326 use tracing_test::traced_test; -327 -328 use super::*; -329 -330 #[tokio::test] -331 #[ignore = "flaky"] -332 #[traced_test] -333 async fn dht_discovery_smoke() -> Result { -334 let ep = crate::Endpoint::builder().bind().await?; -335 let secret = ep.secret_key().clone(); -336 let testnet = pkarr::mainline::Testnet::new_async(3).await.e()?; -337 let client = pkarr::Client::builder() -338 .dht(|builder| builder.bootstrap(&testnet.bootstrap)) -339 .build() -340 .e()?; -341 let discovery = DhtDiscovery::builder() -342 .secret_key(secret.clone()) -343 .initial_publish_delay(Duration::ZERO) -344 .client(client) -345 .build()?; -346 -347 let relay_url: RelayUrl = Url::parse("https://example.com").e()?.into(); -348 -349 let data = NodeData::default().with_relay_url(Some(relay_url.clone())); -350 discovery.publish(&data); +223 if let Some(url) = &self.pkarr_relay { +224 builder +225 .relays(&[url.clone()]) +226 .map_err(|e| DiscoveryError::from_err("pkarr", e))?; +227 } +228 builder +229 .build() +230 .map_err(|e| DiscoveryError::from_err("pkarr", e))? +231 } +232 }; +233 let ttl = self.ttl.unwrap_or(DEFAULT_PKARR_TTL); +234 let include_direct_addresses = self.include_direct_addresses; +235 +236 Ok(DhtDiscovery(Arc::new(Inner { +237 pkarr, +238 ttl, +239 relay_url: self.pkarr_relay, +240 include_direct_addresses, +241 secret_key: self.secret_key, +242 initial_publish_delay: self.initial_publish_delay, +243 republish_delay: self.republish_delay, +244 task: Default::default(), +245 }))) +246 } +247} +248 +249impl DhtDiscovery { +250 /// Creates a new builder for [`DhtDiscovery`]. +251 pub fn builder() -> Builder { +252 Builder::default() +253 } +254 +255 /// Periodically publishes the node address to the DHT and/or relay. +256 async fn publish_loop(self, keypair: SecretKey, signed_packet: SignedPacket) { +257 let this = self; +258 let z32 = pkarr::PublicKey::try_from(keypair.public().as_bytes()) +259 .expect("valid public key") +260 .to_z32(); +261 // initial delay. If the task gets aborted before this delay is over, +262 // we have not published anything to the DHT yet. +263 time::sleep(this.0.initial_publish_delay).await; +264 loop { +265 // TODO: publish takes a compare-and-swap timestamp, make use of that. +266 let res = this.0.pkarr.publish(&signed_packet, None).await; +267 match res { +268 Ok(()) => { +269 tracing::debug!("pkarr publish success. published under {z32}",); +270 } +271 Err(e) => { +272 // we could do a smaller delay here, but in general DHT publish +273 // not working is due to a network issue, and if the network changes +274 // the task will be restarted anyway. +275 // +276 // Being unable to publish to the DHT is something that is expected +277 // to happen from time to time, so this does not warrant a error log. +278 tracing::warn!("pkarr publish error: {}", e); +279 } +280 } +281 time::sleep(this.0.republish_delay).await; +282 } +283 } +284} +285 +286impl Discovery for DhtDiscovery { +287 fn publish(&self, data: &NodeData) { +288 let Some(keypair) = &self.0.secret_key else { +289 tracing::debug!("no keypair set, not publishing"); +290 return; +291 }; +292 tracing::debug!("publishing {data:?}"); +293 let mut info = NodeInfo::from_parts(keypair.public(), data.clone()); +294 if !self.0.include_direct_addresses { +295 info.clear_direct_addresses(); +296 } +297 let Ok(signed_packet) = info.to_pkarr_signed_packet(keypair, self.0.ttl) else { +298 tracing::warn!("failed to create signed packet"); +299 return; +300 }; +301 let this = self.clone(); +302 let curr = task::spawn(this.publish_loop(keypair.clone(), signed_packet)); +303 let mut task = self.0.task.lock().expect("poisoned"); +304 *task = Some(AbortOnDropHandle::new(curr)); +305 } +306 +307 fn resolve( +308 &self, +309 _endpoint: Endpoint, +310 node_id: NodeId, +311 ) -> Option<BoxStream<Result<DiscoveryItem, DiscoveryError>>> { +312 let pkarr_public_key = +313 pkarr::PublicKey::try_from(node_id.as_bytes()).expect("valid public key"); +314 tracing::info!("resolving {} as {}", node_id, pkarr_public_key.to_z32()); +315 let discovery = self.0.clone(); +316 let stream = n0_future::stream::once_future(async move { +317 discovery.resolve_pkarr(pkarr_public_key).await +318 }) +319 .filter_map(|x| x) +320 .boxed(); +321 Some(stream) +322 } +323} +324 +325#[cfg(test)] +326mod tests { +327 use std::collections::BTreeSet; +328 +329 use iroh_base::RelayUrl; +330 use n0_snafu::{Result, ResultExt}; +331 use tracing_test::traced_test; +332 +333 use super::*; +334 +335 #[tokio::test] +336 #[ignore = "flaky"] +337 #[traced_test] +338 async fn dht_discovery_smoke() -> Result { +339 let ep = crate::Endpoint::builder().bind().await?; +340 let secret = ep.secret_key().clone(); +341 let testnet = pkarr::mainline::Testnet::new_async(3).await.e()?; +342 let client = pkarr::Client::builder() +343 .dht(|builder| builder.bootstrap(&testnet.bootstrap)) +344 .build() +345 .e()?; +346 let discovery = DhtDiscovery::builder() +347 .secret_key(secret.clone()) +348 .initial_publish_delay(Duration::ZERO) +349 .client(client) +350 .build()?; 351 -352 // publish is fire and forget, so we have no way to wait until it is done. -353 tokio::time::timeout(Duration::from_secs(30), async move { -354 loop { -355 tokio::time::sleep(Duration::from_millis(200)).await; -356 let mut found_relay_urls = BTreeSet::new(); -357 let items = discovery -358 .resolve(ep.clone(), secret.public()) -359 .unwrap() -360 .collect::<Vec<_>>() -361 .await; -362 for item in items.into_iter().flatten() { -363 if let Some(url) = item.relay_url() { -364 found_relay_urls.insert(url.clone()); -365 } -366 } -367 if found_relay_urls.contains(&relay_url) { -368 break; -369 } -370 } -371 }) -372 .await -373 .expect("timeout, relay_url not found on DHT"); -374 Ok(()) -375 } -376}

\ No newline at end of file +352 let relay_url: RelayUrl = Url::parse("https://example.com").e()?.into(); +353 +354 let data = NodeData::default().with_relay_url(Some(relay_url.clone())); +355 discovery.publish(&data); +356 +357 // publish is fire and forget, so we have no way to wait until it is done. +358 tokio::time::timeout(Duration::from_secs(30), async move { +359 loop { +360 tokio::time::sleep(Duration::from_millis(200)).await; +361 let mut found_relay_urls = BTreeSet::new(); +362 let items = discovery +363 .resolve(ep.clone(), secret.public()) +364 .unwrap() +365 .collect::<Vec<_>>() +366 .await; +367 for item in items.into_iter().flatten() { +368 if let Some(url) = item.relay_url() { +369 found_relay_urls.insert(url.clone()); +370 } +371 } +372 if found_relay_urls.contains(&relay_url) { +373 break; +374 } +375 } +376 }) +377 .await +378 .expect("timeout, relay_url not found on DHT"); +379 Ok(()) +380 } +381}
\ No newline at end of file diff --git a/pr/3314/docs/src/iroh/net_report.rs.html b/pr/3314/docs/src/iroh/net_report.rs.html index 4c2dd3accb..f153c98d2f 100644 --- a/pr/3314/docs/src/iroh/net_report.rs.html +++ b/pr/3314/docs/src/iroh/net_report.rs.html @@ -148,901 +148,914 @@ 148 fn current(&self) -> Vec<ProbeReport> { 149 let mut reports = Vec::new(); 150 if let Some((_, ref conn)) = self.v4 { -151 if let Some(r) = conn.observer.get() { -152 reports.push(ProbeReport::QadIpv4(r)); -153 } -154 } -155 -156 if let Some((_, ref conn)) = self.v6 { -157 if let Some(r) = conn.observer.get() { -158 reports.push(ProbeReport::QadIpv6(r)); -159 } -160 } -161 -162 reports -163 } -164 -165 fn watch_v4(&self) -> impl n0_future::Stream<Item = Option<QadProbeReport>> + Unpin { -166 let watcher = self.v4.as_ref().map(|(_url, conn)| conn.observer.watch()); -167 -168 if let Some(watcher) = watcher { -169 watcher.stream_updates_only().boxed() -170 } else { -171 n0_future::stream::empty().boxed() -172 } -173 } -174 -175 fn watch_v6(&self) -> impl n0_future::Stream<Item = Option<QadProbeReport>> + Unpin { -176 let watcher = self.v6.as_ref().map(|(_url, conn)| conn.observer.watch()); -177 if let Some(watcher) = watcher { -178 watcher.stream_updates_only().boxed() -179 } else { -180 n0_future::stream::empty().boxed() -181 } -182 } -183} -184 -185#[cfg(not(wasm_browser))] -186#[derive(Debug)] -187struct QadConn { -188 conn: quinn::Connection, -189 observer: Watchable<Option<QadProbeReport>>, -190 _handle: AbortOnDropHandle<()>, -191} -192 -193#[derive(Debug)] -194struct Reports { -195 /// Do a full relay scan, even if last is `Some`. -196 next_full: bool, -197 /// Some previous reports. -198 prev: BTreeMap<Instant, Report>, -199 /// Most recent report. -200 last: Option<Report>, -201 /// Time of last full (non-incremental) report. -202 last_full: Instant, -203} -204 -205impl Default for Reports { -206 fn default() -> Self { -207 Self { -208 next_full: true, -209 prev: Default::default(), -210 last: Default::default(), -211 last_full: Instant::now(), -212 } -213 } -214} -215 -216impl Client { -217 /// Creates a new net_report client. -218 pub(crate) fn new( -219 #[cfg(not(wasm_browser))] dns_resolver: DnsResolver, -220 #[cfg(not(wasm_browser))] ip_mapped_addrs: Option<IpMappedAddresses>, -221 relay_map: RelayMap, -222 opts: Options, -223 metrics: Arc<Metrics>, -224 ) -> Self { -225 let probes = opts.as_protocols(); -226 #[cfg(any(test, feature = "test-utils"))] -227 let insecure_skip_relay_cert_verify = opts.insecure_skip_relay_cert_verify; -228 -229 #[cfg(not(wasm_browser))] -230 let quic_client = opts -231 .quic_config -232 .map(|c| iroh_relay::quic::QuicClient::new(c.ep, c.client_config)); -233 -234 #[cfg(not(wasm_browser))] -235 let socket_state = SocketState { -236 quic_client, -237 dns_resolver, -238 ip_mapped_addrs, -239 }; -240 -241 Client { -242 #[cfg(not(wasm_browser))] -243 socket_state, -244 metrics, -245 reports: Reports::default(), -246 probes, -247 relay_map, -248 qad_conns: QadConns::default(), -249 #[cfg(any(test, feature = "test-utils"))] -250 insecure_skip_relay_cert_verify, -251 } -252 } -253 -254 /// Generates a [`Report`]. -255 /// -256 /// Look at [`Options`] for the different configuration options. -257 pub(crate) async fn get_report(&mut self, if_state: IfStateDetails, is_major: bool) -> Report { -258 let now = Instant::now(); -259 -260 let mut do_full = is_major -261 || self.reports.next_full -262 || now.duration_since(self.reports.last_full) > FULL_REPORT_INTERVAL; +151 if let Some(mut r) = conn.observer.get() { +152 // grab latest rtt +153 r.latency = conn.conn.rtt(); +154 reports.push(ProbeReport::QadIpv4(r)); +155 } +156 } +157 +158 if let Some((_, ref conn)) = self.v6 { +159 if let Some(mut r) = conn.observer.get() { +160 // grab latest rtt +161 r.latency = conn.conn.rtt(); +162 reports.push(ProbeReport::QadIpv6(r)); +163 } +164 } +165 +166 reports +167 } +168 +169 fn watch_v4(&self) -> impl n0_future::Stream<Item = Option<QadProbeReport>> + Unpin { +170 let watcher = self.v4.as_ref().map(|(_url, conn)| conn.observer.watch()); +171 +172 if let Some(watcher) = watcher { +173 watcher.stream_updates_only().boxed() +174 } else { +175 n0_future::stream::empty().boxed() +176 } +177 } +178 +179 fn watch_v6(&self) -> impl n0_future::Stream<Item = Option<QadProbeReport>> + Unpin { +180 let watcher = self.v6.as_ref().map(|(_url, conn)| conn.observer.watch()); +181 if let Some(watcher) = watcher { +182 watcher.stream_updates_only().boxed() +183 } else { +184 n0_future::stream::empty().boxed() +185 } +186 } +187} +188 +189#[cfg(not(wasm_browser))] +190#[derive(Debug)] +191struct QadConn { +192 conn: quinn::Connection, +193 observer: Watchable<Option<QadProbeReport>>, +194 _handle: AbortOnDropHandle<()>, +195} +196 +197#[derive(Debug)] +198struct Reports { +199 /// Do a full relay scan, even if last is `Some`. +200 next_full: bool, +201 /// Some previous reports. +202 prev: BTreeMap<Instant, Report>, +203 /// Most recent report. +204 last: Option<Report>, +205 /// Time of last full (non-incremental) report. +206 last_full: Instant, +207} +208 +209impl Default for Reports { +210 fn default() -> Self { +211 Self { +212 next_full: true, +213 prev: Default::default(), +214 last: Default::default(), +215 last_full: Instant::now(), +216 } +217 } +218} +219 +220impl Client { +221 /// Creates a new net_report client. +222 pub(crate) fn new( +223 #[cfg(not(wasm_browser))] dns_resolver: DnsResolver, +224 #[cfg(not(wasm_browser))] ip_mapped_addrs: Option<IpMappedAddresses>, +225 relay_map: RelayMap, +226 opts: Options, +227 metrics: Arc<Metrics>, +228 ) -> Self { +229 let probes = opts.as_protocols(); +230 #[cfg(any(test, feature = "test-utils"))] +231 let insecure_skip_relay_cert_verify = opts.insecure_skip_relay_cert_verify; +232 +233 #[cfg(not(wasm_browser))] +234 let quic_client = opts +235 .quic_config +236 .map(|c| iroh_relay::quic::QuicClient::new(c.ep, c.client_config)); +237 +238 #[cfg(not(wasm_browser))] +239 let socket_state = SocketState { +240 quic_client, +241 dns_resolver, +242 ip_mapped_addrs, +243 }; +244 +245 Client { +246 #[cfg(not(wasm_browser))] +247 socket_state, +248 metrics, +249 reports: Reports::default(), +250 probes, +251 relay_map, +252 qad_conns: QadConns::default(), +253 #[cfg(any(test, feature = "test-utils"))] +254 insecure_skip_relay_cert_verify, +255 } +256 } +257 +258 /// Generates a [`Report`]. +259 /// +260 /// Look at [`Options`] for the different configuration options. +261 pub(crate) async fn get_report(&mut self, if_state: IfStateDetails, is_major: bool) -> Report { +262 let now = Instant::now(); 263 -264 debug!(%do_full, "net_report starting"); -265 -266 // If the last report had a captive portal and reported no UDP access, -267 // it's possible that we didn't get a useful net_report due to the -268 // captive portal blocking us. If so, make this report a full (non-incremental) one. -269 if !do_full { -270 if let Some(ref last) = self.reports.last { -271 if !last.has_udp() && last.captive_portal == Some(true) { -272 do_full = true; -273 } -274 } -275 } -276 if do_full { -277 self.reports.last = None; // causes ProbePlan::new below to do a full (initial) plan -278 self.reports.next_full = false; -279 self.reports.last_full = now; -280 self.metrics.reports_full.inc(); -281 } -282 self.metrics.reports.inc(); -283 -284 let enough_relays = std::cmp::min(self.relay_map.len(), ENOUGH_NODES); -285 #[cfg(wasm_browser)] -286 let if_state = IfStateDetails::default(); -287 #[cfg(not(wasm_browser))] -288 let if_state = IfStateDetails { -289 have_v4: if_state.have_v4, -290 have_v6: if_state.have_v6, -291 }; -292 -293 let mut report = Report::default(); -294 -295 #[cfg(not(wasm_browser))] -296 let reports = self -297 .spawn_qad_probes(&if_state, enough_relays, do_full) -298 .await; -299 -300 #[cfg(not(wasm_browser))] -301 for r in reports { -302 report.update(&r); -303 } -304 -305 let (actor, mut probe_rx) = reportgen::Client::new( -306 self.reports.last.clone(), -307 self.relay_map.clone(), -308 self.probes.clone(), -309 if_state, -310 #[cfg(not(wasm_browser))] -311 self.socket_state.clone(), -312 #[cfg(any(test, feature = "test-utils"))] -313 self.insecure_skip_relay_cert_verify, -314 ); -315 -316 let mut timeout_fut = std::pin::pin!(MaybeFuture::default()); -317 -318 #[cfg(not(wasm_browser))] -319 let mut qad_v4_stream = self.qad_conns.watch_v4(); -320 #[cfg(not(wasm_browser))] -321 let mut qad_v6_stream = self.qad_conns.watch_v6(); -322 -323 loop { -324 tokio::select! { -325 biased; +264 let mut do_full = is_major +265 || self.reports.next_full +266 || now.duration_since(self.reports.last_full) > FULL_REPORT_INTERVAL; +267 +268 debug!(%do_full, "net_report starting"); +269 +270 // If the last report had a captive portal and reported no UDP access, +271 // it's possible that we didn't get a useful net_report due to the +272 // captive portal blocking us. If so, make this report a full (non-incremental) one. +273 if !do_full { +274 if let Some(ref last) = self.reports.last { +275 if !last.has_udp() && last.captive_portal == Some(true) { +276 do_full = true; +277 } +278 } +279 } +280 if do_full { +281 self.reports.last = None; // causes ProbePlan::new below to do a full (initial) plan +282 self.reports.next_full = false; +283 self.reports.last_full = now; +284 self.metrics.reports_full.inc(); +285 } +286 self.metrics.reports.inc(); +287 +288 let enough_relays = std::cmp::min(self.relay_map.len(), ENOUGH_NODES); +289 #[cfg(wasm_browser)] +290 let if_state = IfStateDetails::default(); +291 #[cfg(not(wasm_browser))] +292 let if_state = IfStateDetails { +293 have_v4: if_state.have_v4, +294 have_v6: if_state.have_v6, +295 }; +296 +297 let mut report = Report::default(); +298 +299 #[cfg(not(wasm_browser))] +300 let reports = self +301 .spawn_qad_probes(&if_state, enough_relays, do_full) +302 .await; +303 +304 #[cfg(not(wasm_browser))] +305 for r in reports { +306 report.update(&r); +307 } +308 +309 let (actor, mut probe_rx) = reportgen::Client::new( +310 self.reports.last.clone(), +311 self.relay_map.clone(), +312 self.probes.clone(), +313 if_state, +314 #[cfg(not(wasm_browser))] +315 self.socket_state.clone(), +316 #[cfg(any(test, feature = "test-utils"))] +317 self.insecure_skip_relay_cert_verify, +318 ); +319 +320 let mut timeout_fut = std::pin::pin!(MaybeFuture::default()); +321 +322 #[cfg(not(wasm_browser))] +323 let mut qad_v4_stream = self.qad_conns.watch_v4(); +324 #[cfg(not(wasm_browser))] +325 let mut qad_v6_stream = self.qad_conns.watch_v6(); 326 -327 _ = &mut timeout_fut, if timeout_fut.is_some() => { -328 trace!("timeout done, shutting down"); -329 drop(actor); // shuts down the probes -330 break; -331 } -332 -333 Some(Some(r)) = qad_v4_stream.next() => { -334 trace!(?r, "new report from QAD V4"); -335 report.update(&ProbeReport::QadIpv4(r)); -336 } -337 -338 Some(Some(r)) = qad_v6_stream.next() => { -339 trace!(?r, "new report from QAD V6"); -340 report.update(&ProbeReport::QadIpv6(r)); -341 } -342 -343 maybe_probe = probe_rx.recv() => { -344 let Some(probe_res) = maybe_probe else { -345 break; -346 }; -347 trace!(?probe_res, "handling probe"); -348 match probe_res { -349 ProbeFinished::Regular(probe) => match probe { -350 Ok(probe) => { -351 report.update(&probe); -352 if timeout_fut.is_none() { -353 if let Some(timeout) = self.have_enough_reports(enough_relays, &report) { -354 timeout_fut.as_mut().set_future(time::sleep(timeout)); -355 } -356 } -357 } -358 Err(err) => { -359 trace!("probe errored: {:?}", err); -360 } -361 }, -362 #[cfg(not(wasm_browser))] -363 ProbeFinished::CaptivePortal(portal) => { -364 report.captive_portal = portal; -365 } -366 } -367 } -368 } -369 } -370 -371 self.add_report_history_and_set_preferred_relay(&mut report); -372 debug!( -373 ?report, -374 "generated report in {:02}ms", -375 now.elapsed().as_millis() -376 ); -377 -378 report -379 } -380 -381 #[cfg(not(wasm_browser))] -382 async fn spawn_qad_probes( -383 &mut self, -384 if_state: &IfStateDetails, -385 enough_relays: usize, -386 do_full: bool, -387 ) -> Vec<ProbeReport> { -388 debug!("spawning QAD probes"); -389 -390 let Some(ref quic_client) = self.socket_state.quic_client else { -391 return Vec::new(); -392 }; +327 loop { +328 tokio::select! { +329 biased; +330 +331 _ = &mut timeout_fut, if timeout_fut.is_some() => { +332 trace!("timeout done, shutting down"); +333 drop(actor); // shuts down the probes +334 break; +335 } +336 +337 Some(Some(r)) = qad_v4_stream.next() => { +338 trace!(?r, "new report from QAD V4"); +339 report.update(&ProbeReport::QadIpv4(r)); +340 } +341 +342 Some(Some(r)) = qad_v6_stream.next() => { +343 trace!(?r, "new report from QAD V6"); +344 report.update(&ProbeReport::QadIpv6(r)); +345 } +346 +347 maybe_probe = probe_rx.recv() => { +348 let Some(probe_res) = maybe_probe else { +349 break; +350 }; +351 trace!(?probe_res, "handling probe"); +352 match probe_res { +353 ProbeFinished::Regular(probe) => match probe { +354 Ok(probe) => { +355 report.update(&probe); +356 if timeout_fut.is_none() { +357 if let Some(timeout) = self.have_enough_reports(enough_relays, &report) { +358 timeout_fut.as_mut().set_future(time::sleep(timeout)); +359 } +360 } +361 } +362 Err(err) => { +363 trace!("probe errored: {:?}", err); +364 } +365 }, +366 #[cfg(not(wasm_browser))] +367 ProbeFinished::CaptivePortal(portal) => { +368 report.captive_portal = portal; +369 } +370 } +371 } +372 } +373 } +374 +375 self.add_report_history_and_set_preferred_relay(&mut report); +376 debug!( +377 ?report, +378 "generated report in {:02}ms", +379 now.elapsed().as_millis() +380 ); +381 +382 report +383 } +384 +385 #[cfg(not(wasm_browser))] +386 async fn spawn_qad_probes( +387 &mut self, +388 if_state: &IfStateDetails, +389 enough_relays: usize, +390 do_full: bool, +391 ) -> Vec<ProbeReport> { +392 debug!("spawning QAD probes"); 393 -394 if do_full { -395 // clear out existing connections if we are doing a full reset -396 self.qad_conns.clear(); -397 } -398 -399 if let Some((url, conn)) = &self.qad_conns.v4 { -400 // verify conn is still around -401 if let Some(reason) = conn.conn.close_reason() { -402 trace!(?url, "QAD v4 conn closed: {}", reason); -403 self.qad_conns.v4.take(); -404 } -405 } -406 if let Some((url, conn)) = &self.qad_conns.v6 { -407 // verify conn is still around -408 if let Some(reason) = conn.conn.close_reason() { -409 trace!(?url, "QAD v6 conn closed: {}", reason); -410 self.qad_conns.v6.take(); -411 } -412 } -413 if self.qad_conns.v4.is_some() && self.qad_conns.v6.is_some() == if_state.have_v6 { -414 trace!("not spawning QAD, already have probes"); -415 return self.qad_conns.current(); +394 let Some(ref quic_client) = self.socket_state.quic_client else { +395 return Vec::new(); +396 }; +397 +398 if do_full { +399 // clear out existing connections if we are doing a full reset +400 self.qad_conns.clear(); +401 } +402 +403 if let Some((url, conn)) = &self.qad_conns.v4 { +404 // verify conn is still around +405 if let Some(reason) = conn.conn.close_reason() { +406 trace!(?url, "QAD v4 conn closed: {}", reason); +407 self.qad_conns.v4.take(); +408 } +409 } +410 if let Some((url, conn)) = &self.qad_conns.v6 { +411 // verify conn is still around +412 if let Some(reason) = conn.conn.close_reason() { +413 trace!(?url, "QAD v6 conn closed: {}", reason); +414 self.qad_conns.v6.take(); +415 } 416 } -417 -418 // TODO: randomize choice? -419 const MAX_RELAYS: usize = 5; -420 -421 let mut v4_buf = JoinSet::new(); -422 let cancel_v4 = CancellationToken::new(); -423 let mut v6_buf = JoinSet::new(); -424 let cancel_v6 = CancellationToken::new(); -425 -426 for relay_node in self.relay_map.nodes().take(MAX_RELAYS) { -427 if if_state.have_v4 { -428 debug!(?relay_node.url, "v4 QAD probe"); -429 let ip_mapped_addrs = self.socket_state.ip_mapped_addrs.clone(); -430 let relay_node = relay_node.clone(); -431 let dns_resolver = self.socket_state.dns_resolver.clone(); -432 let quic_client = quic_client.clone(); -433 -434 v4_buf.spawn( -435 cancel_v4 -436 .child_token() -437 .run_until_cancelled_owned(time::timeout( -438 PROBES_TIMEOUT, -439 run_probe_v4(ip_mapped_addrs, relay_node, quic_client, dns_resolver), -440 )), -441 ); -442 } -443 -444 if if_state.have_v6 { -445 debug!(?relay_node.url, "v6 QAD probe"); -446 let ip_mapped_addrs = self.socket_state.ip_mapped_addrs.clone(); -447 let relay_node = relay_node.clone(); -448 let dns_resolver = self.socket_state.dns_resolver.clone(); -449 let quic_client = quic_client.clone(); -450 v6_buf.spawn( -451 cancel_v6 -452 .child_token() -453 .run_until_cancelled_owned(time::timeout( -454 PROBES_TIMEOUT, -455 run_probe_v6(ip_mapped_addrs, relay_node, quic_client, dns_resolver), -456 )), -457 ); -458 } -459 } -460 -461 let mut reports = Vec::new(); -462 -463 loop { -464 trace!("tick: qad probes"); -465 -466 if reports.len() >= enough_relays { -467 debug!("enough probes: {}", reports.len()); -468 cancel_v4.cancel(); -469 cancel_v6.cancel(); -470 break; -471 } -472 -473 // TODO: verify select and join_next work as expected -474 tokio::select! { -475 biased; +417 if self.qad_conns.v4.is_some() && self.qad_conns.v6.is_some() == if_state.have_v6 { +418 trace!("not spawning QAD, already have probes"); +419 return self.qad_conns.current(); +420 } +421 +422 // TODO: randomize choice? +423 const MAX_RELAYS: usize = 5; +424 +425 let mut v4_buf = JoinSet::new(); +426 let cancel_v4 = CancellationToken::new(); +427 let mut v6_buf = JoinSet::new(); +428 let cancel_v6 = CancellationToken::new(); +429 +430 for relay_node in self.relay_map.nodes().take(MAX_RELAYS) { +431 if if_state.have_v4 { +432 debug!(?relay_node.url, "v4 QAD probe"); +433 let ip_mapped_addrs = self.socket_state.ip_mapped_addrs.clone(); +434 let relay_node = relay_node.clone(); +435 let dns_resolver = self.socket_state.dns_resolver.clone(); +436 let quic_client = quic_client.clone(); +437 +438 v4_buf.spawn( +439 cancel_v4 +440 .child_token() +441 .run_until_cancelled_owned(time::timeout( +442 PROBES_TIMEOUT, +443 run_probe_v4(ip_mapped_addrs, relay_node, quic_client, dns_resolver), +444 )), +445 ); +446 } +447 +448 if if_state.have_v6 { +449 debug!(?relay_node.url, "v6 QAD probe"); +450 let ip_mapped_addrs = self.socket_state.ip_mapped_addrs.clone(); +451 let relay_node = relay_node.clone(); +452 let dns_resolver = self.socket_state.dns_resolver.clone(); +453 let quic_client = quic_client.clone(); +454 v6_buf.spawn( +455 cancel_v6 +456 .child_token() +457 .run_until_cancelled_owned(time::timeout( +458 PROBES_TIMEOUT, +459 run_probe_v6(ip_mapped_addrs, relay_node, quic_client, dns_resolver), +460 )), +461 ); +462 } +463 } +464 +465 let mut reports = Vec::new(); +466 +467 loop { +468 trace!("tick: qad probes"); +469 +470 if reports.len() >= enough_relays { +471 debug!("enough probes: {}", reports.len()); +472 cancel_v4.cancel(); +473 cancel_v6.cancel(); +474 break; +475 } 476 -477 val = v4_buf.join_next(), if !v4_buf.is_empty() => { -478 if let Some(Ok(Some(Ok(res)))) = val { -479 match res { -480 Ok((r, conn)) => { -481 debug!(?r, "got v4 QAD conn"); -482 let url = r.node.clone(); -483 reports.push(ProbeReport::QadIpv4(r)); -484 if self.qad_conns.v4.is_none() { -485 self.qad_conns.v4.replace((url, conn)); -486 } else { -487 conn.conn.close(QUIC_ADDR_DISC_CLOSE_CODE, QUIC_ADDR_DISC_CLOSE_REASON); -488 } -489 } -490 Err(err) => { -491 debug!("probe v4 failed: {:?}", err); -492 } -493 } -494 } else { -495 dbg!(val); -496 } -497 } -498 val = v6_buf.join_next(), if !v6_buf.is_empty() => { -499 if let Some(Ok(Some(Ok(res)))) = val { -500 match res { -501 Ok((r, conn)) => { -502 debug!(?r, "got v6 QAD conn"); -503 let url = r.node.clone(); -504 reports.push(ProbeReport::QadIpv6(r)); -505 if self.qad_conns.v6.is_none() { -506 self.qad_conns.v6.replace((url, conn)); -507 } else { -508 conn.conn.close(QUIC_ADDR_DISC_CLOSE_CODE, QUIC_ADDR_DISC_CLOSE_REASON); -509 } -510 } -511 Err(err) => { -512 debug!("probe v6 failed: {:?}", err); -513 } -514 } -515 } else { -516 dbg!(val); -517 } -518 } -519 else => { -520 break; -521 } -522 } -523 } -524 -525 reports -526 } -527 -528 fn have_enough_reports(&self, enough_relays: usize, report: &Report) -> Option<Duration> { -529 // Once we've heard from enough relay servers (3), start a timer to give up on the other -530 // probes. The timer's duration is a function of whether this is our initial full -531 // probe or an incremental one. For incremental ones, wait for the duration of the -532 // slowest relay. For initial ones, double that. -533 let latencies: Vec<Duration> = report.relay_latency.iter().map(|(_, l)| l).collect(); -534 let have_enough_latencies = latencies.len() >= enough_relays; -535 -536 if have_enough_latencies { -537 let timeout = match self.reports.last.is_some() { -538 true => Duration::from_secs(0), -539 false => latencies -540 .iter() -541 .max() -542 .copied() -543 .unwrap_or(DEFAULT_MAX_LATENCY), -544 }; -545 debug!( -546 reports=latencies.len(), -547 delay=?timeout, -548 "Have enough probe reports, aborting further probes soon", -549 ); -550 -551 Some(timeout) -552 } else { -553 None -554 } -555 } -556 -557 /// Adds `r` to the set of recent Reports and mutates `r.preferred_relay` to contain the best recent one. -558 fn add_report_history_and_set_preferred_relay(&mut self, r: &mut Report) { -559 let mut prev_relay = None; -560 if let Some(ref last) = self.reports.last { -561 prev_relay.clone_from(&last.preferred_relay); -562 } -563 let now = Instant::now(); -564 const MAX_AGE: Duration = Duration::from_secs(5 * 60); -565 -566 // relay ID => its best recent latency in last MAX_AGE -567 let mut best_recent = RelayLatencies::default(); -568 -569 // chain the current report as we are still mutating it -570 let prevs_iter = self -571 .reports -572 .prev -573 .iter() -574 .map(|(a, b)| -> (&Instant, &Report) { (a, b) }); +477 // TODO: verify select and join_next work as expected +478 tokio::select! { +479 biased; +480 +481 val = v4_buf.join_next(), if !v4_buf.is_empty() => { +482 if let Some(Ok(Some(Ok(res)))) = val { +483 match res { +484 Ok((r, conn)) => { +485 debug!(?r, "got v4 QAD conn"); +486 let url = r.node.clone(); +487 reports.push(ProbeReport::QadIpv4(r)); +488 if self.qad_conns.v4.is_none() { +489 self.qad_conns.v4.replace((url, conn)); +490 } else { +491 conn.conn.close(QUIC_ADDR_DISC_CLOSE_CODE, QUIC_ADDR_DISC_CLOSE_REASON); +492 } +493 } +494 Err(err) => { +495 debug!("probe v4 failed: {:?}", err); +496 } +497 } +498 } else { +499 dbg!(val); +500 } +501 } +502 val = v6_buf.join_next(), if !v6_buf.is_empty() => { +503 if let Some(Ok(Some(Ok(res)))) = val { +504 match res { +505 Ok((r, conn)) => { +506 debug!(?r, "got v6 QAD conn"); +507 let url = r.node.clone(); +508 reports.push(ProbeReport::QadIpv6(r)); +509 if self.qad_conns.v6.is_none() { +510 self.qad_conns.v6.replace((url, conn)); +511 } else { +512 conn.conn.close(QUIC_ADDR_DISC_CLOSE_CODE, QUIC_ADDR_DISC_CLOSE_REASON); +513 } +514 } +515 Err(err) => { +516 debug!("probe v6 failed: {:?}", err); +517 } +518 } +519 } else { +520 dbg!(val); +521 } +522 } +523 else => { +524 break; +525 } +526 } +527 } +528 +529 reports +530 } +531 +532 fn have_enough_reports(&self, enough_relays: usize, report: &Report) -> Option<Duration> { +533 // Once we've heard from enough relay servers (3), start a timer to give up on the other +534 // probes. The timer's duration is a function of whether this is our initial full +535 // probe or an incremental one. For incremental ones, wait for the duration of the +536 // slowest relay. For initial ones, double that. +537 let latencies: Vec<Duration> = report.relay_latency.iter().map(|(_, l)| l).collect(); +538 let have_enough_latencies = latencies.len() >= enough_relays; +539 +540 if have_enough_latencies { +541 let timeout = match self.reports.last.is_some() { +542 true => Duration::from_secs(0), +543 false => latencies +544 .iter() +545 .max() +546 .copied() +547 .unwrap_or(DEFAULT_MAX_LATENCY), +548 }; +549 debug!( +550 reports=latencies.len(), +551 delay=?timeout, +552 "Have enough probe reports, aborting further probes soon", +553 ); +554 +555 Some(timeout) +556 } else { +557 None +558 } +559 } +560 +561 /// Adds `r` to the set of recent Reports and mutates `r.preferred_relay` to contain the best recent one. +562 fn add_report_history_and_set_preferred_relay(&mut self, r: &mut Report) { +563 let mut prev_relay = None; +564 if let Some(ref last) = self.reports.last { +565 prev_relay.clone_from(&last.preferred_relay); +566 +567 // If we don't have new information, copy this from the last report +568 if r.mapping_varies_by_dest_ipv4.is_none() { +569 r.mapping_varies_by_dest_ipv4 = last.mapping_varies_by_dest_ipv4; +570 } +571 if r.mapping_varies_by_dest_ipv6.is_none() { +572 r.mapping_varies_by_dest_ipv6 = last.mapping_varies_by_dest_ipv6; +573 } +574 } 575 -576 let mut to_remove = Vec::new(); -577 for (t, pr) in prevs_iter { -578 if now.duration_since(*t) > MAX_AGE { -579 to_remove.push(*t); -580 continue; -581 } -582 best_recent.merge(&pr.relay_latency); -583 } -584 // merge in current run -585 best_recent.merge(&r.relay_latency); -586 -587 for t in to_remove { -588 self.reports.prev.remove(&t); -589 } -590 -591 // Then, pick which currently-alive relay server from the -592 // current report has the best latency over the past MAX_AGE. -593 let mut best_any = Duration::default(); -594 let mut old_relay_cur_latency = Duration::default(); -595 { -596 for (url, duration) in r.relay_latency.iter() { -597 if Some(url) == prev_relay.as_ref() { -598 old_relay_cur_latency = duration; -599 } -600 if let Some(best) = best_recent.get(url) { -601 if r.preferred_relay.is_none() || best < best_any { -602 best_any = best; -603 r.preferred_relay.replace(url.clone()); -604 } -605 } -606 } -607 -608 // If we're changing our preferred relay but the old one's still -609 // accessible and the new one's not much better, just stick with -610 // where we are. -611 if prev_relay.is_some() -612 && r.preferred_relay != prev_relay -613 && !old_relay_cur_latency.is_zero() -614 && best_any > old_relay_cur_latency / 3 * 2 -615 { -616 r.preferred_relay = prev_relay; -617 } -618 } -619 -620 self.reports.prev.insert(now, r.clone()); -621 self.reports.last = Some(r.clone()); -622 } -623} -624 -625async fn run_probe_v4( -626 ip_mapped_addrs: Option<IpMappedAddresses>, -627 relay_node: Arc<RelayNode>, -628 quic_client: QuicClient, -629 dns_resolver: DnsResolver, -630) -> n0_snafu::Result<(QadProbeReport, QadConn)> { -631 let relay_addr_orig = reportgen::get_relay_addr_ipv4(&dns_resolver, &relay_node).await?; -632 let relay_addr = -633 reportgen::maybe_to_mapped_addr(ip_mapped_addrs.as_ref(), relay_addr_orig.into()); -634 -635 debug!(?relay_addr_orig, ?relay_addr, "relay addr v4"); -636 let host = relay_node.url.host_str().unwrap(); -637 let conn = quic_client.create_conn(relay_addr, host).await?; -638 let mut receiver = conn.observed_external_addr(); -639 -640 // wait for an addr -641 let addr = receiver -642 .wait_for(|addr| addr.is_some()) -643 .await -644 .unwrap() -645 .expect("known"); -646 let report = QadProbeReport { -647 node: relay_node.url.clone(), -648 addr: SocketAddr::new(addr.ip().to_canonical(), addr.port()), -649 latency: conn.rtt(), -650 }; -651 -652 let observer = Watchable::new(None); -653 // TODO: this is sad -654 let ob = observer.clone(); -655 let node = relay_node.url.clone(); -656 let conn2 = conn.clone(); -657 let handle = task::spawn(async move { -658 loop { -659 let val = *receiver.borrow(); -660 // if we've sent to an ipv4 address, but received an observed address -661 // that is ivp6 then the address is an [IPv4-Mapped IPv6 Addresses](https://doc.rust-lang.org/beta/std/net/struct.Ipv6Addr.html#ipv4-mapped-ipv6-addresses) -662 let val = val.map(|val| SocketAddr::new(val.ip().to_canonical(), val.port())); -663 let latency = conn2.rtt(); -664 trace!(?val, ?relay_addr, ?latency, "got addr V4"); -665 if ob -666 .set(val.map(|addr| QadProbeReport { -667 node: node.clone(), -668 addr, -669 latency, -670 })) -671 .is_err() -672 { -673 // cancel if the observer is gone -674 break; -675 } -676 if receiver.changed().await.is_err() { -677 break; -678 } -679 } -680 }); -681 let handle = AbortOnDropHandle::new(handle); -682 -683 Ok(( -684 report, -685 QadConn { -686 conn, -687 observer, -688 _handle: handle, -689 }, -690 )) -691} -692 -693async fn run_probe_v6( -694 ip_mapped_addrs: Option<IpMappedAddresses>, -695 relay_node: Arc<RelayNode>, -696 quic_client: QuicClient, -697 dns_resolver: DnsResolver, -698) -> n0_snafu::Result<(QadProbeReport, QadConn)> { -699 let relay_addr_orig = reportgen::get_relay_addr_ipv6(&dns_resolver, &relay_node).await?; -700 let relay_addr = -701 reportgen::maybe_to_mapped_addr(ip_mapped_addrs.as_ref(), relay_addr_orig.into()); -702 -703 debug!(?relay_addr_orig, ?relay_addr, "relay addr v6"); -704 let host = relay_node.url.host_str().unwrap(); -705 let conn = quic_client.create_conn(relay_addr, host).await?; -706 let mut receiver = conn.observed_external_addr(); -707 -708 // wait for an addr -709 let addr = receiver -710 .wait_for(|addr| addr.is_some()) -711 .await -712 .unwrap() -713 .expect("known"); -714 let report = QadProbeReport { -715 node: relay_node.url.clone(), -716 addr: SocketAddr::new(addr.ip().to_canonical(), addr.port()), -717 latency: conn.rtt(), -718 }; -719 -720 let observer = Watchable::new(None); -721 // TODO: this is sad -722 let ob = observer.clone(); -723 let node = relay_node.url.clone(); -724 let conn2 = conn.clone(); -725 let handle = task::spawn(async move { -726 loop { -727 let val = *receiver.borrow(); -728 // if we've sent to an ipv4 address, but received an observed address -729 // that is ivp6 then the address is an IPv4-Mapped IPv6 Addresses -730 let val = val.map(|val| SocketAddr::new(val.ip().to_canonical(), val.port())); -731 let latency = conn2.rtt(); -732 trace!(?val, ?relay_addr, ?latency, "got addr V6"); -733 if ob -734 .set(val.map(|addr| QadProbeReport { -735 node: node.clone(), -736 addr, -737 latency, -738 })) -739 .is_err() -740 { -741 // cancel if the observer is gone -742 break; -743 } -744 if receiver.changed().await.is_err() { -745 break; -746 } -747 } -748 }); -749 let handle = AbortOnDropHandle::new(handle); -750 -751 Ok(( -752 report, -753 QadConn { -754 conn, -755 observer, -756 _handle: handle, -757 }, -758 )) -759} -760 -761#[cfg(test)] -762mod test_utils { -763 //! Creates a relay server against which to perform tests -764 -765 use iroh_relay::{server, RelayNode, RelayQuicConfig}; -766 -767 pub(crate) async fn relay() -> (server::Server, RelayNode) { -768 let server = server::Server::spawn(server::testing::server_config()) -769 .await -770 .expect("should serve relay"); -771 let quic = Some(RelayQuicConfig { -772 port: server.quic_addr().expect("server should run quic").port(), -773 }); -774 let node_desc = RelayNode { -775 url: server.https_url().expect("should work as relay"), -776 quic, -777 }; -778 -779 (server, node_desc) -780 } -781 -782 /// Create a [`crate::RelayMap`] of the given size. -783 /// -784 /// This function uses [`relay`]. Note that the returned map uses internal order that will -785 /// often _not_ match the order of the servers. -786 pub(crate) async fn relay_map(relays: usize) -> (Vec<server::Server>, crate::RelayMap) { -787 let mut servers = Vec::with_capacity(relays); -788 let mut nodes = Vec::with_capacity(relays); -789 for _ in 0..relays { -790 let (relay_server, node) = relay().await; -791 servers.push(relay_server); -792 nodes.push(node); -793 } -794 (servers, crate::RelayMap::from_iter(nodes)) -795 } -796} -797 -798#[cfg(test)] -799mod tests { -800 use std::net::{Ipv4Addr, SocketAddr}; -801 -802 use iroh_base::RelayUrl; -803 use iroh_relay::dns::DnsResolver; -804 use n0_snafu::{Result, ResultExt}; -805 use tokio_util::sync::CancellationToken; -806 use tracing_test::traced_test; -807 -808 use super::*; -809 use crate::net_report::probes::Probe; +576 let now = Instant::now(); +577 const MAX_AGE: Duration = Duration::from_secs(5 * 60); +578 +579 // relay ID => its best recent latency in last MAX_AGE +580 let mut best_recent = RelayLatencies::default(); +581 +582 // chain the current report as we are still mutating it +583 let prevs_iter = self +584 .reports +585 .prev +586 .iter() +587 .map(|(a, b)| -> (&Instant, &Report) { (a, b) }); +588 +589 let mut to_remove = Vec::new(); +590 for (t, pr) in prevs_iter { +591 if now.duration_since(*t) > MAX_AGE { +592 to_remove.push(*t); +593 continue; +594 } +595 best_recent.merge(&pr.relay_latency); +596 } +597 // merge in current run +598 best_recent.merge(&r.relay_latency); +599 +600 for t in to_remove { +601 self.reports.prev.remove(&t); +602 } +603 +604 // Then, pick which currently-alive relay server from the +605 // current report has the best latency over the past MAX_AGE. +606 let mut best_any = Duration::default(); +607 let mut old_relay_cur_latency = Duration::default(); +608 { +609 for (url, duration) in r.relay_latency.iter() { +610 if Some(url) == prev_relay.as_ref() { +611 old_relay_cur_latency = duration; +612 } +613 if let Some(best) = best_recent.get(url) { +614 if r.preferred_relay.is_none() || best < best_any { +615 best_any = best; +616 r.preferred_relay.replace(url.clone()); +617 } +618 } +619 } +620 +621 // If we're changing our preferred relay but the old one's still +622 // accessible and the new one's not much better, just stick with +623 // where we are. +624 if prev_relay.is_some() +625 && r.preferred_relay != prev_relay +626 && !old_relay_cur_latency.is_zero() +627 && best_any > old_relay_cur_latency / 3 * 2 +628 { +629 r.preferred_relay = prev_relay; +630 } +631 } +632 +633 self.reports.prev.insert(now, r.clone()); +634 self.reports.last = Some(r.clone()); +635 } +636} +637 +638async fn run_probe_v4( +639 ip_mapped_addrs: Option<IpMappedAddresses>, +640 relay_node: Arc<RelayNode>, +641 quic_client: QuicClient, +642 dns_resolver: DnsResolver, +643) -> n0_snafu::Result<(QadProbeReport, QadConn)> { +644 let relay_addr_orig = reportgen::get_relay_addr_ipv4(&dns_resolver, &relay_node).await?; +645 let relay_addr = +646 reportgen::maybe_to_mapped_addr(ip_mapped_addrs.as_ref(), relay_addr_orig.into()); +647 +648 debug!(?relay_addr_orig, ?relay_addr, "relay addr v4"); +649 let host = relay_node.url.host_str().unwrap(); +650 let conn = quic_client.create_conn(relay_addr, host).await?; +651 let mut receiver = conn.observed_external_addr(); +652 +653 // wait for an addr +654 let addr = receiver +655 .wait_for(|addr| addr.is_some()) +656 .await +657 .unwrap() +658 .expect("known"); +659 let report = QadProbeReport { +660 node: relay_node.url.clone(), +661 addr: SocketAddr::new(addr.ip().to_canonical(), addr.port()), +662 latency: conn.rtt(), +663 }; +664 +665 let observer = Watchable::new(None); +666 // TODO: this is sad +667 let ob = observer.clone(); +668 let node = relay_node.url.clone(); +669 let conn2 = conn.clone(); +670 let handle = task::spawn(async move { +671 loop { +672 let val = *receiver.borrow(); +673 // if we've sent to an ipv4 address, but received an observed address +674 // that is ivp6 then the address is an [IPv4-Mapped IPv6 Addresses](https://doc.rust-lang.org/beta/std/net/struct.Ipv6Addr.html#ipv4-mapped-ipv6-addresses) +675 let val = val.map(|val| SocketAddr::new(val.ip().to_canonical(), val.port())); +676 let latency = conn2.rtt(); +677 trace!(?val, ?relay_addr, ?latency, "got addr V4"); +678 if ob +679 .set(val.map(|addr| QadProbeReport { +680 node: node.clone(), +681 addr, +682 latency, +683 })) +684 .is_err() +685 { +686 // cancel if the observer is gone +687 break; +688 } +689 if receiver.changed().await.is_err() { +690 break; +691 } +692 } +693 }); +694 let handle = AbortOnDropHandle::new(handle); +695 +696 Ok(( +697 report, +698 QadConn { +699 conn, +700 observer, +701 _handle: handle, +702 }, +703 )) +704} +705 +706async fn run_probe_v6( +707 ip_mapped_addrs: Option<IpMappedAddresses>, +708 relay_node: Arc<RelayNode>, +709 quic_client: QuicClient, +710 dns_resolver: DnsResolver, +711) -> n0_snafu::Result<(QadProbeReport, QadConn)> { +712 let relay_addr_orig = reportgen::get_relay_addr_ipv6(&dns_resolver, &relay_node).await?; +713 let relay_addr = +714 reportgen::maybe_to_mapped_addr(ip_mapped_addrs.as_ref(), relay_addr_orig.into()); +715 +716 debug!(?relay_addr_orig, ?relay_addr, "relay addr v6"); +717 let host = relay_node.url.host_str().unwrap(); +718 let conn = quic_client.create_conn(relay_addr, host).await?; +719 let mut receiver = conn.observed_external_addr(); +720 +721 // wait for an addr +722 let addr = receiver +723 .wait_for(|addr| addr.is_some()) +724 .await +725 .unwrap() +726 .expect("known"); +727 let report = QadProbeReport { +728 node: relay_node.url.clone(), +729 addr: SocketAddr::new(addr.ip().to_canonical(), addr.port()), +730 latency: conn.rtt(), +731 }; +732 +733 let observer = Watchable::new(None); +734 // TODO: this is sad +735 let ob = observer.clone(); +736 let node = relay_node.url.clone(); +737 let conn2 = conn.clone(); +738 let handle = task::spawn(async move { +739 loop { +740 let val = *receiver.borrow(); +741 // if we've sent to an ipv4 address, but received an observed address +742 // that is ivp6 then the address is an IPv4-Mapped IPv6 Addresses +743 let val = val.map(|val| SocketAddr::new(val.ip().to_canonical(), val.port())); +744 let latency = conn2.rtt(); +745 trace!(?val, ?relay_addr, ?latency, "got addr V6"); +746 if ob +747 .set(val.map(|addr| QadProbeReport { +748 node: node.clone(), +749 addr, +750 latency, +751 })) +752 .is_err() +753 { +754 // cancel if the observer is gone +755 break; +756 } +757 if receiver.changed().await.is_err() { +758 break; +759 } +760 } +761 }); +762 let handle = AbortOnDropHandle::new(handle); +763 +764 Ok(( +765 report, +766 QadConn { +767 conn, +768 observer, +769 _handle: handle, +770 }, +771 )) +772} +773 +774#[cfg(test)] +775mod test_utils { +776 //! Creates a relay server against which to perform tests +777 +778 use iroh_relay::{server, RelayNode, RelayQuicConfig}; +779 +780 pub(crate) async fn relay() -> (server::Server, RelayNode) { +781 let server = server::Server::spawn(server::testing::server_config()) +782 .await +783 .expect("should serve relay"); +784 let quic = Some(RelayQuicConfig { +785 port: server.quic_addr().expect("server should run quic").port(), +786 }); +787 let node_desc = RelayNode { +788 url: server.https_url().expect("should work as relay"), +789 quic, +790 }; +791 +792 (server, node_desc) +793 } +794 +795 /// Create a [`crate::RelayMap`] of the given size. +796 /// +797 /// This function uses [`relay`]. Note that the returned map uses internal order that will +798 /// often _not_ match the order of the servers. +799 pub(crate) async fn relay_map(relays: usize) -> (Vec<server::Server>, crate::RelayMap) { +800 let mut servers = Vec::with_capacity(relays); +801 let mut nodes = Vec::with_capacity(relays); +802 for _ in 0..relays { +803 let (relay_server, node) = relay().await; +804 servers.push(relay_server); +805 nodes.push(node); +806 } +807 (servers, crate::RelayMap::from_iter(nodes)) +808 } +809} 810 -811 #[tokio::test] -812 #[traced_test] -813 async fn test_basic() -> Result<()> { -814 let (server, relay) = test_utils::relay().await; -815 let client_config = iroh_relay::client::make_dangerous_client_config(); -816 let ep = quinn::Endpoint::client(SocketAddr::new(Ipv4Addr::LOCALHOST.into(), 0)).e()?; -817 let quic_addr_disc = QuicConfig { -818 ep: ep.clone(), -819 client_config, -820 ipv4: true, -821 ipv6: true, -822 }; -823 let relay_map = RelayMap::from(relay); -824 -825 let resolver = DnsResolver::new(); -826 let opts = Options::default().quic_config(Some(quic_addr_disc.clone())); -827 let mut client = Client::new( -828 resolver.clone(), -829 None, -830 relay_map.clone(), -831 opts.clone(), -832 Default::default(), -833 ); -834 let if_state = IfStateDetails::fake(); -835 -836 // Note that the ProbePlan will change with each iteration. -837 for i in 0..5 { -838 let cancel = CancellationToken::new(); -839 println!("--round {}", i); -840 let r = client.get_report(if_state.clone(), false).await; -841 -842 assert!(r.has_udp(), "want UDP"); -843 assert_eq!( -844 r.relay_latency.len(), -845 1, -846 "expected 1 key in RelayLatency; got {}", -847 r.relay_latency.len() -848 ); -849 assert!( -850 r.relay_latency.iter().next().is_some(), -851 "expected key 1 in RelayLatency; got {:?}", -852 r.relay_latency -853 ); -854 assert!(r.global_v4.is_some(), "expected globalV4 set"); -855 assert!(r.preferred_relay.is_some(),); -856 cancel.cancel(); -857 } -858 -859 ep.wait_idle().await; -860 server.shutdown().await?; -861 -862 Ok(()) -863 } -864 -865 #[tokio::test(flavor = "current_thread", start_paused = true)] -866 async fn test_add_report_history_set_preferred_relay() -> Result { -867 fn relay_url(i: u16) -> RelayUrl { -868 format!("http://{i}.com").parse().unwrap() -869 } -870 -871 // report returns a *Report from (relay host, Duration)+ pairs. -872 fn report(a: impl IntoIterator<Item = (&'static str, u64)>) -> Option<Report> { -873 let mut report = Report::default(); -874 for (s, d) in a { -875 assert!(s.starts_with('d'), "invalid relay server key"); -876 let id: u16 = s[1..].parse().unwrap(); -877 report.relay_latency.update_relay( -878 relay_url(id), -879 Duration::from_secs(d), -880 Probe::QadIpv4, -881 ); -882 } +811#[cfg(test)] +812mod tests { +813 use std::net::{Ipv4Addr, SocketAddr}; +814 +815 use iroh_base::RelayUrl; +816 use iroh_relay::dns::DnsResolver; +817 use n0_snafu::{Result, ResultExt}; +818 use tokio_util::sync::CancellationToken; +819 use tracing_test::traced_test; +820 +821 use super::*; +822 use crate::net_report::probes::Probe; +823 +824 #[tokio::test] +825 #[traced_test] +826 async fn test_basic() -> Result<()> { +827 let (server, relay) = test_utils::relay().await; +828 let client_config = iroh_relay::client::make_dangerous_client_config(); +829 let ep = quinn::Endpoint::client(SocketAddr::new(Ipv4Addr::LOCALHOST.into(), 0)).e()?; +830 let quic_addr_disc = QuicConfig { +831 ep: ep.clone(), +832 client_config, +833 ipv4: true, +834 ipv6: true, +835 }; +836 let relay_map = RelayMap::from(relay); +837 +838 let resolver = DnsResolver::new(); +839 let opts = Options::default().quic_config(Some(quic_addr_disc.clone())); +840 let mut client = Client::new( +841 resolver.clone(), +842 None, +843 relay_map.clone(), +844 opts.clone(), +845 Default::default(), +846 ); +847 let if_state = IfStateDetails::fake(); +848 +849 // Note that the ProbePlan will change with each iteration. +850 for i in 0..5 { +851 let cancel = CancellationToken::new(); +852 println!("--round {}", i); +853 let r = client.get_report(if_state.clone(), false).await; +854 +855 assert!(r.has_udp(), "want UDP"); +856 assert_eq!( +857 r.relay_latency.len(), +858 1, +859 "expected 1 key in RelayLatency; got {}", +860 r.relay_latency.len() +861 ); +862 assert!( +863 r.relay_latency.iter().next().is_some(), +864 "expected key 1 in RelayLatency; got {:?}", +865 r.relay_latency +866 ); +867 assert!(r.global_v4.is_some(), "expected globalV4 set"); +868 assert!(r.preferred_relay.is_some(),); +869 cancel.cancel(); +870 } +871 +872 ep.wait_idle().await; +873 server.shutdown().await?; +874 +875 Ok(()) +876 } +877 +878 #[tokio::test(flavor = "current_thread", start_paused = true)] +879 async fn test_add_report_history_set_preferred_relay() -> Result { +880 fn relay_url(i: u16) -> RelayUrl { +881 format!("http://{i}.com").parse().unwrap() +882 } 883 -884 Some(report) -885 } -886 struct Step { -887 /// Delay in seconds -888 after: u64, -889 r: Option<Report>, -890 } -891 struct Test { -892 name: &'static str, -893 steps: Vec<Step>, -894 /// want PreferredRelay on final step -895 want_relay: Option<RelayUrl>, -896 // wanted len(c.prev) -897 want_prev_len: usize, +884 // report returns a *Report from (relay host, Duration)+ pairs. +885 fn report(a: impl IntoIterator<Item = (&'static str, u64)>) -> Option<Report> { +886 let mut report = Report::default(); +887 for (s, d) in a { +888 assert!(s.starts_with('d'), "invalid relay server key"); +889 let id: u16 = s[1..].parse().unwrap(); +890 report.relay_latency.update_relay( +891 relay_url(id), +892 Duration::from_secs(d), +893 Probe::QadIpv4, +894 ); +895 } +896 +897 Some(report) 898 } -899 -900 let tests = [ -901 Test { -902 name: "first_reading", -903 steps: vec![Step { -904 after: 0, -905 r: report([("d1", 2), ("d2", 3)]), -906 }], -907 want_prev_len: 1, -908 want_relay: Some(relay_url(1)), -909 }, -910 Test { -911 name: "with_two", -912 steps: vec![ -913 Step { -914 after: 0, -915 r: report([("d1", 2), ("d2", 3)]), -916 }, -917 Step { -918 after: 1, -919 r: report([("d1", 4), ("d2", 3)]), -920 }, -921 ], -922 want_prev_len: 2, -923 want_relay: Some(relay_url(1)), // t0's d1 of 2 is still best -924 }, -925 Test { -926 name: "but_now_d1_gone", -927 steps: vec![ -928 Step { -929 after: 0, -930 r: report([("d1", 2), ("d2", 3)]), -931 }, -932 Step { -933 after: 1, -934 r: report([("d1", 4), ("d2", 3)]), -935 }, -936 Step { -937 after: 2, -938 r: report([("d2", 3)]), -939 }, -940 ], -941 want_prev_len: 3, -942 want_relay: Some(relay_url(2)), // only option -943 }, -944 Test { -945 name: "d1_is_back", -946 steps: vec![ -947 Step { -948 after: 0, -949 r: report([("d1", 2), ("d2", 3)]), -950 }, -951 Step { -952 after: 1, -953 r: report([("d1", 4), ("d2", 3)]), -954 }, -955 Step { -956 after: 2, -957 r: report([("d2", 3)]), -958 }, -959 Step { -960 after: 3, -961 r: report([("d1", 4), ("d2", 3)]), -962 }, // same as 2 seconds ago -963 ], -964 want_prev_len: 4, -965 want_relay: Some(relay_url(1)), // t0's d1 of 2 is still best -966 }, -967 Test { -968 name: "things_clean_up", -969 steps: vec![ -970 Step { -971 after: 0, -972 r: report([("d1", 1), ("d2", 2)]), -973 }, -974 Step { -975 after: 1, -976 r: report([("d1", 1), ("d2", 2)]), -977 }, -978 Step { -979 after: 2, -980 r: report([("d1", 1), ("d2", 2)]), -981 }, -982 Step { -983 after: 3, -984 r: report([("d1", 1), ("d2", 2)]), -985 }, -986 Step { -987 after: 10 * 60, -988 r: report([("d3", 3)]), -989 }, -990 ], -991 want_prev_len: 1, // t=[0123]s all gone. (too old, older than 10 min) -992 want_relay: Some(relay_url(3)), // only option -993 }, -994 Test { -995 name: "preferred_relay_hysteresis_no_switch", -996 steps: vec![ -997 Step { -998 after: 0, -999 r: report([("d1", 4), ("d2", 5)]), -1000 }, -1001 Step { -1002 after: 1, -1003 r: report([("d1", 4), ("d2", 3)]), -1004 }, -1005 ], -1006 want_prev_len: 2, -1007 want_relay: Some(relay_url(1)), // 2 didn't get fast enough -1008 }, -1009 Test { -1010 name: "preferred_relay_hysteresis_do_switch", -1011 steps: vec![ -1012 Step { -1013 after: 0, -1014 r: report([("d1", 4), ("d2", 5)]), -1015 }, -1016 Step { -1017 after: 1, -1018 r: report([("d1", 4), ("d2", 1)]), -1019 }, -1020 ], -1021 want_prev_len: 2, -1022 want_relay: Some(relay_url(2)), // 2 got fast enough -1023 }, -1024 ]; -1025 let resolver = DnsResolver::new(); -1026 for mut tt in tests { -1027 println!("test: {}", tt.name); -1028 let relay_map = RelayMap::empty(); -1029 let opts = Options::default(); -1030 let mut client = -1031 Client::new(resolver.clone(), None, relay_map, opts, Default::default()); -1032 for s in &mut tt.steps { -1033 // trigger the timer -1034 tokio::time::advance(Duration::from_secs(s.after)).await; -1035 client.add_report_history_and_set_preferred_relay(s.r.as_mut().unwrap()); -1036 } -1037 let last_report = tt.steps.last().unwrap().r.clone().unwrap(); -1038 let got = client.reports.prev.len(); -1039 let want = tt.want_prev_len; -1040 assert_eq!(got, want, "prev length"); -1041 let got = &last_report.preferred_relay; -1042 let want = &tt.want_relay; -1043 assert_eq!(got, want, "preferred_relay"); -1044 } -1045 -1046 Ok(()) -1047 } -1048} \ No newline at end of file +899 struct Step { +900 /// Delay in seconds +901 after: u64, +902 r: Option<Report>, +903 } +904 struct Test { +905 name: &'static str, +906 steps: Vec<Step>, +907 /// want PreferredRelay on final step +908 want_relay: Option<RelayUrl>, +909 // wanted len(c.prev) +910 want_prev_len: usize, +911 } +912 +913 let tests = [ +914 Test { +915 name: "first_reading", +916 steps: vec![Step { +917 after: 0, +918 r: report([("d1", 2), ("d2", 3)]), +919 }], +920 want_prev_len: 1, +921 want_relay: Some(relay_url(1)), +922 }, +923 Test { +924 name: "with_two", +925 steps: vec![ +926 Step { +927 after: 0, +928 r: report([("d1", 2), ("d2", 3)]), +929 }, +930 Step { +931 after: 1, +932 r: report([("d1", 4), ("d2", 3)]), +933 }, +934 ], +935 want_prev_len: 2, +936 want_relay: Some(relay_url(1)), // t0's d1 of 2 is still best +937 }, +938 Test { +939 name: "but_now_d1_gone", +940 steps: vec![ +941 Step { +942 after: 0, +943 r: report([("d1", 2), ("d2", 3)]), +944 }, +945 Step { +946 after: 1, +947 r: report([("d1", 4), ("d2", 3)]), +948 }, +949 Step { +950 after: 2, +951 r: report([("d2", 3)]), +952 }, +953 ], +954 want_prev_len: 3, +955 want_relay: Some(relay_url(2)), // only option +956 }, +957 Test { +958 name: "d1_is_back", +959 steps: vec![ +960 Step { +961 after: 0, +962 r: report([("d1", 2), ("d2", 3)]), +963 }, +964 Step { +965 after: 1, +966 r: report([("d1", 4), ("d2", 3)]), +967 }, +968 Step { +969 after: 2, +970 r: report([("d2", 3)]), +971 }, +972 Step { +973 after: 3, +974 r: report([("d1", 4), ("d2", 3)]), +975 }, // same as 2 seconds ago +976 ], +977 want_prev_len: 4, +978 want_relay: Some(relay_url(1)), // t0's d1 of 2 is still best +979 }, +980 Test { +981 name: "things_clean_up", +982 steps: vec![ +983 Step { +984 after: 0, +985 r: report([("d1", 1), ("d2", 2)]), +986 }, +987 Step { +988 after: 1, +989 r: report([("d1", 1), ("d2", 2)]), +990 }, +991 Step { +992 after: 2, +993 r: report([("d1", 1), ("d2", 2)]), +994 }, +995 Step { +996 after: 3, +997 r: report([("d1", 1), ("d2", 2)]), +998 }, +999 Step { +1000 after: 10 * 60, +1001 r: report([("d3", 3)]), +1002 }, +1003 ], +1004 want_prev_len: 1, // t=[0123]s all gone. (too old, older than 10 min) +1005 want_relay: Some(relay_url(3)), // only option +1006 }, +1007 Test { +1008 name: "preferred_relay_hysteresis_no_switch", +1009 steps: vec![ +1010 Step { +1011 after: 0, +1012 r: report([("d1", 4), ("d2", 5)]), +1013 }, +1014 Step { +1015 after: 1, +1016 r: report([("d1", 4), ("d2", 3)]), +1017 }, +1018 ], +1019 want_prev_len: 2, +1020 want_relay: Some(relay_url(1)), // 2 didn't get fast enough +1021 }, +1022 Test { +1023 name: "preferred_relay_hysteresis_do_switch", +1024 steps: vec![ +1025 Step { +1026 after: 0, +1027 r: report([("d1", 4), ("d2", 5)]), +1028 }, +1029 Step { +1030 after: 1, +1031 r: report([("d1", 4), ("d2", 1)]), +1032 }, +1033 ], +1034 want_prev_len: 2, +1035 want_relay: Some(relay_url(2)), // 2 got fast enough +1036 }, +1037 ]; +1038 let resolver = DnsResolver::new(); +1039 for mut tt in tests { +1040 println!("test: {}", tt.name); +1041 let relay_map = RelayMap::empty(); +1042 let opts = Options::default(); +1043 let mut client = +1044 Client::new(resolver.clone(), None, relay_map, opts, Default::default()); +1045 for s in &mut tt.steps { +1046 // trigger the timer +1047 tokio::time::advance(Duration::from_secs(s.after)).await; +1048 client.add_report_history_and_set_preferred_relay(s.r.as_mut().unwrap()); +1049 } +1050 let last_report = tt.steps.last().unwrap().r.clone().unwrap(); +1051 let got = client.reports.prev.len(); +1052 let want = tt.want_prev_len; +1053 assert_eq!(got, want, "prev length"); +1054 let got = &last_report.preferred_relay; +1055 let want = &tt.want_relay; +1056 assert_eq!(got, want, "preferred_relay"); +1057 } +1058 +1059 Ok(()) +1060 } +1061} \ No newline at end of file diff --git a/pr/3314/docs/src/iroh/net_report/reportgen.rs.html b/pr/3314/docs/src/iroh/net_report/reportgen.rs.html index c5a07415f8..edd226697e 100644 --- a/pr/3314/docs/src/iroh/net_report/reportgen.rs.html +++ b/pr/3314/docs/src/iroh/net_report/reportgen.rs.html @@ -226,704 +226,687 @@ 226 // any reports of working UDP/QUIC? 227 let mut have_udp = false; 228 -229 // initial & re_stun(major): -230 // -231 // par [ -232 // timeout(race(qad_v4_probes)), -233 // timeout(race(qad_v6_probes)), -234 // ] -235 // -236 // if all_error [ -237 // run_https_probes -238 // run_captive_portal_check -239 // ] -240 // -241 // if have_qad_conns [ -242 // store(qad_conns) & keep alive -243 // ] -244 // -245 -246 // Check for probes finishing. -247 while let Some(probe_result) = probes.join_next().await { -248 trace!(?probe_result, num_probes, "processing finished probe"); -249 match probe_result { -250 Ok(report) => { -251 #[cfg_attr(wasm_browser, allow(irrefutable_let_patterns))] -252 if let ProbeFinished::Regular(report) = &report { -253 have_udp |= report.as_ref().map(|r| r.is_udp()).unwrap_or_default(); -254 num_probes -= 1; -255 -256 // If all probes are done & we have_udp cancel captive -257 if num_probes == 0 { -258 debug!("all regular probes done"); -259 debug_assert!(probes.len() <= 1, "{} probes", probes.len()); -260 -261 if have_udp { -262 captive_token.cancel(); -263 } -264 } -265 } -266 self.msg_tx.send(report).await.ok(); -267 } -268 Err(e) => { -269 if e.is_panic() { -270 error!("Task panicked {:?}", e); -271 break; -272 } -273 warn!("probes task join error: {:?}", e); -274 } -275 } -276 } -277 } -278 -279 /// Creates the future which will perform the captive portal check. -280 fn prepare_captive_portal_task(&self, tasks: &mut JoinSet<ProbeFinished>) -> CancellationToken { -281 let token = CancellationToken::new(); -282 -283 // If we're doing a full probe, also check for a captive portal. We -284 // delay by a bit to wait for UDP STUN to finish, to avoid the probe if -285 // it's unnecessary. -286 #[cfg(not(wasm_browser))] -287 if self.last_report.is_none() { -288 // Even if we're doing a non-incremental update, we may want to try our -289 // preferred relay for captive portal detection. -290 let preferred_relay = self -291 .last_report -292 .as_ref() -293 .and_then(|l| l.preferred_relay.clone()); -294 -295 let dns_resolver = self.socket_state.dns_resolver.clone(); -296 let dm = self.relay_map.clone(); -297 let token = token.clone(); -298 tasks.spawn( -299 async move { -300 let res = token -301 .run_until_cancelled_owned(async move { -302 time::sleep(CAPTIVE_PORTAL_DELAY).await; -303 trace!("check started after {CAPTIVE_PORTAL_DELAY:?}"); -304 time::timeout( -305 CAPTIVE_PORTAL_TIMEOUT, -306 check_captive_portal(&dns_resolver, &dm, preferred_relay), -307 ) -308 .await -309 }) -310 .await; -311 let res = match res { -312 Some(Ok(Ok(found))) => Some(found), -313 Some(Ok(Err(err))) => { -314 match err { -315 CaptivePortalError::CreateReqwestClient { source } -316 | CaptivePortalError::HttpRequest { source } -317 if source.is_connect() => -318 { -319 debug!("check_captive_portal failed: {source:#}"); -320 } -321 err => warn!("check_captive_portal error: {err:#}"), -322 } -323 None -324 } -325 Some(Err(time::Elapsed { .. })) => { -326 warn!("probe timed out"); -327 None -328 } -329 None => { -330 trace!("probe cancelled"); -331 None -332 } -333 }; -334 ProbeFinished::CaptivePortal(res) -335 } -336 .instrument(debug_span!("captive-portal")), -337 ); -338 } -339 token -340 } -341 -342 /// Prepares the future which will run all the probes as per generated ProbePlan. -343 /// -344 /// Probes operate like the following: -345 /// -346 /// - A future is created for each probe in all probe sets. -347 /// - All probes in a set are grouped in [`JoinSet`]. -348 /// - All those probe sets are grouped in one overall [`JoinSet`]. -349 /// - This future is polled by the main actor loop to make progress. -350 /// - Once a probe future is polled: -351 /// - Many probes start with a delay, they sleep during this time. -352 /// - When a probe starts it first asks the reportgen [`Actor`] if it is still useful -353 /// to run. If not it aborts the entire probe set. -354 /// - When a probe finishes, its [`ProbeReport`] is yielded to the reportgen actor. -355 /// - Probes get aborted in several ways: -356 /// - A running it can fail and abort the entire probe set if it deems the -357 /// failure permanent. Probes in a probe set are essentially retries. -358 /// - Once there are [`ProbeReport`]s from enough nodes, all remaining probes are -359 /// aborted. That is, the main actor loop stops polling them. -360 fn spawn_probes_task( -361 &self, -362 if_state: IfStateDetails, -363 probes: &mut JoinSet<ProbeFinished>, -364 ) -> CancellationToken { -365 debug!(?if_state, "local interface details"); -366 let plan = match self.last_report { -367 Some(ref report) => { -368 ProbePlan::with_last_report(&self.relay_map, report, &self.protocols) -369 } -370 None => ProbePlan::initial(&self.relay_map, &self.protocols), -371 }; -372 trace!(%plan, "probe plan"); -373 -374 let token = CancellationToken::new(); -375 -376 for probe_set in plan.iter() { -377 let set_token = token.child_token(); -378 let proto = probe_set.proto(); -379 for (delay, relay_node) in probe_set.params() { -380 let probe_token = set_token.child_token(); -381 let set_token = set_token.clone(); -382 -383 let fut = probe_token.run_until_cancelled_owned(time::timeout( -384 PROBES_TIMEOUT, -385 proto.run( -386 *delay, -387 relay_node.clone(), -388 #[cfg(not(wasm_browser))] -389 self.socket_state.clone(), -390 #[cfg(any(test, feature = "test-utils"))] -391 self.insecure_skip_relay_cert_verify, -392 ), -393 )); -394 probes.spawn( -395 async move { -396 let res = fut.await; -397 let res = match res { -398 Some(Ok(Ok(report))) => Ok(report), -399 Some(Ok(Err(RunProbeError::Error(err)))) => { -400 warn!("probe failed: {:#}", err); -401 Err(probes_error::ProbeFailureSnafu {}.into_error(err)) -402 } -403 Some(Ok(Err(RunProbeError::AbortSet(err)))) => { -404 debug!("probe set aborted: {:#}", err); -405 set_token.cancel(); -406 Err(probes_error::ProbeFailureSnafu {}.into_error(err)) -407 } -408 Some(Err(time::Elapsed { .. })) => { -409 Err(probes_error::TimeoutSnafu.build()) -410 } -411 None => Err(probes_error::CancelledSnafu.build()), -412 }; -413 ProbeFinished::Regular(res) -414 } -415 .instrument(debug_span!( -416 "run-probe", -417 ?proto, -418 ?delay, -419 ?relay_node -420 )), -421 ); -422 } -423 } -424 -425 token +229 // Check for probes finishing. +230 while let Some(probe_result) = probes.join_next().await { +231 trace!(?probe_result, num_probes, "processing finished probe"); +232 match probe_result { +233 Ok(report) => { +234 #[cfg_attr(wasm_browser, allow(irrefutable_let_patterns))] +235 if let ProbeFinished::Regular(report) = &report { +236 have_udp |= report.as_ref().map(|r| r.is_udp()).unwrap_or_default(); +237 num_probes -= 1; +238 +239 // If all probes are done & we have_udp cancel captive +240 if num_probes == 0 { +241 debug!("all regular probes done"); +242 debug_assert!(probes.len() <= 1, "{} probes", probes.len()); +243 +244 if have_udp { +245 captive_token.cancel(); +246 } +247 } +248 } +249 self.msg_tx.send(report).await.ok(); +250 } +251 Err(e) => { +252 if e.is_panic() { +253 error!("Task panicked {:?}", e); +254 break; +255 } +256 warn!("probes task join error: {:?}", e); +257 } +258 } +259 } +260 } +261 +262 /// Creates the future which will perform the captive portal check. +263 fn prepare_captive_portal_task(&self, tasks: &mut JoinSet<ProbeFinished>) -> CancellationToken { +264 let token = CancellationToken::new(); +265 +266 // If we're doing a full probe, also check for a captive portal. We +267 // delay by a bit to wait for UDP STUN to finish, to avoid the probe if +268 // it's unnecessary. +269 #[cfg(not(wasm_browser))] +270 if self.last_report.is_none() { +271 // Even if we're doing a non-incremental update, we may want to try our +272 // preferred relay for captive portal detection. +273 let preferred_relay = self +274 .last_report +275 .as_ref() +276 .and_then(|l| l.preferred_relay.clone()); +277 +278 let dns_resolver = self.socket_state.dns_resolver.clone(); +279 let dm = self.relay_map.clone(); +280 let token = token.clone(); +281 tasks.spawn( +282 async move { +283 let res = token +284 .run_until_cancelled_owned(async move { +285 time::sleep(CAPTIVE_PORTAL_DELAY).await; +286 trace!("check started after {CAPTIVE_PORTAL_DELAY:?}"); +287 time::timeout( +288 CAPTIVE_PORTAL_TIMEOUT, +289 check_captive_portal(&dns_resolver, &dm, preferred_relay), +290 ) +291 .await +292 }) +293 .await; +294 let res = match res { +295 Some(Ok(Ok(found))) => Some(found), +296 Some(Ok(Err(err))) => { +297 match err { +298 CaptivePortalError::CreateReqwestClient { source } +299 | CaptivePortalError::HttpRequest { source } +300 if source.is_connect() => +301 { +302 debug!("check_captive_portal failed: {source:#}"); +303 } +304 err => warn!("check_captive_portal error: {err:#}"), +305 } +306 None +307 } +308 Some(Err(time::Elapsed { .. })) => { +309 warn!("probe timed out"); +310 None +311 } +312 None => { +313 trace!("probe cancelled"); +314 None +315 } +316 }; +317 ProbeFinished::CaptivePortal(res) +318 } +319 .instrument(debug_span!("captive-portal")), +320 ); +321 } +322 token +323 } +324 +325 /// Prepares the future which will run all the probes as per generated ProbePlan. +326 /// +327 /// Probes operate like the following: +328 /// +329 /// - A future is created for each probe in all probe sets. +330 /// - All probes in a set are grouped in [`JoinSet`]. +331 /// - All those probe sets are grouped in one overall [`JoinSet`]. +332 /// - This future is polled by the main actor loop to make progress. +333 /// - Once a probe future is polled: +334 /// - Many probes start with a delay, they sleep during this time. +335 /// - When a probe starts it first asks the reportgen [`Actor`] if it is still useful +336 /// to run. If not it aborts the entire probe set. +337 /// - When a probe finishes, its [`ProbeReport`] is yielded to the reportgen actor. +338 /// - Probes get aborted in several ways: +339 /// - A running it can fail and abort the entire probe set if it deems the +340 /// failure permanent. Probes in a probe set are essentially retries. +341 /// - Once there are [`ProbeReport`]s from enough nodes, all remaining probes are +342 /// aborted. That is, the main actor loop stops polling them. +343 fn spawn_probes_task( +344 &self, +345 if_state: IfStateDetails, +346 probes: &mut JoinSet<ProbeFinished>, +347 ) -> CancellationToken { +348 debug!(?if_state, "local interface details"); +349 let plan = match self.last_report { +350 Some(ref report) => { +351 ProbePlan::with_last_report(&self.relay_map, report, &self.protocols) +352 } +353 None => ProbePlan::initial(&self.relay_map, &self.protocols), +354 }; +355 trace!(%plan, "probe plan"); +356 +357 let token = CancellationToken::new(); +358 +359 for probe_set in plan.iter() { +360 let set_token = token.child_token(); +361 let proto = probe_set.proto(); +362 for (delay, relay_node) in probe_set.params() { +363 let probe_token = set_token.child_token(); +364 let set_token = set_token.clone(); +365 +366 let fut = probe_token.run_until_cancelled_owned(time::timeout( +367 PROBES_TIMEOUT, +368 proto.run( +369 *delay, +370 relay_node.clone(), +371 #[cfg(not(wasm_browser))] +372 self.socket_state.clone(), +373 #[cfg(any(test, feature = "test-utils"))] +374 self.insecure_skip_relay_cert_verify, +375 ), +376 )); +377 probes.spawn( +378 async move { +379 let res = fut.await; +380 let res = match res { +381 Some(Ok(Ok(report))) => Ok(report), +382 Some(Ok(Err(RunProbeError::Error(err)))) => { +383 warn!("probe failed: {:#}", err); +384 Err(probes_error::ProbeFailureSnafu {}.into_error(err)) +385 } +386 Some(Ok(Err(RunProbeError::AbortSet(err)))) => { +387 debug!("probe set aborted: {:#}", err); +388 set_token.cancel(); +389 Err(probes_error::ProbeFailureSnafu {}.into_error(err)) +390 } +391 Some(Err(time::Elapsed { .. })) => { +392 Err(probes_error::TimeoutSnafu.build()) +393 } +394 None => Err(probes_error::CancelledSnafu.build()), +395 }; +396 ProbeFinished::Regular(res) +397 } +398 .instrument(debug_span!( +399 "run-probe", +400 ?proto, +401 ?delay, +402 ?relay_node +403 )), +404 ); +405 } +406 } +407 +408 token +409 } +410} +411 +412/// The success result of [`run_probe`]. +413#[derive(Debug, Clone)] +414pub(super) enum ProbeReport { +415 #[cfg(not(wasm_browser))] +416 QadIpv4(QadProbeReport), +417 #[cfg(not(wasm_browser))] +418 QadIpv6(QadProbeReport), +419 Https(HttpsProbeReport), +420} +421 +422impl ProbeReport { +423 #[cfg(not(wasm_browser))] +424 pub(super) fn is_udp(&self) -> bool { +425 matches!(self, Self::QadIpv4(_) | Self::QadIpv6(_)) 426 } -427} -428 -429/// The success result of [`run_probe`]. -430#[derive(Debug, Clone)] -431pub(super) enum ProbeReport { -432 #[cfg(not(wasm_browser))] -433 QadIpv4(QadProbeReport), -434 #[cfg(not(wasm_browser))] -435 QadIpv6(QadProbeReport), -436 Https(HttpsProbeReport), -437} -438 -439impl ProbeReport { -440 #[cfg(not(wasm_browser))] -441 pub(super) fn is_udp(&self) -> bool { -442 matches!(self, Self::QadIpv4(_) | Self::QadIpv6(_)) -443 } +427 +428 #[cfg(wasm_browser)] +429 pub(super) fn is_udp(&self) -> bool { +430 false +431 } +432} +433 +434#[cfg(not(wasm_browser))] +435#[derive(Debug, Clone, PartialEq, Eq)] +436pub(super) struct QadProbeReport { +437 /// The relay node that was probed +438 pub(super) node: RelayUrl, +439 /// The latency to the relay node. +440 pub(super) latency: Duration, +441 /// The discovered public address. +442 pub(super) addr: SocketAddr, +443} 444 -445 #[cfg(wasm_browser)] -446 pub(super) fn is_udp(&self) -> bool { -447 false -448 } -449} -450 -451#[cfg(not(wasm_browser))] -452#[derive(Debug, Clone, PartialEq, Eq)] -453pub(super) struct QadProbeReport { -454 /// The relay node that was probed -455 pub(super) node: RelayUrl, -456 /// The latency to the relay node. -457 pub(super) latency: Duration, -458 /// The discovered public address. -459 pub(super) addr: SocketAddr, -460} -461 -462#[derive(Debug, Clone)] -463pub(super) struct HttpsProbeReport { -464 /// The relay node that was probed -465 pub(super) node: RelayUrl, -466 /// The latency to the relay node. -467 pub(super) latency: Duration, -468} -469 -470/// Errors for [`run_probe`]. -471/// -472/// The main purpose is to signal whether other probes in this probe set should still be -473/// run. Recall that a probe set is normally a set of identical probes with delays, -474/// effectively creating retries, and the first successful probe of a probe set will cancel -475/// the others in the set. So this allows an unsuccessful probe to cancel the remainder of -476/// the set or not. -477#[derive(Debug)] -478enum RunProbeError { -479 /// Abort the current set. -480 AbortSet(ProbeError), -481 /// Continue the other probes in the set. -482 Error(ProbeError), -483} -484 -485#[allow(missing_docs)] -486#[derive(Debug, Snafu)] -487#[snafu(module)] -488#[non_exhaustive] -489pub(super) enum ProbeError { -490 #[snafu(display("Client is gone"))] -491 ClientGone, -492 #[snafu(display("Probe is no longer useful"))] -493 NotUseful, -494 #[snafu(display("Failed to run HTTPS probe"))] -495 Https { source: MeasureHttpsLatencyError }, -496} -497 -498#[allow(missing_docs)] -499#[derive(Debug, Snafu)] -500#[snafu(module)] -501#[non_exhaustive] -502pub(super) enum QuicError { -503 #[snafu(display("No QUIC endpoint available"))] -504 NoEndpoint, -505 #[snafu(display("URL must have 'host' to use QUIC address discovery probes"))] -506 InvalidUrl, -507 #[snafu(display("Failed to get address and latency"))] -508 GetAddr { source: iroh_relay::quic::Error }, -509} -510 -511/// Pieces needed to do QUIC address discovery. -512#[derive(derive_more::Debug, Clone)] -513pub struct QuicConfig { -514 /// A QUIC Endpoint -515 #[debug("quinn::Endpoint")] -516 pub ep: quinn::Endpoint, -517 /// A client config. -518 pub client_config: rustls::ClientConfig, -519 /// Enable ipv4 QUIC address discovery probes -520 pub ipv4: bool, -521 /// Enable ipv6 QUIC address discovery probes -522 pub ipv6: bool, -523} -524 -525impl Probe { -526 /// Executes this particular [`Probe`], including using a delayed start if needed. -527 async fn run( -528 self, -529 delay: Duration, -530 relay_node: Arc<RelayNode>, -531 #[cfg(not(wasm_browser))] socket_state: SocketState, -532 #[cfg(any(test, feature = "test-utils"))] insecure_skip_relay_cert_verify: bool, -533 ) -> Result<ProbeReport, RunProbeError> { -534 if !delay.is_zero() { -535 trace!("delaying probe"); -536 time::sleep(delay).await; -537 } -538 debug!("starting probe"); -539 -540 match self { -541 Probe::Https => { -542 match run_https_probe( -543 #[cfg(not(wasm_browser))] -544 &socket_state.dns_resolver, -545 relay_node.url.clone(), -546 #[cfg(any(test, feature = "test-utils"))] -547 insecure_skip_relay_cert_verify, -548 ) -549 .await -550 { -551 Ok(report) => Ok(ProbeReport::Https(report)), -552 Err(err) => Err(RunProbeError::Error( -553 probe_error::HttpsSnafu.into_error(err), -554 )), -555 } -556 } -557 #[cfg(not(wasm_browser))] -558 Probe::QadIpv4 | Probe::QadIpv6 => unreachable!("must not be used"), -559 } -560 } -561} -562 -563#[cfg(not(wasm_browser))] -564pub(super) fn maybe_to_mapped_addr( -565 ip_mapped_addrs: Option<&IpMappedAddresses>, -566 addr: SocketAddr, -567) -> SocketAddr { -568 if let Some(ip_mapped_addrs) = ip_mapped_addrs { -569 return ip_mapped_addrs.get_or_register(addr).private_socket_addr(); -570 } -571 addr -572} -573 -574#[cfg(not(wasm_browser))] -575#[derive(Debug, Snafu)] -576#[snafu(module)] -577#[non_exhaustive] -578enum CaptivePortalError { -579 #[snafu(transparent)] -580 DnsLookup { source: StaggeredError<DnsError> }, -581 #[snafu(display("Creating HTTP client failed"))] -582 CreateReqwestClient { source: reqwest::Error }, -583 #[snafu(display("HTTP request failed"))] -584 HttpRequest { source: reqwest::Error }, -585} -586 -587/// Reports whether or not we think the system is behind a -588/// captive portal, detected by making a request to a URL that we know should -589/// return a "204 No Content" response and checking if that's what we get. -590/// -591/// The boolean return is whether we think we have a captive portal. -592#[cfg(not(wasm_browser))] -593async fn check_captive_portal( -594 dns_resolver: &DnsResolver, -595 dm: &RelayMap, -596 preferred_relay: Option<RelayUrl>, -597) -> Result<bool, CaptivePortalError> { -598 // If we have a preferred relay node and we can use it for non-STUN requests, try that; -599 // otherwise, pick a random one suitable for non-STUN requests. -600 -601 let preferred_relay = preferred_relay.and_then(|url| dm.get_node(&url).map(|_| url)); -602 -603 let url = match preferred_relay { -604 Some(url) => url, -605 None => { -606 let urls: Vec<_> = dm.nodes().map(|n| n.url.clone()).collect(); -607 if urls.is_empty() { -608 debug!("No suitable relay node for captive portal check"); -609 return Ok(false); -610 } -611 -612 let i = (0..urls.len()) -613 .choose(&mut rand::thread_rng()) -614 .unwrap_or_default(); -615 urls[i].clone() -616 } -617 }; -618 -619 let mut builder = reqwest::ClientBuilder::new().redirect(reqwest::redirect::Policy::none()); -620 -621 if let Some(Host::Domain(domain)) = url.host() { -622 // Use our own resolver rather than getaddrinfo -623 // -624 // Be careful, a non-zero port will override the port in the URI. -625 // -626 // Ideally we would try to resolve **both** IPv4 and IPv6 rather than purely race -627 // them. But our resolver doesn't support that yet. -628 let addrs: Vec<_> = dns_resolver -629 .lookup_ipv4_ipv6_staggered(domain, DNS_TIMEOUT, DNS_STAGGERING_MS) -630 .await? -631 .map(|ipaddr| SocketAddr::new(ipaddr, 0)) -632 .collect(); -633 builder = builder.resolve_to_addrs(domain, &addrs); -634 } -635 let client = builder -636 .build() -637 .context(captive_portal_error::CreateReqwestClientSnafu)?; -638 -639 // Note: the set of valid characters in a challenge and the total -640 // length is limited; see is_challenge_char in bin/iroh-relay for more -641 // details. +445#[derive(Debug, Clone)] +446pub(super) struct HttpsProbeReport { +447 /// The relay node that was probed +448 pub(super) node: RelayUrl, +449 /// The latency to the relay node. +450 pub(super) latency: Duration, +451} +452 +453/// Errors for [`run_probe`]. +454/// +455/// The main purpose is to signal whether other probes in this probe set should still be +456/// run. Recall that a probe set is normally a set of identical probes with delays, +457/// effectively creating retries, and the first successful probe of a probe set will cancel +458/// the others in the set. So this allows an unsuccessful probe to cancel the remainder of +459/// the set or not. +460#[derive(Debug)] +461enum RunProbeError { +462 /// Abort the current set. +463 AbortSet(ProbeError), +464 /// Continue the other probes in the set. +465 Error(ProbeError), +466} +467 +468#[allow(missing_docs)] +469#[derive(Debug, Snafu)] +470#[snafu(module)] +471#[non_exhaustive] +472pub(super) enum ProbeError { +473 #[snafu(display("Client is gone"))] +474 ClientGone, +475 #[snafu(display("Probe is no longer useful"))] +476 NotUseful, +477 #[snafu(display("Failed to run HTTPS probe"))] +478 Https { source: MeasureHttpsLatencyError }, +479} +480 +481#[allow(missing_docs)] +482#[derive(Debug, Snafu)] +483#[snafu(module)] +484#[non_exhaustive] +485pub(super) enum QuicError { +486 #[snafu(display("No QUIC endpoint available"))] +487 NoEndpoint, +488 #[snafu(display("URL must have 'host' to use QUIC address discovery probes"))] +489 InvalidUrl, +490 #[snafu(display("Failed to get address and latency"))] +491 GetAddr { source: iroh_relay::quic::Error }, +492} +493 +494/// Pieces needed to do QUIC address discovery. +495#[derive(derive_more::Debug, Clone)] +496pub struct QuicConfig { +497 /// A QUIC Endpoint +498 #[debug("quinn::Endpoint")] +499 pub ep: quinn::Endpoint, +500 /// A client config. +501 pub client_config: rustls::ClientConfig, +502 /// Enable ipv4 QUIC address discovery probes +503 pub ipv4: bool, +504 /// Enable ipv6 QUIC address discovery probes +505 pub ipv6: bool, +506} +507 +508impl Probe { +509 /// Executes this particular [`Probe`], including using a delayed start if needed. +510 async fn run( +511 self, +512 delay: Duration, +513 relay_node: Arc<RelayNode>, +514 #[cfg(not(wasm_browser))] socket_state: SocketState, +515 #[cfg(any(test, feature = "test-utils"))] insecure_skip_relay_cert_verify: bool, +516 ) -> Result<ProbeReport, RunProbeError> { +517 if !delay.is_zero() { +518 trace!("delaying probe"); +519 time::sleep(delay).await; +520 } +521 debug!("starting probe"); +522 +523 match self { +524 Probe::Https => { +525 match run_https_probe( +526 #[cfg(not(wasm_browser))] +527 &socket_state.dns_resolver, +528 relay_node.url.clone(), +529 #[cfg(any(test, feature = "test-utils"))] +530 insecure_skip_relay_cert_verify, +531 ) +532 .await +533 { +534 Ok(report) => Ok(ProbeReport::Https(report)), +535 Err(err) => Err(RunProbeError::Error( +536 probe_error::HttpsSnafu.into_error(err), +537 )), +538 } +539 } +540 #[cfg(not(wasm_browser))] +541 Probe::QadIpv4 | Probe::QadIpv6 => unreachable!("must not be used"), +542 } +543 } +544} +545 +546#[cfg(not(wasm_browser))] +547pub(super) fn maybe_to_mapped_addr( +548 ip_mapped_addrs: Option<&IpMappedAddresses>, +549 addr: SocketAddr, +550) -> SocketAddr { +551 if let Some(ip_mapped_addrs) = ip_mapped_addrs { +552 return ip_mapped_addrs.get_or_register(addr).private_socket_addr(); +553 } +554 addr +555} +556 +557#[cfg(not(wasm_browser))] +558#[derive(Debug, Snafu)] +559#[snafu(module)] +560#[non_exhaustive] +561enum CaptivePortalError { +562 #[snafu(transparent)] +563 DnsLookup { source: StaggeredError<DnsError> }, +564 #[snafu(display("Creating HTTP client failed"))] +565 CreateReqwestClient { source: reqwest::Error }, +566 #[snafu(display("HTTP request failed"))] +567 HttpRequest { source: reqwest::Error }, +568} +569 +570/// Reports whether or not we think the system is behind a +571/// captive portal, detected by making a request to a URL that we know should +572/// return a "204 No Content" response and checking if that's what we get. +573/// +574/// The boolean return is whether we think we have a captive portal. +575#[cfg(not(wasm_browser))] +576async fn check_captive_portal( +577 dns_resolver: &DnsResolver, +578 dm: &RelayMap, +579 preferred_relay: Option<RelayUrl>, +580) -> Result<bool, CaptivePortalError> { +581 // If we have a preferred relay node and we can use it for non-STUN requests, try that; +582 // otherwise, pick a random one suitable for non-STUN requests. +583 +584 let preferred_relay = preferred_relay.and_then(|url| dm.get_node(&url).map(|_| url)); +585 +586 let url = match preferred_relay { +587 Some(url) => url, +588 None => { +589 let urls: Vec<_> = dm.nodes().map(|n| n.url.clone()).collect(); +590 if urls.is_empty() { +591 debug!("No suitable relay node for captive portal check"); +592 return Ok(false); +593 } +594 +595 let i = (0..urls.len()) +596 .choose(&mut rand::thread_rng()) +597 .unwrap_or_default(); +598 urls[i].clone() +599 } +600 }; +601 +602 let mut builder = reqwest::ClientBuilder::new().redirect(reqwest::redirect::Policy::none()); +603 +604 if let Some(Host::Domain(domain)) = url.host() { +605 // Use our own resolver rather than getaddrinfo +606 // +607 // Be careful, a non-zero port will override the port in the URI. +608 // +609 // Ideally we would try to resolve **both** IPv4 and IPv6 rather than purely race +610 // them. But our resolver doesn't support that yet. +611 let addrs: Vec<_> = dns_resolver +612 .lookup_ipv4_ipv6_staggered(domain, DNS_TIMEOUT, DNS_STAGGERING_MS) +613 .await? +614 .map(|ipaddr| SocketAddr::new(ipaddr, 0)) +615 .collect(); +616 builder = builder.resolve_to_addrs(domain, &addrs); +617 } +618 let client = builder +619 .build() +620 .context(captive_portal_error::CreateReqwestClientSnafu)?; +621 +622 // Note: the set of valid characters in a challenge and the total +623 // length is limited; see is_challenge_char in bin/iroh-relay for more +624 // details. +625 +626 let host_name = url.host_str().unwrap_or_default(); +627 let challenge = format!("ts_{}", host_name); +628 let portal_url = format!("http://{}/generate_204", host_name); +629 let res = client +630 .request(reqwest::Method::GET, portal_url) +631 .header("X-Tailscale-Challenge", &challenge) +632 .send() +633 .await +634 .context(captive_portal_error::HttpRequestSnafu)?; +635 +636 let expected_response = format!("response {challenge}"); +637 let is_valid_response = res +638 .headers() +639 .get("X-Tailscale-Response") +640 .map(|s| s.to_str().unwrap_or_default()) +641 == Some(&expected_response); 642 -643 let host_name = url.host_str().unwrap_or_default(); -644 let challenge = format!("ts_{}", host_name); -645 let portal_url = format!("http://{}/generate_204", host_name); -646 let res = client -647 .request(reqwest::Method::GET, portal_url) -648 .header("X-Tailscale-Challenge", &challenge) -649 .send() -650 .await -651 .context(captive_portal_error::HttpRequestSnafu)?; -652 -653 let expected_response = format!("response {challenge}"); -654 let is_valid_response = res -655 .headers() -656 .get("X-Tailscale-Response") -657 .map(|s| s.to_str().unwrap_or_default()) -658 == Some(&expected_response); -659 -660 debug!( -661 "check_captive_portal url={} status_code={} valid_response={}", -662 res.url(), -663 res.status(), -664 is_valid_response, -665 ); -666 let has_captive = res.status() != 204 || !is_valid_response; +643 debug!( +644 "check_captive_portal url={} status_code={} valid_response={}", +645 res.url(), +646 res.status(), +647 is_valid_response, +648 ); +649 let has_captive = res.status() != 204 || !is_valid_response; +650 +651 Ok(has_captive) +652} +653 +654/// Returns the proper port based on the protocol of the probe. +655#[cfg(not(wasm_browser))] +656fn get_quic_port(relay_node: &RelayNode) -> Option<u16> { +657 if let Some(ref quic) = relay_node.quic { +658 if quic.port == 0 { +659 Some(DEFAULT_RELAY_QUIC_PORT) +660 } else { +661 Some(quic.port) +662 } +663 } else { +664 None +665 } +666} 667 -668 Ok(has_captive) -669} -670 -671/// Returns the proper port based on the protocol of the probe. -672#[cfg(not(wasm_browser))] -673fn get_quic_port(relay_node: &RelayNode) -> Option<u16> { -674 if let Some(ref quic) = relay_node.quic { -675 if quic.port == 0 { -676 Some(DEFAULT_RELAY_QUIC_PORT) -677 } else { -678 Some(quic.port) -679 } -680 } else { -681 None -682 } -683} -684 -685#[cfg(not(wasm_browser))] -686#[derive(Debug, Snafu)] -687#[snafu(module)] -688#[non_exhaustive] -689pub enum GetRelayAddrError { -690 #[snafu(display("No valid hostname in the relay URL"))] -691 InvalidHostname, -692 #[snafu(display("No suitable relay address found"))] -693 NoAddrFound, -694 #[snafu(display("DNS lookup failed"))] -695 DnsLookup { source: StaggeredError<DnsError> }, -696 #[snafu(display("Relay node is not suitable for non-STUN probes"))] -697 UnsupportedRelayNode, -698 #[snafu(display("HTTPS probes are not implemented"))] -699 UnsupportedHttps, -700 #[snafu(display("No port available for this protocol"))] -701 MissingPort, -702} -703 -704/// Returns the IP address to use to communicate to this relay node for quic. -705#[cfg(not(wasm_browser))] -706pub(super) async fn get_relay_addr_ipv4( -707 dns_resolver: &DnsResolver, -708 relay_node: &RelayNode, -709) -> Result<SocketAddrV4, GetRelayAddrError> { -710 let port = get_quic_port(relay_node).context(get_relay_addr_error::MissingPortSnafu)?; -711 relay_lookup_ipv4_staggered(dns_resolver, relay_node, port).await -712} -713 -714#[cfg(not(wasm_browser))] -715pub(super) async fn get_relay_addr_ipv6( -716 dns_resolver: &DnsResolver, -717 relay_node: &RelayNode, -718) -> Result<SocketAddrV6, GetRelayAddrError> { -719 let port = get_quic_port(relay_node).context(get_relay_addr_error::MissingPortSnafu)?; -720 relay_lookup_ipv6_staggered(dns_resolver, relay_node, port).await -721} -722 -723/// Do a staggared ipv4 DNS lookup based on [`RelayNode`] -724/// -725/// `port` is combined with the resolved [`std::net::Ipv4Addr`] to return a [`SocketAddr`] -726#[cfg(not(wasm_browser))] -727async fn relay_lookup_ipv4_staggered( -728 dns_resolver: &DnsResolver, -729 relay: &RelayNode, -730 port: u16, -731) -> Result<SocketAddrV4, GetRelayAddrError> { -732 match relay.url.host() { -733 Some(url::Host::Domain(hostname)) => { -734 trace!(%hostname, "Performing DNS A lookup for relay addr"); -735 match dns_resolver -736 .lookup_ipv4_staggered(hostname, DNS_TIMEOUT, DNS_STAGGERING_MS) -737 .await -738 { -739 Ok(mut addrs) => addrs -740 .next() -741 .map(|ip| ip.to_canonical()) -742 .map(|addr| match addr { -743 IpAddr::V4(ip) => SocketAddrV4::new(ip, port), -744 IpAddr::V6(_) => unreachable!("bad DNS lookup: {:?}", addr), -745 }) -746 .ok_or(get_relay_addr_error::NoAddrFoundSnafu.build()), -747 Err(err) => Err(get_relay_addr_error::DnsLookupSnafu.into_error(err)), -748 } -749 } -750 Some(url::Host::Ipv4(addr)) => Ok(SocketAddrV4::new(addr, port)), -751 Some(url::Host::Ipv6(_addr)) => Err(get_relay_addr_error::NoAddrFoundSnafu.build()), -752 None => Err(get_relay_addr_error::InvalidHostnameSnafu.build()), -753 } -754} -755 -756/// Do a staggared ipv6 DNS lookup based on [`RelayNode`] -757/// -758/// `port` is combined with the resolved [`std::net::Ipv6Addr`] to return a [`SocketAddr`] -759#[cfg(not(wasm_browser))] -760async fn relay_lookup_ipv6_staggered( -761 dns_resolver: &DnsResolver, -762 relay: &RelayNode, -763 port: u16, -764) -> Result<SocketAddrV6, GetRelayAddrError> { -765 match relay.url.host() { -766 Some(url::Host::Domain(hostname)) => { -767 trace!(%hostname, "Performing DNS AAAA lookup for relay addr"); -768 match dns_resolver -769 .lookup_ipv6_staggered(hostname, DNS_TIMEOUT, DNS_STAGGERING_MS) -770 .await -771 { -772 Ok(mut addrs) => addrs -773 .next() -774 .map(|addr| match addr { -775 IpAddr::V4(_) => unreachable!("bad DNS lookup: {:?}", addr), -776 IpAddr::V6(ip) => SocketAddrV6::new(ip, port, 0, 0), -777 }) -778 .ok_or(get_relay_addr_error::NoAddrFoundSnafu.build()), -779 Err(err) => Err(get_relay_addr_error::DnsLookupSnafu.into_error(err)), -780 } -781 } -782 Some(url::Host::Ipv4(_addr)) => Err(get_relay_addr_error::NoAddrFoundSnafu.build()), -783 Some(url::Host::Ipv6(addr)) => Ok(SocketAddrV6::new(addr, port, 0, 0)), -784 None => Err(get_relay_addr_error::InvalidHostnameSnafu.build()), -785 } +668#[cfg(not(wasm_browser))] +669#[derive(Debug, Snafu)] +670#[snafu(module)] +671#[non_exhaustive] +672pub enum GetRelayAddrError { +673 #[snafu(display("No valid hostname in the relay URL"))] +674 InvalidHostname, +675 #[snafu(display("No suitable relay address found"))] +676 NoAddrFound, +677 #[snafu(display("DNS lookup failed"))] +678 DnsLookup { source: StaggeredError<DnsError> }, +679 #[snafu(display("Relay node is not suitable for non-STUN probes"))] +680 UnsupportedRelayNode, +681 #[snafu(display("HTTPS probes are not implemented"))] +682 UnsupportedHttps, +683 #[snafu(display("No port available for this protocol"))] +684 MissingPort, +685} +686 +687/// Returns the IP address to use to communicate to this relay node for quic. +688#[cfg(not(wasm_browser))] +689pub(super) async fn get_relay_addr_ipv4( +690 dns_resolver: &DnsResolver, +691 relay_node: &RelayNode, +692) -> Result<SocketAddrV4, GetRelayAddrError> { +693 let port = get_quic_port(relay_node).context(get_relay_addr_error::MissingPortSnafu)?; +694 relay_lookup_ipv4_staggered(dns_resolver, relay_node, port).await +695} +696 +697#[cfg(not(wasm_browser))] +698pub(super) async fn get_relay_addr_ipv6( +699 dns_resolver: &DnsResolver, +700 relay_node: &RelayNode, +701) -> Result<SocketAddrV6, GetRelayAddrError> { +702 let port = get_quic_port(relay_node).context(get_relay_addr_error::MissingPortSnafu)?; +703 relay_lookup_ipv6_staggered(dns_resolver, relay_node, port).await +704} +705 +706/// Do a staggared ipv4 DNS lookup based on [`RelayNode`] +707/// +708/// `port` is combined with the resolved [`std::net::Ipv4Addr`] to return a [`SocketAddr`] +709#[cfg(not(wasm_browser))] +710async fn relay_lookup_ipv4_staggered( +711 dns_resolver: &DnsResolver, +712 relay: &RelayNode, +713 port: u16, +714) -> Result<SocketAddrV4, GetRelayAddrError> { +715 match relay.url.host() { +716 Some(url::Host::Domain(hostname)) => { +717 trace!(%hostname, "Performing DNS A lookup for relay addr"); +718 match dns_resolver +719 .lookup_ipv4_staggered(hostname, DNS_TIMEOUT, DNS_STAGGERING_MS) +720 .await +721 { +722 Ok(mut addrs) => addrs +723 .next() +724 .map(|ip| ip.to_canonical()) +725 .map(|addr| match addr { +726 IpAddr::V4(ip) => SocketAddrV4::new(ip, port), +727 IpAddr::V6(_) => unreachable!("bad DNS lookup: {:?}", addr), +728 }) +729 .ok_or(get_relay_addr_error::NoAddrFoundSnafu.build()), +730 Err(err) => Err(get_relay_addr_error::DnsLookupSnafu.into_error(err)), +731 } +732 } +733 Some(url::Host::Ipv4(addr)) => Ok(SocketAddrV4::new(addr, port)), +734 Some(url::Host::Ipv6(_addr)) => Err(get_relay_addr_error::NoAddrFoundSnafu.build()), +735 None => Err(get_relay_addr_error::InvalidHostnameSnafu.build()), +736 } +737} +738 +739/// Do a staggared ipv6 DNS lookup based on [`RelayNode`] +740/// +741/// `port` is combined with the resolved [`std::net::Ipv6Addr`] to return a [`SocketAddr`] +742#[cfg(not(wasm_browser))] +743async fn relay_lookup_ipv6_staggered( +744 dns_resolver: &DnsResolver, +745 relay: &RelayNode, +746 port: u16, +747) -> Result<SocketAddrV6, GetRelayAddrError> { +748 match relay.url.host() { +749 Some(url::Host::Domain(hostname)) => { +750 trace!(%hostname, "Performing DNS AAAA lookup for relay addr"); +751 match dns_resolver +752 .lookup_ipv6_staggered(hostname, DNS_TIMEOUT, DNS_STAGGERING_MS) +753 .await +754 { +755 Ok(mut addrs) => addrs +756 .next() +757 .map(|addr| match addr { +758 IpAddr::V4(_) => unreachable!("bad DNS lookup: {:?}", addr), +759 IpAddr::V6(ip) => SocketAddrV6::new(ip, port, 0, 0), +760 }) +761 .ok_or(get_relay_addr_error::NoAddrFoundSnafu.build()), +762 Err(err) => Err(get_relay_addr_error::DnsLookupSnafu.into_error(err)), +763 } +764 } +765 Some(url::Host::Ipv4(_addr)) => Err(get_relay_addr_error::NoAddrFoundSnafu.build()), +766 Some(url::Host::Ipv6(addr)) => Ok(SocketAddrV6::new(addr, port, 0, 0)), +767 None => Err(get_relay_addr_error::InvalidHostnameSnafu.build()), +768 } +769} +770 +771#[derive(Debug, Snafu)] +772#[snafu(module)] +773#[non_exhaustive] +774pub enum MeasureHttpsLatencyError { +775 #[snafu(transparent)] +776 InvalidUrl { source: url::ParseError }, +777 #[cfg(not(wasm_browser))] +778 #[snafu(transparent)] +779 DnsLookup { source: StaggeredError<DnsError> }, +780 #[snafu(display("Creating HTTP client failed"))] +781 CreateReqwestClient { source: reqwest::Error }, +782 #[snafu(display("HTTP request failed"))] +783 HttpRequest { source: reqwest::Error }, +784 #[snafu(display("Error response from server {status}: {:?}", status.canonical_reason()))] +785 InvalidResponse { status: StatusCode }, 786} 787 -788#[derive(Debug, Snafu)] -789#[snafu(module)] -790#[non_exhaustive] -791pub enum MeasureHttpsLatencyError { -792 #[snafu(transparent)] -793 InvalidUrl { source: url::ParseError }, -794 #[cfg(not(wasm_browser))] -795 #[snafu(transparent)] -796 DnsLookup { source: StaggeredError<DnsError> }, -797 #[snafu(display("Creating HTTP client failed"))] -798 CreateReqwestClient { source: reqwest::Error }, -799 #[snafu(display("HTTP request failed"))] -800 HttpRequest { source: reqwest::Error }, -801 #[snafu(display("Error response from server {status}: {:?}", status.canonical_reason()))] -802 InvalidResponse { status: StatusCode }, -803} -804 -805/// Executes an HTTPS probe. -806/// -807/// If `certs` is provided they will be added to the trusted root certificates, allowing the -808/// use of self-signed certificates for servers. Currently this is used for testing. -809#[allow(clippy::unused_async)] -810async fn run_https_probe( -811 #[cfg(not(wasm_browser))] dns_resolver: &DnsResolver, -812 relay_node: RelayUrl, -813 #[cfg(any(test, feature = "test-utils"))] insecure_skip_relay_cert_verify: bool, -814) -> Result<HttpsProbeReport, MeasureHttpsLatencyError> { -815 trace!("HTTPS probe start"); -816 let url = relay_node.join(RELAY_PROBE_PATH)?; -817 -818 // This should also use same connection establishment as relay client itself, which -819 // needs to be more configurable so users can do more crazy things: -820 // https://github.com/n0-computer/iroh/issues/2901 -821 let mut builder = reqwest::ClientBuilder::new(); -822 -823 #[cfg(not(wasm_browser))] -824 { -825 builder = builder.redirect(reqwest::redirect::Policy::none()); -826 } -827 -828 #[cfg(not(wasm_browser))] -829 if let Some(Host::Domain(domain)) = url.host() { -830 // Use our own resolver rather than getaddrinfo -831 // -832 // Be careful, a non-zero port will override the port in the URI. -833 // -834 // The relay Client uses `.lookup_ipv4_ipv6` to connect, so use the same function -835 // but staggered for reliability. Ideally this tries to resolve **both** IPv4 and -836 // IPv6 though. But our resolver does not have a function for that yet. -837 let addrs: Vec<_> = dns_resolver -838 .lookup_ipv4_ipv6_staggered(domain, DNS_TIMEOUT, DNS_STAGGERING_MS) -839 .await? -840 .map(|ipaddr| SocketAddr::new(ipaddr, 0)) -841 .collect(); -842 trace!(?addrs, "resolved addrs"); -843 builder = builder.resolve_to_addrs(domain, &addrs); -844 } -845 -846 #[cfg(all(not(wasm_browser), any(test, feature = "test-utils")))] -847 let builder = builder.danger_accept_invalid_certs(insecure_skip_relay_cert_verify); -848 -849 let client = builder -850 .build() -851 .context(measure_https_latency_error::CreateReqwestClientSnafu)?; -852 -853 let start = Instant::now(); -854 let response = client -855 .request(reqwest::Method::GET, url) -856 .send() -857 .await -858 .context(measure_https_latency_error::HttpRequestSnafu)?; -859 let latency = start.elapsed(); -860 if response.status().is_success() { -861 // Drain the response body to be nice to the server, up to a limit. -862 const MAX_BODY_SIZE: usize = 8 << 10; // 8 KiB -863 let mut body_size = 0; -864 let mut stream = response.bytes_stream(); -865 // ignore failing frames -866 while let Some(Ok(chunk)) = stream.next().await { -867 body_size += chunk.len(); -868 if body_size >= MAX_BODY_SIZE { -869 break; -870 } -871 } -872 -873 Ok(HttpsProbeReport { -874 node: relay_node, -875 latency, -876 }) -877 } else { -878 Err(measure_https_latency_error::InvalidResponseSnafu { -879 status: response.status(), -880 } -881 .build()) -882 } -883} +788/// Executes an HTTPS probe. +789/// +790/// If `certs` is provided they will be added to the trusted root certificates, allowing the +791/// use of self-signed certificates for servers. Currently this is used for testing. +792#[allow(clippy::unused_async)] +793async fn run_https_probe( +794 #[cfg(not(wasm_browser))] dns_resolver: &DnsResolver, +795 relay_node: RelayUrl, +796 #[cfg(any(test, feature = "test-utils"))] insecure_skip_relay_cert_verify: bool, +797) -> Result<HttpsProbeReport, MeasureHttpsLatencyError> { +798 trace!("HTTPS probe start"); +799 let url = relay_node.join(RELAY_PROBE_PATH)?; +800 +801 // This should also use same connection establishment as relay client itself, which +802 // needs to be more configurable so users can do more crazy things: +803 // https://github.com/n0-computer/iroh/issues/2901 +804 let mut builder = reqwest::ClientBuilder::new(); +805 +806 #[cfg(not(wasm_browser))] +807 { +808 builder = builder.redirect(reqwest::redirect::Policy::none()); +809 } +810 +811 #[cfg(not(wasm_browser))] +812 if let Some(Host::Domain(domain)) = url.host() { +813 // Use our own resolver rather than getaddrinfo +814 // +815 // Be careful, a non-zero port will override the port in the URI. +816 // +817 // The relay Client uses `.lookup_ipv4_ipv6` to connect, so use the same function +818 // but staggered for reliability. Ideally this tries to resolve **both** IPv4 and +819 // IPv6 though. But our resolver does not have a function for that yet. +820 let addrs: Vec<_> = dns_resolver +821 .lookup_ipv4_ipv6_staggered(domain, DNS_TIMEOUT, DNS_STAGGERING_MS) +822 .await? +823 .map(|ipaddr| SocketAddr::new(ipaddr, 0)) +824 .collect(); +825 trace!(?addrs, "resolved addrs"); +826 builder = builder.resolve_to_addrs(domain, &addrs); +827 } +828 +829 #[cfg(all(not(wasm_browser), any(test, feature = "test-utils")))] +830 let builder = builder.danger_accept_invalid_certs(insecure_skip_relay_cert_verify); +831 +832 let client = builder +833 .build() +834 .context(measure_https_latency_error::CreateReqwestClientSnafu)?; +835 +836 let start = Instant::now(); +837 let response = client +838 .request(reqwest::Method::GET, url) +839 .send() +840 .await +841 .context(measure_https_latency_error::HttpRequestSnafu)?; +842 let latency = start.elapsed(); +843 if response.status().is_success() { +844 // Drain the response body to be nice to the server, up to a limit. +845 const MAX_BODY_SIZE: usize = 8 << 10; // 8 KiB +846 let mut body_size = 0; +847 let mut stream = response.bytes_stream(); +848 // ignore failing frames +849 while let Some(Ok(chunk)) = stream.next().await { +850 body_size += chunk.len(); +851 if body_size >= MAX_BODY_SIZE { +852 break; +853 } +854 } +855 +856 Ok(HttpsProbeReport { +857 node: relay_node, +858 latency, +859 }) +860 } else { +861 Err(measure_https_latency_error::InvalidResponseSnafu { +862 status: response.status(), +863 } +864 .build()) +865 } +866} +867 +868#[cfg(test)] +869mod tests { +870 use std::net::Ipv4Addr; +871 +872 use iroh_relay::dns::DnsResolver; +873 use n0_snafu::{Result, ResultExt}; +874 use tracing_test::traced_test; +875 +876 use super::{super::test_utils, *}; +877 +878 #[tokio::test] +879 async fn test_measure_https_latency() -> Result { +880 let (_server, relay) = test_utils::relay().await; +881 let dns_resolver = DnsResolver::new(); +882 tracing::info!(relay_url = ?relay.url , "RELAY_URL"); +883 let report = run_https_probe(&dns_resolver, relay.url, true).await?; 884 -885#[cfg(test)] -886mod tests { -887 use std::net::Ipv4Addr; -888 -889 use iroh_relay::dns::DnsResolver; -890 use n0_snafu::{Result, ResultExt}; -891 use tracing_test::traced_test; -892 -893 use super::{super::test_utils, *}; -894 -895 #[tokio::test] -896 async fn test_measure_https_latency() -> Result { -897 let (_server, relay) = test_utils::relay().await; -898 let dns_resolver = DnsResolver::new(); -899 tracing::info!(relay_url = ?relay.url , "RELAY_URL"); -900 let report = run_https_probe(&dns_resolver, relay.url, true).await?; +885 assert!(report.latency > Duration::ZERO); +886 +887 Ok(()) +888 } +889 +890 #[tokio::test] +891 #[traced_test] +892 async fn test_qad_probe_v4() -> Result { +893 let (server, relay) = test_utils::relay().await; +894 let relay = Arc::new(relay); +895 let client_config = iroh_relay::client::make_dangerous_client_config(); +896 let ep = quinn::Endpoint::client(SocketAddr::new(Ipv4Addr::LOCALHOST.into(), 0)).e()?; +897 let client_addr = ep.local_addr().e()?; +898 +899 let quic_client = iroh_relay::quic::QuicClient::new(ep.clone(), client_config); +900 let dns_resolver = DnsResolver::default(); 901 -902 assert!(report.latency > Duration::ZERO); -903 -904 Ok(()) -905 } -906 -907 #[tokio::test] -908 #[traced_test] -909 async fn test_qad_probe_v4() -> Result { -910 let (server, relay) = test_utils::relay().await; -911 let relay = Arc::new(relay); -912 let client_config = iroh_relay::client::make_dangerous_client_config(); -913 let ep = quinn::Endpoint::client(SocketAddr::new(Ipv4Addr::LOCALHOST.into(), 0)).e()?; -914 let client_addr = ep.local_addr().e()?; -915 -916 let quic_client = iroh_relay::quic::QuicClient::new(ep.clone(), client_config); -917 let dns_resolver = DnsResolver::default(); -918 -919 let (report, conn) = super::super::run_probe_v4(None, relay, quic_client, dns_resolver) -920 .await -921 .unwrap(); -922 -923 assert_eq!(report.addr, client_addr); -924 drop(conn); -925 ep.wait_idle().await; -926 server.shutdown().await?; -927 Ok(()) -928 } -929} \ No newline at end of file +902 let (report, conn) = super::super::run_probe_v4(None, relay, quic_client, dns_resolver) +903 .await +904 .unwrap(); +905 +906 assert_eq!(report.addr, client_addr); +907 drop(conn); +908 ep.wait_idle().await; +909 server.shutdown().await?; +910 Ok(()) +911 } +912} \ No newline at end of file diff --git a/pr/3314/docs/src/iroh_relay/quic.rs.html b/pr/3314/docs/src/iroh_relay/quic.rs.html index 19020de688..8445a15db2 100644 --- a/pr/3314/docs/src/iroh_relay/quic.rs.html +++ b/pr/3314/docs/src/iroh_relay/quic.rs.html @@ -282,7 +282,7 @@ 282 transport.receive_observed_address_reports(true); 283 284 // keep it alive -285 transport.keep_alive_interval(Some(Duration::from_secs(15))); +285 transport.keep_alive_interval(Some(Duration::from_secs(25))); 286 transport.max_idle_timeout(Some( 287 Duration::from_secs(35).try_into().expect("known value"), 288 ));