From c8a547bc3bd420639bac5adeb31b7a2fcfbc7963 Mon Sep 17 00:00:00 2001 From: dignifiedquire Date: Wed, 23 Jul 2025 09:46:05 +0000 Subject: [PATCH] deploy: 596bcf37c0df064e62ce02a3d25eef12f016fad2 --- .../iroh/endpoint/enum.DirectAddrType.html | 12 +- .../docs/iroh/endpoint/struct.DirectAddr.html | 12 +- pr/3381/docs/src/iroh/magicsock.rs.html | 6020 +++++++++-------- 3 files changed, 3029 insertions(+), 3015 deletions(-) diff --git a/pr/3381/docs/iroh/endpoint/enum.DirectAddrType.html b/pr/3381/docs/iroh/endpoint/enum.DirectAddrType.html index a136eefd4a..3d13d329d6 100644 --- a/pr/3381/docs/iroh/endpoint/enum.DirectAddrType.html +++ b/pr/3381/docs/iroh/endpoint/enum.DirectAddrType.html @@ -1,4 +1,4 @@ -DirectAddrType in iroh::endpoint - Rust

Enum DirectAddrType

Source
pub enum DirectAddrType {
+DirectAddrType in iroh::endpoint - Rust

Enum DirectAddrType

Source
pub enum DirectAddrType {
     Unknown,
     Local,
     Qad,
@@ -20,16 +20,16 @@ get a publicly routable direct address.

It is possible to configure iroh to bound to a specific port and independently configure the router to forward this port to the iroh node. This indicates a situation like this, which still uses QAD to discover the public address.

-

Trait Implementations§

Source§

impl Clone for DirectAddrType

Source§

fn clone(&self) -> DirectAddrType

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 DirectAddrType

Source§

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

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

impl Display for DirectAddrType

Source§

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

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

impl Hash for DirectAddrType

Source§

fn hash<__H: Hasher>(&self, state: &mut __H)

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where +

Trait Implementations§

Source§

impl Clone for DirectAddrType

Source§

fn clone(&self) -> DirectAddrType

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 DirectAddrType

Source§

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

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

impl Display for DirectAddrType

Source§

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

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

impl Hash for DirectAddrType

Source§

fn hash<__H: Hasher>(&self, state: &mut __H)

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, - Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl Ord for DirectAddrType

Source§

fn cmp(&self, other: &DirectAddrType) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 · Source§

fn max(self, other: Self) -> Self
where + Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl Ord for DirectAddrType

Source§

fn cmp(&self, other: &DirectAddrType) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 · Source§

fn max(self, other: Self) -> Self
where Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0 · Source§

fn min(self, other: Self) -> Self
where Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0 · Source§

fn clamp(self, min: Self, max: Self) -> Self
where - Self: Sized,

Restrict a value to a certain interval. Read more
Source§

impl PartialEq for DirectAddrType

Source§

fn eq(&self, other: &DirectAddrType) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, -and should not be overridden without very good reason.
Source§

impl PartialOrd for DirectAddrType

Source§

fn partial_cmp(&self, other: &DirectAddrType) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 · Source§

fn lt(&self, other: &Rhs) -> bool

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 · Source§

fn le(&self, other: &Rhs) -> bool

Tests less than or equal to (for self and other) and is used by the + Self: Sized,
Restrict a value to a certain interval. Read more
Source§

impl PartialEq for DirectAddrType

Source§

fn eq(&self, other: &DirectAddrType) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, +and should not be overridden without very good reason.
Source§

impl PartialOrd for DirectAddrType

Source§

fn partial_cmp(&self, other: &DirectAddrType) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 · Source§

fn lt(&self, other: &Rhs) -> bool

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 · Source§

fn le(&self, other: &Rhs) -> bool

Tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 · Source§

fn gt(&self, other: &Rhs) -> bool

Tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 · Source§

fn ge(&self, other: &Rhs) -> bool

Tests greater than or equal to (for self and other) and is used by -the >= operator. Read more
Source§

impl Copy for DirectAddrType

Source§

impl Eq for DirectAddrType

Source§

impl StructuralPartialEq for DirectAddrType

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where +the >= operator. Read more

Source§

impl Copy for DirectAddrType

Source§

impl Eq for DirectAddrType

Source§

impl StructuralPartialEq for DirectAddrType

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/3381/docs/iroh/endpoint/struct.DirectAddr.html b/pr/3381/docs/iroh/endpoint/struct.DirectAddr.html index 162b86ca74..9dd689c716 100644 --- a/pr/3381/docs/iroh/endpoint/struct.DirectAddr.html +++ b/pr/3381/docs/iroh/endpoint/struct.DirectAddr.html @@ -1,4 +1,4 @@ -DirectAddr in iroh::endpoint - Rust

Struct DirectAddr

Source
pub struct DirectAddr {
+DirectAddr in iroh::endpoint - Rust

Struct DirectAddr

Source
pub struct DirectAddr {
     pub addr: SocketAddr,
     pub typ: DirectAddrType,
 }
Expand description

A direct address on which an iroh-node might be contactable.

@@ -7,16 +7,16 @@ contacted. These can come from various sources depending on the network topolog iroh node, see DirectAddrType for the several kinds of sources.

Fields§

§addr: SocketAddr

The address.

§typ: DirectAddrType

The origin of this direct address.

-

Trait Implementations§

Source§

impl Clone for DirectAddr

Source§

fn clone(&self) -> DirectAddr

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 DirectAddr

Source§

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

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

impl Hash for DirectAddr

Source§

fn hash<__H: Hasher>(&self, state: &mut __H)

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where +

Trait Implementations§

Source§

impl Clone for DirectAddr

Source§

fn clone(&self) -> DirectAddr

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 DirectAddr

Source§

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

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

impl Hash for DirectAddr

Source§

fn hash<__H: Hasher>(&self, state: &mut __H)

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, - Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl Ord for DirectAddr

Source§

fn cmp(&self, other: &DirectAddr) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 · Source§

fn max(self, other: Self) -> Self
where + Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl Ord for DirectAddr

Source§

fn cmp(&self, other: &DirectAddr) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 · Source§

fn max(self, other: Self) -> Self
where Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0 · Source§

fn min(self, other: Self) -> Self
where Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0 · Source§

fn clamp(self, min: Self, max: Self) -> Self
where - Self: Sized,

Restrict a value to a certain interval. Read more
Source§

impl PartialEq for DirectAddr

Source§

fn eq(&self, other: &DirectAddr) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, -and should not be overridden without very good reason.
Source§

impl PartialOrd for DirectAddr

Source§

fn partial_cmp(&self, other: &DirectAddr) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 · Source§

fn lt(&self, other: &Rhs) -> bool

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 · Source§

fn le(&self, other: &Rhs) -> bool

Tests less than or equal to (for self and other) and is used by the + Self: Sized,

Restrict a value to a certain interval. Read more
Source§

impl PartialEq for DirectAddr

Source§

fn eq(&self, other: &DirectAddr) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, +and should not be overridden without very good reason.
Source§

impl PartialOrd for DirectAddr

Source§

fn partial_cmp(&self, other: &DirectAddr) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 · Source§

fn lt(&self, other: &Rhs) -> bool

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 · Source§

fn le(&self, other: &Rhs) -> bool

Tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 · Source§

fn gt(&self, other: &Rhs) -> bool

Tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 · Source§

fn ge(&self, other: &Rhs) -> bool

Tests greater than or equal to (for self and other) and is used by -the >= operator. Read more
Source§

impl Eq for DirectAddr

Source§

impl StructuralPartialEq for DirectAddr

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where +the >= operator. Read more

Source§

impl Eq for DirectAddr

Source§

impl StructuralPartialEq for DirectAddr

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/3381/docs/src/iroh/magicsock.rs.html b/pr/3381/docs/src/iroh/magicsock.rs.html index 0472dd9ea8..d7c33c1b6d 100644 --- a/pr/3381/docs/src/iroh/magicsock.rs.html +++ b/pr/3381/docs/src/iroh/magicsock.rs.html @@ -292,3056 +292,3070 @@ 292 } 293 294 pub(crate) fn register_connection(&self, remote: NodeId, conn: &quinn::Connection) { -295 let weak_handle = conn.weak_handle(); -296 self.connection_map.insert(remote, weak_handle); -297 -298 // TODO: track task -299 // TODO: find a good home for this -300 let mut path_events = conn.path_events(); -301 let _task = task::spawn(async move { -302 loop { -303 match path_events.recv().await { -304 Ok(event) => { -305 info!(remote = %remote, "path event: {:?}", event); -306 } -307 Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => { -308 warn!("lagged path events"); -309 } -310 Err(tokio::sync::broadcast::error::RecvError::Closed) => break, -311 } -312 } -313 }); -314 -315 // open additional paths -316 if let Some(addr) = self.node_map.get_current_addr(remote) { -317 self.add_paths(addr); -318 } -319 } -320 -321 #[cfg(not(wasm_browser))] -322 fn ip_bind_addrs(&self) -> &[SocketAddr] { -323 &self.ip_bind_addrs -324 } -325 -326 fn ip_local_addrs(&self) -> impl Iterator<Item = SocketAddr> { -327 self.local_addr() -328 .into_iter() -329 .filter_map(|addr| addr.into_socket_addr()) -330 } -331 -332 /// Returns `true` if we have at least one candidate address where we can send packets to. -333 pub(crate) fn has_send_address(&self, node_key: PublicKey) -> bool { -334 self.remote_info(node_key) -335 .map(|info| info.has_send_address()) -336 .unwrap_or(false) -337 } -338 -339 /// Return the [`RemoteInfo`]s of all nodes in the node map. -340 pub(crate) fn list_remote_infos(&self) -> Vec<RemoteInfo> { -341 self.node_map.list_remote_infos(Instant::now()) -342 } -343 -344 /// Return the [`RemoteInfo`] for a single node in the node map. -345 pub(crate) fn remote_info(&self, node_id: NodeId) -> Option<RemoteInfo> { -346 self.node_map.remote_info(node_id) -347 } -348 -349 /// Returns a [`Watcher`] for this socket's direct addresses. -350 /// -351 /// The [`MagicSock`] continuously monitors the direct addresses, the network addresses -352 /// it might be able to be contacted on, for changes. Whenever changes are detected -353 /// this [`Watcher`] will yield a new list of addresses. +295 debug!(%remote, "register connection"); +296 let weak_handle = conn.weak_handle(); +297 self.connection_map.insert(remote, weak_handle); +298 +299 // TODO: track task +300 // TODO: find a good home for this +301 let mut path_events = conn.path_events(); +302 let _task = task::spawn( +303 async move { +304 loop { +305 match path_events.recv().await { +306 Ok(event) => { +307 info!(remote = %remote, "path event: {:?}", event); +308 } +309 Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => { +310 warn!("lagged path events"); +311 } +312 Err(tokio::sync::broadcast::error::RecvError::Closed) => break, +313 } +314 } +315 } +316 .instrument(info_span!("path events", %remote)), +317 ); +318 +319 // open additional paths +320 if let Some(addr) = self.node_map.get_current_addr(remote) { +321 self.add_paths(addr); +322 } +323 } +324 +325 #[cfg(not(wasm_browser))] +326 fn ip_bind_addrs(&self) -> &[SocketAddr] { +327 &self.ip_bind_addrs +328 } +329 +330 fn ip_local_addrs(&self) -> impl Iterator<Item = SocketAddr> { +331 self.local_addr() +332 .into_iter() +333 .filter_map(|addr| addr.into_socket_addr()) +334 } +335 +336 /// Returns `true` if we have at least one candidate address where we can send packets to. +337 pub(crate) fn has_send_address(&self, node_key: PublicKey) -> bool { +338 self.remote_info(node_key) +339 .map(|info| info.has_send_address()) +340 .unwrap_or(false) +341 } +342 +343 /// Return the [`RemoteInfo`]s of all nodes in the node map. +344 pub(crate) fn list_remote_infos(&self) -> Vec<RemoteInfo> { +345 self.node_map.list_remote_infos(Instant::now()) +346 } +347 +348 /// Return the [`RemoteInfo`] for a single node in the node map. +349 pub(crate) fn remote_info(&self, node_id: NodeId) -> Option<RemoteInfo> { +350 self.node_map.remote_info(node_id) +351 } +352 +353 /// Returns a [`Watcher`] for this socket's direct addresses. 354 /// -355 /// Upon the first creation on the [`MagicSock`] it may not yet have completed a first -356 /// direct addresses discovery, in this case the current item in this [`Watcher`] will be -357 /// [`None`]. Once the first set of direct addresses are discovered the [`Watcher`] will -358 /// store [`Some`] set of addresses. -359 /// -360 /// To get the current direct addresses, use [`Watcher::initialized`]. -361 /// -362 /// [`Watcher`]: n0_watcher::Watcher -363 /// [`Watcher::initialized`]: n0_watcher::Watcher::initialized -364 pub(crate) fn direct_addresses(&self) -> n0_watcher::Direct<Option<BTreeSet<DirectAddr>>> { -365 self.direct_addrs.addrs.watch() -366 } -367 -368 /// Returns a [`Watcher`] for this socket's net-report. -369 /// -370 /// The [`MagicSock`] continuously monitors the network conditions for changes. -371 /// Whenever changes are detected this [`Watcher`] will yield a new report. -372 /// -373 /// Upon the first creation on the [`MagicSock`] it may not yet have completed -374 /// a first net-report. In this case, the current item in this [`Watcher`] will -375 /// be [`None`]. Once the first report has been run, the [`Watcher`] will -376 /// store [`Some`] report. -377 /// -378 /// To get the current `net-report`, use [`Watcher::initialized`]. -379 /// -380 /// [`Watcher`]: n0_watcher::Watcher -381 /// [`Watcher::initialized`]: n0_watcher::Watcher::initialized -382 pub(crate) fn net_report(&self) -> impl Watcher<Value = Option<Report>> { -383 self.net_report -384 .watch() -385 .map(|(r, _)| r) -386 .expect("disconnected") -387 } -388 -389 /// Watch for changes to the home relay. -390 /// -391 /// Note that this can be used to wait for the initial home relay to be known using -392 /// [`Watcher::initialized`]. -393 pub(crate) fn home_relay(&self) -> impl Watcher<Value = Vec<RelayUrl>> { -394 let res = self.local_addrs_watch.clone().map(|addrs| { -395 addrs -396 .into_iter() -397 .filter_map(|addr| { -398 if let transports::Addr::Relay(url, _) = addr { -399 Some(url) -400 } else { -401 None -402 } -403 }) -404 .collect() -405 }); -406 res.expect("disconnected") -407 } -408 -409 /// Returns a [`n0_watcher::Direct`] that reports the [`ConnectionType`] we have to the -410 /// given `node_id`. -411 /// -412 /// This gets us a copy of the [`n0_watcher::Direct`] for the [`Watchable`] with a [`ConnectionType`] -413 /// that the `NodeMap` stores for each `node_id`'s endpoint. -414 /// -415 /// # Errors -416 /// -417 /// Will return `None` if there is no address information known about the -418 /// given `node_id`. -419 pub(crate) fn conn_type(&self, node_id: NodeId) -> Option<n0_watcher::Direct<ConnectionType>> { -420 self.node_map.conn_type(node_id) -421 } -422 -423 /// Returns the socket address which can be used by the QUIC layer to dial this node. -424 pub(crate) fn get_mapping_addr(&self, node_id: NodeId) -> Option<NodeIdMappedAddr> { -425 self.node_map.get_quic_mapped_addr_for_node_key(node_id) -426 } -427 -428 pub(crate) fn get_direct_addrs(&self, node_id: NodeId) -> Vec<SocketAddr> { -429 self.node_map.get_direct_addrs(node_id) +355 /// The [`MagicSock`] continuously monitors the direct addresses, the network addresses +356 /// it might be able to be contacted on, for changes. Whenever changes are detected +357 /// this [`Watcher`] will yield a new list of addresses. +358 /// +359 /// Upon the first creation on the [`MagicSock`] it may not yet have completed a first +360 /// direct addresses discovery, in this case the current item in this [`Watcher`] will be +361 /// [`None`]. Once the first set of direct addresses are discovered the [`Watcher`] will +362 /// store [`Some`] set of addresses. +363 /// +364 /// To get the current direct addresses, use [`Watcher::initialized`]. +365 /// +366 /// [`Watcher`]: n0_watcher::Watcher +367 /// [`Watcher::initialized`]: n0_watcher::Watcher::initialized +368 pub(crate) fn direct_addresses(&self) -> n0_watcher::Direct<Option<BTreeSet<DirectAddr>>> { +369 self.direct_addrs.addrs.watch() +370 } +371 +372 /// Returns a [`Watcher`] for this socket's net-report. +373 /// +374 /// The [`MagicSock`] continuously monitors the network conditions for changes. +375 /// Whenever changes are detected this [`Watcher`] will yield a new report. +376 /// +377 /// Upon the first creation on the [`MagicSock`] it may not yet have completed +378 /// a first net-report. In this case, the current item in this [`Watcher`] will +379 /// be [`None`]. Once the first report has been run, the [`Watcher`] will +380 /// store [`Some`] report. +381 /// +382 /// To get the current `net-report`, use [`Watcher::initialized`]. +383 /// +384 /// [`Watcher`]: n0_watcher::Watcher +385 /// [`Watcher::initialized`]: n0_watcher::Watcher::initialized +386 pub(crate) fn net_report(&self) -> impl Watcher<Value = Option<Report>> { +387 self.net_report +388 .watch() +389 .map(|(r, _)| r) +390 .expect("disconnected") +391 } +392 +393 /// Watch for changes to the home relay. +394 /// +395 /// Note that this can be used to wait for the initial home relay to be known using +396 /// [`Watcher::initialized`]. +397 pub(crate) fn home_relay(&self) -> impl Watcher<Value = Vec<RelayUrl>> { +398 let res = self.local_addrs_watch.clone().map(|addrs| { +399 addrs +400 .into_iter() +401 .filter_map(|addr| { +402 if let transports::Addr::Relay(url, _) = addr { +403 Some(url) +404 } else { +405 None +406 } +407 }) +408 .collect() +409 }); +410 res.expect("disconnected") +411 } +412 +413 /// Returns a [`n0_watcher::Direct`] that reports the [`ConnectionType`] we have to the +414 /// given `node_id`. +415 /// +416 /// This gets us a copy of the [`n0_watcher::Direct`] for the [`Watchable`] with a [`ConnectionType`] +417 /// that the `NodeMap` stores for each `node_id`'s endpoint. +418 /// +419 /// # Errors +420 /// +421 /// Will return `None` if there is no address information known about the +422 /// given `node_id`. +423 pub(crate) fn conn_type(&self, node_id: NodeId) -> Option<n0_watcher::Direct<ConnectionType>> { +424 self.node_map.conn_type(node_id) +425 } +426 +427 /// Returns the socket address which can be used by the QUIC layer to dial this node. +428 pub(crate) fn get_mapping_addr(&self, node_id: NodeId) -> Option<NodeIdMappedAddr> { +429 self.node_map.get_quic_mapped_addr_for_node_key(node_id) 430 } 431 -432 /// Add addresses for a node to the magic socket's addresbook. -433 #[instrument(skip_all)] -434 pub fn add_node_addr( -435 &self, -436 mut addr: NodeAddr, -437 source: node_map::Source, -438 ) -> Result<(), AddNodeAddrError> { -439 let mut pruned: usize = 0; -440 for my_addr in self.direct_addrs.sockaddrs() { -441 if addr.direct_addresses.remove(&my_addr) { -442 warn!( node_id=addr.node_id.fmt_short(), %my_addr, %source, "not adding our addr for node"); -443 pruned += 1; -444 } -445 } -446 if !addr.is_empty() { -447 // Add addr to the internal NodeMap -448 self.node_map -449 .add_node_addr(addr.clone(), source, &self.metrics.magicsock); -450 -451 if let Some(url) = addr.relay_url() { -452 self.relay_mapped_addrs -453 .get_or_register(url.clone(), addr.node_id); -454 } -455 -456 // Add paths to the existing connections -457 self.add_paths(addr); -458 -459 Ok(()) -460 } else if pruned != 0 { -461 Err(EmptyPrunedSnafu { pruned }.build()) -462 } else { -463 Err(EmptySnafu.build()) -464 } -465 } -466 -467 /// Adds all available addresses in the given `addr` as paths -468 fn add_paths(&self, addr: NodeAddr) { -469 let mut map = self.connection_map.map.lock().expect("poisoned"); -470 let mut to_delete = Vec::new(); -471 if let Some(conns) = map.get_mut(&addr.node_id) { -472 for (i, conn) in conns.into_iter().enumerate() { -473 if let Some(conn) = conn.upgrade() { -474 for addr in addr.direct_addresses() { -475 let conn = conn.clone(); -476 let addr = *addr; -477 task::spawn(async move { -478 match conn -479 .open_path_ensure(addr, quinn_proto::PathStatus::Available) -480 .await -481 { -482 Ok(path) => { -483 path.set_max_idle_timeout(Some( -484 ENDPOINTS_FRESH_ENOUGH_DURATION, -485 )) -486 .ok(); -487 path.set_keep_alive_interval(Some(HEARTBEAT_INTERVAL)).ok(); -488 } -489 Err(err) => { -490 warn!("failed to open path {:?}", err); -491 } -492 } -493 }); -494 } -495 // Insert the relay addr -496 if let Some(addr) = self.get_mapping_addr(addr.node_id) { -497 let conn = conn.clone(); -498 let addr = addr.private_socket_addr(); -499 task::spawn(async move { -500 match conn -501 .open_path_ensure(addr, quinn_proto::PathStatus::Backup) -502 .await -503 { -504 Ok(path) => { -505 // Keep the relay path open -506 path.set_max_idle_timeout(None).ok(); -507 path.set_keep_alive_interval(None).ok(); -508 } -509 Err(err) => { -510 warn!("failed to open path {:?}", err); -511 } -512 } -513 }); -514 } -515 } else { -516 to_delete.push(i); -517 } -518 } -519 // cleanup dead connections -520 let mut i = 0; -521 conns.retain(|_| { -522 let remove = to_delete.contains(&i); -523 i += 1; -524 -525 !remove -526 }); -527 } -528 } -529 -530 /// Stores a new set of direct addresses. -531 /// -532 /// If the direct addresses have changed from the previous set, they are published to -533 /// discovery. -534 pub(super) fn store_direct_addresses(&self, addrs: BTreeSet<DirectAddr>) { -535 let updated = self.direct_addrs.update(addrs); -536 if updated { -537 self.node_map -538 .on_direct_addr_discovered(self.direct_addrs.sockaddrs()); -539 self.publish_my_addr(); -540 } -541 } -542 -543 /// Get a reference to the DNS resolver used in this [`MagicSock`]. -544 #[cfg(not(wasm_browser))] -545 pub(crate) fn dns_resolver(&self) -> &DnsResolver { -546 &self.dns_resolver -547 } -548 -549 /// Reference to optional discovery service -550 pub(crate) fn discovery(&self) -> Option<&dyn Discovery> { -551 self.discovery.as_ref().map(Box::as_ref) -552 } -553 -554 /// Updates the user-defined discovery data for this node. -555 pub(crate) fn set_user_data_for_discovery(&self, user_data: Option<UserData>) { -556 let mut guard = self.discovery_user_data.write().expect("lock poisened"); -557 if *guard != user_data { -558 *guard = user_data; -559 drop(guard); -560 self.publish_my_addr(); -561 } -562 } -563 -564 /// Call to notify the system of potential network changes. -565 pub(crate) async fn network_change(&self) { -566 self.actor_sender -567 .send(ActorMessage::NetworkChange) -568 .await -569 .ok(); -570 } -571 -572 /// Returns a reference to the subscribers channel for discovery events. -573 pub(crate) fn discovery_subscribers(&self) -> &DiscoverySubscribers { -574 &self.discovery_subscribers -575 } -576 -577 #[cfg(test)] -578 async fn force_network_change(&self, is_major: bool) { -579 self.actor_sender -580 .send(ActorMessage::ForceNetworkChange(is_major)) -581 .await -582 .ok(); -583 } -584 -585 #[cfg_attr(windows, allow(dead_code))] -586 fn normalized_local_addr(&self) -> io::Result<SocketAddr> { -587 let addrs = self.local_addrs_watch.get().expect("disconnected"); +432 pub(crate) fn get_direct_addrs(&self, node_id: NodeId) -> Vec<SocketAddr> { +433 self.node_map.get_direct_addrs(node_id) +434 } +435 +436 /// Add addresses for a node to the magic socket's addresbook. +437 #[instrument(skip_all)] +438 pub fn add_node_addr( +439 &self, +440 mut addr: NodeAddr, +441 source: node_map::Source, +442 ) -> Result<(), AddNodeAddrError> { +443 let mut pruned: usize = 0; +444 for my_addr in self.direct_addrs.sockaddrs() { +445 if addr.direct_addresses.remove(&my_addr) { +446 warn!( node_id=addr.node_id.fmt_short(), %my_addr, %source, "not adding our addr for node"); +447 pruned += 1; +448 } +449 } +450 if !addr.is_empty() { +451 // Add addr to the internal NodeMap +452 self.node_map +453 .add_node_addr(addr.clone(), source, &self.metrics.magicsock); +454 +455 if let Some(url) = addr.relay_url() { +456 self.relay_mapped_addrs +457 .get_or_register(url.clone(), addr.node_id); +458 } +459 +460 // Add paths to the existing connections +461 self.add_paths(addr); +462 +463 Ok(()) +464 } else if pruned != 0 { +465 Err(EmptyPrunedSnafu { pruned }.build()) +466 } else { +467 Err(EmptySnafu.build()) +468 } +469 } +470 +471 /// Adds all available addresses in the given `addr` as paths +472 fn add_paths(&self, addr: NodeAddr) { +473 let mut map = self.connection_map.map.lock().expect("poisoned"); +474 let mut to_delete = Vec::new(); +475 if let Some(conns) = map.get_mut(&addr.node_id) { +476 for (i, conn) in conns.into_iter().enumerate() { +477 if let Some(conn) = conn.upgrade() { +478 for addr in addr.direct_addresses() { +479 let conn = conn.clone(); +480 let addr = *addr; +481 task::spawn( +482 async move { +483 debug!(%addr, "open path IP"); +484 match conn +485 .open_path_ensure(addr, quinn_proto::PathStatus::Available) +486 .await +487 { +488 Ok(path) => { +489 path.set_max_idle_timeout(Some( +490 ENDPOINTS_FRESH_ENOUGH_DURATION, +491 )) +492 .ok(); +493 path.set_keep_alive_interval(Some(HEARTBEAT_INTERVAL)).ok(); +494 } +495 Err(err) => { +496 warn!("failed to open path {:?}", err); +497 } +498 } +499 } +500 .instrument(info_span!("open path IP")), +501 ); +502 } +503 // Insert the relay addr +504 if let Some(addr) = self.get_mapping_addr(addr.node_id) { +505 let conn = conn.clone(); +506 let addr = addr.private_socket_addr(); +507 task::spawn( +508 async move { +509 debug!(%addr, "open path relay"); +510 match conn +511 .open_path_ensure(addr, quinn_proto::PathStatus::Backup) +512 .await +513 { +514 Ok(path) => { +515 // Keep the relay path open +516 path.set_max_idle_timeout(None).ok(); +517 path.set_keep_alive_interval(None).ok(); +518 } +519 Err(err) => { +520 warn!("failed to open path {:?}", err); +521 } +522 } +523 } +524 .instrument(info_span!("open path relay")), +525 ); +526 } +527 } else { +528 to_delete.push(i); +529 } +530 } +531 // cleanup dead connections +532 let mut i = 0; +533 conns.retain(|_| { +534 let remove = to_delete.contains(&i); +535 i += 1; +536 +537 !remove +538 }); +539 } +540 } +541 +542 /// Stores a new set of direct addresses. +543 /// +544 /// If the direct addresses have changed from the previous set, they are published to +545 /// discovery. +546 pub(super) fn store_direct_addresses(&self, addrs: BTreeSet<DirectAddr>) { +547 let updated = self.direct_addrs.update(addrs); +548 if updated { +549 self.node_map +550 .on_direct_addr_discovered(self.direct_addrs.sockaddrs()); +551 self.publish_my_addr(); +552 } +553 } +554 +555 /// Get a reference to the DNS resolver used in this [`MagicSock`]. +556 #[cfg(not(wasm_browser))] +557 pub(crate) fn dns_resolver(&self) -> &DnsResolver { +558 &self.dns_resolver +559 } +560 +561 /// Reference to optional discovery service +562 pub(crate) fn discovery(&self) -> Option<&dyn Discovery> { +563 self.discovery.as_ref().map(Box::as_ref) +564 } +565 +566 /// Updates the user-defined discovery data for this node. +567 pub(crate) fn set_user_data_for_discovery(&self, user_data: Option<UserData>) { +568 let mut guard = self.discovery_user_data.write().expect("lock poisened"); +569 if *guard != user_data { +570 *guard = user_data; +571 drop(guard); +572 self.publish_my_addr(); +573 } +574 } +575 +576 /// Call to notify the system of potential network changes. +577 pub(crate) async fn network_change(&self) { +578 self.actor_sender +579 .send(ActorMessage::NetworkChange) +580 .await +581 .ok(); +582 } +583 +584 /// Returns a reference to the subscribers channel for discovery events. +585 pub(crate) fn discovery_subscribers(&self) -> &DiscoverySubscribers { +586 &self.discovery_subscribers +587 } 588 -589 let mut ipv4_addr = None; -590 for addr in addrs { -591 let Some(addr) = addr.into_socket_addr() else { -592 continue; -593 }; -594 if addr.is_ipv6() { -595 return Ok(addr); -596 } -597 if addr.is_ipv4() && ipv4_addr.is_none() { -598 ipv4_addr.replace(addr); -599 } -600 } -601 match ipv4_addr { -602 Some(addr) => Ok(addr), -603 None => Err(io::Error::other("no valid socket available")), -604 } -605 } -606 -607 /// Searches the `node_map` to determine the current transports to be used. -608 #[instrument(skip_all)] -609 fn prepare_send( -610 &self, -611 transmit: &quinn_udp::Transmit, -612 ) -> io::Result<SmallVec<[transports::Addr; 3]>> { -613 self.metrics -614 .magicsock -615 .send_data -616 .inc_by(transmit.contents.len() as _); -617 -618 if self.is_closed() { -619 self.metrics -620 .magicsock -621 .send_data_network_down -622 .inc_by(transmit.contents.len() as _); -623 return Err(io::Error::new( -624 io::ErrorKind::NotConnected, -625 "connection closed", -626 )); -627 } -628 -629 let mut active_paths = SmallVec::<[_; 3]>::new(); -630 -631 match MultipathMappedAddr::from(transmit.destination) { -632 MultipathMappedAddr::Mixed(dest) => { -633 trace!( -634 dst = %dest, -635 src = ?transmit.src_ip, -636 len = %transmit.contents.len(), -637 "sending", -638 ); -639 -640 // Get the node's relay address and best direct address, as well -641 // as any pings that need to be sent for hole-punching purposes. -642 match self.node_map.get_send_addrs( -643 dest, -644 self.ipv6_reported.load(Ordering::Relaxed), -645 &self.metrics.magicsock, -646 ) { -647 Some((node_id, udp_addr, relay_url, ping_actions)) => { -648 if !ping_actions.is_empty() { -649 self.actor_sender -650 .try_send(ActorMessage::PingActions(ping_actions)) -651 .ok(); -652 } -653 // Mixed will send all available addrs -654 -655 if let Some(url) = relay_url { -656 active_paths.push(transports::Addr::Relay(url, node_id)); -657 } -658 if let Some(addr) = udp_addr { -659 active_paths.push(transports::Addr::Ip(addr)); -660 } -661 } -662 None => { -663 error!(%dest, "no NodeState for mapped address"); -664 } -665 } -666 } -667 #[cfg(not(wasm_browser))] -668 MultipathMappedAddr::Ip(addr) => { -669 active_paths.push(transports::Addr::Ip(addr)); -670 } -671 MultipathMappedAddr::Relay(dest) => { -672 trace!( -673 dst = %dest, -674 src = ?transmit.src_ip, -675 len = %transmit.contents.len(), -676 "sending", -677 ); -678 -679 // Check if this is a known IpMappedAddr, and if so, send over UDP -680 // Get the socket addr -681 match self.relay_mapped_addrs.get_url(&dest) { -682 Some((relay, node_id)) => { -683 active_paths.push(transports::Addr::Relay(relay, node_id)); -684 } -685 None => { -686 error!(%dest, "unknown mapped address"); -687 } -688 } -689 } -690 } -691 -692 Ok(active_paths) -693 } -694 -695 /// Process datagrams received from UDP sockets. -696 /// -697 /// All the `bufs` and `metas` should have initialized packets in them. -698 /// -699 /// This fixes up the datagrams to use the correct [`NodeIdMappedAddr`] and extracts DISCO -700 /// packets, processing them inside the magic socket. -701 fn process_datagrams( -702 &self, -703 bufs: &mut [io::IoSliceMut<'_>], -704 metas: &mut [quinn_udp::RecvMeta], -705 source_addrs: &[transports::Addr], -706 ) { -707 debug_assert_eq!(bufs.len(), metas.len(), "non matching bufs & metas"); -708 debug_assert_eq!( -709 bufs.len(), -710 source_addrs.len(), -711 "non matching bufs & source_addrs" -712 ); -713 -714 // Adding the IP address we received something on results in Quinn using this -715 // address on the send path to send from. However we let Quinn use a -716 // NodeIdMappedAddress, not a real address. So we used to substitute our bind address -717 // here so that Quinn would send on the right address. But that would sometimes -718 // result in the wrong address family and Windows trips up on that. -719 // -720 // What should be done is that this dst_ip from the RecvMeta is stored in the -721 // NodeState/PathState. Then on the send path it should be retrieved from the -722 // NodeState/PathSate together with the send address and substituted at send time. -723 // This is relevant for IPv6 link-local addresses where the OS otherwise does not -724 // know which interface to send from. -725 #[cfg(not(windows))] -726 let dst_ip = self.normalized_local_addr().ok().map(|addr| addr.ip()); -727 // Reasoning for this here: -728 // https://github.com/n0-computer/iroh/pull/2595#issuecomment-2290947319 -729 #[cfg(windows)] -730 let dst_ip = None; -731 -732 let mut quic_packets_total = 0; -733 -734 for ((quinn_meta, buf), source_addr) in metas -735 .iter_mut() -736 .zip(bufs.iter_mut()) -737 .zip(source_addrs.iter()) -738 { -739 let mut buf_contains_quic_datagrams = false; -740 let mut quic_datagram_count = 0; -741 if quinn_meta.len > quinn_meta.stride { -742 trace!(%quinn_meta.len, %quinn_meta.stride, "GRO datagram received"); -743 self.metrics.magicsock.recv_gro_datagrams.inc(); -744 } +589 #[cfg(test)] +590 async fn force_network_change(&self, is_major: bool) { +591 self.actor_sender +592 .send(ActorMessage::ForceNetworkChange(is_major)) +593 .await +594 .ok(); +595 } +596 +597 #[cfg_attr(windows, allow(dead_code))] +598 fn normalized_local_addr(&self) -> io::Result<SocketAddr> { +599 let addrs = self.local_addrs_watch.get().expect("disconnected"); +600 +601 let mut ipv4_addr = None; +602 for addr in addrs { +603 let Some(addr) = addr.into_socket_addr() else { +604 continue; +605 }; +606 if addr.is_ipv6() { +607 return Ok(addr); +608 } +609 if addr.is_ipv4() && ipv4_addr.is_none() { +610 ipv4_addr.replace(addr); +611 } +612 } +613 match ipv4_addr { +614 Some(addr) => Ok(addr), +615 None => Err(io::Error::other("no valid socket available")), +616 } +617 } +618 +619 /// Searches the `node_map` to determine the current transports to be used. +620 #[instrument(skip_all)] +621 fn prepare_send( +622 &self, +623 transmit: &quinn_udp::Transmit, +624 ) -> io::Result<SmallVec<[transports::Addr; 3]>> { +625 self.metrics +626 .magicsock +627 .send_data +628 .inc_by(transmit.contents.len() as _); +629 +630 if self.is_closed() { +631 self.metrics +632 .magicsock +633 .send_data_network_down +634 .inc_by(transmit.contents.len() as _); +635 return Err(io::Error::new( +636 io::ErrorKind::NotConnected, +637 "connection closed", +638 )); +639 } +640 +641 let mut active_paths = SmallVec::<[_; 3]>::new(); +642 +643 match MultipathMappedAddr::from(transmit.destination) { +644 MultipathMappedAddr::Mixed(dest) => { +645 trace!( +646 dst = %dest, +647 src = ?transmit.src_ip, +648 len = %transmit.contents.len(), +649 "sending", +650 ); +651 +652 // Get the node's relay address and best direct address, as well +653 // as any pings that need to be sent for hole-punching purposes. +654 match self.node_map.get_send_addrs( +655 dest, +656 self.ipv6_reported.load(Ordering::Relaxed), +657 &self.metrics.magicsock, +658 ) { +659 Some((node_id, _udp_addr, _relay_url, ping_actions)) => { +660 if !ping_actions.is_empty() { +661 self.actor_sender +662 .try_send(ActorMessage::PingActions(ping_actions)) +663 .ok(); +664 } +665 +666 if let Some(addr) = self.node_map.get_current_addr(node_id) { +667 // Mixed will send all available addrs +668 if let Some(ref url) = addr.relay_url { +669 active_paths.push(transports::Addr::Relay(url.clone(), node_id)); +670 } +671 for ip in addr.direct_addresses() { +672 active_paths.push(transports::Addr::Ip(*ip)); +673 } +674 } +675 } +676 None => { +677 error!(%dest, "no NodeState for mapped address"); +678 } +679 } +680 } +681 #[cfg(not(wasm_browser))] +682 MultipathMappedAddr::Ip(addr) => { +683 active_paths.push(transports::Addr::Ip(addr)); +684 } +685 MultipathMappedAddr::Relay(dest) => { +686 trace!( +687 dst = %dest, +688 src = ?transmit.src_ip, +689 len = %transmit.contents.len(), +690 "sending", +691 ); +692 +693 // Check if this is a known IpMappedAddr, and if so, send over UDP +694 // Get the socket addr +695 match self.relay_mapped_addrs.get_url(&dest) { +696 Some((relay, node_id)) => { +697 active_paths.push(transports::Addr::Relay(relay, node_id)); +698 } +699 None => { +700 error!(%dest, "unknown mapped address"); +701 } +702 } +703 } +704 } +705 +706 Ok(active_paths) +707 } +708 +709 /// Process datagrams received from UDP sockets. +710 /// +711 /// All the `bufs` and `metas` should have initialized packets in them. +712 /// +713 /// This fixes up the datagrams to use the correct [`NodeIdMappedAddr`] and extracts DISCO +714 /// packets, processing them inside the magic socket. +715 fn process_datagrams( +716 &self, +717 bufs: &mut [io::IoSliceMut<'_>], +718 metas: &mut [quinn_udp::RecvMeta], +719 source_addrs: &[transports::Addr], +720 ) { +721 debug_assert_eq!(bufs.len(), metas.len(), "non matching bufs & metas"); +722 debug_assert_eq!( +723 bufs.len(), +724 source_addrs.len(), +725 "non matching bufs & source_addrs" +726 ); +727 +728 // Adding the IP address we received something on results in Quinn using this +729 // address on the send path to send from. However we let Quinn use a +730 // NodeIdMappedAddress, not a real address. So we used to substitute our bind address +731 // here so that Quinn would send on the right address. But that would sometimes +732 // result in the wrong address family and Windows trips up on that. +733 // +734 // What should be done is that this dst_ip from the RecvMeta is stored in the +735 // NodeState/PathState. Then on the send path it should be retrieved from the +736 // NodeState/PathSate together with the send address and substituted at send time. +737 // This is relevant for IPv6 link-local addresses where the OS otherwise does not +738 // know which interface to send from. +739 #[cfg(not(windows))] +740 let dst_ip = self.normalized_local_addr().ok().map(|addr| addr.ip()); +741 // Reasoning for this here: +742 // https://github.com/n0-computer/iroh/pull/2595#issuecomment-2290947319 +743 #[cfg(windows)] +744 let dst_ip = None; 745 -746 // Chunk through the datagrams in this GRO payload to find disco -747 // packets and forward them to the actor -748 for datagram in buf[..quinn_meta.len].chunks_mut(quinn_meta.stride) { -749 if datagram.len() < quinn_meta.stride { -750 trace!( -751 len = %datagram.len(), -752 %quinn_meta.stride, -753 "Last GRO datagram smaller than stride", -754 ); -755 } -756 -757 // Detect DISCO datagrams and process them. Overwrite the first -758 // byte of those packets with zero to make Quinn ignore the packet. This -759 // relies on quinn::EndpointConfig::grease_quic_bit being set to `false`, -760 // which we do in Endpoint::bind. -761 if let Some((sender, sealed_box)) = disco::source_and_box(datagram) { -762 trace!(src = ?source_addr, len = %quinn_meta.stride, "UDP recv: disco packet"); -763 self.handle_disco_message(sender, sealed_box, source_addr); -764 datagram[0] = 0u8; -765 } else { -766 trace!(src = ?source_addr, len = %quinn_meta.stride, "UDP recv: quic packet"); -767 match source_addr { -768 transports::Addr::Ip(SocketAddr::V4(..)) => { -769 self.metrics -770 .magicsock -771 .recv_data_ipv4 -772 .inc_by(datagram.len() as _); -773 } -774 transports::Addr::Ip(SocketAddr::V6(..)) => { -775 self.metrics -776 .magicsock -777 .recv_data_ipv6 -778 .inc_by(datagram.len() as _); -779 } -780 transports::Addr::Relay(..) => { -781 self.metrics -782 .magicsock -783 .recv_data_relay -784 .inc_by(datagram.len() as _); -785 } -786 } -787 -788 quic_datagram_count += 1; -789 buf_contains_quic_datagrams = true; -790 } -791 } -792 -793 if buf_contains_quic_datagrams { -794 match source_addr { -795 #[cfg(wasm_browser)] -796 transports::Addr::Ip(_addr) => { -797 panic!("cannot use IP based addressing in the browser"); -798 } -799 #[cfg(not(wasm_browser))] -800 transports::Addr::Ip(addr) => { -801 // UDP -802 -803 // Update the NodeMap and remap RecvMeta to the NodeIdMappedAddr. -804 match self.node_map.receive_udp(*addr) { -805 None => { -806 trace!( -807 src = %addr, -808 count = %quic_datagram_count, -809 len = quinn_meta.len, -810 "UDP recv quic packets", -811 ); -812 -813 quic_packets_total += quic_datagram_count; -814 quinn_meta.addr = *addr; -815 } -816 Some((node_id, quic_mapped_addr)) => { -817 trace!( -818 src = %addr, -819 node = %node_id.fmt_short(), -820 count = %quic_datagram_count, -821 len = quinn_meta.len, -822 "UDP recv quic packets", -823 ); -824 quic_packets_total += quic_datagram_count; -825 quinn_meta.addr = quic_mapped_addr.private_socket_addr(); -826 } -827 } -828 } -829 transports::Addr::Relay(src_url, src_node) => { -830 // Relay -831 let _quic_mapped_addr = self.node_map.receive_relay(src_url, *src_node); -832 let mapped_addr = self -833 .relay_mapped_addrs -834 .get_or_register(src_url.clone(), *src_node); -835 quinn_meta.addr = mapped_addr.private_socket_addr(); -836 } -837 } -838 } else { -839 // If all datagrams in this buf are DISCO, set len to zero to make -840 // Quinn skip the buf completely. -841 quinn_meta.len = 0; -842 } -843 // Normalize local_ip -844 quinn_meta.dst_ip = dst_ip; -845 } -846 -847 if quic_packets_total > 0 { -848 self.metrics -849 .magicsock -850 .recv_datagrams -851 .inc_by(quic_packets_total as _); -852 trace!("UDP recv: {} packets", quic_packets_total); -853 } -854 } -855 -856 /// Handles a discovery message. -857 #[instrument("disco_in", skip_all, fields(node = %sender.fmt_short(), ?src))] -858 fn handle_disco_message(&self, sender: PublicKey, sealed_box: &[u8], src: &transports::Addr) { -859 trace!("handle_disco_message start"); -860 if self.is_closed() { -861 return; -862 } -863 -864 if let transports::Addr::Relay(_, node_id) = src { -865 if node_id != &sender { -866 // TODO: return here? -867 warn!( -868 "Received relay disco message from connection for {}, but with message from {}", -869 node_id.fmt_short(), -870 sender.fmt_short() -871 ); -872 } -873 } -874 -875 // We're now reasonably sure we're expecting communication from -876 // this node, do the heavy crypto lifting to see what they want. -877 let dm = match self.disco.unseal_and_decode(sender, sealed_box) { -878 Ok(dm) => dm, -879 Err(DiscoBoxError::Open { source, .. }) => { -880 warn!(?source, "failed to open disco box"); -881 self.metrics.magicsock.recv_disco_bad_key.inc(); -882 return; -883 } -884 Err(DiscoBoxError::Parse { source, .. }) => { -885 // Couldn't parse it, but it was inside a correctly -886 // signed box, so just ignore it, assuming it's from a -887 // newer version of Tailscale that we don't -888 // understand. Not even worth logging about, lest it -889 // be too spammy for old clients. -890 -891 self.metrics.magicsock.recv_disco_bad_parse.inc(); -892 debug!(?source, "failed to parse disco message"); -893 return; -894 } -895 }; -896 -897 if src.is_relay() { -898 self.metrics.magicsock.recv_disco_relay.inc(); -899 } else { -900 self.metrics.magicsock.recv_disco_udp.inc(); -901 } -902 -903 let span = trace_span!("handle_disco", ?dm); -904 let _guard = span.enter(); -905 trace!("receive disco message"); -906 match dm { -907 disco::Message::Ping(..) | disco::Message::Pong(..) => { -908 unreachable!("not used anymore"); -909 } -910 disco::Message::CallMeMaybe(cm) => { -911 self.metrics.magicsock.recv_disco_call_me_maybe.inc(); -912 match src { -913 transports::Addr::Relay(url, _) => { -914 event!( -915 target: "iroh::_events::call-me-maybe::recv", -916 Level::DEBUG, -917 remote_node = sender.fmt_short(), -918 via = ?url, -919 their_addrs = ?cm.my_numbers, -920 ); -921 } -922 _ => { -923 warn!("call-me-maybe packets should only come via relay"); -924 return; -925 } -926 } -927 -928 // Add new addresses as paths -929 self.add_paths(NodeAddr { -930 node_id: sender, -931 relay_url: None, -932 direct_addresses: cm.my_numbers.iter().copied().collect(), -933 }); -934 -935 self.node_map -936 .handle_call_me_maybe(sender, cm, &self.metrics.magicsock); -937 } -938 } -939 trace!("disco message handled"); -940 } +746 let mut quic_packets_total = 0; +747 +748 for ((quinn_meta, buf), source_addr) in metas +749 .iter_mut() +750 .zip(bufs.iter_mut()) +751 .zip(source_addrs.iter()) +752 { +753 let mut buf_contains_quic_datagrams = false; +754 let mut quic_datagram_count = 0; +755 if quinn_meta.len > quinn_meta.stride { +756 trace!(%quinn_meta.len, %quinn_meta.stride, "GRO datagram received"); +757 self.metrics.magicsock.recv_gro_datagrams.inc(); +758 } +759 +760 // Chunk through the datagrams in this GRO payload to find disco +761 // packets and forward them to the actor +762 for datagram in buf[..quinn_meta.len].chunks_mut(quinn_meta.stride) { +763 if datagram.len() < quinn_meta.stride { +764 trace!( +765 len = %datagram.len(), +766 %quinn_meta.stride, +767 "Last GRO datagram smaller than stride", +768 ); +769 } +770 +771 // Detect DISCO datagrams and process them. Overwrite the first +772 // byte of those packets with zero to make Quinn ignore the packet. This +773 // relies on quinn::EndpointConfig::grease_quic_bit being set to `false`, +774 // which we do in Endpoint::bind. +775 if let Some((sender, sealed_box)) = disco::source_and_box(datagram) { +776 trace!(src = ?source_addr, len = %quinn_meta.stride, "UDP recv: disco packet"); +777 self.handle_disco_message(sender, sealed_box, source_addr); +778 datagram[0] = 0u8; +779 } else { +780 trace!(src = ?source_addr, len = %quinn_meta.stride, "UDP recv: quic packet"); +781 match source_addr { +782 transports::Addr::Ip(SocketAddr::V4(..)) => { +783 self.metrics +784 .magicsock +785 .recv_data_ipv4 +786 .inc_by(datagram.len() as _); +787 } +788 transports::Addr::Ip(SocketAddr::V6(..)) => { +789 self.metrics +790 .magicsock +791 .recv_data_ipv6 +792 .inc_by(datagram.len() as _); +793 } +794 transports::Addr::Relay(..) => { +795 self.metrics +796 .magicsock +797 .recv_data_relay +798 .inc_by(datagram.len() as _); +799 } +800 } +801 +802 quic_datagram_count += 1; +803 buf_contains_quic_datagrams = true; +804 } +805 } +806 +807 if buf_contains_quic_datagrams { +808 match source_addr { +809 #[cfg(wasm_browser)] +810 transports::Addr::Ip(_addr) => { +811 panic!("cannot use IP based addressing in the browser"); +812 } +813 #[cfg(not(wasm_browser))] +814 transports::Addr::Ip(addr) => { +815 // UDP +816 +817 // Update the NodeMap and remap RecvMeta to the NodeIdMappedAddr. +818 match self.node_map.receive_udp(*addr) { +819 None => { +820 trace!( +821 src = %addr, +822 count = %quic_datagram_count, +823 len = quinn_meta.len, +824 "UDP recv quic packets", +825 ); +826 +827 quic_packets_total += quic_datagram_count; +828 quinn_meta.addr = *addr; +829 } +830 Some((node_id, quic_mapped_addr)) => { +831 trace!( +832 src = %addr, +833 node = %node_id.fmt_short(), +834 count = %quic_datagram_count, +835 len = quinn_meta.len, +836 "UDP recv quic packets", +837 ); +838 quic_packets_total += quic_datagram_count; +839 quinn_meta.addr = quic_mapped_addr.private_socket_addr(); +840 } +841 } +842 } +843 transports::Addr::Relay(src_url, src_node) => { +844 // Relay +845 let _quic_mapped_addr = self.node_map.receive_relay(src_url, *src_node); +846 let mapped_addr = self +847 .relay_mapped_addrs +848 .get_or_register(src_url.clone(), *src_node); +849 quinn_meta.addr = mapped_addr.private_socket_addr(); +850 } +851 } +852 } else { +853 // If all datagrams in this buf are DISCO, set len to zero to make +854 // Quinn skip the buf completely. +855 quinn_meta.len = 0; +856 } +857 // Normalize local_ip +858 quinn_meta.dst_ip = dst_ip; +859 } +860 +861 if quic_packets_total > 0 { +862 self.metrics +863 .magicsock +864 .recv_datagrams +865 .inc_by(quic_packets_total as _); +866 trace!("UDP recv: {} packets", quic_packets_total); +867 } +868 } +869 +870 /// Handles a discovery message. +871 #[instrument("disco_in", skip_all, fields(node = %sender.fmt_short(), ?src))] +872 fn handle_disco_message(&self, sender: PublicKey, sealed_box: &[u8], src: &transports::Addr) { +873 trace!("handle_disco_message start"); +874 if self.is_closed() { +875 return; +876 } +877 +878 if let transports::Addr::Relay(_, node_id) = src { +879 if node_id != &sender { +880 // TODO: return here? +881 warn!( +882 "Received relay disco message from connection for {}, but with message from {}", +883 node_id.fmt_short(), +884 sender.fmt_short() +885 ); +886 } +887 } +888 +889 // We're now reasonably sure we're expecting communication from +890 // this node, do the heavy crypto lifting to see what they want. +891 let dm = match self.disco.unseal_and_decode(sender, sealed_box) { +892 Ok(dm) => dm, +893 Err(DiscoBoxError::Open { source, .. }) => { +894 warn!(?source, "failed to open disco box"); +895 self.metrics.magicsock.recv_disco_bad_key.inc(); +896 return; +897 } +898 Err(DiscoBoxError::Parse { source, .. }) => { +899 // Couldn't parse it, but it was inside a correctly +900 // signed box, so just ignore it, assuming it's from a +901 // newer version of Tailscale that we don't +902 // understand. Not even worth logging about, lest it +903 // be too spammy for old clients. +904 +905 self.metrics.magicsock.recv_disco_bad_parse.inc(); +906 debug!(?source, "failed to parse disco message"); +907 return; +908 } +909 }; +910 +911 if src.is_relay() { +912 self.metrics.magicsock.recv_disco_relay.inc(); +913 } else { +914 self.metrics.magicsock.recv_disco_udp.inc(); +915 } +916 +917 let span = trace_span!("handle_disco", ?dm); +918 let _guard = span.enter(); +919 trace!("receive disco message"); +920 match dm { +921 disco::Message::Ping(..) | disco::Message::Pong(..) => { +922 unreachable!("not used anymore"); +923 } +924 disco::Message::CallMeMaybe(cm) => { +925 self.metrics.magicsock.recv_disco_call_me_maybe.inc(); +926 match src { +927 transports::Addr::Relay(url, _) => { +928 event!( +929 target: "iroh::_events::call-me-maybe::recv", +930 Level::DEBUG, +931 remote_node = sender.fmt_short(), +932 via = ?url, +933 their_addrs = ?cm.my_numbers, +934 ); +935 } +936 _ => { +937 warn!("call-me-maybe packets should only come via relay"); +938 return; +939 } +940 } 941 -942 /// Send the given ping actions out. -943 async fn send_ping_actions( -944 &self, -945 _sender: &UdpSender, -946 msgs: Vec<PingAction>, -947 ) -> io::Result<()> { -948 for msg in msgs { -949 // Abort sending as soon as we know we are shutting down. -950 if self.is_closing() || self.is_closed() { -951 return Ok(()); -952 } -953 match msg { -954 PingAction::SendCallMeMaybe { -955 relay_url, -956 dst_node, -957 } => { -958 // Sends the call-me-maybe DISCO message, queuing if addresses are too stale. -959 // -960 // To send the call-me-maybe message, we need to know our current direct addresses. If -961 // this information is too stale, the call-me-maybe is queued while a net_report run is -962 // scheduled. Once this run finishes, the call-me-maybe will be sent. -963 match self.direct_addrs.fresh_enough() { -964 Ok(()) => { -965 let msg = disco::Message::CallMeMaybe( -966 self.direct_addrs.to_call_me_maybe_message(), -967 ); -968 if !self.disco.try_send( -969 SendAddr::Relay(relay_url.clone()), -970 dst_node, -971 msg.clone(), -972 ) { -973 warn!(dstkey = %dst_node.fmt_short(), %relay_url, "relay channel full, dropping call-me-maybe"); -974 } else { -975 debug!(dstkey = %dst_node.fmt_short(), %relay_url, "call-me-maybe sent"); -976 } -977 } -978 Err(last_refresh_ago) => { -979 debug!( -980 ?last_refresh_ago, -981 "want call-me-maybe but direct addrs stale; queuing after restun", -982 ); -983 self.actor_sender -984 .try_send(ActorMessage::ScheduleDirectAddrUpdate( -985 UpdateReason::RefreshForPeering, -986 Some((dst_node, relay_url)), -987 )) -988 .ok(); -989 } -990 } -991 } -992 } -993 } -994 Ok(()) -995 } -996 -997 /// Sends out a disco message. -998 async fn send_disco_message( -999 &self, -1000 sender: &UdpSender, -1001 dst: SendAddr, -1002 dst_key: PublicKey, -1003 msg: disco::Message, -1004 ) -> io::Result<()> { -1005 let dst = match dst { -1006 SendAddr::Udp(addr) => transports::Addr::Ip(addr), -1007 SendAddr::Relay(url) => transports::Addr::Relay(url, dst_key), -1008 }; -1009 -1010 trace!(?dst, %msg, "send disco message (UDP)"); -1011 if self.is_closed() { -1012 return Err(io::Error::new( -1013 io::ErrorKind::NotConnected, -1014 "connection closed", -1015 )); -1016 } -1017 -1018 let pkt = self.disco.encode_and_seal(self.public_key, dst_key, &msg); -1019 -1020 let transmit = transports::Transmit { -1021 contents: &pkt, -1022 ecn: None, -1023 segment_size: None, -1024 }; -1025 -1026 let dst2 = dst.clone(); -1027 match sender.send(&dst2, None, &transmit).await { -1028 Ok(()) => { -1029 trace!(?dst, %msg, "sent disco message"); -1030 self.metrics.magicsock.sent_disco_udp.inc(); -1031 disco_message_sent(&msg, &self.metrics.magicsock); -1032 Ok(()) -1033 } -1034 Err(err) => { -1035 warn!(?dst, ?msg, ?err, "failed to send disco message"); -1036 Err(err) -1037 } -1038 } -1039 } -1040 -1041 /// Publishes our address to a discovery service, if configured. -1042 /// -1043 /// Called whenever our addresses or home relay node changes. -1044 fn publish_my_addr(&self) { -1045 if let Some(ref discovery) = self.discovery { -1046 let relay_url = self.my_relay(); -1047 let direct_addrs = self.direct_addrs.sockaddrs(); -1048 -1049 let user_data = self -1050 .discovery_user_data -1051 .read() -1052 .expect("lock poisened") -1053 .clone(); -1054 if relay_url.is_none() && direct_addrs.is_empty() && user_data.is_none() { -1055 // do not bother publishing if we don't have any information -1056 return; -1057 } -1058 -1059 let data = NodeData::new(relay_url, direct_addrs).with_user_data(user_data); -1060 discovery.publish(&data); -1061 } -1062 } -1063} -1064 -1065/// Definies the translation of addresses in quinn land vs iroh land. -1066/// -1067/// This is necessary, because quinn can only reason about `SocketAddr`s. -1068#[derive(Clone, Debug)] -1069pub(crate) enum MultipathMappedAddr { -1070 /// Used for the initial connection. -1071 /// - Only used for sending -1072 /// - This means send on all known paths/transports -1073 Mixed(NodeIdMappedAddr), -1074 /// Relay based transport address -1075 Relay(IpMappedAddr), // TODO: RelayMappedAddr? -1076 /// IP based transport address -1077 #[cfg(not(wasm_browser))] -1078 Ip(SocketAddr), -1079} -1080 -1081impl From<SocketAddr> for MultipathMappedAddr { -1082 fn from(value: SocketAddr) -> Self { -1083 match value.ip() { -1084 IpAddr::V4(_) => Self::Ip(value), -1085 IpAddr::V6(addr) => { -1086 if let Ok(node_id_mapped_addr) = NodeIdMappedAddr::try_from(addr) { -1087 return Self::Mixed(node_id_mapped_addr); -1088 } -1089 #[cfg(not(wasm_browser))] -1090 if let Ok(ip_mapped_addr) = IpMappedAddr::try_from(addr) { -1091 return Self::Relay(ip_mapped_addr); -1092 } -1093 Self::Ip(value) -1094 } -1095 } -1096 } -1097} -1098 -1099/// Manages currently running direct addr discovery, aka net_report runs. -1100/// -1101/// Invariants: -1102/// - only one direct addr update must be running at a time -1103/// - if an update is scheduled while another one is running, remember that -1104/// and start a new one when the current one has finished -1105#[derive(Debug)] -1106struct DirectAddrUpdateState { -1107 /// If set, start a new update as soon as the current one is finished. -1108 want_update: Option<UpdateReason>, -1109 msock: Arc<MagicSock>, -1110 #[cfg(not(wasm_browser))] -1111 port_mapper: portmapper::Client, -1112 /// The prober that discovers local network conditions, including the closest relay relay and NAT mappings. -1113 net_reporter: Arc<AsyncMutex<net_report::Client>>, -1114 relay_map: RelayMap, -1115 run_done: mpsc::Sender<()>, -1116} -1117 -1118#[derive(Default, Debug, PartialEq, Eq, Clone, Copy)] -1119enum UpdateReason { -1120 /// Initial state -1121 #[default] -1122 None, -1123 RefreshForPeering, -1124 Periodic, -1125 PortmapUpdated, -1126 LinkChangeMajor, -1127 LinkChangeMinor, -1128} -1129 -1130impl UpdateReason { -1131 fn is_major(self) -> bool { -1132 matches!(self, Self::LinkChangeMajor) -1133 } -1134} -1135 -1136impl DirectAddrUpdateState { -1137 fn new( -1138 msock: Arc<MagicSock>, -1139 #[cfg(not(wasm_browser))] port_mapper: portmapper::Client, -1140 net_reporter: Arc<AsyncMutex<net_report::Client>>, -1141 relay_map: RelayMap, -1142 run_done: mpsc::Sender<()>, -1143 ) -> Self { -1144 DirectAddrUpdateState { -1145 want_update: Default::default(), -1146 #[cfg(not(wasm_browser))] -1147 port_mapper, -1148 net_reporter, -1149 msock, -1150 relay_map, -1151 run_done, -1152 } -1153 } -1154 -1155 /// Schedules a new run, either starting it immediately if none is running or -1156 /// scheduling it for later. -1157 fn schedule_run(&mut self, why: UpdateReason, if_state: IfStateDetails) { -1158 match self.net_reporter.clone().try_lock_owned() { -1159 Ok(net_reporter) => { -1160 self.run(why, if_state, net_reporter); -1161 } -1162 Err(_) => { -1163 let _ = self.want_update.insert(why); -1164 } -1165 } -1166 } -1167 -1168 /// If another run is needed, triggers this run, otherwise does nothing. -1169 fn try_run(&mut self, if_state: IfStateDetails) { -1170 match self.net_reporter.clone().try_lock_owned() { -1171 Ok(net_reporter) => { -1172 if let Some(why) = self.want_update.take() { -1173 self.run(why, if_state, net_reporter); -1174 } +942 // Add new addresses as paths +943 self.add_paths(NodeAddr { +944 node_id: sender, +945 relay_url: None, +946 direct_addresses: cm.my_numbers.iter().copied().collect(), +947 }); +948 +949 self.node_map +950 .handle_call_me_maybe(sender, cm, &self.metrics.magicsock); +951 } +952 } +953 trace!("disco message handled"); +954 } +955 +956 /// Send the given ping actions out. +957 async fn send_ping_actions( +958 &self, +959 _sender: &UdpSender, +960 msgs: Vec<PingAction>, +961 ) -> io::Result<()> { +962 for msg in msgs { +963 // Abort sending as soon as we know we are shutting down. +964 if self.is_closing() || self.is_closed() { +965 return Ok(()); +966 } +967 match msg { +968 PingAction::SendCallMeMaybe { +969 relay_url, +970 dst_node, +971 } => { +972 // Sends the call-me-maybe DISCO message, queuing if addresses are too stale. +973 // +974 // To send the call-me-maybe message, we need to know our current direct addresses. If +975 // this information is too stale, the call-me-maybe is queued while a net_report run is +976 // scheduled. Once this run finishes, the call-me-maybe will be sent. +977 match self.direct_addrs.fresh_enough() { +978 Ok(()) => { +979 let msg = disco::Message::CallMeMaybe( +980 self.direct_addrs.to_call_me_maybe_message(), +981 ); +982 if !self.disco.try_send( +983 SendAddr::Relay(relay_url.clone()), +984 dst_node, +985 msg.clone(), +986 ) { +987 warn!(dstkey = %dst_node.fmt_short(), %relay_url, "relay channel full, dropping call-me-maybe"); +988 } else { +989 debug!(dstkey = %dst_node.fmt_short(), %relay_url, "call-me-maybe sent"); +990 } +991 } +992 Err(last_refresh_ago) => { +993 debug!( +994 ?last_refresh_ago, +995 "want call-me-maybe but direct addrs stale; queuing after restun", +996 ); +997 self.actor_sender +998 .try_send(ActorMessage::ScheduleDirectAddrUpdate( +999 UpdateReason::RefreshForPeering, +1000 Some((dst_node, relay_url)), +1001 )) +1002 .ok(); +1003 } +1004 } +1005 } +1006 } +1007 } +1008 Ok(()) +1009 } +1010 +1011 /// Sends out a disco message. +1012 async fn send_disco_message( +1013 &self, +1014 sender: &UdpSender, +1015 dst: SendAddr, +1016 dst_key: PublicKey, +1017 msg: disco::Message, +1018 ) -> io::Result<()> { +1019 let dst = match dst { +1020 SendAddr::Udp(addr) => transports::Addr::Ip(addr), +1021 SendAddr::Relay(url) => transports::Addr::Relay(url, dst_key), +1022 }; +1023 +1024 trace!(?dst, %msg, "send disco message (UDP)"); +1025 if self.is_closed() { +1026 return Err(io::Error::new( +1027 io::ErrorKind::NotConnected, +1028 "connection closed", +1029 )); +1030 } +1031 +1032 let pkt = self.disco.encode_and_seal(self.public_key, dst_key, &msg); +1033 +1034 let transmit = transports::Transmit { +1035 contents: &pkt, +1036 ecn: None, +1037 segment_size: None, +1038 }; +1039 +1040 let dst2 = dst.clone(); +1041 match sender.send(&dst2, None, &transmit).await { +1042 Ok(()) => { +1043 trace!(?dst, %msg, "sent disco message"); +1044 self.metrics.magicsock.sent_disco_udp.inc(); +1045 disco_message_sent(&msg, &self.metrics.magicsock); +1046 Ok(()) +1047 } +1048 Err(err) => { +1049 warn!(?dst, ?msg, ?err, "failed to send disco message"); +1050 Err(err) +1051 } +1052 } +1053 } +1054 +1055 /// Publishes our address to a discovery service, if configured. +1056 /// +1057 /// Called whenever our addresses or home relay node changes. +1058 fn publish_my_addr(&self) { +1059 if let Some(ref discovery) = self.discovery { +1060 let relay_url = self.my_relay(); +1061 let direct_addrs = self.direct_addrs.sockaddrs(); +1062 +1063 let user_data = self +1064 .discovery_user_data +1065 .read() +1066 .expect("lock poisened") +1067 .clone(); +1068 if relay_url.is_none() && direct_addrs.is_empty() && user_data.is_none() { +1069 // do not bother publishing if we don't have any information +1070 return; +1071 } +1072 +1073 let data = NodeData::new(relay_url, direct_addrs).with_user_data(user_data); +1074 discovery.publish(&data); +1075 } +1076 } +1077} +1078 +1079/// Definies the translation of addresses in quinn land vs iroh land. +1080/// +1081/// This is necessary, because quinn can only reason about `SocketAddr`s. +1082#[derive(Clone, Debug)] +1083pub(crate) enum MultipathMappedAddr { +1084 /// Used for the initial connection. +1085 /// - Only used for sending +1086 /// - This means send on all known paths/transports +1087 Mixed(NodeIdMappedAddr), +1088 /// Relay based transport address +1089 Relay(IpMappedAddr), // TODO: RelayMappedAddr? +1090 /// IP based transport address +1091 #[cfg(not(wasm_browser))] +1092 Ip(SocketAddr), +1093} +1094 +1095impl From<SocketAddr> for MultipathMappedAddr { +1096 fn from(value: SocketAddr) -> Self { +1097 match value.ip() { +1098 IpAddr::V4(_) => Self::Ip(value), +1099 IpAddr::V6(addr) => { +1100 if let Ok(node_id_mapped_addr) = NodeIdMappedAddr::try_from(addr) { +1101 return Self::Mixed(node_id_mapped_addr); +1102 } +1103 #[cfg(not(wasm_browser))] +1104 if let Ok(ip_mapped_addr) = IpMappedAddr::try_from(addr) { +1105 return Self::Relay(ip_mapped_addr); +1106 } +1107 Self::Ip(value) +1108 } +1109 } +1110 } +1111} +1112 +1113/// Manages currently running direct addr discovery, aka net_report runs. +1114/// +1115/// Invariants: +1116/// - only one direct addr update must be running at a time +1117/// - if an update is scheduled while another one is running, remember that +1118/// and start a new one when the current one has finished +1119#[derive(Debug)] +1120struct DirectAddrUpdateState { +1121 /// If set, start a new update as soon as the current one is finished. +1122 want_update: Option<UpdateReason>, +1123 msock: Arc<MagicSock>, +1124 #[cfg(not(wasm_browser))] +1125 port_mapper: portmapper::Client, +1126 /// The prober that discovers local network conditions, including the closest relay relay and NAT mappings. +1127 net_reporter: Arc<AsyncMutex<net_report::Client>>, +1128 relay_map: RelayMap, +1129 run_done: mpsc::Sender<()>, +1130} +1131 +1132#[derive(Default, Debug, PartialEq, Eq, Clone, Copy)] +1133enum UpdateReason { +1134 /// Initial state +1135 #[default] +1136 None, +1137 RefreshForPeering, +1138 Periodic, +1139 PortmapUpdated, +1140 LinkChangeMajor, +1141 LinkChangeMinor, +1142} +1143 +1144impl UpdateReason { +1145 fn is_major(self) -> bool { +1146 matches!(self, Self::LinkChangeMajor) +1147 } +1148} +1149 +1150impl DirectAddrUpdateState { +1151 fn new( +1152 msock: Arc<MagicSock>, +1153 #[cfg(not(wasm_browser))] port_mapper: portmapper::Client, +1154 net_reporter: Arc<AsyncMutex<net_report::Client>>, +1155 relay_map: RelayMap, +1156 run_done: mpsc::Sender<()>, +1157 ) -> Self { +1158 DirectAddrUpdateState { +1159 want_update: Default::default(), +1160 #[cfg(not(wasm_browser))] +1161 port_mapper, +1162 net_reporter, +1163 msock, +1164 relay_map, +1165 run_done, +1166 } +1167 } +1168 +1169 /// Schedules a new run, either starting it immediately if none is running or +1170 /// scheduling it for later. +1171 fn schedule_run(&mut self, why: UpdateReason, if_state: IfStateDetails) { +1172 match self.net_reporter.clone().try_lock_owned() { +1173 Ok(net_reporter) => { +1174 self.run(why, if_state, net_reporter); 1175 } 1176 Err(_) => { -1177 // do nothing -1178 } +1177 let _ = self.want_update.insert(why); +1178 } 1179 } 1180 } 1181 -1182 /// Trigger a new run. -1183 fn run( -1184 &mut self, -1185 why: UpdateReason, -1186 if_state: IfStateDetails, -1187 mut net_reporter: tokio::sync::OwnedMutexGuard<net_report::Client>, -1188 ) { -1189 debug!("starting direct addr update ({:?})", why); -1190 #[cfg(not(wasm_browser))] -1191 self.port_mapper.procure_mapping(); -1192 // Don't start a net report probe if we know -1193 // we are shutting down -1194 if self.msock.is_closing() || self.msock.is_closed() { -1195 debug!("skipping net_report, socket is shutting down"); -1196 return; -1197 } -1198 if self.relay_map.is_empty() { -1199 debug!("skipping net_report, empty RelayMap"); -1200 self.msock.net_report.set((None, why)).ok(); -1201 return; -1202 } -1203 -1204 debug!("requesting net_report report"); -1205 let msock = self.msock.clone(); -1206 -1207 let run_done = self.run_done.clone(); -1208 task::spawn( -1209 async move { -1210 let fut = time::timeout( -1211 NET_REPORT_TIMEOUT, -1212 net_reporter.get_report(if_state, why.is_major()), -1213 ); -1214 match fut.await { -1215 Ok(report) => { -1216 msock.net_report.set((Some(report), why)).ok(); -1217 } -1218 Err(time::Elapsed { .. }) => { -1219 warn!("net_report report timed out"); -1220 } -1221 } -1222 -1223 // mark run as finished -1224 debug!("direct addr update done ({:?})", why); -1225 run_done.send(()).await.ok(); -1226 } -1227 .instrument(tracing::Span::current()), -1228 ); -1229 } -1230} -1231 -1232#[allow(missing_docs)] -1233#[common_fields({ -1234 backtrace: Option<snafu::Backtrace>, -1235 #[snafu(implicit)] -1236 span_trace: n0_snafu::SpanTrace, -1237})] -1238#[derive(Debug, Snafu)] -1239#[non_exhaustive] -1240pub enum CreateHandleError { -1241 #[snafu(display("Failed to create bind sockets"))] -1242 BindSockets { source: io::Error }, -1243 #[snafu(display("Failed to create internal quinn endpoint"))] -1244 CreateQuinnEndpoint { source: io::Error }, -1245 #[snafu(display("Failed to create socket state"))] -1246 CreateSocketState { source: io::Error }, -1247 #[snafu(display("Failed to create netmon monitor"))] -1248 CreateNetmonMonitor { source: netmon::Error }, -1249 #[snafu(display("Failed to subscribe netmon monitor"))] -1250 SubscribeNetmonMonitor { source: netmon::Error }, -1251} -1252 -1253impl Handle { -1254 /// Creates a magic [`MagicSock`] listening on [`Options::addr_v4`] and [`Options::addr_v6`]. -1255 async fn new(opts: Options) -> Result<Self, CreateHandleError> { -1256 let Options { -1257 addr_v4, -1258 addr_v6, -1259 secret_key, -1260 relay_map, -1261 node_map, -1262 discovery, -1263 discovery_user_data, -1264 #[cfg(not(wasm_browser))] -1265 dns_resolver, -1266 proxy_url, -1267 server_config, -1268 #[cfg(any(test, feature = "test-utils"))] -1269 insecure_skip_relay_cert_verify, -1270 #[cfg(any(test, feature = "test-utils"))] -1271 path_selection, -1272 metrics, -1273 } = opts; -1274 -1275 let addr_v4 = addr_v4.unwrap_or_else(|| SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)); -1276 -1277 #[cfg(not(wasm_browser))] -1278 let (ip_transports, port_mapper) = -1279 bind_ip(addr_v4, addr_v6, &metrics).context(BindSocketsSnafu)?; -1280 -1281 let relay_mapped_addrs = RelayMappedAddresses::default(); -1282 -1283 let (actor_sender, actor_receiver) = mpsc::channel(256); -1284 -1285 // load the node data -1286 let node_map = node_map.unwrap_or_default(); -1287 #[cfg(any(test, feature = "test-utils"))] -1288 let node_map = NodeMap::load_from_vec(node_map, path_selection, &metrics.magicsock); -1289 #[cfg(not(any(test, feature = "test-utils")))] -1290 let node_map = NodeMap::load_from_vec(node_map, &metrics.magicsock); -1291 -1292 let my_relay = Watchable::new(None); -1293 let ipv6_reported = Arc::new(AtomicBool::new(false)); +1182 /// If another run is needed, triggers this run, otherwise does nothing. +1183 fn try_run(&mut self, if_state: IfStateDetails) { +1184 match self.net_reporter.clone().try_lock_owned() { +1185 Ok(net_reporter) => { +1186 if let Some(why) = self.want_update.take() { +1187 self.run(why, if_state, net_reporter); +1188 } +1189 } +1190 Err(_) => { +1191 // do nothing +1192 } +1193 } +1194 } +1195 +1196 /// Trigger a new run. +1197 fn run( +1198 &mut self, +1199 why: UpdateReason, +1200 if_state: IfStateDetails, +1201 mut net_reporter: tokio::sync::OwnedMutexGuard<net_report::Client>, +1202 ) { +1203 debug!("starting direct addr update ({:?})", why); +1204 #[cfg(not(wasm_browser))] +1205 self.port_mapper.procure_mapping(); +1206 // Don't start a net report probe if we know +1207 // we are shutting down +1208 if self.msock.is_closing() || self.msock.is_closed() { +1209 debug!("skipping net_report, socket is shutting down"); +1210 return; +1211 } +1212 if self.relay_map.is_empty() { +1213 debug!("skipping net_report, empty RelayMap"); +1214 self.msock.net_report.set((None, why)).ok(); +1215 return; +1216 } +1217 +1218 debug!("requesting net_report report"); +1219 let msock = self.msock.clone(); +1220 +1221 let run_done = self.run_done.clone(); +1222 task::spawn( +1223 async move { +1224 let fut = time::timeout( +1225 NET_REPORT_TIMEOUT, +1226 net_reporter.get_report(if_state, why.is_major()), +1227 ); +1228 match fut.await { +1229 Ok(report) => { +1230 msock.net_report.set((Some(report), why)).ok(); +1231 } +1232 Err(time::Elapsed { .. }) => { +1233 warn!("net_report report timed out"); +1234 } +1235 } +1236 +1237 // mark run as finished +1238 debug!("direct addr update done ({:?})", why); +1239 run_done.send(()).await.ok(); +1240 } +1241 .instrument(tracing::Span::current()), +1242 ); +1243 } +1244} +1245 +1246#[allow(missing_docs)] +1247#[common_fields({ +1248 backtrace: Option<snafu::Backtrace>, +1249 #[snafu(implicit)] +1250 span_trace: n0_snafu::SpanTrace, +1251})] +1252#[derive(Debug, Snafu)] +1253#[non_exhaustive] +1254pub enum CreateHandleError { +1255 #[snafu(display("Failed to create bind sockets"))] +1256 BindSockets { source: io::Error }, +1257 #[snafu(display("Failed to create internal quinn endpoint"))] +1258 CreateQuinnEndpoint { source: io::Error }, +1259 #[snafu(display("Failed to create socket state"))] +1260 CreateSocketState { source: io::Error }, +1261 #[snafu(display("Failed to create netmon monitor"))] +1262 CreateNetmonMonitor { source: netmon::Error }, +1263 #[snafu(display("Failed to subscribe netmon monitor"))] +1264 SubscribeNetmonMonitor { source: netmon::Error }, +1265} +1266 +1267impl Handle { +1268 /// Creates a magic [`MagicSock`] listening on [`Options::addr_v4`] and [`Options::addr_v6`]. +1269 async fn new(opts: Options) -> Result<Self, CreateHandleError> { +1270 let Options { +1271 addr_v4, +1272 addr_v6, +1273 secret_key, +1274 relay_map, +1275 node_map, +1276 discovery, +1277 discovery_user_data, +1278 #[cfg(not(wasm_browser))] +1279 dns_resolver, +1280 proxy_url, +1281 server_config, +1282 #[cfg(any(test, feature = "test-utils"))] +1283 insecure_skip_relay_cert_verify, +1284 #[cfg(any(test, feature = "test-utils"))] +1285 path_selection, +1286 metrics, +1287 } = opts; +1288 +1289 let addr_v4 = addr_v4.unwrap_or_else(|| SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)); +1290 +1291 #[cfg(not(wasm_browser))] +1292 let (ip_transports, port_mapper) = +1293 bind_ip(addr_v4, addr_v6, &metrics).context(BindSocketsSnafu)?; 1294 -1295 let relay_transport = RelayTransport::new(RelayActorConfig { -1296 my_relay: my_relay.clone(), -1297 secret_key: secret_key.clone(), -1298 #[cfg(not(wasm_browser))] -1299 dns_resolver: dns_resolver.clone(), -1300 proxy_url: proxy_url.clone(), -1301 ipv6_reported: ipv6_reported.clone(), -1302 #[cfg(any(test, feature = "test-utils"))] -1303 insecure_skip_relay_cert_verify, -1304 metrics: metrics.magicsock.clone(), -1305 }); -1306 let relay_transports = vec![relay_transport]; -1307 -1308 let secret_encryption_key = secret_ed_box(secret_key.secret()); -1309 #[cfg(not(wasm_browser))] -1310 let ipv6 = ip_transports.iter().any(|t| t.bind_addr().is_ipv6()); -1311 -1312 #[cfg(not(wasm_browser))] -1313 let transports = Transports::new(ip_transports, relay_transports); -1314 #[cfg(wasm_browser)] -1315 let transports = Transports::new(relay_transports); -1316 -1317 let (disco, disco_receiver) = DiscoState::new(secret_encryption_key); -1318 -1319 let msock = Arc::new(MagicSock { -1320 public_key: secret_key.public(), -1321 closing: AtomicBool::new(false), -1322 closed: AtomicBool::new(false), -1323 disco, -1324 actor_sender: actor_sender.clone(), -1325 ipv6_reported, -1326 node_map, -1327 connection_map: Default::default(), -1328 relay_mapped_addrs, -1329 discovery, -1330 discovery_user_data: RwLock::new(discovery_user_data), -1331 direct_addrs: Default::default(), -1332 net_report: Watchable::new((None, UpdateReason::None)), -1333 #[cfg(not(wasm_browser))] -1334 dns_resolver: dns_resolver.clone(), -1335 discovery_subscribers: DiscoverySubscribers::new(), -1336 metrics: metrics.clone(), -1337 local_addrs_watch: transports.local_addrs_watch(), -1338 #[cfg(not(wasm_browser))] -1339 ip_bind_addrs: transports.ip_bind_addrs(), -1340 }); -1341 -1342 let mut endpoint_config = quinn::EndpointConfig::default(); -1343 // Setting this to false means that quinn will ignore packets that have the QUIC fixed bit -1344 // set to 0. The fixed bit is the 3rd bit of the first byte of a packet. -1345 // For performance reasons and to not rewrite buffers we pass non-QUIC UDP packets straight -1346 // through to quinn. We set the first byte of the packet to zero, which makes quinn ignore -1347 // the packet if grease_quic_bit is set to false. -1348 endpoint_config.grease_quic_bit(false); -1349 -1350 let sender = transports.create_sender(msock.clone()); -1351 let local_addrs_watch = transports.local_addrs_watch(); -1352 let network_change_sender = transports.create_network_change_sender(); -1353 -1354 let endpoint = quinn::Endpoint::new_with_abstract_socket( -1355 endpoint_config, -1356 Some(server_config), -1357 Box::new(MagicUdpSocket { -1358 socket: msock.clone(), -1359 transports, -1360 }), -1361 #[cfg(not(wasm_browser))] -1362 Arc::new(quinn::TokioRuntime), -1363 #[cfg(wasm_browser)] -1364 Arc::new(crate::web_runtime::WebRuntime), -1365 ) -1366 .context(CreateQuinnEndpointSnafu)?; +1295 let relay_mapped_addrs = RelayMappedAddresses::default(); +1296 +1297 let (actor_sender, actor_receiver) = mpsc::channel(256); +1298 +1299 // load the node data +1300 let node_map = node_map.unwrap_or_default(); +1301 #[cfg(any(test, feature = "test-utils"))] +1302 let node_map = NodeMap::load_from_vec(node_map, path_selection, &metrics.magicsock); +1303 #[cfg(not(any(test, feature = "test-utils")))] +1304 let node_map = NodeMap::load_from_vec(node_map, &metrics.magicsock); +1305 +1306 let my_relay = Watchable::new(None); +1307 let ipv6_reported = Arc::new(AtomicBool::new(false)); +1308 +1309 let relay_transport = RelayTransport::new(RelayActorConfig { +1310 my_relay: my_relay.clone(), +1311 secret_key: secret_key.clone(), +1312 #[cfg(not(wasm_browser))] +1313 dns_resolver: dns_resolver.clone(), +1314 proxy_url: proxy_url.clone(), +1315 ipv6_reported: ipv6_reported.clone(), +1316 #[cfg(any(test, feature = "test-utils"))] +1317 insecure_skip_relay_cert_verify, +1318 metrics: metrics.magicsock.clone(), +1319 }); +1320 let relay_transports = vec![relay_transport]; +1321 +1322 let secret_encryption_key = secret_ed_box(secret_key.secret()); +1323 #[cfg(not(wasm_browser))] +1324 let ipv6 = ip_transports.iter().any(|t| t.bind_addr().is_ipv6()); +1325 +1326 #[cfg(not(wasm_browser))] +1327 let transports = Transports::new(ip_transports, relay_transports); +1328 #[cfg(wasm_browser)] +1329 let transports = Transports::new(relay_transports); +1330 +1331 let (disco, disco_receiver) = DiscoState::new(secret_encryption_key); +1332 +1333 let msock = Arc::new(MagicSock { +1334 public_key: secret_key.public(), +1335 closing: AtomicBool::new(false), +1336 closed: AtomicBool::new(false), +1337 disco, +1338 actor_sender: actor_sender.clone(), +1339 ipv6_reported, +1340 node_map, +1341 connection_map: Default::default(), +1342 relay_mapped_addrs, +1343 discovery, +1344 discovery_user_data: RwLock::new(discovery_user_data), +1345 direct_addrs: Default::default(), +1346 net_report: Watchable::new((None, UpdateReason::None)), +1347 #[cfg(not(wasm_browser))] +1348 dns_resolver: dns_resolver.clone(), +1349 discovery_subscribers: DiscoverySubscribers::new(), +1350 metrics: metrics.clone(), +1351 local_addrs_watch: transports.local_addrs_watch(), +1352 #[cfg(not(wasm_browser))] +1353 ip_bind_addrs: transports.ip_bind_addrs(), +1354 }); +1355 +1356 let mut endpoint_config = quinn::EndpointConfig::default(); +1357 // Setting this to false means that quinn will ignore packets that have the QUIC fixed bit +1358 // set to 0. The fixed bit is the 3rd bit of the first byte of a packet. +1359 // For performance reasons and to not rewrite buffers we pass non-QUIC UDP packets straight +1360 // through to quinn. We set the first byte of the packet to zero, which makes quinn ignore +1361 // the packet if grease_quic_bit is set to false. +1362 endpoint_config.grease_quic_bit(false); +1363 +1364 let sender = transports.create_sender(msock.clone()); +1365 let local_addrs_watch = transports.local_addrs_watch(); +1366 let network_change_sender = transports.create_network_change_sender(); 1367 -1368 let network_monitor = netmon::Monitor::new() -1369 .await -1370 .context(CreateNetmonMonitorSnafu)?; -1371 -1372 let qad_endpoint = endpoint.clone(); -1373 -1374 #[cfg(any(test, feature = "test-utils"))] -1375 let client_config = if insecure_skip_relay_cert_verify { -1376 iroh_relay::client::make_dangerous_client_config() -1377 } else { -1378 default_quic_client_config() -1379 }; -1380 #[cfg(not(any(test, feature = "test-utils")))] -1381 let client_config = default_quic_client_config(); -1382 -1383 let net_report_config = net_report::Options::default(); -1384 #[cfg(not(wasm_browser))] -1385 let net_report_config = net_report_config.quic_config(Some(QuicConfig { -1386 ep: qad_endpoint, -1387 client_config, -1388 ipv4: true, -1389 ipv6, -1390 })); -1391 -1392 #[cfg(any(test, feature = "test-utils"))] -1393 let net_report_config = -1394 net_report_config.insecure_skip_relay_cert_verify(insecure_skip_relay_cert_verify); -1395 -1396 let net_reporter = net_report::Client::new( -1397 #[cfg(not(wasm_browser))] -1398 dns_resolver, -1399 #[cfg(not(wasm_browser))] -1400 relay_map.clone(), -1401 net_report_config, -1402 metrics.net_report.clone(), -1403 ); -1404 -1405 let (direct_addr_done_tx, direct_addr_done_rx) = mpsc::channel(8); -1406 let direct_addr_update_state = DirectAddrUpdateState::new( -1407 msock.clone(), -1408 #[cfg(not(wasm_browser))] -1409 port_mapper, -1410 Arc::new(AsyncMutex::new(net_reporter)), -1411 relay_map, -1412 direct_addr_done_tx, -1413 ); -1414 -1415 let netmon_watcher = network_monitor.interface_state(); -1416 let actor = Actor { -1417 msg_receiver: actor_receiver, -1418 msock: msock.clone(), -1419 periodic_re_stun_timer: new_re_stun_timer(false), -1420 network_monitor, -1421 netmon_watcher, -1422 direct_addr_update_state, -1423 network_change_sender, -1424 direct_addr_done_rx, -1425 pending_call_me_maybes: Default::default(), -1426 disco_receiver, -1427 }; +1368 let endpoint = quinn::Endpoint::new_with_abstract_socket( +1369 endpoint_config, +1370 Some(server_config), +1371 Box::new(MagicUdpSocket { +1372 socket: msock.clone(), +1373 transports, +1374 }), +1375 #[cfg(not(wasm_browser))] +1376 Arc::new(quinn::TokioRuntime), +1377 #[cfg(wasm_browser)] +1378 Arc::new(crate::web_runtime::WebRuntime), +1379 ) +1380 .context(CreateQuinnEndpointSnafu)?; +1381 +1382 let network_monitor = netmon::Monitor::new() +1383 .await +1384 .context(CreateNetmonMonitorSnafu)?; +1385 +1386 let qad_endpoint = endpoint.clone(); +1387 +1388 #[cfg(any(test, feature = "test-utils"))] +1389 let client_config = if insecure_skip_relay_cert_verify { +1390 iroh_relay::client::make_dangerous_client_config() +1391 } else { +1392 default_quic_client_config() +1393 }; +1394 #[cfg(not(any(test, feature = "test-utils")))] +1395 let client_config = default_quic_client_config(); +1396 +1397 let net_report_config = net_report::Options::default(); +1398 #[cfg(not(wasm_browser))] +1399 let net_report_config = net_report_config.quic_config(Some(QuicConfig { +1400 ep: qad_endpoint, +1401 client_config, +1402 ipv4: true, +1403 ipv6, +1404 })); +1405 +1406 #[cfg(any(test, feature = "test-utils"))] +1407 let net_report_config = +1408 net_report_config.insecure_skip_relay_cert_verify(insecure_skip_relay_cert_verify); +1409 +1410 let net_reporter = net_report::Client::new( +1411 #[cfg(not(wasm_browser))] +1412 dns_resolver, +1413 #[cfg(not(wasm_browser))] +1414 relay_map.clone(), +1415 net_report_config, +1416 metrics.net_report.clone(), +1417 ); +1418 +1419 let (direct_addr_done_tx, direct_addr_done_rx) = mpsc::channel(8); +1420 let direct_addr_update_state = DirectAddrUpdateState::new( +1421 msock.clone(), +1422 #[cfg(not(wasm_browser))] +1423 port_mapper, +1424 Arc::new(AsyncMutex::new(net_reporter)), +1425 relay_map, +1426 direct_addr_done_tx, +1427 ); 1428 -1429 let actor_token = CancellationToken::new(); -1430 let token = actor_token.clone(); -1431 let actor_task = task::spawn( -1432 actor -1433 .run(token, local_addrs_watch, sender) -1434 .instrument(info_span!("actor")), -1435 ); -1436 -1437 let actor_task = Arc::new(Mutex::new(Some(AbortOnDropHandle::new(actor_task)))); -1438 -1439 Ok(Handle { -1440 msock, -1441 actor_task, -1442 endpoint, -1443 actor_token, -1444 }) -1445 } -1446 -1447 /// The underlying [`quinn::Endpoint`] -1448 pub fn endpoint(&self) -> &quinn::Endpoint { -1449 &self.endpoint -1450 } -1451 -1452 /// Closes the connection. -1453 /// -1454 /// Only the first close does anything. Any later closes return nil. -1455 /// Polling the socket ([`AsyncUdpSocket::poll_recv`]) will return [`Poll::Pending`] -1456 /// indefinitely after this call. -1457 #[instrument(skip_all)] -1458 pub(crate) async fn close(&self) { -1459 trace!(me = ?self.public_key, "magicsock closing..."); -1460 // Initiate closing all connections, and refuse future connections. -1461 self.endpoint.close(0u16.into(), b""); -1462 -1463 // In the history of this code, this call had been -1464 // - removed: https://github.com/n0-computer/iroh/pull/1753 -1465 // - then added back in: https://github.com/n0-computer/iroh/pull/2227/files#diff-ba27e40e2986a3919b20f6b412ad4fe63154af648610ea5d9ed0b5d5b0e2d780R573 -1466 // - then removed again: https://github.com/n0-computer/iroh/pull/3165 -1467 // and finally added back in together with this comment. -1468 // So before removing this call, please consider carefully. -1469 // Among other things, this call tries its best to make sure that any queued close frames -1470 // (e.g. via the call to `endpoint.close(...)` above), are flushed out to the sockets -1471 // *and acknowledged* (or time out with the "probe timeout" of usually 3 seconds). -1472 // This allows the other endpoints for these connections to be notified to release -1473 // their resources, or - depending on the protocol - that all data was received. -1474 // With the current quinn API, this is the only way to ensure protocol code can use -1475 // connection close codes, and close the endpoint properly. -1476 // If this call is skipped, then connections that protocols close just shortly before the -1477 // call to `Endpoint::close` will in most cases cause connection time-outs on remote ends. -1478 self.endpoint.wait_idle().await; -1479 -1480 if self.msock.is_closed() { -1481 return; -1482 } -1483 self.msock.closing.store(true, Ordering::Relaxed); -1484 self.actor_token.cancel(); -1485 -1486 // MutexGuard is not held across await points -1487 let task = self.actor_task.lock().expect("poisoned").take(); -1488 if let Some(task) = task { -1489 // give the tasks a moment to shutdown cleanly -1490 let shutdown_done = time::timeout(Duration::from_millis(100), async move { -1491 if let Err(err) = task.await { -1492 warn!("unexpected error in task shutdown: {:?}", err); -1493 } -1494 }) -1495 .await; -1496 match shutdown_done { -1497 Ok(_) => trace!("tasks finished in time, shutdown complete"), -1498 Err(time::Elapsed { .. }) => { -1499 // Dropping the task will abort itt -1500 warn!("tasks didn't finish in time, aborting"); -1501 } -1502 } -1503 } -1504 -1505 self.msock.closed.store(true, Ordering::SeqCst); -1506 -1507 trace!("magicsock closed"); -1508 } -1509} -1510 -1511fn default_quic_client_config() -> rustls::ClientConfig { -1512 // create a client config for the endpoint to use for QUIC address discovery -1513 let root_store = -1514 rustls::RootCertStore::from_iter(webpki_roots::TLS_SERVER_ROOTS.iter().cloned()); -1515 rustls::client::ClientConfig::builder_with_provider(Arc::new( -1516 rustls::crypto::ring::default_provider(), -1517 )) -1518 .with_safe_default_protocol_versions() -1519 .expect("ring supports these") -1520 .with_root_certificates(root_store) -1521 .with_no_client_auth() -1522} -1523 -1524#[derive(Debug)] -1525struct DiscoState { -1526 /// Encryption key for this node. -1527 secret_encryption_key: crypto_box::SecretKey, -1528 /// The state for an active DiscoKey. -1529 secrets: Mutex<HashMap<PublicKey, SharedSecret>>, -1530 /// Disco (ping) queue -1531 sender: mpsc::Sender<(SendAddr, PublicKey, disco::Message)>, -1532} -1533 -1534impl DiscoState { -1535 fn new( -1536 secret_encryption_key: crypto_box::SecretKey, -1537 ) -> (Self, mpsc::Receiver<(SendAddr, PublicKey, disco::Message)>) { -1538 let (disco_sender, disco_receiver) = mpsc::channel(256); -1539 -1540 ( -1541 Self { -1542 secret_encryption_key, -1543 secrets: Default::default(), -1544 sender: disco_sender, -1545 }, -1546 disco_receiver, -1547 ) -1548 } -1549 -1550 fn try_send(&self, dst: SendAddr, node_id: PublicKey, msg: disco::Message) -> bool { -1551 self.sender.try_send((dst, node_id, msg)).is_ok() -1552 } +1429 let netmon_watcher = network_monitor.interface_state(); +1430 let actor = Actor { +1431 msg_receiver: actor_receiver, +1432 msock: msock.clone(), +1433 periodic_re_stun_timer: new_re_stun_timer(false), +1434 network_monitor, +1435 netmon_watcher, +1436 direct_addr_update_state, +1437 network_change_sender, +1438 direct_addr_done_rx, +1439 pending_call_me_maybes: Default::default(), +1440 disco_receiver, +1441 }; +1442 +1443 let actor_token = CancellationToken::new(); +1444 let token = actor_token.clone(); +1445 let actor_task = task::spawn( +1446 actor +1447 .run(token, local_addrs_watch, sender) +1448 .instrument(info_span!("actor")), +1449 ); +1450 +1451 let actor_task = Arc::new(Mutex::new(Some(AbortOnDropHandle::new(actor_task)))); +1452 +1453 Ok(Handle { +1454 msock, +1455 actor_task, +1456 endpoint, +1457 actor_token, +1458 }) +1459 } +1460 +1461 /// The underlying [`quinn::Endpoint`] +1462 pub fn endpoint(&self) -> &quinn::Endpoint { +1463 &self.endpoint +1464 } +1465 +1466 /// Closes the connection. +1467 /// +1468 /// Only the first close does anything. Any later closes return nil. +1469 /// Polling the socket ([`AsyncUdpSocket::poll_recv`]) will return [`Poll::Pending`] +1470 /// indefinitely after this call. +1471 #[instrument(skip_all)] +1472 pub(crate) async fn close(&self) { +1473 trace!(me = ?self.public_key, "magicsock closing..."); +1474 // Initiate closing all connections, and refuse future connections. +1475 self.endpoint.close(0u16.into(), b""); +1476 +1477 // In the history of this code, this call had been +1478 // - removed: https://github.com/n0-computer/iroh/pull/1753 +1479 // - then added back in: https://github.com/n0-computer/iroh/pull/2227/files#diff-ba27e40e2986a3919b20f6b412ad4fe63154af648610ea5d9ed0b5d5b0e2d780R573 +1480 // - then removed again: https://github.com/n0-computer/iroh/pull/3165 +1481 // and finally added back in together with this comment. +1482 // So before removing this call, please consider carefully. +1483 // Among other things, this call tries its best to make sure that any queued close frames +1484 // (e.g. via the call to `endpoint.close(...)` above), are flushed out to the sockets +1485 // *and acknowledged* (or time out with the "probe timeout" of usually 3 seconds). +1486 // This allows the other endpoints for these connections to be notified to release +1487 // their resources, or - depending on the protocol - that all data was received. +1488 // With the current quinn API, this is the only way to ensure protocol code can use +1489 // connection close codes, and close the endpoint properly. +1490 // If this call is skipped, then connections that protocols close just shortly before the +1491 // call to `Endpoint::close` will in most cases cause connection time-outs on remote ends. +1492 self.endpoint.wait_idle().await; +1493 +1494 if self.msock.is_closed() { +1495 return; +1496 } +1497 self.msock.closing.store(true, Ordering::Relaxed); +1498 self.actor_token.cancel(); +1499 +1500 // MutexGuard is not held across await points +1501 let task = self.actor_task.lock().expect("poisoned").take(); +1502 if let Some(task) = task { +1503 // give the tasks a moment to shutdown cleanly +1504 let shutdown_done = time::timeout(Duration::from_millis(100), async move { +1505 if let Err(err) = task.await { +1506 warn!("unexpected error in task shutdown: {:?}", err); +1507 } +1508 }) +1509 .await; +1510 match shutdown_done { +1511 Ok(_) => trace!("tasks finished in time, shutdown complete"), +1512 Err(time::Elapsed { .. }) => { +1513 // Dropping the task will abort itt +1514 warn!("tasks didn't finish in time, aborting"); +1515 } +1516 } +1517 } +1518 +1519 self.msock.closed.store(true, Ordering::SeqCst); +1520 +1521 trace!("magicsock closed"); +1522 } +1523} +1524 +1525fn default_quic_client_config() -> rustls::ClientConfig { +1526 // create a client config for the endpoint to use for QUIC address discovery +1527 let root_store = +1528 rustls::RootCertStore::from_iter(webpki_roots::TLS_SERVER_ROOTS.iter().cloned()); +1529 rustls::client::ClientConfig::builder_with_provider(Arc::new( +1530 rustls::crypto::ring::default_provider(), +1531 )) +1532 .with_safe_default_protocol_versions() +1533 .expect("ring supports these") +1534 .with_root_certificates(root_store) +1535 .with_no_client_auth() +1536} +1537 +1538#[derive(Debug)] +1539struct DiscoState { +1540 /// Encryption key for this node. +1541 secret_encryption_key: crypto_box::SecretKey, +1542 /// The state for an active DiscoKey. +1543 secrets: Mutex<HashMap<PublicKey, SharedSecret>>, +1544 /// Disco (ping) queue +1545 sender: mpsc::Sender<(SendAddr, PublicKey, disco::Message)>, +1546} +1547 +1548impl DiscoState { +1549 fn new( +1550 secret_encryption_key: crypto_box::SecretKey, +1551 ) -> (Self, mpsc::Receiver<(SendAddr, PublicKey, disco::Message)>) { +1552 let (disco_sender, disco_receiver) = mpsc::channel(256); 1553 -1554 fn encode_and_seal( -1555 &self, -1556 this_node_id: NodeId, -1557 other_node_id: NodeId, -1558 msg: &disco::Message, -1559 ) -> Bytes { -1560 let mut seal = msg.as_bytes(); -1561 self.get_secret(other_node_id, |secret| secret.seal(&mut seal)); -1562 disco::encode_message(&this_node_id, seal).into() -1563 } -1564 -1565 fn unseal_and_decode( -1566 &self, -1567 node_id: PublicKey, -1568 sealed_box: &[u8], -1569 ) -> Result<disco::Message, DiscoBoxError> { -1570 let mut sealed_box = sealed_box.to_vec(); -1571 self.get_secret(node_id, |secret| secret.open(&mut sealed_box)) -1572 .context(OpenSnafu)?; -1573 disco::Message::from_bytes(&sealed_box).context(ParseSnafu) -1574 } -1575 -1576 fn get_secret<F, T>(&self, node_id: PublicKey, cb: F) -> T -1577 where -1578 F: FnOnce(&mut SharedSecret) -> T, -1579 { -1580 let mut inner = self.secrets.lock().expect("poisoned"); -1581 let x = inner.entry(node_id).or_insert_with(|| { -1582 let public_key = public_ed_box(&node_id.public()); -1583 SharedSecret::new(&self.secret_encryption_key, &public_key) -1584 }); -1585 cb(x) -1586 } -1587} -1588 -1589#[allow(missing_docs)] -1590#[common_fields({ -1591 backtrace: Option<snafu::Backtrace>, -1592 #[snafu(implicit)] -1593 span_trace: n0_snafu::SpanTrace, -1594})] -1595#[derive(Debug, Snafu)] -1596#[non_exhaustive] -1597enum DiscoBoxError { -1598 #[snafu(display("Failed to open crypto box"))] -1599 Open { -1600 #[snafu(source(from(DecryptionError, Box::new)))] -1601 source: Box<DecryptionError>, -1602 }, -1603 #[snafu(display("Failed to parse disco message"))] -1604 Parse { -1605 #[snafu(source(from(disco::ParseError, Box::new)))] -1606 source: Box<disco::ParseError>, -1607 }, -1608} -1609 -1610#[derive(Debug)] -1611struct MagicUdpSocket { -1612 socket: Arc<MagicSock>, -1613 transports: Transports, -1614} -1615 -1616impl AsyncUdpSocket for MagicUdpSocket { -1617 fn create_sender(&self) -> Pin<Box<dyn quinn::UdpSender>> { -1618 Box::pin(self.transports.create_sender(self.socket.clone())) -1619 } -1620 -1621 /// NOTE: Receiving on a closed socket will return [`Poll::Pending`] indefinitely. -1622 fn poll_recv( -1623 &mut self, -1624 cx: &mut Context, -1625 bufs: &mut [io::IoSliceMut<'_>], -1626 metas: &mut [quinn_udp::RecvMeta], -1627 ) -> Poll<io::Result<usize>> { -1628 self.transports.poll_recv(cx, bufs, metas, &self.socket) -1629 } -1630 -1631 #[cfg(not(wasm_browser))] -1632 fn local_addr(&self) -> io::Result<SocketAddr> { -1633 let addrs: Vec<_> = self -1634 .transports -1635 .local_addrs() -1636 .into_iter() -1637 .filter_map(|addr| { -1638 let addr: SocketAddr = addr.into_socket_addr()?; -1639 Some(addr) -1640 }) -1641 .collect(); -1642 -1643 if let Some(addr) = addrs.iter().find(|addr| addr.is_ipv6()) { -1644 return Ok(*addr); -1645 } -1646 if let Some(SocketAddr::V4(addr)) = addrs.first() { -1647 // Pretend to be IPv6, because our `MappedAddr`s need to be IPv6. -1648 let ip = addr.ip().to_ipv6_mapped().into(); -1649 return Ok(SocketAddr::new(ip, addr.port())); -1650 } -1651 -1652 Err(io::Error::other("no valid address available")) -1653 } -1654 -1655 #[cfg(wasm_browser)] -1656 fn local_addr(&self) -> io::Result<SocketAddr> { -1657 // Again, we need to pretend we're IPv6, because of our `MappedAddr`s. -1658 Ok(SocketAddr::new(std::net::Ipv6Addr::LOCALHOST.into(), 0)) -1659 } -1660 -1661 fn max_receive_segments(&self) -> usize { -1662 self.transports.max_receive_segments() -1663 } -1664 -1665 fn may_fragment(&self) -> bool { -1666 self.transports.may_fragment() +1554 ( +1555 Self { +1556 secret_encryption_key, +1557 secrets: Default::default(), +1558 sender: disco_sender, +1559 }, +1560 disco_receiver, +1561 ) +1562 } +1563 +1564 fn try_send(&self, dst: SendAddr, node_id: PublicKey, msg: disco::Message) -> bool { +1565 self.sender.try_send((dst, node_id, msg)).is_ok() +1566 } +1567 +1568 fn encode_and_seal( +1569 &self, +1570 this_node_id: NodeId, +1571 other_node_id: NodeId, +1572 msg: &disco::Message, +1573 ) -> Bytes { +1574 let mut seal = msg.as_bytes(); +1575 self.get_secret(other_node_id, |secret| secret.seal(&mut seal)); +1576 disco::encode_message(&this_node_id, seal).into() +1577 } +1578 +1579 fn unseal_and_decode( +1580 &self, +1581 node_id: PublicKey, +1582 sealed_box: &[u8], +1583 ) -> Result<disco::Message, DiscoBoxError> { +1584 let mut sealed_box = sealed_box.to_vec(); +1585 self.get_secret(node_id, |secret| secret.open(&mut sealed_box)) +1586 .context(OpenSnafu)?; +1587 disco::Message::from_bytes(&sealed_box).context(ParseSnafu) +1588 } +1589 +1590 fn get_secret<F, T>(&self, node_id: PublicKey, cb: F) -> T +1591 where +1592 F: FnOnce(&mut SharedSecret) -> T, +1593 { +1594 let mut inner = self.secrets.lock().expect("poisoned"); +1595 let x = inner.entry(node_id).or_insert_with(|| { +1596 let public_key = public_ed_box(&node_id.public()); +1597 SharedSecret::new(&self.secret_encryption_key, &public_key) +1598 }); +1599 cb(x) +1600 } +1601} +1602 +1603#[allow(missing_docs)] +1604#[common_fields({ +1605 backtrace: Option<snafu::Backtrace>, +1606 #[snafu(implicit)] +1607 span_trace: n0_snafu::SpanTrace, +1608})] +1609#[derive(Debug, Snafu)] +1610#[non_exhaustive] +1611enum DiscoBoxError { +1612 #[snafu(display("Failed to open crypto box"))] +1613 Open { +1614 #[snafu(source(from(DecryptionError, Box::new)))] +1615 source: Box<DecryptionError>, +1616 }, +1617 #[snafu(display("Failed to parse disco message"))] +1618 Parse { +1619 #[snafu(source(from(disco::ParseError, Box::new)))] +1620 source: Box<disco::ParseError>, +1621 }, +1622} +1623 +1624#[derive(Debug)] +1625struct MagicUdpSocket { +1626 socket: Arc<MagicSock>, +1627 transports: Transports, +1628} +1629 +1630impl AsyncUdpSocket for MagicUdpSocket { +1631 fn create_sender(&self) -> Pin<Box<dyn quinn::UdpSender>> { +1632 Box::pin(self.transports.create_sender(self.socket.clone())) +1633 } +1634 +1635 /// NOTE: Receiving on a closed socket will return [`Poll::Pending`] indefinitely. +1636 fn poll_recv( +1637 &mut self, +1638 cx: &mut Context, +1639 bufs: &mut [io::IoSliceMut<'_>], +1640 metas: &mut [quinn_udp::RecvMeta], +1641 ) -> Poll<io::Result<usize>> { +1642 self.transports.poll_recv(cx, bufs, metas, &self.socket) +1643 } +1644 +1645 #[cfg(not(wasm_browser))] +1646 fn local_addr(&self) -> io::Result<SocketAddr> { +1647 let addrs: Vec<_> = self +1648 .transports +1649 .local_addrs() +1650 .into_iter() +1651 .filter_map(|addr| { +1652 let addr: SocketAddr = addr.into_socket_addr()?; +1653 Some(addr) +1654 }) +1655 .collect(); +1656 +1657 if let Some(addr) = addrs.iter().find(|addr| addr.is_ipv6()) { +1658 return Ok(*addr); +1659 } +1660 if let Some(SocketAddr::V4(addr)) = addrs.first() { +1661 // Pretend to be IPv6, because our `MappedAddr`s need to be IPv6. +1662 let ip = addr.ip().to_ipv6_mapped().into(); +1663 return Ok(SocketAddr::new(ip, addr.port())); +1664 } +1665 +1666 Err(io::Error::other("no valid address available")) 1667 } -1668} -1669 -1670#[derive(Debug)] -1671enum ActorMessage { -1672 PingActions(Vec<PingAction>), -1673 NetworkChange, -1674 ScheduleDirectAddrUpdate(UpdateReason, Option<(NodeId, RelayUrl)>), -1675 #[cfg(test)] -1676 ForceNetworkChange(bool), -1677} +1668 +1669 #[cfg(wasm_browser)] +1670 fn local_addr(&self) -> io::Result<SocketAddr> { +1671 // Again, we need to pretend we're IPv6, because of our `MappedAddr`s. +1672 Ok(SocketAddr::new(std::net::Ipv6Addr::LOCALHOST.into(), 0)) +1673 } +1674 +1675 fn max_receive_segments(&self) -> usize { +1676 self.transports.max_receive_segments() +1677 } 1678 -1679struct Actor { -1680 msock: Arc<MagicSock>, -1681 msg_receiver: mpsc::Receiver<ActorMessage>, -1682 /// When set, is an AfterFunc timer that will call MagicSock::do_periodic_stun. -1683 periodic_re_stun_timer: time::Interval, -1684 -1685 network_monitor: netmon::Monitor, -1686 netmon_watcher: n0_watcher::Direct<netmon::State>, -1687 network_change_sender: transports::NetworkChangeSender, -1688 /// Indicates the direct addr update state. -1689 direct_addr_update_state: DirectAddrUpdateState, -1690 direct_addr_done_rx: mpsc::Receiver<()>, -1691 -1692 /// List of CallMeMaybe disco messages that should be sent out after -1693 /// the next endpoint update completes -1694 pending_call_me_maybes: HashMap<PublicKey, RelayUrl>, -1695 disco_receiver: mpsc::Receiver<(SendAddr, PublicKey, disco::Message)>, -1696} -1697 -1698#[cfg(not(wasm_browser))] -1699fn bind_ip( -1700 addr_v4: SocketAddrV4, -1701 addr_v6: Option<SocketAddrV6>, -1702 metrics: &EndpointMetrics, -1703) -> io::Result<(Vec<IpTransport>, portmapper::Client)> { -1704 let port_mapper = -1705 portmapper::Client::with_metrics(Default::default(), metrics.portmapper.clone()); -1706 -1707 let v4 = Arc::new(bind_with_fallback(SocketAddr::V4(addr_v4))?); -1708 let ip4_port = v4.local_addr()?.port(); -1709 let ip6_port = ip4_port.checked_add(1).unwrap_or(ip4_port - 1); -1710 -1711 let addr_v6 = -1712 addr_v6.unwrap_or_else(|| SocketAddrV6::new(Ipv6Addr::UNSPECIFIED, ip6_port, 0, 0)); -1713 -1714 let v6 = match bind_with_fallback(SocketAddr::V6(addr_v6)) { -1715 Ok(sock) => Some(Arc::new(sock)), -1716 Err(err) => { -1717 info!("bind ignoring IPv6 bind failure: {:?}", err); -1718 None -1719 } -1720 }; -1721 -1722 let port = v4.local_addr().map_or(0, |p| p.port()); -1723 -1724 let mut ip = vec![IpTransport::new( -1725 addr_v4.into(), -1726 v4, -1727 metrics.magicsock.clone(), -1728 )]; -1729 if let Some(v6) = v6 { -1730 ip.push(IpTransport::new( -1731 addr_v6.into(), -1732 v6, -1733 metrics.magicsock.clone(), -1734 )) -1735 } -1736 -1737 // NOTE: we can end up with a zero port if `netwatch::UdpSocket::socket_addr` fails -1738 match port.try_into() { -1739 Ok(non_zero_port) => { -1740 port_mapper.update_local_port(non_zero_port); -1741 } -1742 Err(_zero_port) => debug!("Skipping port mapping with zero local port"), -1743 } -1744 -1745 Ok((ip, port_mapper)) -1746} -1747 -1748impl Actor { -1749 async fn run( -1750 mut self, -1751 shutdown_token: CancellationToken, -1752 mut watcher: impl Watcher<Value = Vec<transports::Addr>> + Send + Sync, -1753 sender: UdpSender, -1754 ) { -1755 // Initialize addresses -1756 #[cfg(not(wasm_browser))] -1757 self.update_direct_addresses(None); +1679 fn may_fragment(&self) -> bool { +1680 self.transports.may_fragment() +1681 } +1682} +1683 +1684#[derive(Debug)] +1685enum ActorMessage { +1686 PingActions(Vec<PingAction>), +1687 NetworkChange, +1688 ScheduleDirectAddrUpdate(UpdateReason, Option<(NodeId, RelayUrl)>), +1689 #[cfg(test)] +1690 ForceNetworkChange(bool), +1691} +1692 +1693struct Actor { +1694 msock: Arc<MagicSock>, +1695 msg_receiver: mpsc::Receiver<ActorMessage>, +1696 /// When set, is an AfterFunc timer that will call MagicSock::do_periodic_stun. +1697 periodic_re_stun_timer: time::Interval, +1698 +1699 network_monitor: netmon::Monitor, +1700 netmon_watcher: n0_watcher::Direct<netmon::State>, +1701 network_change_sender: transports::NetworkChangeSender, +1702 /// Indicates the direct addr update state. +1703 direct_addr_update_state: DirectAddrUpdateState, +1704 direct_addr_done_rx: mpsc::Receiver<()>, +1705 +1706 /// List of CallMeMaybe disco messages that should be sent out after +1707 /// the next endpoint update completes +1708 pending_call_me_maybes: HashMap<PublicKey, RelayUrl>, +1709 disco_receiver: mpsc::Receiver<(SendAddr, PublicKey, disco::Message)>, +1710} +1711 +1712#[cfg(not(wasm_browser))] +1713fn bind_ip( +1714 addr_v4: SocketAddrV4, +1715 addr_v6: Option<SocketAddrV6>, +1716 metrics: &EndpointMetrics, +1717) -> io::Result<(Vec<IpTransport>, portmapper::Client)> { +1718 let port_mapper = +1719 portmapper::Client::with_metrics(Default::default(), metrics.portmapper.clone()); +1720 +1721 let v4 = Arc::new(bind_with_fallback(SocketAddr::V4(addr_v4))?); +1722 let ip4_port = v4.local_addr()?.port(); +1723 let ip6_port = ip4_port.checked_add(1).unwrap_or(ip4_port - 1); +1724 +1725 let addr_v6 = +1726 addr_v6.unwrap_or_else(|| SocketAddrV6::new(Ipv6Addr::UNSPECIFIED, ip6_port, 0, 0)); +1727 +1728 let v6 = match bind_with_fallback(SocketAddr::V6(addr_v6)) { +1729 Ok(sock) => Some(Arc::new(sock)), +1730 Err(err) => { +1731 info!("bind ignoring IPv6 bind failure: {:?}", err); +1732 None +1733 } +1734 }; +1735 +1736 let port = v4.local_addr().map_or(0, |p| p.port()); +1737 +1738 let mut ip = vec![IpTransport::new( +1739 addr_v4.into(), +1740 v4, +1741 metrics.magicsock.clone(), +1742 )]; +1743 if let Some(v6) = v6 { +1744 ip.push(IpTransport::new( +1745 addr_v6.into(), +1746 v6, +1747 metrics.magicsock.clone(), +1748 )) +1749 } +1750 +1751 // NOTE: we can end up with a zero port if `netwatch::UdpSocket::socket_addr` fails +1752 match port.try_into() { +1753 Ok(non_zero_port) => { +1754 port_mapper.update_local_port(non_zero_port); +1755 } +1756 Err(_zero_port) => debug!("Skipping port mapping with zero local port"), +1757 } 1758 -1759 // Setup network monitoring -1760 let mut current_netmon_state = self.netmon_watcher.get().expect("missing network state"); +1759 Ok((ip, port_mapper)) +1760} 1761 -1762 #[cfg(not(wasm_browser))] -1763 let mut direct_addr_heartbeat_timer = time::interval(HEARTBEAT_INTERVAL); -1764 -1765 #[cfg(not(wasm_browser))] -1766 let mut portmap_watcher = self -1767 .direct_addr_update_state -1768 .port_mapper -1769 .watch_external_address(); -1770 -1771 let mut discovery_events: BoxStream<DiscoveryItem> = Box::pin(n0_future::stream::empty()); -1772 if let Some(d) = self.msock.discovery() { -1773 if let Some(events) = d.subscribe() { -1774 discovery_events = events; -1775 } -1776 } -1777 -1778 let mut receiver_closed = false; -1779 #[cfg_attr(wasm_browser, allow(unused_mut))] -1780 let mut portmap_watcher_closed = false; -1781 -1782 let mut net_report_watcher = self.msock.net_report.watch(); -1783 -1784 loop { -1785 self.msock.metrics.magicsock.actor_tick_main.inc(); -1786 #[cfg(not(wasm_browser))] -1787 let portmap_watcher_changed = portmap_watcher.changed(); -1788 #[cfg(wasm_browser)] -1789 let portmap_watcher_changed = n0_future::future::pending(); -1790 -1791 #[cfg(not(wasm_browser))] -1792 let direct_addr_heartbeat_timer_tick = direct_addr_heartbeat_timer.tick(); -1793 #[cfg(wasm_browser)] -1794 let direct_addr_heartbeat_timer_tick = n0_future::future::pending(); +1762impl Actor { +1763 async fn run( +1764 mut self, +1765 shutdown_token: CancellationToken, +1766 mut watcher: impl Watcher<Value = Vec<transports::Addr>> + Send + Sync, +1767 sender: UdpSender, +1768 ) { +1769 // Initialize addresses +1770 #[cfg(not(wasm_browser))] +1771 self.update_direct_addresses(None); +1772 +1773 // Setup network monitoring +1774 let mut current_netmon_state = self.netmon_watcher.get().expect("missing network state"); +1775 +1776 #[cfg(not(wasm_browser))] +1777 let mut direct_addr_heartbeat_timer = time::interval(HEARTBEAT_INTERVAL); +1778 +1779 #[cfg(not(wasm_browser))] +1780 let mut portmap_watcher = self +1781 .direct_addr_update_state +1782 .port_mapper +1783 .watch_external_address(); +1784 +1785 let mut discovery_events: BoxStream<DiscoveryItem> = Box::pin(n0_future::stream::empty()); +1786 if let Some(d) = self.msock.discovery() { +1787 if let Some(events) = d.subscribe() { +1788 discovery_events = events; +1789 } +1790 } +1791 +1792 let mut receiver_closed = false; +1793 #[cfg_attr(wasm_browser, allow(unused_mut))] +1794 let mut portmap_watcher_closed = false; 1795 -1796 tokio::select! { -1797 _ = shutdown_token.cancelled() => { -1798 debug!("shutting down"); -1799 return; -1800 } -1801 msg = self.msg_receiver.recv(), if !receiver_closed => { -1802 let Some(msg) = msg else { -1803 trace!("tick: magicsock receiver closed"); -1804 self.msock.metrics.magicsock.actor_tick_other.inc(); -1805 -1806 receiver_closed = true; -1807 continue; -1808 }; +1796 let mut net_report_watcher = self.msock.net_report.watch(); +1797 +1798 loop { +1799 self.msock.metrics.magicsock.actor_tick_main.inc(); +1800 #[cfg(not(wasm_browser))] +1801 let portmap_watcher_changed = portmap_watcher.changed(); +1802 #[cfg(wasm_browser)] +1803 let portmap_watcher_changed = n0_future::future::pending(); +1804 +1805 #[cfg(not(wasm_browser))] +1806 let direct_addr_heartbeat_timer_tick = direct_addr_heartbeat_timer.tick(); +1807 #[cfg(wasm_browser)] +1808 let direct_addr_heartbeat_timer_tick = n0_future::future::pending(); 1809 -1810 trace!(?msg, "tick: msg"); -1811 self.msock.metrics.magicsock.actor_tick_msg.inc(); -1812 self.handle_actor_message(msg, &sender).await; -1813 } -1814 tick = self.periodic_re_stun_timer.tick() => { -1815 trace!("tick: re_stun {:?}", tick); -1816 self.msock.metrics.magicsock.actor_tick_re_stun.inc(); -1817 self.re_stun(UpdateReason::Periodic); -1818 } -1819 new_addr = watcher.updated() => { -1820 match new_addr { -1821 Ok(addrs) => { -1822 if !addrs.is_empty() { -1823 trace!(?addrs, "local addrs"); -1824 self.msock.publish_my_addr(); -1825 } -1826 } -1827 Err(_) => { -1828 warn!("local addr watcher stopped"); -1829 } -1830 } -1831 } -1832 report = net_report_watcher.updated() => { -1833 match report { -1834 Ok((report, _)) => { -1835 self.handle_net_report_report(report); -1836 #[cfg(not(wasm_browser))] -1837 { -1838 self.periodic_re_stun_timer = new_re_stun_timer(true); +1810 tokio::select! { +1811 _ = shutdown_token.cancelled() => { +1812 debug!("shutting down"); +1813 return; +1814 } +1815 msg = self.msg_receiver.recv(), if !receiver_closed => { +1816 let Some(msg) = msg else { +1817 trace!("tick: magicsock receiver closed"); +1818 self.msock.metrics.magicsock.actor_tick_other.inc(); +1819 +1820 receiver_closed = true; +1821 continue; +1822 }; +1823 +1824 trace!(?msg, "tick: msg"); +1825 self.msock.metrics.magicsock.actor_tick_msg.inc(); +1826 self.handle_actor_message(msg, &sender).await; +1827 } +1828 tick = self.periodic_re_stun_timer.tick() => { +1829 trace!("tick: re_stun {:?}", tick); +1830 self.msock.metrics.magicsock.actor_tick_re_stun.inc(); +1831 self.re_stun(UpdateReason::Periodic); +1832 } +1833 new_addr = watcher.updated() => { +1834 match new_addr { +1835 Ok(addrs) => { +1836 if !addrs.is_empty() { +1837 trace!(?addrs, "local addrs"); +1838 self.msock.publish_my_addr(); 1839 } 1840 } 1841 Err(_) => { -1842 warn!("net report watcher stopped"); +1842 warn!("local addr watcher stopped"); 1843 } 1844 } 1845 } -1846 reason = self.direct_addr_done_rx.recv() => { -1847 match reason { -1848 Some(()) => { -1849 // check if a new run needs to be scheduled -1850 let state = self.netmon_watcher.get().expect("disconnected"); -1851 self.direct_addr_update_state.try_run(state.into()); -1852 } -1853 None => { -1854 warn!("direct addr watcher died"); -1855 } -1856 } -1857 } -1858 change = portmap_watcher_changed, if !portmap_watcher_closed => { -1859 #[cfg(not(wasm_browser))] -1860 { -1861 if change.is_err() { -1862 trace!("tick: portmap watcher closed"); -1863 self.msock.metrics.magicsock.actor_tick_other.inc(); -1864 -1865 portmap_watcher_closed = true; -1866 continue; -1867 } -1868 -1869 trace!("tick: portmap changed"); -1870 self.msock.metrics.magicsock.actor_tick_portmap_changed.inc(); -1871 let new_external_address = *portmap_watcher.borrow(); -1872 debug!("external address updated: {new_external_address:?}"); -1873 self.re_stun(UpdateReason::PortmapUpdated); -1874 } -1875 #[cfg(wasm_browser)] -1876 let _unused_in_browsers = change; -1877 }, -1878 _ = direct_addr_heartbeat_timer_tick => { -1879 #[cfg(not(wasm_browser))] -1880 { -1881 trace!( -1882 "tick: direct addr heartbeat {} direct addrs", -1883 self.msock.node_map.node_count(), -1884 ); -1885 self.msock.metrics.magicsock.actor_tick_direct_addr_heartbeat.inc(); -1886 // TODO: this might trigger too many packets at once, pace this -1887 -1888 self.msock.node_map.prune_inactive(); -1889 let msgs = self.msock.node_map.nodes_stayin_alive(); -1890 self.handle_ping_actions(&sender, msgs).await; -1891 } -1892 } -1893 state = self.netmon_watcher.updated() => { -1894 let Ok(state) = state else { -1895 trace!("tick: link change receiver closed"); -1896 self.msock.metrics.magicsock.actor_tick_other.inc(); -1897 continue; -1898 }; -1899 let is_major = state.is_major_change(&current_netmon_state); -1900 current_netmon_state = state; -1901 trace!("tick: link change {}", is_major); -1902 self.msock.metrics.magicsock.actor_link_change.inc(); -1903 self.handle_network_change(is_major).await; -1904 } -1905 // Even if `discovery_events` yields `None`, it could begin to yield -1906 // `Some` again in the future, so we don't want to disable this branch -1907 // forever like we do with the other branches that yield `Option`s -1908 Some(discovery_item) = discovery_events.next() => { -1909 trace!("tick: discovery event, address discovered: {discovery_item:?}"); -1910 let provenance = discovery_item.provenance(); -1911 let node_addr = discovery_item.to_node_addr(); -1912 if let Err(e) = self.msock.add_node_addr( -1913 node_addr, -1914 Source::Discovery { -1915 name: provenance.to_string() -1916 }) { -1917 let node_addr = discovery_item.to_node_addr(); -1918 warn!(?node_addr, "unable to add discovered node address to the node map: {e:?}"); -1919 } -1920 // Send the discovery item to the subscribers of the discovery broadcast stream. -1921 self.msock.discovery_subscribers.send(discovery_item); -1922 } -1923 Some((dst, dst_key, msg)) = self.disco_receiver.recv() => { -1924 if let Err(err) = self.msock.send_disco_message(&sender, dst.clone(), dst_key, msg).await { -1925 warn!(%dst, node = %dst_key.fmt_short(), ?err, "failed to send disco message (UDP)"); -1926 } -1927 } -1928 } -1929 } -1930 } -1931 -1932 async fn handle_network_change(&mut self, is_major: bool) { -1933 debug!("link change detected: major? {}", is_major); -1934 -1935 if is_major { -1936 if let Err(err) = self.network_change_sender.rebind() { -1937 warn!("failed to rebind transports: {:?}", err); -1938 } -1939 -1940 #[cfg(not(wasm_browser))] -1941 self.msock.dns_resolver.reset().await; -1942 self.re_stun(UpdateReason::LinkChangeMajor); -1943 self.reset_endpoint_states(); -1944 } else { -1945 self.re_stun(UpdateReason::LinkChangeMinor); -1946 } -1947 } +1846 report = net_report_watcher.updated() => { +1847 match report { +1848 Ok((report, _)) => { +1849 self.handle_net_report_report(report); +1850 #[cfg(not(wasm_browser))] +1851 { +1852 self.periodic_re_stun_timer = new_re_stun_timer(true); +1853 } +1854 } +1855 Err(_) => { +1856 warn!("net report watcher stopped"); +1857 } +1858 } +1859 } +1860 reason = self.direct_addr_done_rx.recv() => { +1861 match reason { +1862 Some(()) => { +1863 // check if a new run needs to be scheduled +1864 let state = self.netmon_watcher.get().expect("disconnected"); +1865 self.direct_addr_update_state.try_run(state.into()); +1866 } +1867 None => { +1868 warn!("direct addr watcher died"); +1869 } +1870 } +1871 } +1872 change = portmap_watcher_changed, if !portmap_watcher_closed => { +1873 #[cfg(not(wasm_browser))] +1874 { +1875 if change.is_err() { +1876 trace!("tick: portmap watcher closed"); +1877 self.msock.metrics.magicsock.actor_tick_other.inc(); +1878 +1879 portmap_watcher_closed = true; +1880 continue; +1881 } +1882 +1883 trace!("tick: portmap changed"); +1884 self.msock.metrics.magicsock.actor_tick_portmap_changed.inc(); +1885 let new_external_address = *portmap_watcher.borrow(); +1886 debug!("external address updated: {new_external_address:?}"); +1887 self.re_stun(UpdateReason::PortmapUpdated); +1888 } +1889 #[cfg(wasm_browser)] +1890 let _unused_in_browsers = change; +1891 }, +1892 _ = direct_addr_heartbeat_timer_tick => { +1893 #[cfg(not(wasm_browser))] +1894 { +1895 trace!( +1896 "tick: direct addr heartbeat {} direct addrs", +1897 self.msock.node_map.node_count(), +1898 ); +1899 self.msock.metrics.magicsock.actor_tick_direct_addr_heartbeat.inc(); +1900 // TODO: this might trigger too many packets at once, pace this +1901 +1902 self.msock.node_map.prune_inactive(); +1903 let msgs = self.msock.node_map.nodes_stayin_alive(); +1904 self.handle_ping_actions(&sender, msgs).await; +1905 } +1906 } +1907 state = self.netmon_watcher.updated() => { +1908 let Ok(state) = state else { +1909 trace!("tick: link change receiver closed"); +1910 self.msock.metrics.magicsock.actor_tick_other.inc(); +1911 continue; +1912 }; +1913 let is_major = state.is_major_change(&current_netmon_state); +1914 current_netmon_state = state; +1915 trace!("tick: link change {}", is_major); +1916 self.msock.metrics.magicsock.actor_link_change.inc(); +1917 self.handle_network_change(is_major).await; +1918 } +1919 // Even if `discovery_events` yields `None`, it could begin to yield +1920 // `Some` again in the future, so we don't want to disable this branch +1921 // forever like we do with the other branches that yield `Option`s +1922 Some(discovery_item) = discovery_events.next() => { +1923 trace!("tick: discovery event, address discovered: {discovery_item:?}"); +1924 let provenance = discovery_item.provenance(); +1925 let node_addr = discovery_item.to_node_addr(); +1926 if let Err(e) = self.msock.add_node_addr( +1927 node_addr, +1928 Source::Discovery { +1929 name: provenance.to_string() +1930 }) { +1931 let node_addr = discovery_item.to_node_addr(); +1932 warn!(?node_addr, "unable to add discovered node address to the node map: {e:?}"); +1933 } +1934 // Send the discovery item to the subscribers of the discovery broadcast stream. +1935 self.msock.discovery_subscribers.send(discovery_item); +1936 } +1937 Some((dst, dst_key, msg)) = self.disco_receiver.recv() => { +1938 if let Err(err) = self.msock.send_disco_message(&sender, dst.clone(), dst_key, msg).await { +1939 warn!(%dst, node = %dst_key.fmt_short(), ?err, "failed to send disco message (UDP)"); +1940 } +1941 } +1942 } +1943 } +1944 } +1945 +1946 async fn handle_network_change(&mut self, is_major: bool) { +1947 debug!("link change detected: major? {}", is_major); 1948 -1949 fn re_stun(&mut self, why: UpdateReason) { -1950 let state = self.netmon_watcher.get().expect("disconnected"); -1951 self.direct_addr_update_state -1952 .schedule_run(why, state.into()); -1953 } -1954 -1955 #[instrument(skip_all)] -1956 async fn handle_ping_actions(&mut self, sender: &UdpSender, msgs: Vec<PingAction>) { -1957 if let Err(err) = self.msock.send_ping_actions(sender, msgs).await { -1958 warn!("Failed to send ping actions: {err:#}"); -1959 } -1960 } -1961 -1962 /// Processes an incoming actor message. -1963 /// -1964 /// Returns `true` if it was a shutdown. -1965 async fn handle_actor_message(&mut self, msg: ActorMessage, sender: &UdpSender) { -1966 match msg { -1967 ActorMessage::NetworkChange => { -1968 self.network_monitor.network_change().await.ok(); -1969 } -1970 ActorMessage::ScheduleDirectAddrUpdate(why, data) => { -1971 if let Some((node, url)) = data { -1972 self.pending_call_me_maybes.insert(node, url); -1973 } -1974 let state = self.netmon_watcher.get().expect("disconnected"); -1975 self.direct_addr_update_state -1976 .schedule_run(why, state.into()); -1977 } -1978 #[cfg(test)] -1979 ActorMessage::ForceNetworkChange(is_major) => { -1980 self.handle_network_change(is_major).await; -1981 } -1982 ActorMessage::PingActions(ping_actions) => { -1983 self.handle_ping_actions(sender, ping_actions).await; -1984 } -1985 } -1986 } -1987 -1988 /// Updates the direct addresses of this magic socket. -1989 /// -1990 /// Updates the [`DiscoveredDirectAddrs`] of this [`MagicSock`] with the current set of -1991 /// direct addresses from: -1992 /// -1993 /// - The portmapper. -1994 /// - A net_report report. -1995 /// - The local interfaces IP addresses. -1996 #[cfg(not(wasm_browser))] -1997 fn update_direct_addresses(&mut self, net_report_report: Option<&net_report::Report>) { -1998 let portmap_watcher = self -1999 .direct_addr_update_state -2000 .port_mapper -2001 .watch_external_address(); -2002 -2003 // We only want to have one DirectAddr for each SocketAddr we have. So we store -2004 // this as a map of SocketAddr -> DirectAddrType. At the end we will construct a -2005 // DirectAddr from each entry. -2006 let mut addrs: BTreeMap<SocketAddr, DirectAddrType> = BTreeMap::new(); -2007 -2008 // First add PortMapper provided addresses. -2009 let maybe_port_mapped = *portmap_watcher.borrow(); -2010 if let Some(portmap_ext) = maybe_port_mapped.map(SocketAddr::V4) { -2011 addrs -2012 .entry(portmap_ext) -2013 .or_insert(DirectAddrType::Portmapped); -2014 } -2015 -2016 // Next add STUN addresses from the net_report report. -2017 if let Some(net_report_report) = net_report_report { -2018 if let Some(global_v4) = net_report_report.global_v4 { -2019 addrs.entry(global_v4.into()).or_insert(DirectAddrType::Qad); -2020 -2021 // If they're behind a hard NAT and are using a fixed -2022 // port locally, assume they might've added a static -2023 // port mapping on their router to the same explicit -2024 // port that we are running with. Worst case it's an invalid candidate mapping. -2025 let port = self.msock.ip_bind_addrs().iter().find_map(|addr| { -2026 if addr.port() != 0 { -2027 Some(addr.port()) -2028 } else { -2029 None -2030 } -2031 }); -2032 -2033 if let Some(port) = port { -2034 if net_report_report -2035 .mapping_varies_by_dest() -2036 .unwrap_or_default() -2037 { -2038 let mut addr = global_v4; -2039 addr.set_port(port); -2040 addrs -2041 .entry(addr.into()) -2042 .or_insert(DirectAddrType::Qad4LocalPort); -2043 } -2044 } -2045 } -2046 if let Some(global_v6) = net_report_report.global_v6 { -2047 addrs.entry(global_v6.into()).or_insert(DirectAddrType::Qad); -2048 } -2049 } -2050 -2051 let local_addrs: Vec<(SocketAddr, SocketAddr)> = self -2052 .msock -2053 .ip_bind_addrs() -2054 .iter() -2055 .copied() -2056 .zip(self.msock.ip_local_addrs()) -2057 .collect(); -2058 -2059 let has_ipv4_unspecified = local_addrs.iter().find_map(|(_, a)| { -2060 if a.is_ipv4() && a.ip().is_unspecified() { -2061 Some(a.port()) -2062 } else { -2063 None -2064 } -2065 }); -2066 let has_ipv6_unspecified = local_addrs.iter().find_map(|(_, a)| { -2067 if a.is_ipv6() && a.ip().is_unspecified() { -2068 Some(a.port()) -2069 } else { -2070 None -2071 } -2072 }); -2073 -2074 // If a socket is bound to the unspecified address, create SocketAddrs for -2075 // each local IP address by pairing it with the port the socket is bound on. -2076 if local_addrs -2077 .iter() -2078 .any(|(_, local)| local.ip().is_unspecified()) -2079 { -2080 let LocalAddresses { -2081 regular: mut ips, -2082 loopback, -2083 } = self -2084 .netmon_watcher -2085 .get() -2086 .expect("netmon disconnected") -2087 .local_addresses; -2088 if ips.is_empty() && addrs.is_empty() { -2089 // Include loopback addresses only if there are no other interfaces -2090 // or public addresses, this allows testing offline. -2091 ips = loopback; -2092 } -2093 -2094 for ip in ips { -2095 let port_if_unspecified = match ip { -2096 IpAddr::V4(_) => has_ipv4_unspecified, -2097 IpAddr::V6(_) => has_ipv6_unspecified, -2098 }; -2099 if let Some(port) = port_if_unspecified { -2100 let addr = SocketAddr::new(ip, port); -2101 addrs.entry(addr).or_insert(DirectAddrType::Local); -2102 } -2103 } -2104 } -2105 -2106 // If a socket is bound to a specific address, add it. -2107 for (bound, local) in local_addrs { -2108 if !bound.ip().is_unspecified() { -2109 addrs.entry(local).or_insert(DirectAddrType::Local); -2110 } -2111 } -2112 -2113 // Finally create and store store all these direct addresses and send any -2114 // queued call-me-maybe messages. -2115 self.msock.store_direct_addresses( -2116 addrs -2117 .iter() -2118 .map(|(addr, typ)| DirectAddr { -2119 addr: *addr, -2120 typ: *typ, -2121 }) -2122 .collect(), -2123 ); -2124 self.send_queued_call_me_maybes(); -2125 } +1949 if is_major { +1950 if let Err(err) = self.network_change_sender.rebind() { +1951 warn!("failed to rebind transports: {:?}", err); +1952 } +1953 +1954 #[cfg(not(wasm_browser))] +1955 self.msock.dns_resolver.reset().await; +1956 self.re_stun(UpdateReason::LinkChangeMajor); +1957 self.reset_endpoint_states(); +1958 } else { +1959 self.re_stun(UpdateReason::LinkChangeMinor); +1960 } +1961 } +1962 +1963 fn re_stun(&mut self, why: UpdateReason) { +1964 let state = self.netmon_watcher.get().expect("disconnected"); +1965 self.direct_addr_update_state +1966 .schedule_run(why, state.into()); +1967 } +1968 +1969 #[instrument(skip_all)] +1970 async fn handle_ping_actions(&mut self, sender: &UdpSender, msgs: Vec<PingAction>) { +1971 if let Err(err) = self.msock.send_ping_actions(sender, msgs).await { +1972 warn!("Failed to send ping actions: {err:#}"); +1973 } +1974 } +1975 +1976 /// Processes an incoming actor message. +1977 /// +1978 /// Returns `true` if it was a shutdown. +1979 async fn handle_actor_message(&mut self, msg: ActorMessage, sender: &UdpSender) { +1980 match msg { +1981 ActorMessage::NetworkChange => { +1982 self.network_monitor.network_change().await.ok(); +1983 } +1984 ActorMessage::ScheduleDirectAddrUpdate(why, data) => { +1985 if let Some((node, url)) = data { +1986 self.pending_call_me_maybes.insert(node, url); +1987 } +1988 let state = self.netmon_watcher.get().expect("disconnected"); +1989 self.direct_addr_update_state +1990 .schedule_run(why, state.into()); +1991 } +1992 #[cfg(test)] +1993 ActorMessage::ForceNetworkChange(is_major) => { +1994 self.handle_network_change(is_major).await; +1995 } +1996 ActorMessage::PingActions(ping_actions) => { +1997 self.handle_ping_actions(sender, ping_actions).await; +1998 } +1999 } +2000 } +2001 +2002 /// Updates the direct addresses of this magic socket. +2003 /// +2004 /// Updates the [`DiscoveredDirectAddrs`] of this [`MagicSock`] with the current set of +2005 /// direct addresses from: +2006 /// +2007 /// - The portmapper. +2008 /// - A net_report report. +2009 /// - The local interfaces IP addresses. +2010 #[cfg(not(wasm_browser))] +2011 fn update_direct_addresses(&mut self, net_report_report: Option<&net_report::Report>) { +2012 let portmap_watcher = self +2013 .direct_addr_update_state +2014 .port_mapper +2015 .watch_external_address(); +2016 +2017 // We only want to have one DirectAddr for each SocketAddr we have. So we store +2018 // this as a map of SocketAddr -> DirectAddrType. At the end we will construct a +2019 // DirectAddr from each entry. +2020 let mut addrs: BTreeMap<SocketAddr, DirectAddrType> = BTreeMap::new(); +2021 +2022 // First add PortMapper provided addresses. +2023 let maybe_port_mapped = *portmap_watcher.borrow(); +2024 if let Some(portmap_ext) = maybe_port_mapped.map(SocketAddr::V4) { +2025 addrs +2026 .entry(portmap_ext) +2027 .or_insert(DirectAddrType::Portmapped); +2028 } +2029 +2030 // Next add STUN addresses from the net_report report. +2031 if let Some(net_report_report) = net_report_report { +2032 if let Some(global_v4) = net_report_report.global_v4 { +2033 addrs.entry(global_v4.into()).or_insert(DirectAddrType::Qad); +2034 +2035 // If they're behind a hard NAT and are using a fixed +2036 // port locally, assume they might've added a static +2037 // port mapping on their router to the same explicit +2038 // port that we are running with. Worst case it's an invalid candidate mapping. +2039 let port = self.msock.ip_bind_addrs().iter().find_map(|addr| { +2040 if addr.port() != 0 { +2041 Some(addr.port()) +2042 } else { +2043 None +2044 } +2045 }); +2046 +2047 if let Some(port) = port { +2048 if net_report_report +2049 .mapping_varies_by_dest() +2050 .unwrap_or_default() +2051 { +2052 let mut addr = global_v4; +2053 addr.set_port(port); +2054 addrs +2055 .entry(addr.into()) +2056 .or_insert(DirectAddrType::Qad4LocalPort); +2057 } +2058 } +2059 } +2060 if let Some(global_v6) = net_report_report.global_v6 { +2061 addrs.entry(global_v6.into()).or_insert(DirectAddrType::Qad); +2062 } +2063 } +2064 +2065 let local_addrs: Vec<(SocketAddr, SocketAddr)> = self +2066 .msock +2067 .ip_bind_addrs() +2068 .iter() +2069 .copied() +2070 .zip(self.msock.ip_local_addrs()) +2071 .collect(); +2072 +2073 let has_ipv4_unspecified = local_addrs.iter().find_map(|(_, a)| { +2074 if a.is_ipv4() && a.ip().is_unspecified() { +2075 Some(a.port()) +2076 } else { +2077 None +2078 } +2079 }); +2080 let has_ipv6_unspecified = local_addrs.iter().find_map(|(_, a)| { +2081 if a.is_ipv6() && a.ip().is_unspecified() { +2082 Some(a.port()) +2083 } else { +2084 None +2085 } +2086 }); +2087 +2088 // If a socket is bound to the unspecified address, create SocketAddrs for +2089 // each local IP address by pairing it with the port the socket is bound on. +2090 if local_addrs +2091 .iter() +2092 .any(|(_, local)| local.ip().is_unspecified()) +2093 { +2094 let LocalAddresses { +2095 regular: mut ips, +2096 loopback, +2097 } = self +2098 .netmon_watcher +2099 .get() +2100 .expect("netmon disconnected") +2101 .local_addresses; +2102 if ips.is_empty() && addrs.is_empty() { +2103 // Include loopback addresses only if there are no other interfaces +2104 // or public addresses, this allows testing offline. +2105 ips = loopback; +2106 } +2107 +2108 for ip in ips { +2109 let port_if_unspecified = match ip { +2110 IpAddr::V4(_) => has_ipv4_unspecified, +2111 IpAddr::V6(_) => has_ipv6_unspecified, +2112 }; +2113 if let Some(port) = port_if_unspecified { +2114 let addr = SocketAddr::new(ip, port); +2115 addrs.entry(addr).or_insert(DirectAddrType::Local); +2116 } +2117 } +2118 } +2119 +2120 // If a socket is bound to a specific address, add it. +2121 for (bound, local) in local_addrs { +2122 if !bound.ip().is_unspecified() { +2123 addrs.entry(local).or_insert(DirectAddrType::Local); +2124 } +2125 } 2126 -2127 fn send_queued_call_me_maybes(&mut self) { -2128 let msg = self.msock.direct_addrs.to_call_me_maybe_message(); -2129 let msg = disco::Message::CallMeMaybe(msg); -2130 // allocate, to minimize locking duration -2131 -2132 for (public_key, url) in self.pending_call_me_maybes.drain() { -2133 if !self -2134 .msock -2135 .disco -2136 .try_send(SendAddr::Relay(url), public_key, msg.clone()) -2137 { -2138 warn!(node = %public_key.fmt_short(), "relay channel full, dropping call-me-maybe"); -2139 } -2140 } -2141 } -2142 -2143 fn handle_net_report_report(&mut self, mut report: Option<net_report::Report>) { -2144 if let Some(ref mut r) = report { -2145 self.msock.ipv6_reported.store(r.udp_v6, Ordering::Relaxed); -2146 if r.preferred_relay.is_none() { -2147 if let Some(my_relay) = self.msock.my_relay() { -2148 r.preferred_relay.replace(my_relay); -2149 } -2150 } -2151 -2152 // Notify all transports -2153 self.network_change_sender.on_network_change(r); +2127 // Finally create and store store all these direct addresses and send any +2128 // queued call-me-maybe messages. +2129 self.msock.store_direct_addresses( +2130 addrs +2131 .iter() +2132 .map(|(addr, typ)| DirectAddr { +2133 addr: *addr, +2134 typ: *typ, +2135 }) +2136 .collect(), +2137 ); +2138 self.send_queued_call_me_maybes(); +2139 } +2140 +2141 fn send_queued_call_me_maybes(&mut self) { +2142 let msg = self.msock.direct_addrs.to_call_me_maybe_message(); +2143 let msg = disco::Message::CallMeMaybe(msg); +2144 // allocate, to minimize locking duration +2145 +2146 for (public_key, url) in self.pending_call_me_maybes.drain() { +2147 if !self +2148 .msock +2149 .disco +2150 .try_send(SendAddr::Relay(url), public_key, msg.clone()) +2151 { +2152 warn!(node = %public_key.fmt_short(), "relay channel full, dropping call-me-maybe"); +2153 } 2154 } -2155 -2156 #[cfg(not(wasm_browser))] -2157 self.update_direct_addresses(report.as_ref()); -2158 } -2159 -2160 /// Resets the preferred address for all nodes. -2161 /// This is called when connectivity changes enough that we no longer trust the old routes. -2162 #[instrument(skip_all)] -2163 fn reset_endpoint_states(&mut self) { -2164 self.msock.node_map.reset_node_states() -2165 } -2166} -2167 -2168fn new_re_stun_timer(initial_delay: bool) -> time::Interval { -2169 // Pick a random duration between 20 and 26 seconds (just under 30s, -2170 // a common UDP NAT timeout on Linux,etc) -2171 let mut rng = rand::thread_rng(); -2172 let d: Duration = rng.gen_range(Duration::from_secs(20)..=Duration::from_secs(26)); -2173 if initial_delay { -2174 debug!("scheduling periodic_stun to run in {}s", d.as_secs()); -2175 time::interval_at(time::Instant::now() + d, d) -2176 } else { -2177 debug!( -2178 "scheduling periodic_stun to run immediately and in {}s", -2179 d.as_secs() -2180 ); -2181 time::interval(d) -2182 } -2183} -2184 -2185#[cfg(not(wasm_browser))] -2186fn bind_with_fallback(mut addr: SocketAddr) -> io::Result<UdpSocket> { -2187 debug!(%addr, "binding"); -2188 -2189 // First try binding a preferred port, if specified -2190 match UdpSocket::bind_full(addr) { -2191 Ok(socket) => { -2192 let local_addr = socket.local_addr()?; -2193 debug!(%addr, %local_addr, "successfully bound"); -2194 return Ok(socket); -2195 } -2196 Err(err) => { -2197 debug!(%addr, "failed to bind: {err:#}"); -2198 // If that was already the fallback port, then error out -2199 if addr.port() == 0 { -2200 return Err(err); -2201 } -2202 } -2203 } -2204 -2205 // Otherwise, try binding with port 0 -2206 addr.set_port(0); -2207 UdpSocket::bind_full(addr) -2208} -2209 -2210/// The discovered direct addresses of this [`MagicSock`]. -2211/// -2212/// These are all the [`DirectAddr`]s that this [`MagicSock`] is aware of for itself. -2213/// They include all locally bound ones as well as those discovered by other mechanisms like -2214/// QAD. -2215#[derive(derive_more::Debug, Default, Clone)] -2216struct DiscoveredDirectAddrs { -2217 /// The last set of discovered direct addresses. -2218 addrs: Watchable<Option<BTreeSet<DirectAddr>>>, -2219 -2220 /// The last time the direct addresses were updated, even if there was no change. -2221 /// -2222 /// This is only ever None at startup. -2223 updated_at: Arc<RwLock<Option<Instant>>>, -2224} -2225 -2226impl DiscoveredDirectAddrs { -2227 /// Updates the direct addresses, returns `true` if they changed, `false` if not. -2228 fn update(&self, addrs: BTreeSet<DirectAddr>) -> bool { -2229 *self.updated_at.write().expect("poisoned") = Some(Instant::now()); -2230 let updated = self.addrs.set(Some(addrs)).is_ok(); -2231 if updated { -2232 event!( -2233 target: "iroh::_events::direct_addrs", -2234 Level::DEBUG, -2235 addrs = ?self.addrs.get(), -2236 ); -2237 } -2238 updated -2239 } -2240 -2241 fn sockaddrs(&self) -> BTreeSet<SocketAddr> { -2242 self.addrs -2243 .get() -2244 .unwrap_or_default() -2245 .into_iter() -2246 .map(|da| da.addr) -2247 .collect() -2248 } -2249 -2250 /// Whether the direct addr information is considered "fresh". -2251 /// -2252 /// If not fresh you should probably update the direct addresses before using this info. -2253 /// -2254 /// Returns `Ok(())` if fresh enough and `Err(elapsed)` if not fresh enough. -2255 /// `elapsed` is the time elapsed since the direct addresses were last updated. -2256 /// -2257 /// If there is no direct address information `Err(Duration::ZERO)` is returned. -2258 fn fresh_enough(&self) -> Result<(), Duration> { -2259 match *self.updated_at.read().expect("poisoned") { -2260 None => Err(Duration::ZERO), -2261 Some(time) => { -2262 let elapsed = time.elapsed(); -2263 if elapsed <= ENDPOINTS_FRESH_ENOUGH_DURATION { -2264 Ok(()) -2265 } else { -2266 Err(elapsed) -2267 } -2268 } -2269 } -2270 } -2271 -2272 fn to_call_me_maybe_message(&self) -> disco::CallMeMaybe { -2273 let my_numbers = self -2274 .addrs -2275 .get() -2276 .unwrap_or_default() -2277 .into_iter() -2278 .map(|da| da.addr) -2279 .collect(); -2280 disco::CallMeMaybe { my_numbers } -2281 } -2282} -2283 -2284/// The fake address used by the QUIC layer to address a node. -2285/// -2286/// You can consider this as nothing more than a lookup key for a node the [`MagicSock`] knows -2287/// about. -2288/// -2289/// [`MagicSock`] can reach a node by several real socket addresses, or maybe even via the relay -2290/// node. The QUIC layer however needs to address a node by a stable [`SocketAddr`] so -2291/// that normal socket APIs can function. Thus when a new node is introduced to a [`MagicSock`] -2292/// it is given a new fake address. This is the type of that address. -2293/// -2294/// It is but a newtype. And in our QUIC-facing socket APIs like [`AsyncUdpSocket`] it -2295/// comes in as the inner [`Ipv6Addr`], in those interfaces we have to be careful to do -2296/// the conversion to this type. -2297#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] -2298pub(crate) struct NodeIdMappedAddr(Ipv6Addr); -2299 -2300/// Can occur when converting a [`SocketAddr`] to an [`NodeIdMappedAddr`] -2301#[derive(Debug, Snafu)] -2302#[snafu(display("Failed to convert"))] -2303pub struct NodeIdMappedAddrError; -2304 -2305/// Counter to always generate unique addresses for [`NodeIdMappedAddr`]. -2306static NODE_ID_ADDR_COUNTER: AtomicU64 = AtomicU64::new(1); -2307 -2308impl NodeIdMappedAddr { -2309 /// The Prefix/L of our Unique Local Addresses. -2310 const ADDR_PREFIXL: u8 = 0xfd; -2311 /// The Global ID used in our Unique Local Addresses. -2312 const ADDR_GLOBAL_ID: [u8; 5] = [21, 7, 10, 81, 11]; -2313 /// The Subnet ID used in our Unique Local Addresses. -2314 const ADDR_SUBNET: [u8; 2] = [0; 2]; -2315 -2316 /// The dummy port used for all [`NodeIdMappedAddr`]s. -2317 const NODE_ID_MAPPED_PORT: u16 = 12345; +2155 } +2156 +2157 fn handle_net_report_report(&mut self, mut report: Option<net_report::Report>) { +2158 if let Some(ref mut r) = report { +2159 self.msock.ipv6_reported.store(r.udp_v6, Ordering::Relaxed); +2160 if r.preferred_relay.is_none() { +2161 if let Some(my_relay) = self.msock.my_relay() { +2162 r.preferred_relay.replace(my_relay); +2163 } +2164 } +2165 +2166 // Notify all transports +2167 self.network_change_sender.on_network_change(r); +2168 } +2169 +2170 #[cfg(not(wasm_browser))] +2171 self.update_direct_addresses(report.as_ref()); +2172 } +2173 +2174 /// Resets the preferred address for all nodes. +2175 /// This is called when connectivity changes enough that we no longer trust the old routes. +2176 #[instrument(skip_all)] +2177 fn reset_endpoint_states(&mut self) { +2178 self.msock.node_map.reset_node_states() +2179 } +2180} +2181 +2182fn new_re_stun_timer(initial_delay: bool) -> time::Interval { +2183 // Pick a random duration between 20 and 26 seconds (just under 30s, +2184 // a common UDP NAT timeout on Linux,etc) +2185 let mut rng = rand::thread_rng(); +2186 let d: Duration = rng.gen_range(Duration::from_secs(20)..=Duration::from_secs(26)); +2187 if initial_delay { +2188 debug!("scheduling periodic_stun to run in {}s", d.as_secs()); +2189 time::interval_at(time::Instant::now() + d, d) +2190 } else { +2191 debug!( +2192 "scheduling periodic_stun to run immediately and in {}s", +2193 d.as_secs() +2194 ); +2195 time::interval(d) +2196 } +2197} +2198 +2199#[cfg(not(wasm_browser))] +2200fn bind_with_fallback(mut addr: SocketAddr) -> io::Result<UdpSocket> { +2201 debug!(%addr, "binding"); +2202 +2203 // First try binding a preferred port, if specified +2204 match UdpSocket::bind_full(addr) { +2205 Ok(socket) => { +2206 let local_addr = socket.local_addr()?; +2207 debug!(%addr, %local_addr, "successfully bound"); +2208 return Ok(socket); +2209 } +2210 Err(err) => { +2211 debug!(%addr, "failed to bind: {err:#}"); +2212 // If that was already the fallback port, then error out +2213 if addr.port() == 0 { +2214 return Err(err); +2215 } +2216 } +2217 } +2218 +2219 // Otherwise, try binding with port 0 +2220 addr.set_port(0); +2221 UdpSocket::bind_full(addr) +2222} +2223 +2224/// The discovered direct addresses of this [`MagicSock`]. +2225/// +2226/// These are all the [`DirectAddr`]s that this [`MagicSock`] is aware of for itself. +2227/// They include all locally bound ones as well as those discovered by other mechanisms like +2228/// QAD. +2229#[derive(derive_more::Debug, Default, Clone)] +2230struct DiscoveredDirectAddrs { +2231 /// The last set of discovered direct addresses. +2232 addrs: Watchable<Option<BTreeSet<DirectAddr>>>, +2233 +2234 /// The last time the direct addresses were updated, even if there was no change. +2235 /// +2236 /// This is only ever None at startup. +2237 updated_at: Arc<RwLock<Option<Instant>>>, +2238} +2239 +2240impl DiscoveredDirectAddrs { +2241 /// Updates the direct addresses, returns `true` if they changed, `false` if not. +2242 fn update(&self, addrs: BTreeSet<DirectAddr>) -> bool { +2243 *self.updated_at.write().expect("poisoned") = Some(Instant::now()); +2244 let updated = self.addrs.set(Some(addrs)).is_ok(); +2245 if updated { +2246 event!( +2247 target: "iroh::_events::direct_addrs", +2248 Level::DEBUG, +2249 addrs = ?self.addrs.get(), +2250 ); +2251 } +2252 updated +2253 } +2254 +2255 fn sockaddrs(&self) -> BTreeSet<SocketAddr> { +2256 self.addrs +2257 .get() +2258 .unwrap_or_default() +2259 .into_iter() +2260 .map(|da| da.addr) +2261 .collect() +2262 } +2263 +2264 /// Whether the direct addr information is considered "fresh". +2265 /// +2266 /// If not fresh you should probably update the direct addresses before using this info. +2267 /// +2268 /// Returns `Ok(())` if fresh enough and `Err(elapsed)` if not fresh enough. +2269 /// `elapsed` is the time elapsed since the direct addresses were last updated. +2270 /// +2271 /// If there is no direct address information `Err(Duration::ZERO)` is returned. +2272 fn fresh_enough(&self) -> Result<(), Duration> { +2273 match *self.updated_at.read().expect("poisoned") { +2274 None => Err(Duration::ZERO), +2275 Some(time) => { +2276 let elapsed = time.elapsed(); +2277 if elapsed <= ENDPOINTS_FRESH_ENOUGH_DURATION { +2278 Ok(()) +2279 } else { +2280 Err(elapsed) +2281 } +2282 } +2283 } +2284 } +2285 +2286 fn to_call_me_maybe_message(&self) -> disco::CallMeMaybe { +2287 let my_numbers = self +2288 .addrs +2289 .get() +2290 .unwrap_or_default() +2291 .into_iter() +2292 .map(|da| da.addr) +2293 .collect(); +2294 disco::CallMeMaybe { my_numbers } +2295 } +2296} +2297 +2298/// The fake address used by the QUIC layer to address a node. +2299/// +2300/// You can consider this as nothing more than a lookup key for a node the [`MagicSock`] knows +2301/// about. +2302/// +2303/// [`MagicSock`] can reach a node by several real socket addresses, or maybe even via the relay +2304/// node. The QUIC layer however needs to address a node by a stable [`SocketAddr`] so +2305/// that normal socket APIs can function. Thus when a new node is introduced to a [`MagicSock`] +2306/// it is given a new fake address. This is the type of that address. +2307/// +2308/// It is but a newtype. And in our QUIC-facing socket APIs like [`AsyncUdpSocket`] it +2309/// comes in as the inner [`Ipv6Addr`], in those interfaces we have to be careful to do +2310/// the conversion to this type. +2311#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] +2312pub(crate) struct NodeIdMappedAddr(Ipv6Addr); +2313 +2314/// Can occur when converting a [`SocketAddr`] to an [`NodeIdMappedAddr`] +2315#[derive(Debug, Snafu)] +2316#[snafu(display("Failed to convert"))] +2317pub struct NodeIdMappedAddrError; 2318 -2319 /// Generates a globally unique fake UDP address. -2320 /// -2321 /// This generates and IPv6 Unique Local Address according to RFC 4193. -2322 pub(crate) fn generate() -> Self { -2323 let mut addr = [0u8; 16]; -2324 addr[0] = Self::ADDR_PREFIXL; -2325 addr[1..6].copy_from_slice(&Self::ADDR_GLOBAL_ID); -2326 addr[6..8].copy_from_slice(&Self::ADDR_SUBNET); -2327 -2328 let counter = NODE_ID_ADDR_COUNTER.fetch_add(1, Ordering::Relaxed); -2329 addr[8..16].copy_from_slice(&counter.to_be_bytes()); -2330 -2331 Self(Ipv6Addr::from(addr)) -2332 } -2333 -2334 /// Returns a consistent [`SocketAddr`] for the [`NodeIdMappedAddr`]. -2335 /// -2336 /// This socket address does not have a routable IP address. -2337 /// -2338 /// This uses a made-up port number, since the port does not play a role in looking up -2339 /// the node in the [`NodeMap`]. This socket address is only to be used to pass into -2340 /// Quinn. -2341 pub(crate) fn private_socket_addr(&self) -> SocketAddr { -2342 SocketAddr::new(IpAddr::from(self.0), Self::NODE_ID_MAPPED_PORT) -2343 } -2344} -2345 -2346impl TryFrom<Ipv6Addr> for NodeIdMappedAddr { -2347 type Error = NodeIdMappedAddrError; -2348 -2349 fn try_from(value: Ipv6Addr) -> Result<Self, Self::Error> { -2350 let octets = value.octets(); -2351 if octets[0] == Self::ADDR_PREFIXL -2352 && octets[1..6] == Self::ADDR_GLOBAL_ID -2353 && octets[6..8] == Self::ADDR_SUBNET -2354 { -2355 return Ok(Self(value)); -2356 } -2357 Err(NodeIdMappedAddrError) -2358 } -2359} -2360 -2361impl std::fmt::Display for NodeIdMappedAddr { -2362 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { -2363 write!(f, "NodeIdMappedAddr({})", self.0) -2364 } -2365} -2366 -2367fn disco_message_sent(msg: &disco::Message, metrics: &MagicsockMetrics) { -2368 match msg { -2369 disco::Message::Ping(_) => { -2370 metrics.sent_disco_ping.inc(); -2371 } -2372 disco::Message::Pong(_) => { -2373 metrics.sent_disco_pong.inc(); -2374 } -2375 disco::Message::CallMeMaybe(_) => { -2376 metrics.sent_disco_call_me_maybe.inc(); -2377 } +2319/// Counter to always generate unique addresses for [`NodeIdMappedAddr`]. +2320static NODE_ID_ADDR_COUNTER: AtomicU64 = AtomicU64::new(1); +2321 +2322impl NodeIdMappedAddr { +2323 /// The Prefix/L of our Unique Local Addresses. +2324 const ADDR_PREFIXL: u8 = 0xfd; +2325 /// The Global ID used in our Unique Local Addresses. +2326 const ADDR_GLOBAL_ID: [u8; 5] = [21, 7, 10, 81, 11]; +2327 /// The Subnet ID used in our Unique Local Addresses. +2328 const ADDR_SUBNET: [u8; 2] = [0; 2]; +2329 +2330 /// The dummy port used for all [`NodeIdMappedAddr`]s. +2331 const NODE_ID_MAPPED_PORT: u16 = 12345; +2332 +2333 /// Generates a globally unique fake UDP address. +2334 /// +2335 /// This generates and IPv6 Unique Local Address according to RFC 4193. +2336 pub(crate) fn generate() -> Self { +2337 let mut addr = [0u8; 16]; +2338 addr[0] = Self::ADDR_PREFIXL; +2339 addr[1..6].copy_from_slice(&Self::ADDR_GLOBAL_ID); +2340 addr[6..8].copy_from_slice(&Self::ADDR_SUBNET); +2341 +2342 let counter = NODE_ID_ADDR_COUNTER.fetch_add(1, Ordering::Relaxed); +2343 addr[8..16].copy_from_slice(&counter.to_be_bytes()); +2344 +2345 Self(Ipv6Addr::from(addr)) +2346 } +2347 +2348 /// Returns a consistent [`SocketAddr`] for the [`NodeIdMappedAddr`]. +2349 /// +2350 /// This socket address does not have a routable IP address. +2351 /// +2352 /// This uses a made-up port number, since the port does not play a role in looking up +2353 /// the node in the [`NodeMap`]. This socket address is only to be used to pass into +2354 /// Quinn. +2355 pub(crate) fn private_socket_addr(&self) -> SocketAddr { +2356 SocketAddr::new(IpAddr::from(self.0), Self::NODE_ID_MAPPED_PORT) +2357 } +2358} +2359 +2360impl TryFrom<Ipv6Addr> for NodeIdMappedAddr { +2361 type Error = NodeIdMappedAddrError; +2362 +2363 fn try_from(value: Ipv6Addr) -> Result<Self, Self::Error> { +2364 let octets = value.octets(); +2365 if octets[0] == Self::ADDR_PREFIXL +2366 && octets[1..6] == Self::ADDR_GLOBAL_ID +2367 && octets[6..8] == Self::ADDR_SUBNET +2368 { +2369 return Ok(Self(value)); +2370 } +2371 Err(NodeIdMappedAddrError) +2372 } +2373} +2374 +2375impl std::fmt::Display for NodeIdMappedAddr { +2376 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { +2377 write!(f, "NodeIdMappedAddr({})", self.0) 2378 } 2379} 2380 -2381/// A *direct address* on which an iroh-node might be contactable. -2382/// -2383/// Direct addresses are UDP socket addresses on which an iroh node could potentially be -2384/// contacted. These can come from various sources depending on the network topology of the -2385/// iroh node, see [`DirectAddrType`] for the several kinds of sources. -2386#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] -2387pub struct DirectAddr { -2388 /// The address. -2389 pub addr: SocketAddr, -2390 /// The origin of this direct address. -2391 pub typ: DirectAddrType, -2392} -2393 -2394/// The type of direct address. -2395/// -2396/// These are the various sources or origins from which an iroh node might have found a -2397/// possible [`DirectAddr`]. -2398#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] -2399pub enum DirectAddrType { -2400 /// Not yet determined.. -2401 Unknown, -2402 /// A locally bound socket address. -2403 Local, -2404 /// Public internet address discovered via QAD. -2405 /// -2406 /// When possible an iroh node will perform QAD to discover which is the address -2407 /// from which it sends data on the public internet. This can be different from locally -2408 /// bound addresses when the node is on a local network which performs NAT or similar. -2409 Qad, -2410 /// An address assigned by the router using port mapping. -2411 /// -2412 /// When possible an iroh node will request a port mapping from the local router to -2413 /// get a publicly routable direct address. -2414 Portmapped, -2415 /// Hard NAT: QAD'ed IPv4 address + local fixed port. -2416 /// -2417 /// It is possible to configure iroh to bound to a specific port and independently -2418 /// configure the router to forward this port to the iroh node. This indicates a -2419 /// situation like this, which still uses QAD to discover the public address. -2420 Qad4LocalPort, -2421} -2422 -2423impl Display for DirectAddrType { -2424 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { -2425 match self { -2426 DirectAddrType::Unknown => write!(f, "?"), -2427 DirectAddrType::Local => write!(f, "local"), -2428 DirectAddrType::Qad => write!(f, "qad"), -2429 DirectAddrType::Portmapped => write!(f, "portmap"), -2430 DirectAddrType::Qad4LocalPort => write!(f, "qad4localport"), -2431 } -2432 } -2433} -2434 -2435#[cfg(test)] -2436mod tests { -2437 use std::{collections::BTreeSet, sync::Arc, time::Duration}; -2438 -2439 use data_encoding::HEXLOWER; -2440 use iroh_base::{NodeAddr, NodeId, PublicKey}; -2441 use n0_future::{time, StreamExt}; -2442 use n0_snafu::{Result, ResultExt}; -2443 use n0_watcher::Watcher; -2444 use quinn::ServerConfig; -2445 use rand::{Rng, RngCore}; -2446 use tokio::task::JoinSet; -2447 use tokio_util::task::AbortOnDropHandle; -2448 use tracing::{error, info, info_span, instrument, Instrument}; -2449 use tracing_test::traced_test; -2450 -2451 use super::{NodeIdMappedAddr, Options}; -2452 use crate::{ -2453 dns::DnsResolver, -2454 endpoint::{DirectAddr, PathSelection, Source}, -2455 magicsock::{node_map, Handle, MagicSock}, -2456 tls, Endpoint, RelayMap, RelayMode, SecretKey, -2457 }; -2458 -2459 const ALPN: &[u8] = b"n0/test/1"; -2460 -2461 impl Default for Options { -2462 fn default() -> Self { -2463 let secret_key = SecretKey::generate(rand::rngs::OsRng); -2464 let server_config = make_default_server_config(&secret_key); -2465 Options { -2466 addr_v4: None, -2467 addr_v6: None, -2468 secret_key, -2469 relay_map: RelayMap::empty(), -2470 node_map: None, -2471 discovery: None, -2472 proxy_url: None, -2473 dns_resolver: DnsResolver::new(), -2474 server_config, -2475 #[cfg(any(test, feature = "test-utils"))] -2476 insecure_skip_relay_cert_verify: false, -2477 #[cfg(any(test, feature = "test-utils"))] -2478 path_selection: PathSelection::default(), -2479 discovery_user_data: None, -2480 metrics: Default::default(), -2481 } -2482 } -2483 } -2484 -2485 /// Generate a server config with no ALPNS and a default transport configuration -2486 fn make_default_server_config(secret_key: &SecretKey) -> ServerConfig { -2487 let quic_server_config = -2488 crate::tls::TlsConfig::new(secret_key.clone()).make_server_config(vec![], false); -2489 let mut server_config = ServerConfig::with_crypto(Arc::new(quic_server_config)); -2490 server_config.transport_config(Arc::new(quinn::TransportConfig::default())); -2491 server_config -2492 } -2493 -2494 impl MagicSock { -2495 #[track_caller] -2496 pub fn add_test_addr(&self, node_addr: NodeAddr) { -2497 self.add_node_addr( -2498 node_addr, -2499 Source::NamedApp { -2500 name: "test".into(), -2501 }, -2502 ) -2503 .unwrap() -2504 } -2505 } -2506 -2507 /// Magicsock plus wrappers for sending packets -2508 #[derive(Clone)] -2509 struct MagicStack { -2510 secret_key: SecretKey, -2511 endpoint: Endpoint, -2512 } -2513 -2514 impl MagicStack { -2515 async fn new(relay_mode: RelayMode) -> Self { -2516 let secret_key = SecretKey::generate(rand::thread_rng()); -2517 -2518 let mut transport_config = quinn::TransportConfig::default(); -2519 transport_config.max_idle_timeout(Some(Duration::from_secs(10).try_into().unwrap())); +2381fn disco_message_sent(msg: &disco::Message, metrics: &MagicsockMetrics) { +2382 match msg { +2383 disco::Message::Ping(_) => { +2384 metrics.sent_disco_ping.inc(); +2385 } +2386 disco::Message::Pong(_) => { +2387 metrics.sent_disco_pong.inc(); +2388 } +2389 disco::Message::CallMeMaybe(_) => { +2390 metrics.sent_disco_call_me_maybe.inc(); +2391 } +2392 } +2393} +2394 +2395/// A *direct address* on which an iroh-node might be contactable. +2396/// +2397/// Direct addresses are UDP socket addresses on which an iroh node could potentially be +2398/// contacted. These can come from various sources depending on the network topology of the +2399/// iroh node, see [`DirectAddrType`] for the several kinds of sources. +2400#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] +2401pub struct DirectAddr { +2402 /// The address. +2403 pub addr: SocketAddr, +2404 /// The origin of this direct address. +2405 pub typ: DirectAddrType, +2406} +2407 +2408/// The type of direct address. +2409/// +2410/// These are the various sources or origins from which an iroh node might have found a +2411/// possible [`DirectAddr`]. +2412#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] +2413pub enum DirectAddrType { +2414 /// Not yet determined.. +2415 Unknown, +2416 /// A locally bound socket address. +2417 Local, +2418 /// Public internet address discovered via QAD. +2419 /// +2420 /// When possible an iroh node will perform QAD to discover which is the address +2421 /// from which it sends data on the public internet. This can be different from locally +2422 /// bound addresses when the node is on a local network which performs NAT or similar. +2423 Qad, +2424 /// An address assigned by the router using port mapping. +2425 /// +2426 /// When possible an iroh node will request a port mapping from the local router to +2427 /// get a publicly routable direct address. +2428 Portmapped, +2429 /// Hard NAT: QAD'ed IPv4 address + local fixed port. +2430 /// +2431 /// It is possible to configure iroh to bound to a specific port and independently +2432 /// configure the router to forward this port to the iroh node. This indicates a +2433 /// situation like this, which still uses QAD to discover the public address. +2434 Qad4LocalPort, +2435} +2436 +2437impl Display for DirectAddrType { +2438 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { +2439 match self { +2440 DirectAddrType::Unknown => write!(f, "?"), +2441 DirectAddrType::Local => write!(f, "local"), +2442 DirectAddrType::Qad => write!(f, "qad"), +2443 DirectAddrType::Portmapped => write!(f, "portmap"), +2444 DirectAddrType::Qad4LocalPort => write!(f, "qad4localport"), +2445 } +2446 } +2447} +2448 +2449#[cfg(test)] +2450mod tests { +2451 use std::{collections::BTreeSet, sync::Arc, time::Duration}; +2452 +2453 use data_encoding::HEXLOWER; +2454 use iroh_base::{NodeAddr, NodeId, PublicKey}; +2455 use n0_future::{time, StreamExt}; +2456 use n0_snafu::{Result, ResultExt}; +2457 use n0_watcher::Watcher; +2458 use quinn::ServerConfig; +2459 use rand::{Rng, RngCore}; +2460 use tokio::task::JoinSet; +2461 use tokio_util::task::AbortOnDropHandle; +2462 use tracing::{error, info, info_span, instrument, Instrument}; +2463 use tracing_test::traced_test; +2464 +2465 use super::{NodeIdMappedAddr, Options}; +2466 use crate::{ +2467 dns::DnsResolver, +2468 endpoint::{DirectAddr, PathSelection, Source}, +2469 magicsock::{node_map, Handle, MagicSock}, +2470 tls, Endpoint, RelayMap, RelayMode, SecretKey, +2471 }; +2472 +2473 const ALPN: &[u8] = b"n0/test/1"; +2474 +2475 impl Default for Options { +2476 fn default() -> Self { +2477 let secret_key = SecretKey::generate(rand::rngs::OsRng); +2478 let server_config = make_default_server_config(&secret_key); +2479 Options { +2480 addr_v4: None, +2481 addr_v6: None, +2482 secret_key, +2483 relay_map: RelayMap::empty(), +2484 node_map: None, +2485 discovery: None, +2486 proxy_url: None, +2487 dns_resolver: DnsResolver::new(), +2488 server_config, +2489 #[cfg(any(test, feature = "test-utils"))] +2490 insecure_skip_relay_cert_verify: false, +2491 #[cfg(any(test, feature = "test-utils"))] +2492 path_selection: PathSelection::default(), +2493 discovery_user_data: None, +2494 metrics: Default::default(), +2495 } +2496 } +2497 } +2498 +2499 /// Generate a server config with no ALPNS and a default transport configuration +2500 fn make_default_server_config(secret_key: &SecretKey) -> ServerConfig { +2501 let quic_server_config = +2502 crate::tls::TlsConfig::new(secret_key.clone()).make_server_config(vec![], false); +2503 let mut server_config = ServerConfig::with_crypto(Arc::new(quic_server_config)); +2504 server_config.transport_config(Arc::new(quinn::TransportConfig::default())); +2505 server_config +2506 } +2507 +2508 impl MagicSock { +2509 #[track_caller] +2510 pub fn add_test_addr(&self, node_addr: NodeAddr) { +2511 self.add_node_addr( +2512 node_addr, +2513 Source::NamedApp { +2514 name: "test".into(), +2515 }, +2516 ) +2517 .unwrap() +2518 } +2519 } 2520 -2521 let endpoint = Endpoint::builder() -2522 .secret_key(secret_key.clone()) -2523 .transport_config(transport_config) -2524 .relay_mode(relay_mode) -2525 .alpns(vec![ALPN.to_vec()]) -2526 .bind() -2527 .await -2528 .unwrap(); -2529 -2530 Self { -2531 secret_key, -2532 endpoint, -2533 } -2534 } -2535 -2536 fn tracked_endpoints(&self) -> Vec<PublicKey> { -2537 self.endpoint -2538 .magic_sock() -2539 .list_remote_infos() -2540 .into_iter() -2541 .map(|ep| ep.node_id) -2542 .collect() -2543 } -2544 -2545 fn public(&self) -> PublicKey { -2546 self.secret_key.public() -2547 } -2548 } +2521 /// Magicsock plus wrappers for sending packets +2522 #[derive(Clone)] +2523 struct MagicStack { +2524 secret_key: SecretKey, +2525 endpoint: Endpoint, +2526 } +2527 +2528 impl MagicStack { +2529 async fn new(relay_mode: RelayMode) -> Self { +2530 let secret_key = SecretKey::generate(rand::thread_rng()); +2531 +2532 let mut transport_config = quinn::TransportConfig::default(); +2533 transport_config.max_idle_timeout(Some(Duration::from_secs(10).try_into().unwrap())); +2534 +2535 let endpoint = Endpoint::builder() +2536 .secret_key(secret_key.clone()) +2537 .transport_config(transport_config) +2538 .relay_mode(relay_mode) +2539 .alpns(vec![ALPN.to_vec()]) +2540 .bind() +2541 .await +2542 .unwrap(); +2543 +2544 Self { +2545 secret_key, +2546 endpoint, +2547 } +2548 } 2549 -2550 /// Monitors endpoint changes and plumbs things together. -2551 /// -2552 /// This is a way of connecting endpoints without a relay server. Whenever the local -2553 /// endpoints of a magic endpoint change this address is added to the other magic -2554 /// sockets. This function will await until the endpoints are connected the first time -2555 /// before returning. -2556 /// -2557 /// When the returned drop guard is dropped, the tasks doing this updating are stopped. -2558 #[instrument(skip_all)] -2559 async fn mesh_stacks(stacks: Vec<MagicStack>) -> Result<JoinSet<()>> { -2560 /// Registers endpoint addresses of a node to all other nodes. -2561 fn update_direct_addrs( -2562 stacks: &[MagicStack], -2563 my_idx: usize, -2564 new_addrs: BTreeSet<DirectAddr>, -2565 ) { -2566 let me = &stacks[my_idx]; -2567 for (i, m) in stacks.iter().enumerate() { -2568 if i == my_idx { -2569 continue; -2570 } -2571 -2572 let addr = NodeAddr { -2573 node_id: me.public(), -2574 relay_url: None, -2575 direct_addresses: new_addrs.iter().map(|ep| ep.addr).collect(), -2576 }; -2577 m.endpoint.magic_sock().add_test_addr(addr); -2578 } -2579 } -2580 -2581 // For each node, start a task which monitors its local endpoints and registers them -2582 // with the other nodes as local endpoints become known. -2583 let mut tasks = JoinSet::new(); -2584 for (my_idx, m) in stacks.iter().enumerate() { -2585 let m = m.clone(); -2586 let stacks = stacks.clone(); -2587 tasks.spawn(async move { -2588 let me = m.endpoint.node_id().fmt_short(); -2589 let mut stream = m.endpoint.direct_addresses().stream().filter_map(|i| i); -2590 while let Some(new_eps) = stream.next().await { -2591 info!(%me, "conn{} endpoints update: {:?}", my_idx + 1, new_eps); -2592 update_direct_addrs(&stacks, my_idx, new_eps); -2593 } -2594 }); -2595 } -2596 -2597 // Wait for all nodes to be registered with each other. -2598 time::timeout(Duration::from_secs(10), async move { -2599 let all_node_ids: Vec<_> = stacks.iter().map(|ms| ms.endpoint.node_id()).collect(); -2600 loop { -2601 let mut ready = Vec::with_capacity(stacks.len()); -2602 for ms in stacks.iter() { -2603 let endpoints = ms.tracked_endpoints(); -2604 let my_node_id = ms.endpoint.node_id(); -2605 let all_nodes_meshed = all_node_ids -2606 .iter() -2607 .filter(|node_id| **node_id != my_node_id) -2608 .all(|node_id| endpoints.contains(node_id)); -2609 ready.push(all_nodes_meshed); -2610 } -2611 if ready.iter().all(|meshed| *meshed) { -2612 break; -2613 } -2614 time::sleep(Duration::from_millis(200)).await; -2615 } -2616 }) -2617 .await -2618 .context("timeout")?; -2619 info!("all nodes meshed"); -2620 Ok(tasks) -2621 } -2622 -2623 #[instrument(skip_all, fields(me = %ep.endpoint.node_id().fmt_short()))] -2624 async fn echo_receiver(ep: MagicStack, loss: ExpectedLoss) -> Result { -2625 info!("accepting conn"); -2626 let conn = ep.endpoint.accept().await.expect("no conn"); -2627 -2628 info!("connecting"); -2629 let conn = conn.await.context("connecting")?; -2630 info!("accepting bi"); -2631 let (mut send_bi, mut recv_bi) = conn.accept_bi().await.context("accept bi")?; -2632 -2633 info!("reading"); -2634 let val = recv_bi -2635 .read_to_end(usize::MAX) -2636 .await -2637 .context("read to end")?; -2638 -2639 info!("replying"); -2640 for chunk in val.chunks(12) { -2641 send_bi.write_all(chunk).await.context("write all")?; -2642 } -2643 -2644 info!("finishing"); -2645 send_bi.finish().context("finish")?; -2646 send_bi.stopped().await.context("stopped")?; -2647 -2648 let stats = conn.stats(); -2649 info!("stats: {:#?}", stats); -2650 // TODO: ensure panics in this function are reported ok -2651 if matches!(loss, ExpectedLoss::AlmostNone) { -2652 for (id, path) in &stats.paths { -2653 assert!( -2654 path.lost_packets < 10, -2655 "[receiver] path {id:?} should not loose many packets", -2656 ); -2657 } -2658 } -2659 -2660 info!("close"); -2661 conn.close(0u32.into(), b"done"); -2662 info!("wait idle"); -2663 ep.endpoint.endpoint().wait_idle().await; -2664 -2665 Ok(()) -2666 } -2667 -2668 #[instrument(skip_all, fields(me = %ep.endpoint.node_id().fmt_short()))] -2669 async fn echo_sender( -2670 ep: MagicStack, -2671 dest_id: PublicKey, -2672 msg: &[u8], -2673 loss: ExpectedLoss, -2674 ) -> Result { -2675 info!("connecting to {}", dest_id.fmt_short()); -2676 let dest = NodeAddr::new(dest_id); -2677 let conn = ep.endpoint.connect(dest, ALPN).await?; +2550 fn tracked_endpoints(&self) -> Vec<PublicKey> { +2551 self.endpoint +2552 .magic_sock() +2553 .list_remote_infos() +2554 .into_iter() +2555 .map(|ep| ep.node_id) +2556 .collect() +2557 } +2558 +2559 fn public(&self) -> PublicKey { +2560 self.secret_key.public() +2561 } +2562 } +2563 +2564 /// Monitors endpoint changes and plumbs things together. +2565 /// +2566 /// This is a way of connecting endpoints without a relay server. Whenever the local +2567 /// endpoints of a magic endpoint change this address is added to the other magic +2568 /// sockets. This function will await until the endpoints are connected the first time +2569 /// before returning. +2570 /// +2571 /// When the returned drop guard is dropped, the tasks doing this updating are stopped. +2572 #[instrument(skip_all)] +2573 async fn mesh_stacks(stacks: Vec<MagicStack>) -> Result<JoinSet<()>> { +2574 /// Registers endpoint addresses of a node to all other nodes. +2575 fn update_direct_addrs( +2576 stacks: &[MagicStack], +2577 my_idx: usize, +2578 new_addrs: BTreeSet<DirectAddr>, +2579 ) { +2580 let me = &stacks[my_idx]; +2581 for (i, m) in stacks.iter().enumerate() { +2582 if i == my_idx { +2583 continue; +2584 } +2585 +2586 let addr = NodeAddr { +2587 node_id: me.public(), +2588 relay_url: None, +2589 direct_addresses: new_addrs.iter().map(|ep| ep.addr).collect(), +2590 }; +2591 m.endpoint.magic_sock().add_test_addr(addr); +2592 } +2593 } +2594 +2595 // For each node, start a task which monitors its local endpoints and registers them +2596 // with the other nodes as local endpoints become known. +2597 let mut tasks = JoinSet::new(); +2598 for (my_idx, m) in stacks.iter().enumerate() { +2599 let m = m.clone(); +2600 let stacks = stacks.clone(); +2601 tasks.spawn(async move { +2602 let me = m.endpoint.node_id().fmt_short(); +2603 let mut stream = m.endpoint.direct_addresses().stream().filter_map(|i| i); +2604 while let Some(new_eps) = stream.next().await { +2605 info!(%me, "conn{} endpoints update: {:?}", my_idx + 1, new_eps); +2606 update_direct_addrs(&stacks, my_idx, new_eps); +2607 } +2608 }); +2609 } +2610 +2611 // Wait for all nodes to be registered with each other. +2612 time::timeout(Duration::from_secs(10), async move { +2613 let all_node_ids: Vec<_> = stacks.iter().map(|ms| ms.endpoint.node_id()).collect(); +2614 loop { +2615 let mut ready = Vec::with_capacity(stacks.len()); +2616 for ms in stacks.iter() { +2617 let endpoints = ms.tracked_endpoints(); +2618 let my_node_id = ms.endpoint.node_id(); +2619 let all_nodes_meshed = all_node_ids +2620 .iter() +2621 .filter(|node_id| **node_id != my_node_id) +2622 .all(|node_id| endpoints.contains(node_id)); +2623 ready.push(all_nodes_meshed); +2624 } +2625 if ready.iter().all(|meshed| *meshed) { +2626 break; +2627 } +2628 time::sleep(Duration::from_millis(200)).await; +2629 } +2630 }) +2631 .await +2632 .context("timeout")?; +2633 info!("all nodes meshed"); +2634 Ok(tasks) +2635 } +2636 +2637 #[instrument(skip_all, fields(me = %ep.endpoint.node_id().fmt_short()))] +2638 async fn echo_receiver(ep: MagicStack, loss: ExpectedLoss) -> Result { +2639 info!("accepting conn"); +2640 let conn = ep.endpoint.accept().await.expect("no conn"); +2641 +2642 info!("connecting"); +2643 let conn = conn.await.context("connecting")?; +2644 info!("accepting bi"); +2645 let (mut send_bi, mut recv_bi) = conn.accept_bi().await.context("accept bi")?; +2646 +2647 info!("reading"); +2648 let val = recv_bi +2649 .read_to_end(usize::MAX) +2650 .await +2651 .context("read to end")?; +2652 +2653 info!("replying"); +2654 for chunk in val.chunks(12) { +2655 send_bi.write_all(chunk).await.context("write all")?; +2656 } +2657 +2658 info!("finishing"); +2659 send_bi.finish().context("finish")?; +2660 send_bi.stopped().await.context("stopped")?; +2661 +2662 let stats = conn.stats(); +2663 info!("stats: {:#?}", stats); +2664 // TODO: ensure panics in this function are reported ok +2665 if matches!(loss, ExpectedLoss::AlmostNone) { +2666 for (id, path) in &stats.paths { +2667 assert!( +2668 path.lost_packets < 10, +2669 "[receiver] path {id:?} should not loose many packets", +2670 ); +2671 } +2672 } +2673 +2674 info!("close"); +2675 conn.close(0u32.into(), b"done"); +2676 info!("wait idle"); +2677 ep.endpoint.endpoint().wait_idle().await; 2678 -2679 info!("opening bi"); -2680 let (mut send_bi, mut recv_bi) = conn.open_bi().await.context("open bi")?; +2679 Ok(()) +2680 } 2681 -2682 info!("writing message"); -2683 send_bi.write_all(msg).await.context("write all")?; -2684 -2685 info!("finishing"); -2686 send_bi.finish().context("finish")?; -2687 send_bi.stopped().await.context("stopped")?; -2688 -2689 info!("reading_to_end"); -2690 let val = recv_bi -2691 .read_to_end(usize::MAX) -2692 .await -2693 .context("read to end")?; -2694 assert_eq!( -2695 val, -2696 msg, -2697 "[sender] expected {}, got {}", -2698 HEXLOWER.encode(msg), -2699 HEXLOWER.encode(&val) -2700 ); -2701 -2702 let stats = conn.stats(); -2703 info!("stats: {:#?}", stats); -2704 if matches!(loss, ExpectedLoss::AlmostNone) { -2705 for (id, path) in &stats.paths { -2706 assert!( -2707 path.lost_packets < 10, -2708 "[sender] path {id:?} should not loose many packets", -2709 ); -2710 } -2711 } -2712 -2713 info!("close"); -2714 conn.close(0u32.into(), b"done"); -2715 info!("wait idle"); -2716 ep.endpoint.endpoint().wait_idle().await; -2717 Ok(()) -2718 } -2719 -2720 #[derive(Debug, Copy, Clone)] -2721 enum ExpectedLoss { -2722 AlmostNone, -2723 YeahSure, -2724 } -2725 -2726 /// Runs a roundtrip between the [`echo_sender`] and [`echo_receiver`]. -2727 async fn run_roundtrip( -2728 sender: MagicStack, -2729 receiver: MagicStack, -2730 payload: &[u8], -2731 loss: ExpectedLoss, -2732 ) { -2733 let send_node_id = sender.endpoint.node_id(); -2734 let recv_node_id = receiver.endpoint.node_id(); -2735 info!("\nroundtrip: {send_node_id:#} -> {recv_node_id:#}"); -2736 -2737 let receiver_task = tokio::spawn(echo_receiver(receiver, loss)); -2738 let sender_res = echo_sender(sender, recv_node_id, payload, loss).await; -2739 let sender_is_err = match sender_res { -2740 Ok(()) => false, -2741 Err(err) => { -2742 eprintln!("[sender] Error:\n{err:#?}"); -2743 true -2744 } -2745 }; -2746 let receiver_is_err = match receiver_task.await { -2747 Ok(Ok(())) => false, -2748 Ok(Err(err)) => { -2749 eprintln!("[receiver] Error:\n{err:#?}"); -2750 true -2751 } -2752 Err(joinerr) => { -2753 if joinerr.is_panic() { -2754 std::panic::resume_unwind(joinerr.into_panic()); -2755 } else { -2756 eprintln!("[receiver] Error:\n{joinerr:#?}"); -2757 } -2758 true -2759 } -2760 }; -2761 if sender_is_err || receiver_is_err { -2762 panic!("Sender or receiver errored"); -2763 } -2764 } -2765 -2766 #[tokio::test(flavor = "multi_thread")] -2767 #[traced_test] -2768 async fn test_two_devices_roundtrip_quinn_magic() -> Result { -2769 let m1 = MagicStack::new(RelayMode::Disabled).await; -2770 let m2 = MagicStack::new(RelayMode::Disabled).await; -2771 -2772 let _guard = mesh_stacks(vec![m1.clone(), m2.clone()]).await?; -2773 -2774 for i in 0..5 { -2775 info!("\n-- round {i}"); -2776 run_roundtrip( -2777 m1.clone(), -2778 m2.clone(), -2779 b"hello m1", -2780 ExpectedLoss::AlmostNone, -2781 ) -2782 .await; -2783 run_roundtrip( -2784 m2.clone(), -2785 m1.clone(), -2786 b"hello m2", -2787 ExpectedLoss::AlmostNone, -2788 ) -2789 .await; -2790 -2791 info!("\n-- larger data"); -2792 let mut data = vec![0u8; 10 * 1024]; -2793 rand::thread_rng().fill_bytes(&mut data); -2794 run_roundtrip(m1.clone(), m2.clone(), &data, ExpectedLoss::AlmostNone).await; -2795 run_roundtrip(m2.clone(), m1.clone(), &data, ExpectedLoss::AlmostNone).await; -2796 } -2797 -2798 Ok(()) -2799 } -2800 -2801 #[tokio::test] -2802 #[traced_test] -2803 async fn test_regression_network_change_rebind_wakes_connection_driver() -> n0_snafu::Result { -2804 let m1 = MagicStack::new(RelayMode::Disabled).await; -2805 let m2 = MagicStack::new(RelayMode::Disabled).await; -2806 -2807 println!("Net change"); -2808 m1.endpoint.magic_sock().force_network_change(true).await; -2809 tokio::time::sleep(Duration::from_secs(1)).await; // wait for socket rebinding -2810 -2811 let _guard = mesh_stacks(vec![m1.clone(), m2.clone()]).await?; -2812 -2813 let _handle = AbortOnDropHandle::new(tokio::spawn({ -2814 let endpoint = m2.endpoint.clone(); -2815 async move { -2816 while let Some(incoming) = endpoint.accept().await { -2817 println!("Incoming first conn!"); -2818 let conn = incoming.await.e()?; -2819 conn.closed().await; -2820 } -2821 -2822 Ok::<_, n0_snafu::Error>(()) -2823 } -2824 })); -2825 -2826 println!("first conn!"); -2827 let conn = m1 -2828 .endpoint -2829 .connect(m2.endpoint.node_addr().initialized().await?, ALPN) -2830 .await?; -2831 println!("Closing first conn"); -2832 conn.close(0u32.into(), b"bye lolz"); -2833 conn.closed().await; -2834 println!("Closed first conn"); +2682 #[instrument(skip_all, fields(me = %ep.endpoint.node_id().fmt_short()))] +2683 async fn echo_sender( +2684 ep: MagicStack, +2685 dest_id: PublicKey, +2686 msg: &[u8], +2687 loss: ExpectedLoss, +2688 ) -> Result { +2689 info!("connecting to {}", dest_id.fmt_short()); +2690 let dest = NodeAddr::new(dest_id); +2691 let conn = ep.endpoint.connect(dest, ALPN).await?; +2692 +2693 info!("opening bi"); +2694 let (mut send_bi, mut recv_bi) = conn.open_bi().await.context("open bi")?; +2695 +2696 info!("writing message"); +2697 send_bi.write_all(msg).await.context("write all")?; +2698 +2699 info!("finishing"); +2700 send_bi.finish().context("finish")?; +2701 send_bi.stopped().await.context("stopped")?; +2702 +2703 info!("reading_to_end"); +2704 let val = recv_bi +2705 .read_to_end(usize::MAX) +2706 .await +2707 .context("read to end")?; +2708 assert_eq!( +2709 val, +2710 msg, +2711 "[sender] expected {}, got {}", +2712 HEXLOWER.encode(msg), +2713 HEXLOWER.encode(&val) +2714 ); +2715 +2716 let stats = conn.stats(); +2717 info!("stats: {:#?}", stats); +2718 if matches!(loss, ExpectedLoss::AlmostNone) { +2719 for (id, path) in &stats.paths { +2720 assert!( +2721 path.lost_packets < 10, +2722 "[sender] path {id:?} should not loose many packets", +2723 ); +2724 } +2725 } +2726 +2727 info!("close"); +2728 conn.close(0u32.into(), b"done"); +2729 info!("wait idle"); +2730 ep.endpoint.endpoint().wait_idle().await; +2731 Ok(()) +2732 } +2733 +2734 #[derive(Debug, Copy, Clone)] +2735 enum ExpectedLoss { +2736 AlmostNone, +2737 YeahSure, +2738 } +2739 +2740 /// Runs a roundtrip between the [`echo_sender`] and [`echo_receiver`]. +2741 async fn run_roundtrip( +2742 sender: MagicStack, +2743 receiver: MagicStack, +2744 payload: &[u8], +2745 loss: ExpectedLoss, +2746 ) { +2747 let send_node_id = sender.endpoint.node_id(); +2748 let recv_node_id = receiver.endpoint.node_id(); +2749 info!("\nroundtrip: {send_node_id:#} -> {recv_node_id:#}"); +2750 +2751 let receiver_task = tokio::spawn(echo_receiver(receiver, loss)); +2752 let sender_res = echo_sender(sender, recv_node_id, payload, loss).await; +2753 let sender_is_err = match sender_res { +2754 Ok(()) => false, +2755 Err(err) => { +2756 eprintln!("[sender] Error:\n{err:#?}"); +2757 true +2758 } +2759 }; +2760 let receiver_is_err = match receiver_task.await { +2761 Ok(Ok(())) => false, +2762 Ok(Err(err)) => { +2763 eprintln!("[receiver] Error:\n{err:#?}"); +2764 true +2765 } +2766 Err(joinerr) => { +2767 if joinerr.is_panic() { +2768 std::panic::resume_unwind(joinerr.into_panic()); +2769 } else { +2770 eprintln!("[receiver] Error:\n{joinerr:#?}"); +2771 } +2772 true +2773 } +2774 }; +2775 if sender_is_err || receiver_is_err { +2776 panic!("Sender or receiver errored"); +2777 } +2778 } +2779 +2780 #[tokio::test(flavor = "multi_thread")] +2781 #[traced_test] +2782 async fn test_two_devices_roundtrip_quinn_magic() -> Result { +2783 let m1 = MagicStack::new(RelayMode::Disabled).await; +2784 let m2 = MagicStack::new(RelayMode::Disabled).await; +2785 +2786 let _guard = mesh_stacks(vec![m1.clone(), m2.clone()]).await?; +2787 +2788 for i in 0..5 { +2789 info!("\n-- round {i}"); +2790 run_roundtrip( +2791 m1.clone(), +2792 m2.clone(), +2793 b"hello m1", +2794 ExpectedLoss::AlmostNone, +2795 ) +2796 .await; +2797 run_roundtrip( +2798 m2.clone(), +2799 m1.clone(), +2800 b"hello m2", +2801 ExpectedLoss::AlmostNone, +2802 ) +2803 .await; +2804 +2805 info!("\n-- larger data"); +2806 let mut data = vec![0u8; 10 * 1024]; +2807 rand::thread_rng().fill_bytes(&mut data); +2808 run_roundtrip(m1.clone(), m2.clone(), &data, ExpectedLoss::AlmostNone).await; +2809 run_roundtrip(m2.clone(), m1.clone(), &data, ExpectedLoss::AlmostNone).await; +2810 } +2811 +2812 Ok(()) +2813 } +2814 +2815 #[tokio::test] +2816 #[traced_test] +2817 async fn test_regression_network_change_rebind_wakes_connection_driver() -> n0_snafu::Result { +2818 let m1 = MagicStack::new(RelayMode::Disabled).await; +2819 let m2 = MagicStack::new(RelayMode::Disabled).await; +2820 +2821 println!("Net change"); +2822 m1.endpoint.magic_sock().force_network_change(true).await; +2823 tokio::time::sleep(Duration::from_secs(1)).await; // wait for socket rebinding +2824 +2825 let _guard = mesh_stacks(vec![m1.clone(), m2.clone()]).await?; +2826 +2827 let _handle = AbortOnDropHandle::new(tokio::spawn({ +2828 let endpoint = m2.endpoint.clone(); +2829 async move { +2830 while let Some(incoming) = endpoint.accept().await { +2831 println!("Incoming first conn!"); +2832 let conn = incoming.await.e()?; +2833 conn.closed().await; +2834 } 2835 -2836 Ok(()) -2837 } -2838 -2839 #[tokio::test(flavor = "multi_thread")] -2840 #[traced_test] -2841 async fn test_two_devices_roundtrip_network_change() -> Result { -2842 time::timeout( -2843 Duration::from_secs(90), -2844 test_two_devices_roundtrip_network_change_impl(), -2845 ) -2846 .await -2847 .context("timeout")? -2848 } +2836 Ok::<_, n0_snafu::Error>(()) +2837 } +2838 })); +2839 +2840 println!("first conn!"); +2841 let conn = m1 +2842 .endpoint +2843 .connect(m2.endpoint.node_addr().initialized().await?, ALPN) +2844 .await?; +2845 println!("Closing first conn"); +2846 conn.close(0u32.into(), b"bye lolz"); +2847 conn.closed().await; +2848 println!("Closed first conn"); 2849 -2850 /// Same structure as `test_two_devices_roundtrip_quinn_magic`, but interrupts regularly -2851 /// with (simulated) network changes. -2852 async fn test_two_devices_roundtrip_network_change_impl() -> Result { -2853 let m1 = MagicStack::new(RelayMode::Disabled).await; -2854 let m2 = MagicStack::new(RelayMode::Disabled).await; -2855 -2856 let _guard = mesh_stacks(vec![m1.clone(), m2.clone()]).await?; -2857 -2858 let offset = || { -2859 let delay = rand::thread_rng().gen_range(10..=500); -2860 Duration::from_millis(delay) -2861 }; -2862 let rounds = 5; +2850 Ok(()) +2851 } +2852 +2853 #[tokio::test(flavor = "multi_thread")] +2854 #[traced_test] +2855 async fn test_two_devices_roundtrip_network_change() -> Result { +2856 time::timeout( +2857 Duration::from_secs(90), +2858 test_two_devices_roundtrip_network_change_impl(), +2859 ) +2860 .await +2861 .context("timeout")? +2862 } 2863 -2864 // Regular network changes to m1 only. -2865 let m1_network_change_guard = { -2866 let m1 = m1.clone(); -2867 let task = tokio::spawn(async move { -2868 loop { -2869 println!("[m1] network change"); -2870 m1.endpoint.magic_sock().force_network_change(true).await; -2871 time::sleep(offset()).await; -2872 } -2873 }); -2874 AbortOnDropHandle::new(task) +2864 /// Same structure as `test_two_devices_roundtrip_quinn_magic`, but interrupts regularly +2865 /// with (simulated) network changes. +2866 async fn test_two_devices_roundtrip_network_change_impl() -> Result { +2867 let m1 = MagicStack::new(RelayMode::Disabled).await; +2868 let m2 = MagicStack::new(RelayMode::Disabled).await; +2869 +2870 let _guard = mesh_stacks(vec![m1.clone(), m2.clone()]).await?; +2871 +2872 let offset = || { +2873 let delay = rand::thread_rng().gen_range(10..=500); +2874 Duration::from_millis(delay) 2875 }; -2876 -2877 for i in 0..rounds { -2878 println!("-- [m1 changes] round {}", i + 1); -2879 run_roundtrip(m1.clone(), m2.clone(), b"hello m1", ExpectedLoss::YeahSure).await; -2880 run_roundtrip(m2.clone(), m1.clone(), b"hello m2", ExpectedLoss::YeahSure).await; -2881 -2882 println!("-- [m1 changes] larger data"); -2883 let mut data = vec![0u8; 10 * 1024]; -2884 rand::thread_rng().fill_bytes(&mut data); -2885 run_roundtrip(m1.clone(), m2.clone(), &data, ExpectedLoss::YeahSure).await; -2886 run_roundtrip(m2.clone(), m1.clone(), &data, ExpectedLoss::YeahSure).await; -2887 } -2888 -2889 std::mem::drop(m1_network_change_guard); +2876 let rounds = 5; +2877 +2878 // Regular network changes to m1 only. +2879 let m1_network_change_guard = { +2880 let m1 = m1.clone(); +2881 let task = tokio::spawn(async move { +2882 loop { +2883 println!("[m1] network change"); +2884 m1.endpoint.magic_sock().force_network_change(true).await; +2885 time::sleep(offset()).await; +2886 } +2887 }); +2888 AbortOnDropHandle::new(task) +2889 }; 2890 -2891 // Regular network changes to m2 only. -2892 let m2_network_change_guard = { -2893 let m2 = m2.clone(); -2894 let task = tokio::spawn(async move { -2895 loop { -2896 println!("[m2] network change"); -2897 m2.endpoint.magic_sock().force_network_change(true).await; -2898 time::sleep(offset()).await; -2899 } -2900 }); -2901 AbortOnDropHandle::new(task) -2902 }; -2903 -2904 for i in 0..rounds { -2905 println!("-- [m2 changes] round {}", i + 1); -2906 run_roundtrip(m1.clone(), m2.clone(), b"hello m1", ExpectedLoss::YeahSure).await; -2907 run_roundtrip(m2.clone(), m1.clone(), b"hello m2", ExpectedLoss::YeahSure).await; -2908 -2909 println!("-- [m2 changes] larger data"); -2910 let mut data = vec![0u8; 10 * 1024]; -2911 rand::thread_rng().fill_bytes(&mut data); -2912 run_roundtrip(m1.clone(), m2.clone(), &data, ExpectedLoss::YeahSure).await; -2913 run_roundtrip(m2.clone(), m1.clone(), &data, ExpectedLoss::YeahSure).await; -2914 } -2915 -2916 std::mem::drop(m2_network_change_guard); +2891 for i in 0..rounds { +2892 println!("-- [m1 changes] round {}", i + 1); +2893 run_roundtrip(m1.clone(), m2.clone(), b"hello m1", ExpectedLoss::YeahSure).await; +2894 run_roundtrip(m2.clone(), m1.clone(), b"hello m2", ExpectedLoss::YeahSure).await; +2895 +2896 println!("-- [m1 changes] larger data"); +2897 let mut data = vec![0u8; 10 * 1024]; +2898 rand::thread_rng().fill_bytes(&mut data); +2899 run_roundtrip(m1.clone(), m2.clone(), &data, ExpectedLoss::YeahSure).await; +2900 run_roundtrip(m2.clone(), m1.clone(), &data, ExpectedLoss::YeahSure).await; +2901 } +2902 +2903 std::mem::drop(m1_network_change_guard); +2904 +2905 // Regular network changes to m2 only. +2906 let m2_network_change_guard = { +2907 let m2 = m2.clone(); +2908 let task = tokio::spawn(async move { +2909 loop { +2910 println!("[m2] network change"); +2911 m2.endpoint.magic_sock().force_network_change(true).await; +2912 time::sleep(offset()).await; +2913 } +2914 }); +2915 AbortOnDropHandle::new(task) +2916 }; 2917 -2918 // Regular network changes to both m1 and m2 only. -2919 let m1_m2_network_change_guard = { -2920 let m1 = m1.clone(); -2921 let m2 = m2.clone(); -2922 let task = tokio::spawn(async move { -2923 println!("-- [m1] network change"); -2924 m1.endpoint.magic_sock().force_network_change(true).await; -2925 println!("-- [m2] network change"); -2926 m2.endpoint.magic_sock().force_network_change(true).await; -2927 time::sleep(offset()).await; -2928 }); -2929 AbortOnDropHandle::new(task) -2930 }; +2918 for i in 0..rounds { +2919 println!("-- [m2 changes] round {}", i + 1); +2920 run_roundtrip(m1.clone(), m2.clone(), b"hello m1", ExpectedLoss::YeahSure).await; +2921 run_roundtrip(m2.clone(), m1.clone(), b"hello m2", ExpectedLoss::YeahSure).await; +2922 +2923 println!("-- [m2 changes] larger data"); +2924 let mut data = vec![0u8; 10 * 1024]; +2925 rand::thread_rng().fill_bytes(&mut data); +2926 run_roundtrip(m1.clone(), m2.clone(), &data, ExpectedLoss::YeahSure).await; +2927 run_roundtrip(m2.clone(), m1.clone(), &data, ExpectedLoss::YeahSure).await; +2928 } +2929 +2930 std::mem::drop(m2_network_change_guard); 2931 -2932 for i in 0..rounds { -2933 println!("-- [m1 & m2 changes] round {}", i + 1); -2934 run_roundtrip(m1.clone(), m2.clone(), b"hello m1", ExpectedLoss::YeahSure).await; -2935 run_roundtrip(m2.clone(), m1.clone(), b"hello m2", ExpectedLoss::YeahSure).await; -2936 -2937 println!("-- [m1 & m2 changes] larger data"); -2938 let mut data = vec![0u8; 10 * 1024]; -2939 rand::thread_rng().fill_bytes(&mut data); -2940 run_roundtrip(m1.clone(), m2.clone(), &data, ExpectedLoss::YeahSure).await; -2941 run_roundtrip(m2.clone(), m1.clone(), &data, ExpectedLoss::YeahSure).await; -2942 } -2943 -2944 std::mem::drop(m1_m2_network_change_guard); -2945 Ok(()) -2946 } -2947 -2948 #[tokio::test(flavor = "multi_thread")] -2949 #[traced_test] -2950 async fn test_two_devices_setup_teardown() -> Result { -2951 for i in 0..10 { -2952 println!("-- round {i}"); -2953 println!("setting up magic stack"); -2954 let m1 = MagicStack::new(RelayMode::Disabled).await; -2955 let m2 = MagicStack::new(RelayMode::Disabled).await; -2956 -2957 let _guard = mesh_stacks(vec![m1.clone(), m2.clone()]).await?; -2958 -2959 println!("closing endpoints"); -2960 let msock1 = m1.endpoint.magic_sock(); -2961 let msock2 = m2.endpoint.magic_sock(); -2962 m1.endpoint.close().await; -2963 m2.endpoint.close().await; -2964 -2965 assert!(msock1.msock.is_closed()); -2966 assert!(msock2.msock.is_closed()); -2967 } -2968 Ok(()) -2969 } +2932 // Regular network changes to both m1 and m2 only. +2933 let m1_m2_network_change_guard = { +2934 let m1 = m1.clone(); +2935 let m2 = m2.clone(); +2936 let task = tokio::spawn(async move { +2937 println!("-- [m1] network change"); +2938 m1.endpoint.magic_sock().force_network_change(true).await; +2939 println!("-- [m2] network change"); +2940 m2.endpoint.magic_sock().force_network_change(true).await; +2941 time::sleep(offset()).await; +2942 }); +2943 AbortOnDropHandle::new(task) +2944 }; +2945 +2946 for i in 0..rounds { +2947 println!("-- [m1 & m2 changes] round {}", i + 1); +2948 run_roundtrip(m1.clone(), m2.clone(), b"hello m1", ExpectedLoss::YeahSure).await; +2949 run_roundtrip(m2.clone(), m1.clone(), b"hello m2", ExpectedLoss::YeahSure).await; +2950 +2951 println!("-- [m1 & m2 changes] larger data"); +2952 let mut data = vec![0u8; 10 * 1024]; +2953 rand::thread_rng().fill_bytes(&mut data); +2954 run_roundtrip(m1.clone(), m2.clone(), &data, ExpectedLoss::YeahSure).await; +2955 run_roundtrip(m2.clone(), m1.clone(), &data, ExpectedLoss::YeahSure).await; +2956 } +2957 +2958 std::mem::drop(m1_m2_network_change_guard); +2959 Ok(()) +2960 } +2961 +2962 #[tokio::test(flavor = "multi_thread")] +2963 #[traced_test] +2964 async fn test_two_devices_setup_teardown() -> Result { +2965 for i in 0..10 { +2966 println!("-- round {i}"); +2967 println!("setting up magic stack"); +2968 let m1 = MagicStack::new(RelayMode::Disabled).await; +2969 let m2 = MagicStack::new(RelayMode::Disabled).await; 2970 -2971 #[tokio::test] -2972 #[traced_test] -2973 async fn test_local_endpoints() { -2974 let ms = Handle::new(Default::default()).await.unwrap(); -2975 -2976 // See if we can get endpoints. -2977 let eps0 = ms.direct_addresses().initialized().await.unwrap(); -2978 println!("{eps0:?}"); -2979 assert!(!eps0.is_empty()); -2980 -2981 // Getting the endpoints again immediately should give the same results. -2982 let eps1 = ms.direct_addresses().initialized().await.unwrap(); -2983 println!("{eps1:?}"); -2984 assert_eq!(eps0, eps1); -2985 } -2986 -2987 /// Creates a new [`quinn::Endpoint`] hooked up to a [`MagicSock`]. -2988 /// -2989 /// This is without involving [`crate::endpoint::Endpoint`]. The socket will accept -2990 /// connections using [`ALPN`]. -2991 /// -2992 /// Use [`magicsock_connect`] to establish connections. -2993 #[instrument(name = "ep", skip_all, fields(me = secret_key.public().fmt_short()))] -2994 async fn magicsock_ep(secret_key: SecretKey) -> Result<Handle> { -2995 let quic_server_config = -2996 tls::TlsConfig::new(secret_key.clone()).make_server_config(vec![ALPN.to_vec()], true); -2997 let mut server_config = ServerConfig::with_crypto(Arc::new(quic_server_config)); -2998 server_config.transport_config(Arc::new(quinn::TransportConfig::default())); -2999 -3000 let dns_resolver = DnsResolver::new(); -3001 let opts = Options { -3002 addr_v4: None, -3003 addr_v6: None, -3004 secret_key: secret_key.clone(), -3005 relay_map: RelayMap::empty(), -3006 node_map: None, -3007 discovery: None, -3008 discovery_user_data: None, -3009 dns_resolver, -3010 proxy_url: None, -3011 server_config, -3012 insecure_skip_relay_cert_verify: false, -3013 path_selection: PathSelection::default(), -3014 metrics: Default::default(), -3015 }; -3016 let msock = MagicSock::spawn(opts).await?; -3017 Ok(msock) -3018 } -3019 -3020 /// Connects from `ep` returned by [`magicsock_ep`] to the `node_id`. -3021 /// -3022 /// Uses [`ALPN`], `node_id`, must match `addr`. -3023 #[instrument(name = "connect", skip_all, fields(me = ep_secret_key.public().fmt_short()))] -3024 async fn magicsock_connect( -3025 ep: &quinn::Endpoint, -3026 ep_secret_key: SecretKey, -3027 addr: NodeIdMappedAddr, -3028 node_id: NodeId, -3029 ) -> Result<quinn::Connection> { -3030 // Endpoint::connect sets this, do the same to have similar behaviour. -3031 let mut transport_config = quinn::TransportConfig::default(); -3032 transport_config.keep_alive_interval(Some(Duration::from_secs(1))); +2971 let _guard = mesh_stacks(vec![m1.clone(), m2.clone()]).await?; +2972 +2973 println!("closing endpoints"); +2974 let msock1 = m1.endpoint.magic_sock(); +2975 let msock2 = m2.endpoint.magic_sock(); +2976 m1.endpoint.close().await; +2977 m2.endpoint.close().await; +2978 +2979 assert!(msock1.msock.is_closed()); +2980 assert!(msock2.msock.is_closed()); +2981 } +2982 Ok(()) +2983 } +2984 +2985 #[tokio::test] +2986 #[traced_test] +2987 async fn test_local_endpoints() { +2988 let ms = Handle::new(Default::default()).await.unwrap(); +2989 +2990 // See if we can get endpoints. +2991 let eps0 = ms.direct_addresses().initialized().await.unwrap(); +2992 println!("{eps0:?}"); +2993 assert!(!eps0.is_empty()); +2994 +2995 // Getting the endpoints again immediately should give the same results. +2996 let eps1 = ms.direct_addresses().initialized().await.unwrap(); +2997 println!("{eps1:?}"); +2998 assert_eq!(eps0, eps1); +2999 } +3000 +3001 /// Creates a new [`quinn::Endpoint`] hooked up to a [`MagicSock`]. +3002 /// +3003 /// This is without involving [`crate::endpoint::Endpoint`]. The socket will accept +3004 /// connections using [`ALPN`]. +3005 /// +3006 /// Use [`magicsock_connect`] to establish connections. +3007 #[instrument(name = "ep", skip_all, fields(me = secret_key.public().fmt_short()))] +3008 async fn magicsock_ep(secret_key: SecretKey) -> Result<Handle> { +3009 let quic_server_config = +3010 tls::TlsConfig::new(secret_key.clone()).make_server_config(vec![ALPN.to_vec()], true); +3011 let mut server_config = ServerConfig::with_crypto(Arc::new(quic_server_config)); +3012 server_config.transport_config(Arc::new(quinn::TransportConfig::default())); +3013 +3014 let dns_resolver = DnsResolver::new(); +3015 let opts = Options { +3016 addr_v4: None, +3017 addr_v6: None, +3018 secret_key: secret_key.clone(), +3019 relay_map: RelayMap::empty(), +3020 node_map: None, +3021 discovery: None, +3022 discovery_user_data: None, +3023 dns_resolver, +3024 proxy_url: None, +3025 server_config, +3026 insecure_skip_relay_cert_verify: false, +3027 path_selection: PathSelection::default(), +3028 metrics: Default::default(), +3029 }; +3030 let msock = MagicSock::spawn(opts).await?; +3031 Ok(msock) +3032 } 3033 -3034 magicsock_connect_with_transport_config( -3035 ep, -3036 ep_secret_key, -3037 addr, -3038 node_id, -3039 Arc::new(transport_config), -3040 ) -3041 .await -3042 } -3043 -3044 /// Connects from `ep` returned by [`magicsock_ep`] to the `node_id`. -3045 /// -3046 /// This version allows customising the transport config. -3047 /// -3048 /// Uses [`ALPN`], `node_id`, must match `addr`. -3049 #[instrument(name = "connect", skip_all, fields(me = ep_secret_key.public().fmt_short()))] -3050 async fn magicsock_connect_with_transport_config( -3051 ep: &quinn::Endpoint, -3052 ep_secret_key: SecretKey, -3053 mapped_addr: NodeIdMappedAddr, -3054 node_id: NodeId, -3055 transport_config: Arc<quinn::TransportConfig>, -3056 ) -> Result<quinn::Connection> { -3057 let alpns = vec![ALPN.to_vec()]; -3058 let quic_client_config = -3059 tls::TlsConfig::new(ep_secret_key.clone()).make_client_config(alpns, true); -3060 let mut client_config = quinn::ClientConfig::new(Arc::new(quic_client_config)); -3061 client_config.transport_config(transport_config); -3062 let connect = ep -3063 .connect_with( -3064 client_config, -3065 mapped_addr.private_socket_addr(), -3066 &tls::name::encode(node_id), -3067 ) -3068 .context("connect")?; -3069 let connection = connect.await.e()?; -3070 Ok(connection) -3071 } -3072 -3073 #[tokio::test] -3074 #[traced_test] -3075 async fn test_try_send_no_send_addr() { -3076 // Regression test: if there is no send_addr we should keep being able to use the -3077 // Endpoint. -3078 -3079 let secret_key_1 = SecretKey::from_bytes(&[1u8; 32]); -3080 let secret_key_2 = SecretKey::from_bytes(&[2u8; 32]); -3081 let node_id_2 = secret_key_2.public(); -3082 let secret_key_missing_node = SecretKey::from_bytes(&[255u8; 32]); -3083 let node_id_missing_node = secret_key_missing_node.public(); -3084 -3085 let msock_1 = magicsock_ep(secret_key_1.clone()).await.unwrap(); +3034 /// Connects from `ep` returned by [`magicsock_ep`] to the `node_id`. +3035 /// +3036 /// Uses [`ALPN`], `node_id`, must match `addr`. +3037 #[instrument(name = "connect", skip_all, fields(me = ep_secret_key.public().fmt_short()))] +3038 async fn magicsock_connect( +3039 ep: &quinn::Endpoint, +3040 ep_secret_key: SecretKey, +3041 addr: NodeIdMappedAddr, +3042 node_id: NodeId, +3043 ) -> Result<quinn::Connection> { +3044 // Endpoint::connect sets this, do the same to have similar behaviour. +3045 let mut transport_config = quinn::TransportConfig::default(); +3046 transport_config.keep_alive_interval(Some(Duration::from_secs(1))); +3047 +3048 magicsock_connect_with_transport_config( +3049 ep, +3050 ep_secret_key, +3051 addr, +3052 node_id, +3053 Arc::new(transport_config), +3054 ) +3055 .await +3056 } +3057 +3058 /// Connects from `ep` returned by [`magicsock_ep`] to the `node_id`. +3059 /// +3060 /// This version allows customising the transport config. +3061 /// +3062 /// Uses [`ALPN`], `node_id`, must match `addr`. +3063 #[instrument(name = "connect", skip_all, fields(me = ep_secret_key.public().fmt_short()))] +3064 async fn magicsock_connect_with_transport_config( +3065 ep: &quinn::Endpoint, +3066 ep_secret_key: SecretKey, +3067 mapped_addr: NodeIdMappedAddr, +3068 node_id: NodeId, +3069 transport_config: Arc<quinn::TransportConfig>, +3070 ) -> Result<quinn::Connection> { +3071 let alpns = vec![ALPN.to_vec()]; +3072 let quic_client_config = +3073 tls::TlsConfig::new(ep_secret_key.clone()).make_client_config(alpns, true); +3074 let mut client_config = quinn::ClientConfig::new(Arc::new(quic_client_config)); +3075 client_config.transport_config(transport_config); +3076 let connect = ep +3077 .connect_with( +3078 client_config, +3079 mapped_addr.private_socket_addr(), +3080 &tls::name::encode(node_id), +3081 ) +3082 .context("connect")?; +3083 let connection = connect.await.e()?; +3084 Ok(connection) +3085 } 3086 -3087 // Generate an address not present in the NodeMap. -3088 let bad_addr = NodeIdMappedAddr::generate(); -3089 -3090 // 500ms is rather fast here. Running this locally it should always be the correct -3091 // timeout. If this is too slow however the test will not become flaky as we are -3092 // expecting the timeout, we might just get the timeout for the wrong reason. But -3093 // this speeds up the test. -3094 let res = tokio::time::timeout( -3095 Duration::from_millis(500), -3096 magicsock_connect( -3097 msock_1.endpoint(), -3098 secret_key_1.clone(), -3099 bad_addr, -3100 node_id_missing_node, -3101 ), -3102 ) -3103 .await; -3104 assert!(res.is_err(), "expecting timeout"); -3105 -3106 // Now check we can still create another connection with this endpoint. -3107 let msock_2 = magicsock_ep(secret_key_2.clone()).await.unwrap(); -3108 -3109 // This needs an accept task -3110 let accept_task = tokio::spawn({ -3111 async fn accept(ep: quinn::Endpoint) -> Result<()> { -3112 let incoming = ep.accept().await.context("no incoming")?; -3113 let _conn = incoming -3114 .accept() -3115 .context("accept")? -3116 .await -3117 .context("connecting")?; -3118 -3119 // Keep this connection alive for a while -3120 tokio::time::sleep(Duration::from_secs(10)).await; -3121 info!("accept finished"); -3122 Ok(()) -3123 } -3124 let ep = msock_2.endpoint().clone(); -3125 async move { -3126 if let Err(err) = accept(ep).await { -3127 error!("{err:#}"); -3128 } -3129 } -3130 .instrument(info_span!("ep2.accept, me = node_id_2.fmt_short()")) -3131 }); -3132 let _accept_task = AbortOnDropHandle::new(accept_task); -3133 -3134 let node_addr_2 = NodeAddr { -3135 node_id: node_id_2, -3136 relay_url: None, -3137 direct_addresses: msock_2 -3138 .direct_addresses() -3139 .initialized() -3140 .await -3141 .expect("no direct addrs") -3142 .into_iter() -3143 .map(|x| x.addr) -3144 .collect(), -3145 }; -3146 msock_1 -3147 .add_node_addr( -3148 node_addr_2, -3149 Source::NamedApp { -3150 name: "test".into(), -3151 }, -3152 ) -3153 .unwrap(); -3154 let addr = msock_1.get_mapping_addr(node_id_2).unwrap(); -3155 let res = tokio::time::timeout( -3156 Duration::from_secs(10), -3157 magicsock_connect(msock_1.endpoint(), secret_key_1.clone(), addr, node_id_2), -3158 ) -3159 .await -3160 .expect("timeout while connecting"); -3161 -3162 // aka assert!(res.is_ok()) but with nicer error reporting. -3163 res.unwrap(); -3164 -3165 // TODO: Now check if we can connect to a repaired ep_3, but we can't modify that -3166 // much internal state for now. -3167 } -3168 -3169 #[tokio::test] -3170 #[traced_test] -3171 async fn test_try_send_no_udp_addr_or_relay_url() { -3172 // This specifically tests the `if udp_addr.is_none() && relay_url.is_none()` -3173 // behaviour of MagicSock::try_send. -3174 -3175 let secret_key_1 = SecretKey::from_bytes(&[1u8; 32]); -3176 let secret_key_2 = SecretKey::from_bytes(&[2u8; 32]); -3177 let node_id_2 = secret_key_2.public(); +3087 #[tokio::test] +3088 #[traced_test] +3089 async fn test_try_send_no_send_addr() { +3090 // Regression test: if there is no send_addr we should keep being able to use the +3091 // Endpoint. +3092 +3093 let secret_key_1 = SecretKey::from_bytes(&[1u8; 32]); +3094 let secret_key_2 = SecretKey::from_bytes(&[2u8; 32]); +3095 let node_id_2 = secret_key_2.public(); +3096 let secret_key_missing_node = SecretKey::from_bytes(&[255u8; 32]); +3097 let node_id_missing_node = secret_key_missing_node.public(); +3098 +3099 let msock_1 = magicsock_ep(secret_key_1.clone()).await.unwrap(); +3100 +3101 // Generate an address not present in the NodeMap. +3102 let bad_addr = NodeIdMappedAddr::generate(); +3103 +3104 // 500ms is rather fast here. Running this locally it should always be the correct +3105 // timeout. If this is too slow however the test will not become flaky as we are +3106 // expecting the timeout, we might just get the timeout for the wrong reason. But +3107 // this speeds up the test. +3108 let res = tokio::time::timeout( +3109 Duration::from_millis(500), +3110 magicsock_connect( +3111 msock_1.endpoint(), +3112 secret_key_1.clone(), +3113 bad_addr, +3114 node_id_missing_node, +3115 ), +3116 ) +3117 .await; +3118 assert!(res.is_err(), "expecting timeout"); +3119 +3120 // Now check we can still create another connection with this endpoint. +3121 let msock_2 = magicsock_ep(secret_key_2.clone()).await.unwrap(); +3122 +3123 // This needs an accept task +3124 let accept_task = tokio::spawn({ +3125 async fn accept(ep: quinn::Endpoint) -> Result<()> { +3126 let incoming = ep.accept().await.context("no incoming")?; +3127 let _conn = incoming +3128 .accept() +3129 .context("accept")? +3130 .await +3131 .context("connecting")?; +3132 +3133 // Keep this connection alive for a while +3134 tokio::time::sleep(Duration::from_secs(10)).await; +3135 info!("accept finished"); +3136 Ok(()) +3137 } +3138 let ep = msock_2.endpoint().clone(); +3139 async move { +3140 if let Err(err) = accept(ep).await { +3141 error!("{err:#}"); +3142 } +3143 } +3144 .instrument(info_span!("ep2.accept, me = node_id_2.fmt_short()")) +3145 }); +3146 let _accept_task = AbortOnDropHandle::new(accept_task); +3147 +3148 let node_addr_2 = NodeAddr { +3149 node_id: node_id_2, +3150 relay_url: None, +3151 direct_addresses: msock_2 +3152 .direct_addresses() +3153 .initialized() +3154 .await +3155 .expect("no direct addrs") +3156 .into_iter() +3157 .map(|x| x.addr) +3158 .collect(), +3159 }; +3160 msock_1 +3161 .add_node_addr( +3162 node_addr_2, +3163 Source::NamedApp { +3164 name: "test".into(), +3165 }, +3166 ) +3167 .unwrap(); +3168 let addr = msock_1.get_mapping_addr(node_id_2).unwrap(); +3169 let res = tokio::time::timeout( +3170 Duration::from_secs(10), +3171 magicsock_connect(msock_1.endpoint(), secret_key_1.clone(), addr, node_id_2), +3172 ) +3173 .await +3174 .expect("timeout while connecting"); +3175 +3176 // aka assert!(res.is_ok()) but with nicer error reporting. +3177 res.unwrap(); 3178 -3179 let msock_1 = magicsock_ep(secret_key_1.clone()).await.unwrap(); -3180 let msock_2 = magicsock_ep(secret_key_2.clone()).await.unwrap(); -3181 let ep_2 = msock_2.endpoint().clone(); +3179 // TODO: Now check if we can connect to a repaired ep_3, but we can't modify that +3180 // much internal state for now. +3181 } 3182 -3183 // We need a task to accept the connection. -3184 let accept_task = tokio::spawn({ -3185 async fn accept(ep: quinn::Endpoint) -> Result<()> { -3186 let incoming = ep.accept().await.context("no incoming")?; -3187 let conn = incoming -3188 .accept() -3189 .context("accept")? -3190 .await -3191 .context("connecting")?; -3192 let mut stream = conn.accept_uni().await.context("accept uni")?; -3193 stream.read_to_end(1 << 16).await.context("read to end")?; -3194 info!("accept finished"); -3195 Ok(()) -3196 } -3197 async move { -3198 if let Err(err) = accept(ep_2).await { -3199 error!("{err:#}"); -3200 } -3201 } -3202 .instrument(info_span!("ep2.accept", me = node_id_2.fmt_short())) -3203 }); -3204 let _accept_task = AbortOnDropHandle::new(accept_task); -3205 -3206 // Add an empty entry in the NodeMap of ep_1 -3207 msock_1 -3208 .add_node_addr( -3209 NodeAddr { -3210 node_id: node_id_2, -3211 relay_url: None, -3212 direct_addresses: Default::default(), -3213 }, -3214 Source::NamedApp { -3215 name: "test".into(), -3216 }, -3217 ) -3218 .unwrap(); -3219 let addr_2 = msock_1.get_mapping_addr(node_id_2).unwrap(); -3220 -3221 // Set a low max_idle_timeout so quinn gives up on this quickly and our test does -3222 // not take forever. You need to check the log output to verify this is really -3223 // triggering the correct error. -3224 // In test_try_send_no_send_addr() above you may have noticed we used -3225 // tokio::time::timeout() on the connection attempt instead. Here however we want -3226 // Quinn itself to have fully given up on the connection attempt because we will -3227 // later connect to **the same** node. If Quinn did not give up on the connection -3228 // we'd close it on drop, and the retransmits of the close packets would interfere -3229 // with the next handshake, closing it during the handshake. This makes the test a -3230 // little slower though. -3231 let mut transport_config = quinn::TransportConfig::default(); -3232 transport_config.max_idle_timeout(Some(Duration::from_millis(200).try_into().unwrap())); -3233 let res = magicsock_connect_with_transport_config( -3234 msock_1.endpoint(), -3235 secret_key_1.clone(), -3236 addr_2, -3237 node_id_2, -3238 Arc::new(transport_config), -3239 ) -3240 .await; -3241 assert!(res.is_err(), "expected timeout"); -3242 info!("first connect timed out as expected"); -3243 -3244 // Provide correct addressing information -3245 msock_1 -3246 .add_node_addr( -3247 NodeAddr { -3248 node_id: node_id_2, -3249 relay_url: None, -3250 direct_addresses: msock_2 -3251 .direct_addresses() -3252 .initialized() -3253 .await -3254 .expect("no direct addrs") -3255 .into_iter() -3256 .map(|x| x.addr) -3257 .collect(), -3258 }, -3259 Source::NamedApp { -3260 name: "test".into(), -3261 }, -3262 ) -3263 .unwrap(); -3264 -3265 // We can now connect -3266 tokio::time::timeout(Duration::from_secs(10), async move { -3267 info!("establishing new connection"); -3268 let conn = -3269 magicsock_connect(msock_1.endpoint(), secret_key_1.clone(), addr_2, node_id_2) -3270 .await -3271 .unwrap(); -3272 info!("have connection"); -3273 let mut stream = conn.open_uni().await.unwrap(); -3274 stream.write_all(b"hello").await.unwrap(); -3275 stream.finish().unwrap(); -3276 stream.stopped().await.unwrap(); -3277 info!("finished stream"); -3278 }) -3279 .await -3280 .expect("connection timed out"); -3281 -3282 // TODO: could remove the addresses again, send, add it back and see it recover. -3283 // But we don't have that much private access to the NodeMap. This will do for now. -3284 } -3285 -3286 #[tokio::test] -3287 async fn test_add_node_addr() -> Result { -3288 let stack = MagicStack::new(RelayMode::Default).await; -3289 let mut rng = rand::thread_rng(); -3290 -3291 assert_eq!(stack.endpoint.magic_sock().node_map.node_count(), 0); -3292 -3293 // Empty -3294 let empty_addr = NodeAddr { -3295 node_id: SecretKey::generate(&mut rng).public(), -3296 relay_url: None, -3297 direct_addresses: Default::default(), -3298 }; -3299 let err = stack -3300 .endpoint -3301 .magic_sock() -3302 .add_node_addr(empty_addr, node_map::Source::App) -3303 .unwrap_err(); -3304 assert!(err -3305 .to_string() -3306 .to_lowercase() -3307 .contains("empty addressing info")); -3308 -3309 // relay url only -3310 let addr = NodeAddr { -3311 node_id: SecretKey::generate(&mut rng).public(), -3312 relay_url: Some("http://my-relay.com".parse().unwrap()), -3313 direct_addresses: Default::default(), -3314 }; -3315 stack -3316 .endpoint -3317 .magic_sock() -3318 .add_node_addr(addr, node_map::Source::App)?; -3319 assert_eq!(stack.endpoint.magic_sock().node_map.node_count(), 1); -3320 -3321 // addrs only -3322 let addr = NodeAddr { -3323 node_id: SecretKey::generate(&mut rng).public(), -3324 relay_url: None, -3325 direct_addresses: ["127.0.0.1:1234".parse().unwrap()].into_iter().collect(), -3326 }; -3327 stack -3328 .endpoint -3329 .magic_sock() -3330 .add_node_addr(addr, node_map::Source::App)?; -3331 assert_eq!(stack.endpoint.magic_sock().node_map.node_count(), 2); -3332 -3333 // both -3334 let addr = NodeAddr { -3335 node_id: SecretKey::generate(&mut rng).public(), -3336 relay_url: Some("http://my-relay.com".parse().unwrap()), -3337 direct_addresses: ["127.0.0.1:1234".parse().unwrap()].into_iter().collect(), -3338 }; -3339 stack -3340 .endpoint -3341 .magic_sock() -3342 .add_node_addr(addr, node_map::Source::App)?; -3343 assert_eq!(stack.endpoint.magic_sock().node_map.node_count(), 3); -3344 -3345 Ok(()) -3346 } -3347}

\ No newline at end of file +3183 #[tokio::test] +3184 #[traced_test] +3185 async fn test_try_send_no_udp_addr_or_relay_url() { +3186 // This specifically tests the `if udp_addr.is_none() && relay_url.is_none()` +3187 // behaviour of MagicSock::try_send. +3188 +3189 let secret_key_1 = SecretKey::from_bytes(&[1u8; 32]); +3190 let secret_key_2 = SecretKey::from_bytes(&[2u8; 32]); +3191 let node_id_2 = secret_key_2.public(); +3192 +3193 let msock_1 = magicsock_ep(secret_key_1.clone()).await.unwrap(); +3194 let msock_2 = magicsock_ep(secret_key_2.clone()).await.unwrap(); +3195 let ep_2 = msock_2.endpoint().clone(); +3196 +3197 // We need a task to accept the connection. +3198 let accept_task = tokio::spawn({ +3199 async fn accept(ep: quinn::Endpoint) -> Result<()> { +3200 let incoming = ep.accept().await.context("no incoming")?; +3201 let conn = incoming +3202 .accept() +3203 .context("accept")? +3204 .await +3205 .context("connecting")?; +3206 let mut stream = conn.accept_uni().await.context("accept uni")?; +3207 stream.read_to_end(1 << 16).await.context("read to end")?; +3208 info!("accept finished"); +3209 Ok(()) +3210 } +3211 async move { +3212 if let Err(err) = accept(ep_2).await { +3213 error!("{err:#}"); +3214 } +3215 } +3216 .instrument(info_span!("ep2.accept", me = node_id_2.fmt_short())) +3217 }); +3218 let _accept_task = AbortOnDropHandle::new(accept_task); +3219 +3220 // Add an empty entry in the NodeMap of ep_1 +3221 msock_1.node_map.add_node_addr( +3222 NodeAddr { +3223 node_id: node_id_2, +3224 relay_url: None, +3225 direct_addresses: Default::default(), +3226 }, +3227 Source::NamedApp { +3228 name: "test".into(), +3229 }, +3230 &msock_1.metrics.magicsock, +3231 ); +3232 +3233 let addr_2 = msock_1.get_mapping_addr(node_id_2).unwrap(); +3234 +3235 // Set a low max_idle_timeout so quinn gives up on this quickly and our test does +3236 // not take forever. You need to check the log output to verify this is really +3237 // triggering the correct error. +3238 // In test_try_send_no_send_addr() above you may have noticed we used +3239 // tokio::time::timeout() on the connection attempt instead. Here however we want +3240 // Quinn itself to have fully given up on the connection attempt because we will +3241 // later connect to **the same** node. If Quinn did not give up on the connection +3242 // we'd close it on drop, and the retransmits of the close packets would interfere +3243 // with the next handshake, closing it during the handshake. This makes the test a +3244 // little slower though. +3245 let mut transport_config = quinn::TransportConfig::default(); +3246 transport_config.max_idle_timeout(Some(Duration::from_millis(200).try_into().unwrap())); +3247 let res = magicsock_connect_with_transport_config( +3248 msock_1.endpoint(), +3249 secret_key_1.clone(), +3250 addr_2, +3251 node_id_2, +3252 Arc::new(transport_config), +3253 ) +3254 .await; +3255 assert!(res.is_err(), "expected timeout"); +3256 info!("first connect timed out as expected"); +3257 +3258 // Provide correct addressing information +3259 msock_1 +3260 .add_node_addr( +3261 NodeAddr { +3262 node_id: node_id_2, +3263 relay_url: None, +3264 direct_addresses: msock_2 +3265 .direct_addresses() +3266 .initialized() +3267 .await +3268 .expect("no direct addrs") +3269 .into_iter() +3270 .map(|x| x.addr) +3271 .collect(), +3272 }, +3273 Source::NamedApp { +3274 name: "test".into(), +3275 }, +3276 ) +3277 .unwrap(); +3278 +3279 // We can now connect +3280 tokio::time::timeout(Duration::from_secs(10), async move { +3281 info!("establishing new connection"); +3282 let conn = +3283 magicsock_connect(msock_1.endpoint(), secret_key_1.clone(), addr_2, node_id_2) +3284 .await +3285 .unwrap(); +3286 info!("have connection"); +3287 let mut stream = conn.open_uni().await.unwrap(); +3288 stream.write_all(b"hello").await.unwrap(); +3289 stream.finish().unwrap(); +3290 stream.stopped().await.unwrap(); +3291 info!("finished stream"); +3292 }) +3293 .await +3294 .expect("connection timed out"); +3295 +3296 // TODO: could remove the addresses again, send, add it back and see it recover. +3297 // But we don't have that much private access to the NodeMap. This will do for now. +3298 } +3299 +3300 #[tokio::test] +3301 async fn test_add_node_addr() -> Result { +3302 let stack = MagicStack::new(RelayMode::Default).await; +3303 let mut rng = rand::thread_rng(); +3304 +3305 assert_eq!(stack.endpoint.magic_sock().node_map.node_count(), 0); +3306 +3307 // Empty +3308 let empty_addr = NodeAddr { +3309 node_id: SecretKey::generate(&mut rng).public(), +3310 relay_url: None, +3311 direct_addresses: Default::default(), +3312 }; +3313 let err = stack +3314 .endpoint +3315 .magic_sock() +3316 .add_node_addr(empty_addr, node_map::Source::App) +3317 .unwrap_err(); +3318 assert!(err +3319 .to_string() +3320 .to_lowercase() +3321 .contains("empty addressing info")); +3322 +3323 // relay url only +3324 let addr = NodeAddr { +3325 node_id: SecretKey::generate(&mut rng).public(), +3326 relay_url: Some("http://my-relay.com".parse().unwrap()), +3327 direct_addresses: Default::default(), +3328 }; +3329 stack +3330 .endpoint +3331 .magic_sock() +3332 .add_node_addr(addr, node_map::Source::App)?; +3333 assert_eq!(stack.endpoint.magic_sock().node_map.node_count(), 1); +3334 +3335 // addrs only +3336 let addr = NodeAddr { +3337 node_id: SecretKey::generate(&mut rng).public(), +3338 relay_url: None, +3339 direct_addresses: ["127.0.0.1:1234".parse().unwrap()].into_iter().collect(), +3340 }; +3341 stack +3342 .endpoint +3343 .magic_sock() +3344 .add_node_addr(addr, node_map::Source::App)?; +3345 assert_eq!(stack.endpoint.magic_sock().node_map.node_count(), 2); +3346 +3347 // both +3348 let addr = NodeAddr { +3349 node_id: SecretKey::generate(&mut rng).public(), +3350 relay_url: Some("http://my-relay.com".parse().unwrap()), +3351 direct_addresses: ["127.0.0.1:1234".parse().unwrap()].into_iter().collect(), +3352 }; +3353 stack +3354 .endpoint +3355 .magic_sock() +3356 .add_node_addr(addr, node_map::Source::App)?; +3357 assert_eq!(stack.endpoint.magic_sock().node_map.node_count(), 3); +3358 +3359 Ok(()) +3360 } +3361} \ No newline at end of file