diff --git a/pr/3434/docs/iroh/endpoint/enum.DirectAddrType.html b/pr/3434/docs/iroh/endpoint/enum.DirectAddrType.html index 858dbfafbe..6811545974 100644 --- a/pr/3434/docs/iroh/endpoint/enum.DirectAddrType.html +++ b/pr/3434/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§

§

impl Freeze for DirectAddrType

§

impl RefUnwindSafe for DirectAddrType

§

impl Send for DirectAddrType

§

impl Sync for DirectAddrType

§

impl Unpin for DirectAddrType

§

impl UnwindSafe for DirectAddrType

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/3434/docs/iroh/endpoint/index.html b/pr/3434/docs/iroh/endpoint/index.html index 153201c8af..77f5a2a427 100644 --- a/pr/3434/docs/iroh/endpoint/index.html +++ b/pr/3434/docs/iroh/endpoint/index.html @@ -1,4 +1,4 @@ -iroh::endpoint - Rust

Module endpoint

Source
Expand description

The Endpoint allows establishing connections to other iroh nodes.

+iroh::endpoint - Rust

Module endpoint

Source
Expand description

The Endpoint allows establishing connections to other iroh nodes.

The Endpoint is the main API interface to manage a local iroh node. It allows connecting to and accepting connections from other nodes. See the module docs for more details on how iroh connections work.

diff --git a/pr/3434/docs/iroh/endpoint/struct.DirectAddr.html b/pr/3434/docs/iroh/endpoint/struct.DirectAddr.html index 582f51144f..76ccd5c41a 100644 --- a/pr/3434/docs/iroh/endpoint/struct.DirectAddr.html +++ b/pr/3434/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§

§

impl Freeze for DirectAddr

§

impl RefUnwindSafe for DirectAddr

§

impl Send for DirectAddr

§

impl Sync for DirectAddr

§

impl Unpin for DirectAddr

§

impl UnwindSafe for DirectAddr

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§

§

impl Freeze for DirectAddr

§

impl RefUnwindSafe for DirectAddr

§

impl Send for DirectAddr

§

impl Sync for DirectAddr

§

impl Unpin for DirectAddr

§

impl UnwindSafe for DirectAddr

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/3434/docs/src/iroh/endpoint.rs.html b/pr/3434/docs/src/iroh/endpoint.rs.html index c9be81486c..0adb820b6b 100644 --- a/pr/3434/docs/src/iroh/endpoint.rs.html +++ b/pr/3434/docs/src/iroh/endpoint.rs.html @@ -3199,8 +3199,8 @@ 3199 3200 /// Test that peers are properly restored 3201 #[tokio::test] -3202 // #[traced_test] -3203 async fn connect_multi() -> Result { +3202 #[traced_test] +3203 async fn connect_multi_time() -> Result { 3204 let n = 32; 3205 3206 const NOOP_ALPN: &[u8] = b"noop"; @@ -3266,12 +3266,7 @@ 3266 3267 println!("Round 0: {}s, {}s per connection", dt0, dt0 / (n as f64)); 3268 println!("Round 1: {}s, {}s per connection", dt1, dt1 / (n as f64)); -3269 assert!( -3270 dt0 / dt1 < 20.0, -3271 "First round: {}s, second round {}s", -3272 dt0, -3273 dt1 -3274 ); -3275 Ok(()) -3276 } -3277}

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