pub enum DirectAddrType {
+DirectAddrType in iroh::endpoint - Rust 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
impl Clone for DirectAddrType
Source§fn clone(&self) -> DirectAddrType
fn clone(&self) -> DirectAddrType
1.0.0 · Source§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
source. Read moreSource§impl Debug for DirectAddrType
impl Debug for DirectAddrType
Source§impl Display for DirectAddrType
impl Display for DirectAddrType
Source§impl Hash for DirectAddrType
impl Hash for DirectAddrType
1.3.0 · Source§fn hash_slice<H>(data: &[Self], state: &mut H)where
+
fn hash_slice<H>(data: &[Self], state: &mut H)where
+
Trait Implementations§
Source§impl Clone for DirectAddrType
impl Clone for DirectAddrType
Source§fn clone(&self) -> DirectAddrType
fn clone(&self) -> DirectAddrType
1.0.0 · Source§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
source. Read moreSource§impl Debug for DirectAddrType
impl Debug for DirectAddrType
Source§impl Display for DirectAddrType
impl Display for DirectAddrType
Source§impl Hash for DirectAddrType
impl Hash for DirectAddrType
Source§impl Ord for DirectAddrType
impl Ord for DirectAddrType
Source§impl Ord for DirectAddrType
impl Ord for DirectAddrType
Source§fn cmp(&self, other: &DirectAddrType) -> Ordering
fn cmp(&self, other: &DirectAddrType) -> Ordering
1.21.0 · Source§fn max(self, other: Self) -> Selfwhere
Self: Sized,
fn max(self, other: Self) -> Selfwhere
Self: Sized,
Source§impl PartialEq for DirectAddrType
impl PartialEq for DirectAddrType
Source§impl PartialOrd for DirectAddrType
impl PartialOrd for DirectAddrType
Source§impl PartialEq for DirectAddrType
impl PartialEq for DirectAddrType
Source§impl PartialOrd for DirectAddrType
impl PartialOrd for DirectAddrType
impl Copy for DirectAddrType
impl Eq for DirectAddrType
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§
impl Copy for DirectAddrType
impl Eq for DirectAddrType
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§
§impl<'a, T, E> AsTaggedExplicit<'a, E> for Twhere
T: 'a,
impl<'a, T, E> AsTaggedExplicit<'a, E> for Twhere
T: 'a,
§impl<'a, T, E> AsTaggedImplicit<'a, E> for Twhere
T: 'a,
impl<'a, T, E> AsTaggedImplicit<'a, E> for Twhere
T: 'a,
fn implicit(
diff --git a/pr/3381/docs/iroh/endpoint/struct.DirectAddr.html b/pr/3381/docs/iroh/endpoint/struct.DirectAddr.html
index ea98ba29ce..2e1e4c028f 100644
--- a/pr/3381/docs/iroh/endpoint/struct.DirectAddr.html
+++ b/pr/3381/docs/iroh/endpoint/struct.DirectAddr.html
@@ -1,4 +1,4 @@
-DirectAddr in iroh::endpoint - Rust pub struct DirectAddr {
+DirectAddr in iroh::endpoint - Rust 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: SocketAddrThe address.
§typ: DirectAddrTypeThe origin of this direct address.
-Trait Implementations§
Source§impl Clone for DirectAddr
Source§fn clone(&self) -> DirectAddr
Returns a copy of the value. Read more1.0.0 · Source§fn clone_from(&mut self, source: &Self)
Performs copy-assignment from source. Read moreSource§impl Debug for DirectAddr
Source§impl Hash for DirectAddr
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 more1.0.0 · Source§fn clone_from(&mut self, source: &Self)
Performs copy-assignment from source. Read moreSource§impl Debug for DirectAddr
Source§impl Hash for DirectAddr
Source§impl Ord for DirectAddr
Source§impl Ord for DirectAddr
Source§fn cmp(&self, other: &DirectAddr) -> Ordering
1.21.0 · Source§fn max(self, other: Self) -> Selfwhere
Self: Sized,
Compares and returns the maximum of two values. Read moreSource§impl PartialEq for DirectAddr
Source§impl PartialOrd for DirectAddr
Source§impl PartialEq for DirectAddr
Source§impl PartialOrd for DirectAddr
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 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§
§impl<'a, T, E> AsTaggedExplicit<'a, E> for Twhere
T: 'a,
§impl<'a, T, E> AsTaggedImplicit<'a, E> for Twhere
T: 'a,
§fn implicit(
diff --git a/pr/3381/docs/iroh_relay/client/enum.ReceivedMessage.html b/pr/3381/docs/iroh_relay/client/enum.ReceivedMessage.html
index d67f15652a..d204d79567 100644
--- a/pr/3381/docs/iroh_relay/client/enum.ReceivedMessage.html
+++ b/pr/3381/docs/iroh_relay/client/enum.ReceivedMessage.html
@@ -1,9 +1,9 @@
ReceivedMessage in iroh_relay::client - Rust pub enum ReceivedMessage {
ReceivedPacket {
- remote_node_id: NodeId,
+ remote_node_id: NodeId,
data: Bytes,
},
- NodeGone(NodeId),
+ NodeGone(NodeId),
Ping([u8; 8]),
Pong([u8; 8]),
KeepAlive,
@@ -17,9 +17,9 @@
}
Expand description
The messages received from a framed relay stream.
This is a type-validated version of the Frames on the RelayCodec.
Variants§
§ReceivedPacket
Represents an incoming packet.
-Fields
§NodeGone(NodeId)
Indicates that the client identified by the underlying public key had previously sent you a
packet but has now disconnected from the server.
§Ping([u8; 8])
Request from a client or server to reply to the
other side with a ReceivedMessage::Pong with the given payload.
diff --git a/pr/3381/docs/iroh_relay/client/enum.SendMessage.html b/pr/3381/docs/iroh_relay/client/enum.SendMessage.html
index 1efae8feee..b6279d244c 100644
--- a/pr/3381/docs/iroh_relay/client/enum.SendMessage.html
+++ b/pr/3381/docs/iroh_relay/client/enum.SendMessage.html
@@ -1,9 +1,9 @@
SendMessage in iroh_relay::client - Rust pub enum SendMessage {
- SendPacket(NodeId, Bytes),
+ SendPacket(NodeId, Bytes),
Ping([u8; 8]),
Pong([u8; 8]),
}
Expand description
Messages we can send to a relay server.
-Variants§
§SendPacket(NodeId, Bytes)
Send a packet of data to the NodeId.
+Variants§
§SendPacket(NodeId, Bytes)
Send a packet of data to the [NodeId].
§Ping([u8; 8])
Sends a ping message to the connected relay server.
§Pong([u8; 8])
Sends a pong message to the connected relay server.
Trait Implementations§
Source§impl Debug for SendMessage
Source§impl Sink<SendMessage> for Client
Source§fn poll_ready(
diff --git a/pr/3381/docs/iroh_relay/client/struct.ClientBuilder.html b/pr/3381/docs/iroh_relay/client/struct.ClientBuilder.html
index 26ccff11ea..bfafcd37c8 100644
--- a/pr/3381/docs/iroh_relay/client/struct.ClientBuilder.html
+++ b/pr/3381/docs/iroh_relay/client/struct.ClientBuilder.html
@@ -1,7 +1,7 @@
ClientBuilder in iroh_relay::client - Rust pub struct ClientBuilder { /* private fields */ }
Expand description
Build a Client.
Implementations§
Source§impl ClientBuilder
Sourcepub fn new(
- url: impl Into<RelayUrl>,
- secret_key: SecretKey,
+ url: impl Into<RelayUrl>,
+ secret_key: SecretKey,
dns_resolver: DnsResolver,
) -> Self
Create a new ClientBuilder
Sourcepub fn protocol(self, protocol: Protocol) -> Self
Sets whether to connect to the relay via websockets or not.
diff --git a/pr/3381/docs/iroh_relay/dns/struct.DnsResolver.html b/pr/3381/docs/iroh_relay/dns/struct.DnsResolver.html
index f9da8945f9..f83d48fca0 100644
--- a/pr/3381/docs/iroh_relay/dns/struct.DnsResolver.html
+++ b/pr/3381/docs/iroh_relay/dns/struct.DnsResolver.html
@@ -68,9 +68,9 @@ at T+0ms, T+200ms and T+300ms. The timeout is applied as stated in
summary of all errors otherwise.
Sourcepub async fn lookup_node_by_id(
&self,
- node_id: &NodeId,
+ node_id: &NodeId,
origin: &str,
-) -> Result<NodeInfo, LookupError>
Looks up node info by NodeId and origin domain name.
+) -> Result<NodeInfo, LookupError>Looks up node info by [NodeId] and origin domain name.
To lookup nodes that published their node info to the DNS servers run by n0,
pass N0_DNS_NODE_ORIGIN_PROD as origin.
Sourcepub async fn lookup_node_by_domain_name(
@@ -88,10 +88,10 @@ at T+0ms, T+200ms and T+300ms. The result of the first successful call is return
summary of all errors otherwise.
Sourcepub async fn lookup_node_by_id_staggered(
&self,
- node_id: &NodeId,
+ node_id: &NodeId,
origin: &str,
delays_ms: &[u64],
-) -> Result<NodeInfo, StaggeredError<LookupError>>
Looks up node info by NodeId and origin domain name.
+) -> Result<NodeInfo, StaggeredError<LookupError>>Looks up node info by [NodeId] and origin domain name.
From the moment this function is called, each lookup is scheduled after the delays in
delays_ms with the first call being done immediately. [200ms, 300ms] results in calls
at T+0ms, T+200ms and T+300ms. The result of the first successful call is returned, or a
diff --git a/pr/3381/docs/iroh_relay/index.html b/pr/3381/docs/iroh_relay/index.html
index 0dffafd7bb..a95da1d81a 100644
--- a/pr/3381/docs/iroh_relay/index.html
+++ b/pr/3381/docs/iroh_relay/index.html
@@ -25,6 +25,6 @@ Tailscale.
QAD support and expose metrics.
-Re-exports§
pub use protos::relay::MAX_PACKET_SIZE;
Modules§
- client
- Exposes
Client, which allows to establish connections to a relay server. - defaults
- Default values used in the relay.
- dns
Non-wasm_browser - DNS resolver
- http
- HTTP-specific constants for the relay server and client.
- node_
info - Support for handling DNS resource records for dialing by
NodeId. - protos
- Protocols used by the iroh-relay
- quic
- Create a QUIC server that accepts connections
+
Re-exports§
pub use protos::relay::MAX_PACKET_SIZE;
Modules§
- client
- Exposes
Client, which allows to establish connections to a relay server. - defaults
- Default values used in the relay.
- dns
Non-wasm_browser - DNS resolver
- http
- HTTP-specific constants for the relay server and client.
- node_
info - Support for handling DNS resource records for dialing by [
NodeId]. - protos
- Protocols used by the iroh-relay
- quic
- Create a QUIC server that accepts connections
for QUIC address discovery.
- server
server - A fully-fledged iroh-relay server over HTTP or HTTPS.
Structs§
- Ping
Tracker - Tracks pings on a single relay connection.
- Relay
Map - Configuration of all the relay servers that can be used.
- Relay
Node - Information on a specific relay server.
- Relay
QuicConfig - Configuration for speaking to the QUIC endpoint on the relay
server to do QUIC address discovery.
\ No newline at end of file
diff --git a/pr/3381/docs/iroh_relay/node_info/index.html b/pr/3381/docs/iroh_relay/node_info/index.html
index 35bc283b6f..48e4910fda 100644
--- a/pr/3381/docs/iroh_relay/node_info/index.html
+++ b/pr/3381/docs/iroh_relay/node_info/index.html
@@ -1,5 +1,5 @@
-iroh_relay::node_info - Rust Expand description
Support for handling DNS resource records for dialing by NodeId.
-Dialing by NodeId is supported by iroh nodes publishing Pkarr records to DNS
+
iroh_relay::node_info - Rust Expand description
Support for handling DNS resource records for dialing by [NodeId].
+Dialing by [NodeId] is supported by iroh nodes publishing Pkarr records to DNS
servers or the Mainline DHT. This module supports creating and parsing these records.
DNS records are published under the following names:
_iroh.<z32-node-id>.<origin-domain> TXT
@@ -8,7 +8,7 @@ servers or the Mainline DHT. This module supports creating and parsing these re
_iroh is the record name as defined by IROH_TXT_NAME.
-<z32-node-id> is the z-base-32 encoding of the NodeId.
+<z32-node-id> is the z-base-32 encoding of the [NodeId].
<origin-domain> is the domain name of the publishing DNS server,
@@ -23,12 +23,12 @@ servers or the Mainline DHT. This module supports creating and parsing these re
in RFC1464. The following attributes are defined:
- Structs§
- MaxLength
ExceededError - Error returned when an input value is too long for
UserData. - Node
Data - Data about a node that may be published to and resolved from discovery services.
- Node
Info - Information about a node that may be published to and resolved from discovery services.
- User
Data - Under the hood this is a UTF-8 String is no longer than
UserData::MAX_LENGTH bytes.
Enums§
- Decoding
Error - Encoding
Error - Lookup
Error Non-wasm_browser - Parse
Error
Constants§
- IROH_
TXT_NAME - The DNS name for the iroh TXT record.
Traits§
Structs§
- MaxLength
ExceededError - Error returned when an input value is too long for
UserData. - Node
Data - Data about a node that may be published to and resolved from discovery services.
- Node
Info - Information about a node that may be published to and resolved from discovery services.
- User
Data - Under the hood this is a UTF-8 String is no longer than
UserData::MAX_LENGTH bytes.
Enums§
- Decoding
Error - Encoding
Error - Lookup
Error Non-wasm_browser - Parse
Error
Constants§
- IROH_
TXT_NAME - The DNS name for the iroh TXT record.
Traits§
- Node
IdExt - Extension methods for [
NodeId] to encode to and decode from [z32],
which is the encoding used in [pkarr] domain names.
\ No newline at end of file
diff --git a/pr/3381/docs/iroh_relay/node_info/struct.NodeData.html b/pr/3381/docs/iroh_relay/node_info/struct.NodeData.html
index c0ab566f79..5e8b8f53c0 100644
--- a/pr/3381/docs/iroh_relay/node_info/struct.NodeData.html
+++ b/pr/3381/docs/iroh_relay/node_info/struct.NodeData.html
@@ -1,20 +1,20 @@
NodeData in iroh_relay::node_info - Rust pub struct NodeData { /* private fields */ }
Expand description
Data about a node that may be published to and resolved from discovery services.
-This includes an optional RelayUrl, a set of direct addresses, and the optional
+
This includes an optional [RelayUrl], a set of direct addresses, and the optional
UserData, a string that can be set by applications and is not parsed or used by iroh
itself.
-This struct does not include the node’s NodeId, only the data about a certain
-node. See NodeInfo for a struct that contains a NodeId with associated NodeData.
+This struct does not include the node’s [NodeId], only the data about a certain
+node. See NodeInfo for a struct that contains a [NodeId] with associated NodeData.
Implementations§
Source§impl NodeData
Sourcepub fn new(
- relay_url: Option<RelayUrl>,
+ relay_url: Option<RelayUrl>,
direct_addresses: BTreeSet<SocketAddr>,
) -> Self
Creates a new NodeData with a relay URL and a set of direct addresses.
-Sourcepub fn with_relay_url(self, relay_url: Option<RelayUrl>) -> Self
Sets the relay URL and returns the updated node data.
+Sourcepub fn with_relay_url(self, relay_url: Option<RelayUrl>) -> Self
Sets the relay URL and returns the updated node data.
Sourcepub fn with_direct_addresses(
self,
direct_addresses: BTreeSet<SocketAddr>,
) -> Self
Sets the direct addresses and returns the updated node data.
Sourcepub fn with_user_data(self, user_data: Option<UserData>) -> Self
Sets the user-defined data and returns the updated node data.
-Sourcepub fn user_data(&self) -> Option<&UserData>
Returns the optional user-defined data of the node.
Sourcepub fn direct_addresses(&self) -> &BTreeSet<SocketAddr>
Returns the direct addresses of the node.
Sourcepub fn clear_direct_addresses(&mut self)
Removes all direct addresses from the node data.
@@ -22,9 +22,9 @@ node. See IntoIterator<Item = SocketAddr>,
)Adds direct addresses to the node data.
-Sourcepub fn set_relay_url(&mut self, relay_url: Option<RelayUrl>)
Sets the relay URL of the node data.
+Sourcepub fn set_relay_url(&mut self, relay_url: Option<RelayUrl>)
Sets the relay URL of the node data.
Sourcepub fn set_user_data(&mut self, user_data: Option<UserData>)
Sets the user-defined data of the node data.
-Trait Implementations§
Trait Implementations§
Source§impl Eq for NodeData
Source§impl StructuralPartialEq for NodeData
Auto Trait Implementations§
§impl Freeze for NodeData
§impl RefUnwindSafe for NodeData
§impl Send for NodeData
§impl Sync for NodeData
§impl Unpin for NodeData
§impl UnwindSafe for NodeData
Blanket Implementations§
§impl<'a, T, E> AsTaggedExplicit<'a, E> for Twhere
T: 'a,
§impl<'a, T, E> AsTaggedImplicit<'a, E> for Twhere
diff --git a/pr/3381/docs/iroh_relay/node_info/struct.NodeInfo.html b/pr/3381/docs/iroh_relay/node_info/struct.NodeInfo.html
index 6b5ba1f068..28fba3c4c9 100644
--- a/pr/3381/docs/iroh_relay/node_info/struct.NodeInfo.html
+++ b/pr/3381/docs/iroh_relay/node_info/struct.NodeInfo.html
@@ -1,32 +1,32 @@
NodeInfo in iroh_relay::node_info - Rust pub struct NodeInfo {
- pub node_id: NodeId,
+ pub node_id: NodeId,
pub data: NodeData,
}
Expand description
Fields§
§node_id: NodeIdThe NodeId of the node this is about.
+This struct couples a [NodeId] with its associated NodeData.
+Fields§
§node_id: NodeIdThe [NodeId] of the node this is about.
§data: NodeDataThe information published about the node.
-Implementations§
Source§impl NodeInfo
Sourcepub fn from_parts(node_id: NodeId, data: NodeData) -> Self
Creates a new NodeInfo from its parts.
-Sourcepub fn with_relay_url(self, relay_url: Option<RelayUrl>) -> Self
Sets the relay URL and returns the updated node info.
+Implementations§
Source§impl NodeInfo
Sourcepub fn from_parts(node_id: NodeId, data: NodeData) -> Self
Creates a new NodeInfo from its parts.
+Sourcepub fn with_relay_url(self, relay_url: Option<RelayUrl>) -> Self
Sets the relay URL and returns the updated node info.
Sourcepub fn with_direct_addresses(
self,
direct_addresses: BTreeSet<SocketAddr>,
) -> Self
Sets the direct addresses and returns the updated node info.
Sourcepub fn with_user_data(self, user_data: Option<UserData>) -> Self
Sets the user-defined data and returns the updated node info.
-Sourcepub fn to_node_addr(&self) -> NodeAddr
Converts into a NodeAddr by cloning the needed fields.
-Sourcepub fn into_node_addr(self) -> NodeAddr
Converts into a NodeAddr without cloning.
+Sourcepub fn to_node_addr(&self) -> NodeAddr
Converts into a [NodeAddr] by cloning the needed fields.
+Sourcepub fn into_node_addr(self) -> NodeAddr
Converts into a [NodeAddr] without cloning.
Sourcepub fn from_txt_lookup(lookup: TxtLookup) -> Result<Self, ParseError>
Available on non-wasm_browser only.
Parses a NodeInfo from a TXT records lookup.
Sourcepub fn from_pkarr_signed_packet(
packet: &SignedPacket,
) -> Result<Self, ParseError>
Parses a NodeInfo from a [pkarr::SignedPacket].
Sourcepub fn to_pkarr_signed_packet(
&self,
- secret_key: &SecretKey,
+ secret_key: &SecretKey,
ttl: u32,
) -> Result<SignedPacket, EncodingError>
Creates a [pkarr::SignedPacket].
-This constructs a DNS packet and signs it with a SecretKey.
+This constructs a DNS packet and signs it with a [SecretKey].
Sourcepub fn to_txt_strings(&self) -> Vec<String>
Converts into a list of {key}={value} strings.
-Methods from Deref<Target = NodeData>§
Sourcepub fn user_data(&self) -> Option<&UserData>
Returns the optional user-defined data of the node.
Sourcepub fn direct_addresses(&self) -> &BTreeSet<SocketAddr>
Returns the direct addresses of the node.
Sourcepub fn clear_direct_addresses(&mut self)
Removes all direct addresses from the node data.
@@ -34,9 +34,9 @@
&mut self,
addrs: impl IntoIterator<Item = SocketAddr>,
)Adds direct addresses to the node data.
-Sourcepub fn set_relay_url(&mut self, relay_url: Option<RelayUrl>)
Sets the relay URL of the node data.
+Sourcepub fn set_relay_url(&mut self, relay_url: Option<RelayUrl>)
Sets the relay URL of the node data.
Sourcepub fn set_user_data(&mut self, user_data: Option<UserData>)
Sets the user-defined data of the node data.
-Trait Implementations§
Trait Implementations§
Source§impl Eq for NodeInfo
Source§impl StructuralPartialEq for NodeInfo
Auto Trait Implementations§
§impl Freeze for NodeInfo
§impl RefUnwindSafe for NodeInfo
§impl Send for NodeInfo
§impl Sync for NodeInfo
§impl Unpin for NodeInfo
§impl UnwindSafe for NodeInfo
Blanket Implementations§
§impl<'a, T, E> AsTaggedExplicit<'a, E> for Twhere
T: 'a,
§impl<'a, T, E> AsTaggedImplicit<'a, E> for Twhere
diff --git a/pr/3381/docs/iroh_relay/node_info/trait.NodeIdExt.html b/pr/3381/docs/iroh_relay/node_info/trait.NodeIdExt.html
index b4a8808135..d668a07cef 100644
--- a/pr/3381/docs/iroh_relay/node_info/trait.NodeIdExt.html
+++ b/pr/3381/docs/iroh_relay/node_info/trait.NodeIdExt.html
@@ -1,9 +1,9 @@
NodeIdExt in iroh_relay::node_info - Rust pub trait NodeIdExt {
// Required methods
fn to_z32(&self) -> String;
- fn from_z32(s: &str) -> Result<NodeId, DecodingError>;
-}
Expand description
Extension methods for NodeId to encode to and decode from [z32],
+ fn from_z32(s: &str) -> Result<NodeId, DecodingError>;
+}Expand description
Extension methods for [NodeId] to encode to and decode from [z32],
which is the encoding used in [pkarr] domain names.
-
Required Methods§
Dyn Compatibility§
This trait is not dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.
Implementations on Foreign Types§
Implementors§
\ No newline at end of file
+Required Methods§
Sourcefn from_z32(s: &str) -> Result<NodeId, DecodingError>
Parses a [NodeId] from [z-base-32] encoding.
+Dyn Compatibility§
This trait is not dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.
Implementations on Foreign Types§
Implementors§
\ No newline at end of file
diff --git a/pr/3381/docs/iroh_relay/server/enum.AccessConfig.html b/pr/3381/docs/iroh_relay/server/enum.AccessConfig.html
index c318e01200..9c6c400b3e 100644
--- a/pr/3381/docs/iroh_relay/server/enum.AccessConfig.html
+++ b/pr/3381/docs/iroh_relay/server/enum.AccessConfig.html
@@ -1,10 +1,10 @@
AccessConfig in iroh_relay::server - Rust pub enum AccessConfig {
Everyone,
- Restricted(Box<dyn Fn(NodeId) -> Boxed<Access> + Send + Sync + 'static>),
+ Restricted(Box<dyn Fn(NodeId) -> Boxed<Access> + Send + Sync + 'static>),
}
Available on crate feature server only.Expand description
Controls which nodes are allowed to use the relay.
Variants§
§Everyone
Everyone
-§Restricted(Box<dyn Fn(NodeId) -> Boxed<Access> + Send + Sync + 'static>)
Only nodes for which the function returns Access::Allow.
-Implementations§
Source§impl AccessConfig
Implementations§
Source§impl AccessConfig
Sourcepub async fn is_allowed(&self, node: NodeId) -> bool
Is this node allowed?
Trait Implementations§
Auto Trait Implementations§
§impl Freeze for AccessConfig
§impl !RefUnwindSafe for AccessConfig
§impl Send for AccessConfig
§impl Sync for AccessConfig
§impl Unpin for AccessConfig
§impl !UnwindSafe for AccessConfig
Blanket Implementations§
§impl<'a, T, E> AsTaggedExplicit<'a, E> for Twhere
T: 'a,
§impl<'a, T, E> AsTaggedImplicit<'a, E> for Twhere
diff --git a/pr/3381/docs/iroh_relay/server/struct.Server.html b/pr/3381/docs/iroh_relay/server/struct.Server.html
index 33a6a8b24f..1d0dc22b7b 100644
--- a/pr/3381/docs/iroh_relay/server/struct.Server.html
+++ b/pr/3381/docs/iroh_relay/server/struct.Server.html
@@ -17,9 +17,9 @@ case there is an error in the server before it is shut down.
Sourcepub fn http_addr(&self) -> Option<SocketAddr>
The socket address the HTTP server is listening on.
Sourcepub fn quic_addr(&self) -> Option<SocketAddr>
The socket address the QUIC server is listening on.
Sourcepub fn certificates(&self) -> Option<Vec<CertificateDer<'static>>>
The certificates chain if configured with manual TLS certificates.
-Sourcepub fn https_url(&self) -> Option<RelayUrl>
Available on crate feature test-utils only.
Get the server’s https RelayUrl.
+Sourcepub fn https_url(&self) -> Option<RelayUrl>
Available on crate feature test-utils only.
Get the server’s https [RelayUrl].
This uses Self::https_addr so it’s mostly useful for local development.
-Sourcepub fn http_url(&self) -> Option<RelayUrl>
Available on crate feature test-utils only.
Get the server’s http RelayUrl.
+Sourcepub fn http_url(&self) -> Option<RelayUrl>
Available on crate feature test-utils only.
Get the server’s http [RelayUrl].
This uses Self::http_addr so it’s mostly useful for local development.
Sourcepub fn metrics(&self) -> &RelayMetrics
Returns the metrics collected in the relay server.
Trait Implementations§
Auto Trait Implementations§
§impl Freeze for Server
§impl RefUnwindSafe for Server
§impl Send for Server
§impl Sync for Server
§impl Unpin for Server
§impl UnwindSafe for Server
Blanket Implementations§
Source§impl<T> Any for Twhere
diff --git a/pr/3381/docs/iroh_relay/struct.RelayMap.html b/pr/3381/docs/iroh_relay/struct.RelayMap.html
index b284268144..8ab9e60978 100644
--- a/pr/3381/docs/iroh_relay/struct.RelayMap.html
+++ b/pr/3381/docs/iroh_relay/struct.RelayMap.html
@@ -1,15 +1,15 @@
RelayMap in iroh_relay - Rust pub struct RelayMap { /* private fields */ }
Expand description
Configuration of all the relay servers that can be used.
-Implementations§
Source§impl RelayMap
Implementations§
Trait Implementations§
Trait Implementations§
Source§impl FromIterator<RelayNode> for RelayMap
Source§impl FromIterator<RelayUrl> for RelayMap
Source§impl FromIterator<RelayNode> for RelayMap
Source§impl FromIterator<RelayUrl> for RelayMap
Source§impl PartialEq for RelayMap
Source§fn eq(&self, other: &RelayMap) -> 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,
diff --git a/pr/3381/docs/iroh_relay/struct.RelayNode.html b/pr/3381/docs/iroh_relay/struct.RelayNode.html
index 2c5ac7dc6c..588d10e2b3 100644
--- a/pr/3381/docs/iroh_relay/struct.RelayNode.html
+++ b/pr/3381/docs/iroh_relay/struct.RelayNode.html
@@ -1,14 +1,14 @@
RelayNode in iroh_relay - Rust pub struct RelayNode {
- pub url: RelayUrl,
+ pub url: RelayUrl,
pub quic: Option<RelayQuicConfig>,
}
Expand description
Information on a specific relay server.
Includes the Url where it can be dialed.
-Fields§
§url: RelayUrlThe RelayUrl where this relay server can be dialed.
+Fields§
§url: RelayUrlThe [RelayUrl] where this relay server can be dialed.
§quic: Option<RelayQuicConfig>Configuration to speak to the QUIC endpoint on the relay server.
When None, we will not attempt to do QUIC address discovery
with this relay server.
Trait Implementations§
Source§impl<'de> Deserialize<'de> for RelayNode
Source§fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>where
- __D: Deserializer<'de>,
Deserialize this value from the given Serde deserializer. Read moreSource§impl FromIterator<RelayNode> for RelayMap
Source§impl FromIterator<RelayNode> for RelayMap
Source§impl Ord for RelayNode
Source§impl PartialEq for RelayNode
Source§fn eq(&self, other: &RelayNode) -> 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,
diff --git a/pr/3381/docs/src/iroh/magicsock.rs.html b/pr/3381/docs/src/iroh/magicsock.rs.html
index 5dabf264a0..f2d76f1aad 100644
--- a/pr/3381/docs/src/iroh/magicsock.rs.html
+++ b/pr/3381/docs/src/iroh/magicsock.rs.html
@@ -471,2961 +471,2956 @@
471 let conn = conn.clone();
472 let addr = addr.private_socket_addr();
473 task::spawn(async move {
-474 match conn
-475 .open_path(addr, quinn_proto::PathStatus::Available)
-476 .await
-477 {
-478 Ok(path) => {
-479 path.set_max_idle_timeout(Some(
-480 ENDPOINTS_FRESH_ENOUGH_DURATION,
-481 ))
-482 .ok();
-483 path.set_keep_alive_interval(Some(HEARTBEAT_INTERVAL)).ok();
-484 }
-485 Err(err) => {
-486 warn!("failed to open path {:?}", err);
-487 }
-488 }
-489 });
-490 }
-491 } else {
-492 to_delete.push(i);
-493 }
-494 }
-495 // cleanup dead connections
-496 let mut i = 0;
-497 conns.retain(|_| {
-498 let remove = to_delete.contains(&i);
-499 i += 1;
+474 match conn.open_path(addr, quinn_proto::PathStatus::Backup).await {
+475 Ok(path) => {
+476 // Keep the relay path open
+477 path.set_max_idle_timeout(None).ok();
+478 path.set_keep_alive_interval(None).ok();
+479 }
+480 Err(err) => {
+481 warn!("failed to open path {:?}", err);
+482 }
+483 }
+484 });
+485 }
+486 } else {
+487 to_delete.push(i);
+488 }
+489 }
+490 // cleanup dead connections
+491 let mut i = 0;
+492 conns.retain(|_| {
+493 let remove = to_delete.contains(&i);
+494 i += 1;
+495
+496 !remove
+497 });
+498 }
+499 }
500
-501 !remove
-502 });
-503 }
-504 }
-505
-506 /// Stores a new set of direct addresses.
-507 ///
-508 /// If the direct addresses have changed from the previous set, they are published to
-509 /// discovery.
-510 pub(super) fn store_direct_addresses(&self, addrs: BTreeSet<DirectAddr>) {
-511 let updated = self.direct_addrs.update(addrs);
-512 if updated {
-513 self.node_map
-514 .on_direct_addr_discovered(self.direct_addrs.sockaddrs());
-515 self.publish_my_addr();
-516 }
-517 }
-518
-519 /// Get a reference to the DNS resolver used in this [`MagicSock`].
-520 #[cfg(not(wasm_browser))]
-521 pub(crate) fn dns_resolver(&self) -> &DnsResolver {
-522 &self.dns_resolver
+501 /// Stores a new set of direct addresses.
+502 ///
+503 /// If the direct addresses have changed from the previous set, they are published to
+504 /// discovery.
+505 pub(super) fn store_direct_addresses(&self, addrs: BTreeSet<DirectAddr>) {
+506 let updated = self.direct_addrs.update(addrs);
+507 if updated {
+508 self.node_map
+509 .on_direct_addr_discovered(self.direct_addrs.sockaddrs());
+510 self.publish_my_addr();
+511 }
+512 }
+513
+514 /// Get a reference to the DNS resolver used in this [`MagicSock`].
+515 #[cfg(not(wasm_browser))]
+516 pub(crate) fn dns_resolver(&self) -> &DnsResolver {
+517 &self.dns_resolver
+518 }
+519
+520 /// Reference to optional discovery service
+521 pub(crate) fn discovery(&self) -> Option<&dyn Discovery> {
+522 self.discovery.as_ref().map(Box::as_ref)
523 }
524
-525 /// Reference to optional discovery service
-526 pub(crate) fn discovery(&self) -> Option<&dyn Discovery> {
-527 self.discovery.as_ref().map(Box::as_ref)
-528 }
-529
-530 /// Updates the user-defined discovery data for this node.
-531 pub(crate) fn set_user_data_for_discovery(&self, user_data: Option<UserData>) {
-532 let mut guard = self.discovery_user_data.write().expect("lock poisened");
-533 if *guard != user_data {
-534 *guard = user_data;
-535 drop(guard);
-536 self.publish_my_addr();
-537 }
-538 }
-539
-540 /// Call to notify the system of potential network changes.
-541 pub(crate) async fn network_change(&self) {
-542 self.actor_sender
-543 .send(ActorMessage::NetworkChange)
-544 .await
-545 .ok();
+525 /// Updates the user-defined discovery data for this node.
+526 pub(crate) fn set_user_data_for_discovery(&self, user_data: Option<UserData>) {
+527 let mut guard = self.discovery_user_data.write().expect("lock poisened");
+528 if *guard != user_data {
+529 *guard = user_data;
+530 drop(guard);
+531 self.publish_my_addr();
+532 }
+533 }
+534
+535 /// Call to notify the system of potential network changes.
+536 pub(crate) async fn network_change(&self) {
+537 self.actor_sender
+538 .send(ActorMessage::NetworkChange)
+539 .await
+540 .ok();
+541 }
+542
+543 /// Returns a reference to the subscribers channel for discovery events.
+544 pub(crate) fn discovery_subscribers(&self) -> &DiscoverySubscribers {
+545 &self.discovery_subscribers
546 }
547
-548 /// Returns a reference to the subscribers channel for discovery events.
-549 pub(crate) fn discovery_subscribers(&self) -> &DiscoverySubscribers {
-550 &self.discovery_subscribers
-551 }
-552
-553 #[cfg(test)]
-554 async fn force_network_change(&self, is_major: bool) {
-555 self.actor_sender
-556 .send(ActorMessage::ForceNetworkChange(is_major))
-557 .await
-558 .ok();
-559 }
-560
-561 #[cfg_attr(windows, allow(dead_code))]
-562 fn normalized_local_addr(&self) -> io::Result<SocketAddr> {
-563 let addrs = self.local_addrs_watch.get().expect("disconnected");
-564
-565 let mut ipv4_addr = None;
-566 for addr in addrs {
-567 let Some(addr) = addr.into_socket_addr() else {
-568 continue;
-569 };
-570 if addr.is_ipv6() {
-571 return Ok(addr);
-572 }
-573 if addr.is_ipv4() && ipv4_addr.is_none() {
-574 ipv4_addr.replace(addr);
-575 }
-576 }
-577 match ipv4_addr {
-578 Some(addr) => Ok(addr),
-579 None => Err(io::Error::other("no valid socket available")),
-580 }
-581 }
-582
-583 /// Searches the `node_map` to determine the current transports to be used.
-584 #[instrument(skip_all)]
-585 fn prepare_send(
-586 &self,
-587 transmit: &quinn_udp::Transmit,
-588 ) -> io::Result<SmallVec<[transports::Addr; 3]>> {
-589 self.metrics
-590 .magicsock
-591 .send_data
-592 .inc_by(transmit.contents.len() as _);
-593
-594 if self.is_closed() {
-595 self.metrics
-596 .magicsock
-597 .send_data_network_down
-598 .inc_by(transmit.contents.len() as _);
-599 return Err(io::Error::new(
-600 io::ErrorKind::NotConnected,
-601 "connection closed",
-602 ));
-603 }
-604
-605 let mut active_paths = SmallVec::<[_; 3]>::new();
-606
-607 match MappedAddr::from(transmit.destination) {
-608 MappedAddr::None(addr) => {
-609 active_paths.push(transports::Addr::from(addr));
-610 }
-611 MappedAddr::NodeId(dest) => {
-612 trace!(
-613 dst = %dest,
-614 src = ?transmit.src_ip,
-615 len = %transmit.contents.len(),
-616 "sending",
-617 );
-618
-619 // Get the node's relay address and best direct address, as well
-620 // as any pings that need to be sent for hole-punching purposes.
-621 match self.node_map.get_send_addrs(
-622 dest,
-623 self.ipv6_reported.load(Ordering::Relaxed),
-624 &self.metrics.magicsock,
-625 ) {
-626 Some((node_id, _udp_addr, relay_url, ping_actions)) => {
-627 if !ping_actions.is_empty() {
-628 self.actor_sender
-629 .try_send(ActorMessage::PingActions(ping_actions))
-630 .ok();
+548 #[cfg(test)]
+549 async fn force_network_change(&self, is_major: bool) {
+550 self.actor_sender
+551 .send(ActorMessage::ForceNetworkChange(is_major))
+552 .await
+553 .ok();
+554 }
+555
+556 #[cfg_attr(windows, allow(dead_code))]
+557 fn normalized_local_addr(&self) -> io::Result<SocketAddr> {
+558 let addrs = self.local_addrs_watch.get().expect("disconnected");
+559
+560 let mut ipv4_addr = None;
+561 for addr in addrs {
+562 let Some(addr) = addr.into_socket_addr() else {
+563 continue;
+564 };
+565 if addr.is_ipv6() {
+566 return Ok(addr);
+567 }
+568 if addr.is_ipv4() && ipv4_addr.is_none() {
+569 ipv4_addr.replace(addr);
+570 }
+571 }
+572 match ipv4_addr {
+573 Some(addr) => Ok(addr),
+574 None => Err(io::Error::other("no valid socket available")),
+575 }
+576 }
+577
+578 /// Searches the `node_map` to determine the current transports to be used.
+579 #[instrument(skip_all)]
+580 fn prepare_send(
+581 &self,
+582 transmit: &quinn_udp::Transmit,
+583 ) -> io::Result<SmallVec<[transports::Addr; 3]>> {
+584 self.metrics
+585 .magicsock
+586 .send_data
+587 .inc_by(transmit.contents.len() as _);
+588
+589 if self.is_closed() {
+590 self.metrics
+591 .magicsock
+592 .send_data_network_down
+593 .inc_by(transmit.contents.len() as _);
+594 return Err(io::Error::new(
+595 io::ErrorKind::NotConnected,
+596 "connection closed",
+597 ));
+598 }
+599
+600 let mut active_paths = SmallVec::<[_; 3]>::new();
+601
+602 match MappedAddr::from(transmit.destination) {
+603 MappedAddr::None(addr) => {
+604 active_paths.push(transports::Addr::from(addr));
+605 }
+606 MappedAddr::NodeId(dest) => {
+607 trace!(
+608 dst = %dest,
+609 src = ?transmit.src_ip,
+610 len = %transmit.contents.len(),
+611 "sending",
+612 );
+613
+614 // Get the node's relay address and best direct address, as well
+615 // as any pings that need to be sent for hole-punching purposes.
+616 match self.node_map.get_send_addrs(
+617 dest,
+618 self.ipv6_reported.load(Ordering::Relaxed),
+619 &self.metrics.magicsock,
+620 ) {
+621 Some((node_id, _udp_addr, relay_url, ping_actions)) => {
+622 if !ping_actions.is_empty() {
+623 self.actor_sender
+624 .try_send(ActorMessage::PingActions(ping_actions))
+625 .ok();
+626 }
+627 // NodeId mapped addrs are only used for relays, currently.
+628 // IP based addrs will have been added as individual paths
+629 if let Some(url) = relay_url {
+630 active_paths.push(transports::Addr::Relay(url, node_id));
631 }
-632 // NodeId mapped addrs are only used for relays, currently.
-633 // IP based addrs will have been added as individual paths
-634 if let Some(url) = relay_url {
-635 active_paths.push(transports::Addr::Relay(url, node_id));
-636 }
-637 }
-638 None => {
-639 error!(%dest, "no NodeState for mapped address");
-640 }
-641 }
-642 }
-643 #[cfg(not(wasm_browser))]
-644 MappedAddr::Ip(dest) => {
-645 trace!(
-646 dst = %dest,
-647 src = ?transmit.src_ip,
-648 len = %transmit.contents.len(),
-649 "sending",
-650 );
-651
-652 // Check if this is a known IpMappedAddr, and if so, send over UDP
-653 // Get the socket addr
-654 match self.ip_mapped_addrs.get_ip_addr(&dest) {
-655 Some(addr) => {
-656 active_paths.push(transports::Addr::from(addr));
-657 }
-658 None => {
-659 error!(%dest, "unknown mapped address");
-660 }
-661 }
-662 }
-663 }
-664
-665 Ok(active_paths)
-666 }
-667
-668 /// Process datagrams received from UDP sockets.
-669 ///
-670 /// All the `bufs` and `metas` should have initialized packets in them.
-671 ///
-672 /// This fixes up the datagrams to use the correct [`NodeIdMappedAddr`] and extracts DISCO
-673 /// packets, processing them inside the magic socket.
-674 fn process_datagrams(
-675 &self,
-676 bufs: &mut [io::IoSliceMut<'_>],
-677 metas: &mut [quinn_udp::RecvMeta],
-678 source_addrs: &[transports::Addr],
-679 ) {
-680 debug_assert_eq!(bufs.len(), metas.len(), "non matching bufs & metas");
-681 debug_assert_eq!(
-682 bufs.len(),
-683 source_addrs.len(),
-684 "non matching bufs & source_addrs"
-685 );
-686
-687 // Adding the IP address we received something on results in Quinn using this
-688 // address on the send path to send from. However we let Quinn use a
-689 // NodeIdMappedAddress, not a real address. So we used to substitute our bind address
-690 // here so that Quinn would send on the right address. But that would sometimes
-691 // result in the wrong address family and Windows trips up on that.
-692 //
-693 // What should be done is that this dst_ip from the RecvMeta is stored in the
-694 // NodeState/PathState. Then on the send path it should be retrieved from the
-695 // NodeState/PathSate together with the send address and substituted at send time.
-696 // This is relevant for IPv6 link-local addresses where the OS otherwise does not
-697 // know which interface to send from.
-698 #[cfg(not(windows))]
-699 let dst_ip = self.normalized_local_addr().ok().map(|addr| addr.ip());
-700 // Reasoning for this here:
-701 // https://github.com/n0-computer/iroh/pull/2595#issuecomment-2290947319
-702 #[cfg(windows)]
-703 let dst_ip = None;
-704
-705 let mut quic_packets_total = 0;
-706
-707 for ((quinn_meta, buf), source_addr) in metas
-708 .iter_mut()
-709 .zip(bufs.iter_mut())
-710 .zip(source_addrs.iter())
-711 {
-712 let mut buf_contains_quic_datagrams = false;
-713 let mut quic_datagram_count = 0;
-714 if quinn_meta.len > quinn_meta.stride {
-715 trace!(%quinn_meta.len, %quinn_meta.stride, "GRO datagram received");
-716 self.metrics.magicsock.recv_gro_datagrams.inc();
-717 }
-718
-719 // Chunk through the datagrams in this GRO payload to find disco
-720 // packets and forward them to the actor
-721 for datagram in buf[..quinn_meta.len].chunks_mut(quinn_meta.stride) {
-722 if datagram.len() < quinn_meta.stride {
-723 trace!(
-724 len = %datagram.len(),
-725 %quinn_meta.stride,
-726 "Last GRO datagram smaller than stride",
-727 );
-728 }
-729
-730 // Detect DISCO datagrams and process them. Overwrite the first
-731 // byte of those packets with zero to make Quinn ignore the packet. This
-732 // relies on quinn::EndpointConfig::grease_quic_bit being set to `false`,
-733 // which we do in Endpoint::bind.
-734 if let Some((sender, sealed_box)) = disco::source_and_box(datagram) {
-735 trace!(src = ?source_addr, len = %quinn_meta.stride, "UDP recv: disco packet");
-736 self.handle_disco_message(sender, sealed_box, source_addr);
-737 datagram[0] = 0u8;
-738 } else {
-739 trace!(src = ?source_addr, len = %quinn_meta.stride, "UDP recv: quic packet");
-740 match source_addr {
-741 transports::Addr::Ip(SocketAddr::V4(..)) => {
-742 self.metrics
-743 .magicsock
-744 .recv_data_ipv4
-745 .inc_by(datagram.len() as _);
-746 }
-747 transports::Addr::Ip(SocketAddr::V6(..)) => {
-748 self.metrics
-749 .magicsock
-750 .recv_data_ipv6
-751 .inc_by(datagram.len() as _);
-752 }
-753 transports::Addr::Relay(..) => {
-754 self.metrics
-755 .magicsock
-756 .recv_data_relay
-757 .inc_by(datagram.len() as _);
-758 }
-759 }
+632 }
+633 None => {
+634 error!(%dest, "no NodeState for mapped address");
+635 }
+636 }
+637 }
+638 #[cfg(not(wasm_browser))]
+639 MappedAddr::Ip(dest) => {
+640 trace!(
+641 dst = %dest,
+642 src = ?transmit.src_ip,
+643 len = %transmit.contents.len(),
+644 "sending",
+645 );
+646
+647 // Check if this is a known IpMappedAddr, and if so, send over UDP
+648 // Get the socket addr
+649 match self.ip_mapped_addrs.get_ip_addr(&dest) {
+650 Some(addr) => {
+651 active_paths.push(transports::Addr::from(addr));
+652 }
+653 None => {
+654 error!(%dest, "unknown mapped address");
+655 }
+656 }
+657 }
+658 }
+659
+660 Ok(active_paths)
+661 }
+662
+663 /// Process datagrams received from UDP sockets.
+664 ///
+665 /// All the `bufs` and `metas` should have initialized packets in them.
+666 ///
+667 /// This fixes up the datagrams to use the correct [`NodeIdMappedAddr`] and extracts DISCO
+668 /// packets, processing them inside the magic socket.
+669 fn process_datagrams(
+670 &self,
+671 bufs: &mut [io::IoSliceMut<'_>],
+672 metas: &mut [quinn_udp::RecvMeta],
+673 source_addrs: &[transports::Addr],
+674 ) {
+675 debug_assert_eq!(bufs.len(), metas.len(), "non matching bufs & metas");
+676 debug_assert_eq!(
+677 bufs.len(),
+678 source_addrs.len(),
+679 "non matching bufs & source_addrs"
+680 );
+681
+682 // Adding the IP address we received something on results in Quinn using this
+683 // address on the send path to send from. However we let Quinn use a
+684 // NodeIdMappedAddress, not a real address. So we used to substitute our bind address
+685 // here so that Quinn would send on the right address. But that would sometimes
+686 // result in the wrong address family and Windows trips up on that.
+687 //
+688 // What should be done is that this dst_ip from the RecvMeta is stored in the
+689 // NodeState/PathState. Then on the send path it should be retrieved from the
+690 // NodeState/PathSate together with the send address and substituted at send time.
+691 // This is relevant for IPv6 link-local addresses where the OS otherwise does not
+692 // know which interface to send from.
+693 #[cfg(not(windows))]
+694 let dst_ip = self.normalized_local_addr().ok().map(|addr| addr.ip());
+695 // Reasoning for this here:
+696 // https://github.com/n0-computer/iroh/pull/2595#issuecomment-2290947319
+697 #[cfg(windows)]
+698 let dst_ip = None;
+699
+700 let mut quic_packets_total = 0;
+701
+702 for ((quinn_meta, buf), source_addr) in metas
+703 .iter_mut()
+704 .zip(bufs.iter_mut())
+705 .zip(source_addrs.iter())
+706 {
+707 let mut buf_contains_quic_datagrams = false;
+708 let mut quic_datagram_count = 0;
+709 if quinn_meta.len > quinn_meta.stride {
+710 trace!(%quinn_meta.len, %quinn_meta.stride, "GRO datagram received");
+711 self.metrics.magicsock.recv_gro_datagrams.inc();
+712 }
+713
+714 // Chunk through the datagrams in this GRO payload to find disco
+715 // packets and forward them to the actor
+716 for datagram in buf[..quinn_meta.len].chunks_mut(quinn_meta.stride) {
+717 if datagram.len() < quinn_meta.stride {
+718 trace!(
+719 len = %datagram.len(),
+720 %quinn_meta.stride,
+721 "Last GRO datagram smaller than stride",
+722 );
+723 }
+724
+725 // Detect DISCO datagrams and process them. Overwrite the first
+726 // byte of those packets with zero to make Quinn ignore the packet. This
+727 // relies on quinn::EndpointConfig::grease_quic_bit being set to `false`,
+728 // which we do in Endpoint::bind.
+729 if let Some((sender, sealed_box)) = disco::source_and_box(datagram) {
+730 trace!(src = ?source_addr, len = %quinn_meta.stride, "UDP recv: disco packet");
+731 self.handle_disco_message(sender, sealed_box, source_addr);
+732 datagram[0] = 0u8;
+733 } else {
+734 trace!(src = ?source_addr, len = %quinn_meta.stride, "UDP recv: quic packet");
+735 match source_addr {
+736 transports::Addr::Ip(SocketAddr::V4(..)) => {
+737 self.metrics
+738 .magicsock
+739 .recv_data_ipv4
+740 .inc_by(datagram.len() as _);
+741 }
+742 transports::Addr::Ip(SocketAddr::V6(..)) => {
+743 self.metrics
+744 .magicsock
+745 .recv_data_ipv6
+746 .inc_by(datagram.len() as _);
+747 }
+748 transports::Addr::Relay(..) => {
+749 self.metrics
+750 .magicsock
+751 .recv_data_relay
+752 .inc_by(datagram.len() as _);
+753 }
+754 }
+755
+756 quic_datagram_count += 1;
+757 buf_contains_quic_datagrams = true;
+758 }
+759 }
760
-761 quic_datagram_count += 1;
-762 buf_contains_quic_datagrams = true;
-763 }
-764 }
-765
-766 if buf_contains_quic_datagrams {
-767 match source_addr {
-768 #[cfg(wasm_browser)]
-769 transports::Addr::Ip(_addr) => {
-770 panic!("cannot use IP based addressing in the browser");
-771 }
-772 #[cfg(not(wasm_browser))]
-773 transports::Addr::Ip(addr) => {
-774 // UDP
-775
-776 // Update the NodeMap and remap RecvMeta to the NodeIdMappedAddr.
-777 match self.node_map.receive_udp(*addr) {
-778 None => {
-779 // Check if this address is mapped to an IpMappedAddr
-780 if let Some(ip_mapped_addr) =
-781 self.ip_mapped_addrs.get_mapped_addr(addr)
-782 {
-783 trace!(
-784 src = %addr,
-785 count = %quic_datagram_count,
-786 len = quinn_meta.len,
-787 "UDP recv QUIC address discovery packets",
-788 );
-789 quic_packets_total += quic_datagram_count;
-790 quinn_meta.addr = ip_mapped_addr.private_socket_addr();
-791 } else {
-792 warn!(
-793 src = %addr,
-794 count = %quic_datagram_count,
-795 len = quinn_meta.len,
-796 "UDP recv quic packets: no node state found, skipping",
-797 );
-798 // If we have no node state for the from addr, set len to 0 to make
-799 // quinn skip the buf completely.
-800 quinn_meta.len = 0;
-801 }
-802 }
-803 Some((node_id, quic_mapped_addr)) => {
-804 trace!(
-805 src = %addr,
-806 node = %node_id.fmt_short(),
-807 count = %quic_datagram_count,
-808 len = quinn_meta.len,
-809 "UDP recv quic packets",
-810 );
-811 quic_packets_total += quic_datagram_count;
-812 quinn_meta.addr = quic_mapped_addr.private_socket_addr();
-813 }
-814 }
+761 if buf_contains_quic_datagrams {
+762 match source_addr {
+763 #[cfg(wasm_browser)]
+764 transports::Addr::Ip(_addr) => {
+765 panic!("cannot use IP based addressing in the browser");
+766 }
+767 #[cfg(not(wasm_browser))]
+768 transports::Addr::Ip(addr) => {
+769 // UDP
+770
+771 // Update the NodeMap and remap RecvMeta to the NodeIdMappedAddr.
+772 match self.node_map.receive_udp(*addr) {
+773 None => {
+774 // Check if this address is mapped to an IpMappedAddr
+775 if let Some(ip_mapped_addr) =
+776 self.ip_mapped_addrs.get_mapped_addr(addr)
+777 {
+778 trace!(
+779 src = %addr,
+780 count = %quic_datagram_count,
+781 len = quinn_meta.len,
+782 "UDP recv QUIC address discovery packets",
+783 );
+784 quic_packets_total += quic_datagram_count;
+785 quinn_meta.addr = ip_mapped_addr.private_socket_addr();
+786 } else {
+787 warn!(
+788 src = %addr,
+789 count = %quic_datagram_count,
+790 len = quinn_meta.len,
+791 "UDP recv quic packets: no node state found, skipping",
+792 );
+793 // If we have no node state for the from addr, set len to 0 to make
+794 // quinn skip the buf completely.
+795 quinn_meta.len = 0;
+796 }
+797 }
+798 Some((node_id, quic_mapped_addr)) => {
+799 trace!(
+800 src = %addr,
+801 node = %node_id.fmt_short(),
+802 count = %quic_datagram_count,
+803 len = quinn_meta.len,
+804 "UDP recv quic packets",
+805 );
+806 quic_packets_total += quic_datagram_count;
+807 quinn_meta.addr = quic_mapped_addr.private_socket_addr();
+808 }
+809 }
+810 }
+811 transports::Addr::Relay(src_url, src_node) => {
+812 // Relay
+813 let quic_mapped_addr = self.node_map.receive_relay(src_url, *src_node);
+814 quinn_meta.addr = quic_mapped_addr.private_socket_addr();
815 }
-816 transports::Addr::Relay(src_url, src_node) => {
-817 // Relay
-818 let quic_mapped_addr = self.node_map.receive_relay(src_url, *src_node);
-819 quinn_meta.addr = quic_mapped_addr.private_socket_addr();
-820 }
-821 }
-822 } else {
-823 // If all datagrams in this buf are DISCO, set len to zero to make
-824 // Quinn skip the buf completely.
-825 quinn_meta.len = 0;
-826 }
-827 // Normalize local_ip
-828 quinn_meta.dst_ip = dst_ip;
-829 }
-830
-831 if quic_packets_total > 0 {
-832 self.metrics
-833 .magicsock
-834 .recv_datagrams
-835 .inc_by(quic_packets_total as _);
-836 trace!("UDP recv: {} packets", quic_packets_total);
-837 }
-838 }
-839
-840 /// Handles a discovery message.
-841 #[instrument("disco_in", skip_all, fields(node = %sender.fmt_short(), ?src))]
-842 fn handle_disco_message(&self, sender: PublicKey, sealed_box: &[u8], src: &transports::Addr) {
-843 trace!("handle_disco_message start");
-844 if self.is_closed() {
-845 return;
-846 }
-847
-848 if let transports::Addr::Relay(_, node_id) = src {
-849 if node_id != &sender {
-850 // TODO: return here?
-851 warn!(
-852 "Received relay disco message from connection for {}, but with message from {}",
-853 node_id.fmt_short(),
-854 sender.fmt_short()
-855 );
-856 }
-857 }
-858
-859 // We're now reasonably sure we're expecting communication from
-860 // this node, do the heavy crypto lifting to see what they want.
-861 let dm = match self.disco.unseal_and_decode(sender, sealed_box) {
-862 Ok(dm) => dm,
-863 Err(DiscoBoxError::Open { source, .. }) => {
-864 warn!(?source, "failed to open disco box");
-865 self.metrics.magicsock.recv_disco_bad_key.inc();
-866 return;
-867 }
-868 Err(DiscoBoxError::Parse { source, .. }) => {
-869 // Couldn't parse it, but it was inside a correctly
-870 // signed box, so just ignore it, assuming it's from a
-871 // newer version of Tailscale that we don't
-872 // understand. Not even worth logging about, lest it
-873 // be too spammy for old clients.
-874
-875 self.metrics.magicsock.recv_disco_bad_parse.inc();
-876 debug!(?source, "failed to parse disco message");
-877 return;
-878 }
-879 };
-880
-881 if src.is_relay() {
-882 self.metrics.magicsock.recv_disco_relay.inc();
-883 } else {
-884 self.metrics.magicsock.recv_disco_udp.inc();
-885 }
-886
-887 let span = trace_span!("handle_disco", ?dm);
-888 let _guard = span.enter();
-889 trace!("receive disco message");
-890 match dm {
-891 disco::Message::Ping(ping) => {
-892 self.metrics.magicsock.recv_disco_ping.inc();
-893 self.handle_ping(ping, sender, src);
-894 }
-895 disco::Message::Pong(pong) => {
-896 self.metrics.magicsock.recv_disco_pong.inc();
-897 self.node_map.handle_pong(sender, src, pong);
-898 }
-899 disco::Message::CallMeMaybe(cm) => {
-900 self.metrics.magicsock.recv_disco_call_me_maybe.inc();
-901 match src {
-902 transports::Addr::Relay(url, _) => {
-903 event!(
-904 target: "iroh::_events::call-me-maybe::recv",
-905 Level::DEBUG,
-906 remote_node = sender.fmt_short(),
-907 via = ?url,
-908 their_addrs = ?cm.my_numbers,
-909 );
-910 }
-911 _ => {
-912 warn!("call-me-maybe packets should only come via relay");
-913 return;
-914 }
-915 }
-916
-917 // Add new addresses as paths
-918 self.add_paths(NodeAddr {
-919 node_id: sender,
-920 relay_url: None,
-921 direct_addresses: cm.my_numbers.iter().copied().collect(),
-922 });
-923
-924 let ping_actions =
-925 self.node_map
-926 .handle_call_me_maybe(sender, cm, &self.metrics.magicsock);
-927
-928 for action in ping_actions {
-929 match action {
-930 PingAction::SendCallMeMaybe { .. } => {
-931 warn!("Unexpected CallMeMaybe as response of handling a CallMeMaybe");
-932 }
-933 PingAction::SendPing(ping) => {
-934 self.send_ping_queued(ping);
-935 }
-936 }
-937 }
-938 }
-939 }
-940 trace!("disco message handled");
-941 }
-942
-943 /// Handle a ping message.
-944 fn handle_ping(&self, dm: disco::Ping, sender: NodeId, src: &transports::Addr) {
-945 // Insert the ping into the node map, and return whether a ping with this tx_id was already
-946 // received.
-947 let addr: SendAddr = src.clone().into();
-948 let handled = self.node_map.handle_ping(sender, addr.clone(), dm.tx_id);
-949 match handled.role {
-950 PingRole::Duplicate => {
-951 debug!(?src, tx = %HEXLOWER.encode(&dm.tx_id), "received ping: path already confirmed, skip");
-952 return;
-953 }
-954 PingRole::LikelyHeartbeat => {}
-955 PingRole::NewPath => {
-956 debug!(?src, tx = %HEXLOWER.encode(&dm.tx_id), "received ping: new path");
-957 }
-958 PingRole::Activate => {
-959 debug!(?src, tx = %HEXLOWER.encode(&dm.tx_id), "received ping: path active");
-960 }
-961 }
-962
-963 // Send a pong.
-964 debug!(tx = %HEXLOWER.encode(&dm.tx_id), %addr, dstkey = %sender.fmt_short(),
-965 "sending pong");
-966 let pong = disco::Message::Pong(disco::Pong {
-967 tx_id: dm.tx_id,
-968 ping_observed_addr: addr.clone(),
-969 });
-970 event!(
-971 target: "iroh::_events::pong::sent",
-972 Level::DEBUG,
-973 remote_node = %sender.fmt_short(),
-974 dst = ?addr,
-975 txn = ?dm.tx_id,
-976 );
-977
-978 if !self.disco.try_send(addr.clone(), sender, pong) {
-979 warn!(%addr, "failed to queue pong");
-980 }
-981
-982 if let Some(ping) = handled.needs_ping_back {
-983 debug!(
-984 %addr,
-985 dstkey = %sender.fmt_short(),
-986 "sending direct ping back",
-987 );
-988 self.send_ping_queued(ping);
-989 }
-990 }
-991
-992 fn send_ping_queued(&self, ping: SendPing) {
-993 let SendPing {
-994 id,
-995 dst,
-996 dst_node,
-997 tx_id,
-998 purpose,
-999 } = ping;
-1000 let msg = disco::Message::Ping(disco::Ping {
-1001 tx_id,
-1002 node_key: self.public_key,
-1003 });
-1004 let sent = self.disco.try_send(dst.clone(), dst_node, msg);
-1005 if sent {
-1006 let msg_sender = self.actor_sender.clone();
-1007 trace!(%dst, tx = %HEXLOWER.encode(&tx_id), ?purpose, "ping sent (queued)");
-1008 self.node_map
-1009 .notify_ping_sent(id, dst, tx_id, purpose, msg_sender);
-1010 } else {
-1011 warn!(dst = ?dst, tx = %HEXLOWER.encode(&tx_id), ?purpose, "failed to send ping: queues full");
-1012 }
-1013 }
-1014
-1015 /// Send the given ping actions out.
-1016 async fn send_ping_actions(&self, sender: &UdpSender, msgs: Vec<PingAction>) -> io::Result<()> {
-1017 for msg in msgs {
-1018 // Abort sending as soon as we know we are shutting down.
-1019 if self.is_closing() || self.is_closed() {
-1020 return Ok(());
-1021 }
-1022 match msg {
-1023 PingAction::SendCallMeMaybe {
-1024 relay_url,
-1025 dst_node,
-1026 } => {
-1027 // Sends the call-me-maybe DISCO message, queuing if addresses are too stale.
-1028 //
-1029 // To send the call-me-maybe message, we need to know our current direct addresses. If
-1030 // this information is too stale, the call-me-maybe is queued while a net_report run is
-1031 // scheduled. Once this run finishes, the call-me-maybe will be sent.
-1032 match self.direct_addrs.fresh_enough() {
-1033 Ok(()) => {
-1034 let msg = disco::Message::CallMeMaybe(
-1035 self.direct_addrs.to_call_me_maybe_message(),
-1036 );
-1037 if !self.disco.try_send(
-1038 SendAddr::Relay(relay_url.clone()),
-1039 dst_node,
-1040 msg.clone(),
-1041 ) {
-1042 warn!(dstkey = %dst_node.fmt_short(), %relay_url, "relay channel full, dropping call-me-maybe");
-1043 } else {
-1044 debug!(dstkey = %dst_node.fmt_short(), %relay_url, "call-me-maybe sent");
-1045 }
-1046 }
-1047 Err(last_refresh_ago) => {
-1048 debug!(
-1049 ?last_refresh_ago,
-1050 "want call-me-maybe but direct addrs stale; queuing after restun",
-1051 );
-1052 self.actor_sender
-1053 .try_send(ActorMessage::ScheduleDirectAddrUpdate(
-1054 UpdateReason::RefreshForPeering,
-1055 Some((dst_node, relay_url)),
-1056 ))
-1057 .ok();
-1058 }
-1059 }
-1060 }
-1061 PingAction::SendPing(SendPing {
-1062 id,
-1063 dst,
-1064 dst_node,
-1065 tx_id,
-1066 purpose,
-1067 }) => {
-1068 let msg = disco::Message::Ping(disco::Ping {
-1069 tx_id,
-1070 node_key: self.public_key,
-1071 });
-1072
-1073 self.send_disco_message(sender, dst.clone(), dst_node, msg)
-1074 .await?;
-1075 debug!(%dst, tx = %HEXLOWER.encode(&tx_id), ?purpose, "ping sent");
-1076 let msg_sender = self.actor_sender.clone();
-1077 self.node_map
-1078 .notify_ping_sent(id, dst, tx_id, purpose, msg_sender);
-1079 }
-1080 }
-1081 }
-1082 Ok(())
-1083 }
-1084
-1085 /// Sends out a disco message.
-1086 async fn send_disco_message(
-1087 &self,
-1088 sender: &UdpSender,
-1089 dst: SendAddr,
-1090 dst_key: PublicKey,
-1091 msg: disco::Message,
-1092 ) -> io::Result<()> {
-1093 let dst = match dst {
-1094 SendAddr::Udp(addr) => transports::Addr::Ip(addr),
-1095 SendAddr::Relay(url) => transports::Addr::Relay(url, dst_key),
-1096 };
-1097
-1098 trace!(?dst, %msg, "send disco message (UDP)");
-1099 if self.is_closed() {
-1100 return Err(io::Error::new(
-1101 io::ErrorKind::NotConnected,
-1102 "connection closed",
-1103 ));
-1104 }
-1105
-1106 let pkt = self.disco.encode_and_seal(self.public_key, dst_key, &msg);
-1107
-1108 let transmit = transports::Transmit {
-1109 contents: &pkt,
-1110 ecn: None,
-1111 segment_size: None,
-1112 };
-1113
-1114 let dst2 = dst.clone();
-1115 match sender.send(&dst2, None, &transmit).await {
-1116 Ok(()) => {
-1117 trace!(?dst, %msg, "sent disco message");
-1118 self.metrics.magicsock.sent_disco_udp.inc();
-1119 disco_message_sent(&msg, &self.metrics.magicsock);
-1120 Ok(())
-1121 }
-1122 Err(err) => {
-1123 warn!(?dst, ?msg, ?err, "failed to send disco message");
-1124 Err(err)
-1125 }
-1126 }
-1127 }
-1128
-1129 /// Publishes our address to a discovery service, if configured.
-1130 ///
-1131 /// Called whenever our addresses or home relay node changes.
-1132 fn publish_my_addr(&self) {
-1133 if let Some(ref discovery) = self.discovery {
-1134 let relay_url = self.my_relay();
-1135 let direct_addrs = self.direct_addrs.sockaddrs();
-1136
-1137 let user_data = self
-1138 .discovery_user_data
-1139 .read()
-1140 .expect("lock poisened")
-1141 .clone();
-1142 if relay_url.is_none() && direct_addrs.is_empty() && user_data.is_none() {
-1143 // do not bother publishing if we don't have any information
-1144 return;
-1145 }
-1146
-1147 let data = NodeData::new(relay_url, direct_addrs).with_user_data(user_data);
-1148 discovery.publish(&data);
-1149 }
-1150 }
-1151}
-1152
-1153#[derive(Clone, Debug)]
-1154enum MappedAddr {
-1155 NodeId(NodeIdMappedAddr),
-1156 #[cfg(not(wasm_browser))]
-1157 Ip(IpMappedAddr),
-1158 None(SocketAddr),
-1159}
-1160
-1161impl From<SocketAddr> for MappedAddr {
-1162 fn from(value: SocketAddr) -> Self {
-1163 match value.ip() {
-1164 IpAddr::V4(_) => MappedAddr::None(value),
-1165 IpAddr::V6(addr) => {
-1166 if let Ok(node_id_mapped_addr) = NodeIdMappedAddr::try_from(addr) {
-1167 return MappedAddr::NodeId(node_id_mapped_addr);
-1168 }
-1169 #[cfg(not(wasm_browser))]
-1170 if let Ok(ip_mapped_addr) = IpMappedAddr::try_from(addr) {
-1171 return MappedAddr::Ip(ip_mapped_addr);
-1172 }
-1173 MappedAddr::None(value)
-1174 }
-1175 }
-1176 }
-1177}
-1178
-1179/// Manages currently running direct addr discovery, aka net_report runs.
-1180///
-1181/// Invariants:
-1182/// - only one direct addr update must be running at a time
-1183/// - if an update is scheduled while another one is running, remember that
-1184/// and start a new one when the current one has finished
-1185#[derive(Debug)]
-1186struct DirectAddrUpdateState {
-1187 /// If set, start a new update as soon as the current one is finished.
-1188 want_update: Option<UpdateReason>,
-1189 msock: Arc<MagicSock>,
-1190 #[cfg(not(wasm_browser))]
-1191 port_mapper: portmapper::Client,
-1192 /// The prober that discovers local network conditions, including the closest relay relay and NAT mappings.
-1193 net_reporter: Arc<AsyncMutex<net_report::Client>>,
-1194 relay_map: RelayMap,
-1195 run_done: mpsc::Sender<()>,
-1196}
-1197
-1198#[derive(Default, Debug, PartialEq, Eq, Clone, Copy)]
-1199enum UpdateReason {
-1200 /// Initial state
-1201 #[default]
-1202 None,
-1203 RefreshForPeering,
-1204 Periodic,
-1205 PortmapUpdated,
-1206 LinkChangeMajor,
-1207 LinkChangeMinor,
-1208}
-1209
-1210impl UpdateReason {
-1211 fn is_major(self) -> bool {
-1212 matches!(self, Self::LinkChangeMajor)
-1213 }
-1214}
-1215
-1216impl DirectAddrUpdateState {
-1217 fn new(
-1218 msock: Arc<MagicSock>,
-1219 #[cfg(not(wasm_browser))] port_mapper: portmapper::Client,
-1220 net_reporter: Arc<AsyncMutex<net_report::Client>>,
-1221 relay_map: RelayMap,
-1222 run_done: mpsc::Sender<()>,
-1223 ) -> Self {
-1224 DirectAddrUpdateState {
-1225 want_update: Default::default(),
-1226 #[cfg(not(wasm_browser))]
-1227 port_mapper,
-1228 net_reporter,
-1229 msock,
-1230 relay_map,
-1231 run_done,
-1232 }
-1233 }
-1234
-1235 /// Schedules a new run, either starting it immediately if none is running or
-1236 /// scheduling it for later.
-1237 fn schedule_run(&mut self, why: UpdateReason, if_state: IfStateDetails) {
-1238 match self.net_reporter.clone().try_lock_owned() {
-1239 Ok(net_reporter) => {
-1240 self.run(why, if_state, net_reporter);
-1241 }
-1242 Err(_) => {
-1243 let _ = self.want_update.insert(why);
-1244 }
-1245 }
-1246 }
-1247
-1248 /// If another run is needed, triggers this run, otherwise does nothing.
-1249 fn try_run(&mut self, if_state: IfStateDetails) {
-1250 match self.net_reporter.clone().try_lock_owned() {
-1251 Ok(net_reporter) => {
-1252 if let Some(why) = self.want_update.take() {
-1253 self.run(why, if_state, net_reporter);
-1254 }
-1255 }
-1256 Err(_) => {
-1257 // do nothing
-1258 }
-1259 }
-1260 }
-1261
-1262 /// Trigger a new run.
-1263 fn run(
-1264 &mut self,
-1265 why: UpdateReason,
-1266 if_state: IfStateDetails,
-1267 mut net_reporter: tokio::sync::OwnedMutexGuard<net_report::Client>,
-1268 ) {
-1269 debug!("starting direct addr update ({:?})", why);
-1270 #[cfg(not(wasm_browser))]
-1271 self.port_mapper.procure_mapping();
-1272 // Don't start a net report probe if we know
-1273 // we are shutting down
-1274 if self.msock.is_closing() || self.msock.is_closed() {
-1275 debug!("skipping net_report, socket is shutting down");
+816 }
+817 } else {
+818 // If all datagrams in this buf are DISCO, set len to zero to make
+819 // Quinn skip the buf completely.
+820 quinn_meta.len = 0;
+821 }
+822 // Normalize local_ip
+823 quinn_meta.dst_ip = dst_ip;
+824 }
+825
+826 if quic_packets_total > 0 {
+827 self.metrics
+828 .magicsock
+829 .recv_datagrams
+830 .inc_by(quic_packets_total as _);
+831 trace!("UDP recv: {} packets", quic_packets_total);
+832 }
+833 }
+834
+835 /// Handles a discovery message.
+836 #[instrument("disco_in", skip_all, fields(node = %sender.fmt_short(), ?src))]
+837 fn handle_disco_message(&self, sender: PublicKey, sealed_box: &[u8], src: &transports::Addr) {
+838 trace!("handle_disco_message start");
+839 if self.is_closed() {
+840 return;
+841 }
+842
+843 if let transports::Addr::Relay(_, node_id) = src {
+844 if node_id != &sender {
+845 // TODO: return here?
+846 warn!(
+847 "Received relay disco message from connection for {}, but with message from {}",
+848 node_id.fmt_short(),
+849 sender.fmt_short()
+850 );
+851 }
+852 }
+853
+854 // We're now reasonably sure we're expecting communication from
+855 // this node, do the heavy crypto lifting to see what they want.
+856 let dm = match self.disco.unseal_and_decode(sender, sealed_box) {
+857 Ok(dm) => dm,
+858 Err(DiscoBoxError::Open { source, .. }) => {
+859 warn!(?source, "failed to open disco box");
+860 self.metrics.magicsock.recv_disco_bad_key.inc();
+861 return;
+862 }
+863 Err(DiscoBoxError::Parse { source, .. }) => {
+864 // Couldn't parse it, but it was inside a correctly
+865 // signed box, so just ignore it, assuming it's from a
+866 // newer version of Tailscale that we don't
+867 // understand. Not even worth logging about, lest it
+868 // be too spammy for old clients.
+869
+870 self.metrics.magicsock.recv_disco_bad_parse.inc();
+871 debug!(?source, "failed to parse disco message");
+872 return;
+873 }
+874 };
+875
+876 if src.is_relay() {
+877 self.metrics.magicsock.recv_disco_relay.inc();
+878 } else {
+879 self.metrics.magicsock.recv_disco_udp.inc();
+880 }
+881
+882 let span = trace_span!("handle_disco", ?dm);
+883 let _guard = span.enter();
+884 trace!("receive disco message");
+885 match dm {
+886 disco::Message::Ping(ping) => {
+887 self.metrics.magicsock.recv_disco_ping.inc();
+888 self.handle_ping(ping, sender, src);
+889 }
+890 disco::Message::Pong(pong) => {
+891 self.metrics.magicsock.recv_disco_pong.inc();
+892 self.node_map.handle_pong(sender, src, pong);
+893 }
+894 disco::Message::CallMeMaybe(cm) => {
+895 self.metrics.magicsock.recv_disco_call_me_maybe.inc();
+896 match src {
+897 transports::Addr::Relay(url, _) => {
+898 event!(
+899 target: "iroh::_events::call-me-maybe::recv",
+900 Level::DEBUG,
+901 remote_node = sender.fmt_short(),
+902 via = ?url,
+903 their_addrs = ?cm.my_numbers,
+904 );
+905 }
+906 _ => {
+907 warn!("call-me-maybe packets should only come via relay");
+908 return;
+909 }
+910 }
+911
+912 // Add new addresses as paths
+913 self.add_paths(NodeAddr {
+914 node_id: sender,
+915 relay_url: None,
+916 direct_addresses: cm.my_numbers.iter().copied().collect(),
+917 });
+918
+919 let ping_actions =
+920 self.node_map
+921 .handle_call_me_maybe(sender, cm, &self.metrics.magicsock);
+922
+923 for action in ping_actions {
+924 match action {
+925 PingAction::SendCallMeMaybe { .. } => {
+926 warn!("Unexpected CallMeMaybe as response of handling a CallMeMaybe");
+927 }
+928 PingAction::SendPing(ping) => {
+929 self.send_ping_queued(ping);
+930 }
+931 }
+932 }
+933 }
+934 }
+935 trace!("disco message handled");
+936 }
+937
+938 /// Handle a ping message.
+939 fn handle_ping(&self, dm: disco::Ping, sender: NodeId, src: &transports::Addr) {
+940 // Insert the ping into the node map, and return whether a ping with this tx_id was already
+941 // received.
+942 let addr: SendAddr = src.clone().into();
+943 let handled = self.node_map.handle_ping(sender, addr.clone(), dm.tx_id);
+944 match handled.role {
+945 PingRole::Duplicate => {
+946 debug!(?src, tx = %HEXLOWER.encode(&dm.tx_id), "received ping: path already confirmed, skip");
+947 return;
+948 }
+949 PingRole::LikelyHeartbeat => {}
+950 PingRole::NewPath => {
+951 debug!(?src, tx = %HEXLOWER.encode(&dm.tx_id), "received ping: new path");
+952 }
+953 PingRole::Activate => {
+954 debug!(?src, tx = %HEXLOWER.encode(&dm.tx_id), "received ping: path active");
+955 }
+956 }
+957
+958 // Send a pong.
+959 debug!(tx = %HEXLOWER.encode(&dm.tx_id), %addr, dstkey = %sender.fmt_short(),
+960 "sending pong");
+961 let pong = disco::Message::Pong(disco::Pong {
+962 tx_id: dm.tx_id,
+963 ping_observed_addr: addr.clone(),
+964 });
+965 event!(
+966 target: "iroh::_events::pong::sent",
+967 Level::DEBUG,
+968 remote_node = %sender.fmt_short(),
+969 dst = ?addr,
+970 txn = ?dm.tx_id,
+971 );
+972
+973 if !self.disco.try_send(addr.clone(), sender, pong) {
+974 warn!(%addr, "failed to queue pong");
+975 }
+976
+977 if let Some(ping) = handled.needs_ping_back {
+978 debug!(
+979 %addr,
+980 dstkey = %sender.fmt_short(),
+981 "sending direct ping back",
+982 );
+983 self.send_ping_queued(ping);
+984 }
+985 }
+986
+987 fn send_ping_queued(&self, ping: SendPing) {
+988 let SendPing {
+989 id,
+990 dst,
+991 dst_node,
+992 tx_id,
+993 purpose,
+994 } = ping;
+995 let msg = disco::Message::Ping(disco::Ping {
+996 tx_id,
+997 node_key: self.public_key,
+998 });
+999 let sent = self.disco.try_send(dst.clone(), dst_node, msg);
+1000 if sent {
+1001 let msg_sender = self.actor_sender.clone();
+1002 trace!(%dst, tx = %HEXLOWER.encode(&tx_id), ?purpose, "ping sent (queued)");
+1003 self.node_map
+1004 .notify_ping_sent(id, dst, tx_id, purpose, msg_sender);
+1005 } else {
+1006 warn!(dst = ?dst, tx = %HEXLOWER.encode(&tx_id), ?purpose, "failed to send ping: queues full");
+1007 }
+1008 }
+1009
+1010 /// Send the given ping actions out.
+1011 async fn send_ping_actions(&self, sender: &UdpSender, msgs: Vec<PingAction>) -> io::Result<()> {
+1012 for msg in msgs {
+1013 // Abort sending as soon as we know we are shutting down.
+1014 if self.is_closing() || self.is_closed() {
+1015 return Ok(());
+1016 }
+1017 match msg {
+1018 PingAction::SendCallMeMaybe {
+1019 relay_url,
+1020 dst_node,
+1021 } => {
+1022 // Sends the call-me-maybe DISCO message, queuing if addresses are too stale.
+1023 //
+1024 // To send the call-me-maybe message, we need to know our current direct addresses. If
+1025 // this information is too stale, the call-me-maybe is queued while a net_report run is
+1026 // scheduled. Once this run finishes, the call-me-maybe will be sent.
+1027 match self.direct_addrs.fresh_enough() {
+1028 Ok(()) => {
+1029 let msg = disco::Message::CallMeMaybe(
+1030 self.direct_addrs.to_call_me_maybe_message(),
+1031 );
+1032 if !self.disco.try_send(
+1033 SendAddr::Relay(relay_url.clone()),
+1034 dst_node,
+1035 msg.clone(),
+1036 ) {
+1037 warn!(dstkey = %dst_node.fmt_short(), %relay_url, "relay channel full, dropping call-me-maybe");
+1038 } else {
+1039 debug!(dstkey = %dst_node.fmt_short(), %relay_url, "call-me-maybe sent");
+1040 }
+1041 }
+1042 Err(last_refresh_ago) => {
+1043 debug!(
+1044 ?last_refresh_ago,
+1045 "want call-me-maybe but direct addrs stale; queuing after restun",
+1046 );
+1047 self.actor_sender
+1048 .try_send(ActorMessage::ScheduleDirectAddrUpdate(
+1049 UpdateReason::RefreshForPeering,
+1050 Some((dst_node, relay_url)),
+1051 ))
+1052 .ok();
+1053 }
+1054 }
+1055 }
+1056 PingAction::SendPing(SendPing {
+1057 id,
+1058 dst,
+1059 dst_node,
+1060 tx_id,
+1061 purpose,
+1062 }) => {
+1063 let msg = disco::Message::Ping(disco::Ping {
+1064 tx_id,
+1065 node_key: self.public_key,
+1066 });
+1067
+1068 self.send_disco_message(sender, dst.clone(), dst_node, msg)
+1069 .await?;
+1070 debug!(%dst, tx = %HEXLOWER.encode(&tx_id), ?purpose, "ping sent");
+1071 let msg_sender = self.actor_sender.clone();
+1072 self.node_map
+1073 .notify_ping_sent(id, dst, tx_id, purpose, msg_sender);
+1074 }
+1075 }
+1076 }
+1077 Ok(())
+1078 }
+1079
+1080 /// Sends out a disco message.
+1081 async fn send_disco_message(
+1082 &self,
+1083 sender: &UdpSender,
+1084 dst: SendAddr,
+1085 dst_key: PublicKey,
+1086 msg: disco::Message,
+1087 ) -> io::Result<()> {
+1088 let dst = match dst {
+1089 SendAddr::Udp(addr) => transports::Addr::Ip(addr),
+1090 SendAddr::Relay(url) => transports::Addr::Relay(url, dst_key),
+1091 };
+1092
+1093 trace!(?dst, %msg, "send disco message (UDP)");
+1094 if self.is_closed() {
+1095 return Err(io::Error::new(
+1096 io::ErrorKind::NotConnected,
+1097 "connection closed",
+1098 ));
+1099 }
+1100
+1101 let pkt = self.disco.encode_and_seal(self.public_key, dst_key, &msg);
+1102
+1103 let transmit = transports::Transmit {
+1104 contents: &pkt,
+1105 ecn: None,
+1106 segment_size: None,
+1107 };
+1108
+1109 let dst2 = dst.clone();
+1110 match sender.send(&dst2, None, &transmit).await {
+1111 Ok(()) => {
+1112 trace!(?dst, %msg, "sent disco message");
+1113 self.metrics.magicsock.sent_disco_udp.inc();
+1114 disco_message_sent(&msg, &self.metrics.magicsock);
+1115 Ok(())
+1116 }
+1117 Err(err) => {
+1118 warn!(?dst, ?msg, ?err, "failed to send disco message");
+1119 Err(err)
+1120 }
+1121 }
+1122 }
+1123
+1124 /// Publishes our address to a discovery service, if configured.
+1125 ///
+1126 /// Called whenever our addresses or home relay node changes.
+1127 fn publish_my_addr(&self) {
+1128 if let Some(ref discovery) = self.discovery {
+1129 let relay_url = self.my_relay();
+1130 let direct_addrs = self.direct_addrs.sockaddrs();
+1131
+1132 let user_data = self
+1133 .discovery_user_data
+1134 .read()
+1135 .expect("lock poisened")
+1136 .clone();
+1137 if relay_url.is_none() && direct_addrs.is_empty() && user_data.is_none() {
+1138 // do not bother publishing if we don't have any information
+1139 return;
+1140 }
+1141
+1142 let data = NodeData::new(relay_url, direct_addrs).with_user_data(user_data);
+1143 discovery.publish(&data);
+1144 }
+1145 }
+1146}
+1147
+1148#[derive(Clone, Debug)]
+1149enum MappedAddr {
+1150 NodeId(NodeIdMappedAddr),
+1151 #[cfg(not(wasm_browser))]
+1152 Ip(IpMappedAddr),
+1153 None(SocketAddr),
+1154}
+1155
+1156impl From<SocketAddr> for MappedAddr {
+1157 fn from(value: SocketAddr) -> Self {
+1158 match value.ip() {
+1159 IpAddr::V4(_) => MappedAddr::None(value),
+1160 IpAddr::V6(addr) => {
+1161 if let Ok(node_id_mapped_addr) = NodeIdMappedAddr::try_from(addr) {
+1162 return MappedAddr::NodeId(node_id_mapped_addr);
+1163 }
+1164 #[cfg(not(wasm_browser))]
+1165 if let Ok(ip_mapped_addr) = IpMappedAddr::try_from(addr) {
+1166 return MappedAddr::Ip(ip_mapped_addr);
+1167 }
+1168 MappedAddr::None(value)
+1169 }
+1170 }
+1171 }
+1172}
+1173
+1174/// Manages currently running direct addr discovery, aka net_report runs.
+1175///
+1176/// Invariants:
+1177/// - only one direct addr update must be running at a time
+1178/// - if an update is scheduled while another one is running, remember that
+1179/// and start a new one when the current one has finished
+1180#[derive(Debug)]
+1181struct DirectAddrUpdateState {
+1182 /// If set, start a new update as soon as the current one is finished.
+1183 want_update: Option<UpdateReason>,
+1184 msock: Arc<MagicSock>,
+1185 #[cfg(not(wasm_browser))]
+1186 port_mapper: portmapper::Client,
+1187 /// The prober that discovers local network conditions, including the closest relay relay and NAT mappings.
+1188 net_reporter: Arc<AsyncMutex<net_report::Client>>,
+1189 relay_map: RelayMap,
+1190 run_done: mpsc::Sender<()>,
+1191}
+1192
+1193#[derive(Default, Debug, PartialEq, Eq, Clone, Copy)]
+1194enum UpdateReason {
+1195 /// Initial state
+1196 #[default]
+1197 None,
+1198 RefreshForPeering,
+1199 Periodic,
+1200 PortmapUpdated,
+1201 LinkChangeMajor,
+1202 LinkChangeMinor,
+1203}
+1204
+1205impl UpdateReason {
+1206 fn is_major(self) -> bool {
+1207 matches!(self, Self::LinkChangeMajor)
+1208 }
+1209}
+1210
+1211impl DirectAddrUpdateState {
+1212 fn new(
+1213 msock: Arc<MagicSock>,
+1214 #[cfg(not(wasm_browser))] port_mapper: portmapper::Client,
+1215 net_reporter: Arc<AsyncMutex<net_report::Client>>,
+1216 relay_map: RelayMap,
+1217 run_done: mpsc::Sender<()>,
+1218 ) -> Self {
+1219 DirectAddrUpdateState {
+1220 want_update: Default::default(),
+1221 #[cfg(not(wasm_browser))]
+1222 port_mapper,
+1223 net_reporter,
+1224 msock,
+1225 relay_map,
+1226 run_done,
+1227 }
+1228 }
+1229
+1230 /// Schedules a new run, either starting it immediately if none is running or
+1231 /// scheduling it for later.
+1232 fn schedule_run(&mut self, why: UpdateReason, if_state: IfStateDetails) {
+1233 match self.net_reporter.clone().try_lock_owned() {
+1234 Ok(net_reporter) => {
+1235 self.run(why, if_state, net_reporter);
+1236 }
+1237 Err(_) => {
+1238 let _ = self.want_update.insert(why);
+1239 }
+1240 }
+1241 }
+1242
+1243 /// If another run is needed, triggers this run, otherwise does nothing.
+1244 fn try_run(&mut self, if_state: IfStateDetails) {
+1245 match self.net_reporter.clone().try_lock_owned() {
+1246 Ok(net_reporter) => {
+1247 if let Some(why) = self.want_update.take() {
+1248 self.run(why, if_state, net_reporter);
+1249 }
+1250 }
+1251 Err(_) => {
+1252 // do nothing
+1253 }
+1254 }
+1255 }
+1256
+1257 /// Trigger a new run.
+1258 fn run(
+1259 &mut self,
+1260 why: UpdateReason,
+1261 if_state: IfStateDetails,
+1262 mut net_reporter: tokio::sync::OwnedMutexGuard<net_report::Client>,
+1263 ) {
+1264 debug!("starting direct addr update ({:?})", why);
+1265 #[cfg(not(wasm_browser))]
+1266 self.port_mapper.procure_mapping();
+1267 // Don't start a net report probe if we know
+1268 // we are shutting down
+1269 if self.msock.is_closing() || self.msock.is_closed() {
+1270 debug!("skipping net_report, socket is shutting down");
+1271 return;
+1272 }
+1273 if self.relay_map.is_empty() {
+1274 debug!("skipping net_report, empty RelayMap");
+1275 self.msock.net_report.set((None, why)).ok();
1276 return;
1277 }
-1278 if self.relay_map.is_empty() {
-1279 debug!("skipping net_report, empty RelayMap");
-1280 self.msock.net_report.set((None, why)).ok();
-1281 return;
-1282 }
-1283
-1284 debug!("requesting net_report report");
-1285 let msock = self.msock.clone();
-1286
-1287 let run_done = self.run_done.clone();
-1288 task::spawn(async move {
-1289 let fut = time::timeout(
-1290 NET_REPORT_TIMEOUT,
-1291 net_reporter.get_report(if_state, why.is_major()),
-1292 );
-1293 match fut.await {
-1294 Ok(report) => {
-1295 msock.net_report.set((Some(report), why)).ok();
-1296 }
-1297 Err(time::Elapsed { .. }) => {
-1298 warn!("net_report report timed out");
-1299 }
-1300 }
-1301
-1302 // mark run as finished
-1303 debug!("direct addr update done ({:?})", why);
-1304 run_done.send(()).await.ok();
-1305 });
-1306 }
-1307}
-1308
-1309#[allow(missing_docs)]
-1310#[common_fields({
-1311 backtrace: Option<snafu::Backtrace>,
-1312 #[snafu(implicit)]
-1313 span_trace: n0_snafu::SpanTrace,
-1314})]
-1315#[derive(Debug, Snafu)]
-1316#[non_exhaustive]
-1317pub enum CreateHandleError {
-1318 #[snafu(display("Failed to create bind sockets"))]
-1319 BindSockets { source: io::Error },
-1320 #[snafu(display("Failed to create internal quinn endpoint"))]
-1321 CreateQuinnEndpoint { source: io::Error },
-1322 #[snafu(display("Failed to create socket state"))]
-1323 CreateSocketState { source: io::Error },
-1324 #[snafu(display("Failed to create netmon monitor"))]
-1325 CreateNetmonMonitor { source: netmon::Error },
-1326 #[snafu(display("Failed to subscribe netmon monitor"))]
-1327 SubscribeNetmonMonitor { source: netmon::Error },
-1328}
-1329
-1330impl Handle {
-1331 /// Creates a magic [`MagicSock`] listening on [`Options::addr_v4`] and [`Options::addr_v6`].
-1332 async fn new(opts: Options) -> Result<Self, CreateHandleError> {
-1333 let Options {
-1334 addr_v4,
-1335 addr_v6,
-1336 secret_key,
-1337 relay_map,
-1338 relay_protocol,
-1339 node_map,
-1340 discovery,
-1341 discovery_user_data,
-1342 #[cfg(not(wasm_browser))]
-1343 dns_resolver,
-1344 proxy_url,
-1345 server_config,
-1346 #[cfg(any(test, feature = "test-utils"))]
-1347 insecure_skip_relay_cert_verify,
-1348 #[cfg(any(test, feature = "test-utils"))]
-1349 path_selection,
-1350 metrics,
-1351 } = opts;
-1352
-1353 let addr_v4 = addr_v4.unwrap_or_else(|| SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0));
-1354
-1355 #[cfg(not(wasm_browser))]
-1356 let (ip_transports, port_mapper) =
-1357 bind_ip(addr_v4, addr_v6, &metrics).context(BindSocketsSnafu)?;
-1358
-1359 let ip_mapped_addrs = IpMappedAddresses::default();
-1360
-1361 let (actor_sender, actor_receiver) = mpsc::channel(256);
-1362
-1363 // load the node data
-1364 let node_map = node_map.unwrap_or_default();
-1365 #[cfg(any(test, feature = "test-utils"))]
-1366 let node_map = NodeMap::load_from_vec(node_map, path_selection, &metrics.magicsock);
-1367 #[cfg(not(any(test, feature = "test-utils")))]
-1368 let node_map = NodeMap::load_from_vec(node_map, &metrics.magicsock);
-1369
-1370 let my_relay = Watchable::new(None);
-1371 let ipv6_reported = Arc::new(AtomicBool::new(false));
-1372
-1373 let relay_transport = RelayTransport::new(RelayActorConfig {
-1374 my_relay: my_relay.clone(),
-1375 secret_key: secret_key.clone(),
-1376 #[cfg(not(wasm_browser))]
-1377 dns_resolver: dns_resolver.clone(),
-1378 proxy_url: proxy_url.clone(),
-1379 ipv6_reported: ipv6_reported.clone(),
-1380 #[cfg(any(test, feature = "test-utils"))]
-1381 insecure_skip_relay_cert_verify,
-1382 metrics: metrics.magicsock.clone(),
-1383 protocol: relay_protocol,
-1384 });
-1385 let relay_transports = vec![relay_transport];
-1386
-1387 let secret_encryption_key = secret_ed_box(secret_key.secret());
-1388 #[cfg(not(wasm_browser))]
-1389 let ipv6 = ip_transports.iter().any(|t| t.bind_addr().is_ipv6());
+1278
+1279 debug!("requesting net_report report");
+1280 let msock = self.msock.clone();
+1281
+1282 let run_done = self.run_done.clone();
+1283 task::spawn(async move {
+1284 let fut = time::timeout(
+1285 NET_REPORT_TIMEOUT,
+1286 net_reporter.get_report(if_state, why.is_major()),
+1287 );
+1288 match fut.await {
+1289 Ok(report) => {
+1290 msock.net_report.set((Some(report), why)).ok();
+1291 }
+1292 Err(time::Elapsed { .. }) => {
+1293 warn!("net_report report timed out");
+1294 }
+1295 }
+1296
+1297 // mark run as finished
+1298 debug!("direct addr update done ({:?})", why);
+1299 run_done.send(()).await.ok();
+1300 });
+1301 }
+1302}
+1303
+1304#[allow(missing_docs)]
+1305#[common_fields({
+1306 backtrace: Option<snafu::Backtrace>,
+1307 #[snafu(implicit)]
+1308 span_trace: n0_snafu::SpanTrace,
+1309})]
+1310#[derive(Debug, Snafu)]
+1311#[non_exhaustive]
+1312pub enum CreateHandleError {
+1313 #[snafu(display("Failed to create bind sockets"))]
+1314 BindSockets { source: io::Error },
+1315 #[snafu(display("Failed to create internal quinn endpoint"))]
+1316 CreateQuinnEndpoint { source: io::Error },
+1317 #[snafu(display("Failed to create socket state"))]
+1318 CreateSocketState { source: io::Error },
+1319 #[snafu(display("Failed to create netmon monitor"))]
+1320 CreateNetmonMonitor { source: netmon::Error },
+1321 #[snafu(display("Failed to subscribe netmon monitor"))]
+1322 SubscribeNetmonMonitor { source: netmon::Error },
+1323}
+1324
+1325impl Handle {
+1326 /// Creates a magic [`MagicSock`] listening on [`Options::addr_v4`] and [`Options::addr_v6`].
+1327 async fn new(opts: Options) -> Result<Self, CreateHandleError> {
+1328 let Options {
+1329 addr_v4,
+1330 addr_v6,
+1331 secret_key,
+1332 relay_map,
+1333 relay_protocol,
+1334 node_map,
+1335 discovery,
+1336 discovery_user_data,
+1337 #[cfg(not(wasm_browser))]
+1338 dns_resolver,
+1339 proxy_url,
+1340 server_config,
+1341 #[cfg(any(test, feature = "test-utils"))]
+1342 insecure_skip_relay_cert_verify,
+1343 #[cfg(any(test, feature = "test-utils"))]
+1344 path_selection,
+1345 metrics,
+1346 } = opts;
+1347
+1348 let addr_v4 = addr_v4.unwrap_or_else(|| SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0));
+1349
+1350 #[cfg(not(wasm_browser))]
+1351 let (ip_transports, port_mapper) =
+1352 bind_ip(addr_v4, addr_v6, &metrics).context(BindSocketsSnafu)?;
+1353
+1354 let ip_mapped_addrs = IpMappedAddresses::default();
+1355
+1356 let (actor_sender, actor_receiver) = mpsc::channel(256);
+1357
+1358 // load the node data
+1359 let node_map = node_map.unwrap_or_default();
+1360 #[cfg(any(test, feature = "test-utils"))]
+1361 let node_map = NodeMap::load_from_vec(node_map, path_selection, &metrics.magicsock);
+1362 #[cfg(not(any(test, feature = "test-utils")))]
+1363 let node_map = NodeMap::load_from_vec(node_map, &metrics.magicsock);
+1364
+1365 let my_relay = Watchable::new(None);
+1366 let ipv6_reported = Arc::new(AtomicBool::new(false));
+1367
+1368 let relay_transport = RelayTransport::new(RelayActorConfig {
+1369 my_relay: my_relay.clone(),
+1370 secret_key: secret_key.clone(),
+1371 #[cfg(not(wasm_browser))]
+1372 dns_resolver: dns_resolver.clone(),
+1373 proxy_url: proxy_url.clone(),
+1374 ipv6_reported: ipv6_reported.clone(),
+1375 #[cfg(any(test, feature = "test-utils"))]
+1376 insecure_skip_relay_cert_verify,
+1377 metrics: metrics.magicsock.clone(),
+1378 protocol: relay_protocol,
+1379 });
+1380 let relay_transports = vec![relay_transport];
+1381
+1382 let secret_encryption_key = secret_ed_box(secret_key.secret());
+1383 #[cfg(not(wasm_browser))]
+1384 let ipv6 = ip_transports.iter().any(|t| t.bind_addr().is_ipv6());
+1385
+1386 #[cfg(not(wasm_browser))]
+1387 let transports = Transports::new(ip_transports, relay_transports);
+1388 #[cfg(wasm_browser)]
+1389 let transports = Transports::new(relay_transports);
1390
-1391 #[cfg(not(wasm_browser))]
-1392 let transports = Transports::new(ip_transports, relay_transports);
-1393 #[cfg(wasm_browser)]
-1394 let transports = Transports::new(relay_transports);
-1395
-1396 let (disco, disco_receiver) = DiscoState::new(secret_encryption_key);
-1397
-1398 let msock = Arc::new(MagicSock {
-1399 public_key: secret_key.public(),
-1400 closing: AtomicBool::new(false),
-1401 closed: AtomicBool::new(false),
-1402 disco,
-1403 actor_sender: actor_sender.clone(),
-1404 ipv6_reported,
-1405 node_map,
-1406 connection_map: Default::default(),
-1407 ip_mapped_addrs: ip_mapped_addrs.clone(),
-1408 discovery,
-1409 discovery_user_data: RwLock::new(discovery_user_data),
-1410 direct_addrs: Default::default(),
-1411 net_report: Watchable::new((None, UpdateReason::None)),
+1391 let (disco, disco_receiver) = DiscoState::new(secret_encryption_key);
+1392
+1393 let msock = Arc::new(MagicSock {
+1394 public_key: secret_key.public(),
+1395 closing: AtomicBool::new(false),
+1396 closed: AtomicBool::new(false),
+1397 disco,
+1398 actor_sender: actor_sender.clone(),
+1399 ipv6_reported,
+1400 node_map,
+1401 connection_map: Default::default(),
+1402 ip_mapped_addrs: ip_mapped_addrs.clone(),
+1403 discovery,
+1404 discovery_user_data: RwLock::new(discovery_user_data),
+1405 direct_addrs: Default::default(),
+1406 net_report: Watchable::new((None, UpdateReason::None)),
+1407 #[cfg(not(wasm_browser))]
+1408 dns_resolver: dns_resolver.clone(),
+1409 discovery_subscribers: DiscoverySubscribers::new(),
+1410 metrics: metrics.clone(),
+1411 local_addrs_watch: transports.local_addrs_watch(),
1412 #[cfg(not(wasm_browser))]
-1413 dns_resolver: dns_resolver.clone(),
-1414 discovery_subscribers: DiscoverySubscribers::new(),
-1415 metrics: metrics.clone(),
-1416 local_addrs_watch: transports.local_addrs_watch(),
-1417 #[cfg(not(wasm_browser))]
-1418 ip_bind_addrs: transports.ip_bind_addrs(),
-1419 });
-1420
-1421 let mut endpoint_config = quinn::EndpointConfig::default();
-1422 // Setting this to false means that quinn will ignore packets that have the QUIC fixed bit
-1423 // set to 0. The fixed bit is the 3rd bit of the first byte of a packet.
-1424 // For performance reasons and to not rewrite buffers we pass non-QUIC UDP packets straight
-1425 // through to quinn. We set the first byte of the packet to zero, which makes quinn ignore
-1426 // the packet if grease_quic_bit is set to false.
-1427 endpoint_config.grease_quic_bit(false);
-1428
-1429 let sender = transports.create_sender(msock.clone());
-1430 let local_addrs_watch = transports.local_addrs_watch();
-1431 let network_change_sender = transports.create_network_change_sender();
-1432
-1433 let endpoint = quinn::Endpoint::new_with_abstract_socket(
-1434 endpoint_config,
-1435 Some(server_config),
-1436 Box::new(MagicUdpSocket {
-1437 socket: msock.clone(),
-1438 transports,
-1439 }),
-1440 #[cfg(not(wasm_browser))]
-1441 Arc::new(quinn::TokioRuntime),
-1442 #[cfg(wasm_browser)]
-1443 Arc::new(crate::web_runtime::WebRuntime),
-1444 )
-1445 .context(CreateQuinnEndpointSnafu)?;
-1446
-1447 let network_monitor = netmon::Monitor::new()
-1448 .await
-1449 .context(CreateNetmonMonitorSnafu)?;
-1450
-1451 let qad_endpoint = endpoint.clone();
-1452
-1453 #[cfg(any(test, feature = "test-utils"))]
-1454 let client_config = if insecure_skip_relay_cert_verify {
-1455 iroh_relay::client::make_dangerous_client_config()
-1456 } else {
-1457 default_quic_client_config()
-1458 };
-1459 #[cfg(not(any(test, feature = "test-utils")))]
-1460 let client_config = default_quic_client_config();
-1461
-1462 let net_report_config = net_report::Options::default();
-1463 #[cfg(not(wasm_browser))]
-1464 let net_report_config = net_report_config.quic_config(Some(QuicConfig {
-1465 ep: qad_endpoint,
-1466 client_config,
-1467 ipv4: true,
-1468 ipv6,
-1469 }));
-1470
-1471 #[cfg(any(test, feature = "test-utils"))]
-1472 let net_report_config =
-1473 net_report_config.insecure_skip_relay_cert_verify(insecure_skip_relay_cert_verify);
-1474
-1475 let net_reporter = net_report::Client::new(
-1476 #[cfg(not(wasm_browser))]
-1477 dns_resolver,
-1478 #[cfg(not(wasm_browser))]
-1479 Some(ip_mapped_addrs),
-1480 relay_map.clone(),
-1481 net_report_config,
-1482 metrics.net_report.clone(),
-1483 );
-1484
-1485 let (direct_addr_done_tx, direct_addr_done_rx) = mpsc::channel(8);
-1486 let direct_addr_update_state = DirectAddrUpdateState::new(
-1487 msock.clone(),
-1488 #[cfg(not(wasm_browser))]
-1489 port_mapper,
-1490 Arc::new(AsyncMutex::new(net_reporter)),
-1491 relay_map,
-1492 direct_addr_done_tx,
-1493 );
-1494
-1495 let netmon_watcher = network_monitor.interface_state();
-1496 let actor = Actor {
-1497 msg_receiver: actor_receiver,
-1498 msock: msock.clone(),
-1499 periodic_re_stun_timer: new_re_stun_timer(false),
-1500 network_monitor,
-1501 netmon_watcher,
-1502 direct_addr_update_state,
-1503 network_change_sender,
-1504 direct_addr_done_rx,
-1505 pending_call_me_maybes: Default::default(),
-1506 disco_receiver,
-1507 };
-1508
-1509 let actor_token = CancellationToken::new();
-1510 let token = actor_token.clone();
-1511 let actor_task = task::spawn(
-1512 actor
-1513 .run(token, local_addrs_watch, sender)
-1514 .instrument(info_span!("actor")),
-1515 );
-1516
-1517 let actor_task = Arc::new(Mutex::new(Some(AbortOnDropHandle::new(actor_task))));
-1518
-1519 Ok(Handle {
-1520 msock,
-1521 actor_task,
-1522 endpoint,
-1523 actor_token,
-1524 })
+1413 ip_bind_addrs: transports.ip_bind_addrs(),
+1414 });
+1415
+1416 let mut endpoint_config = quinn::EndpointConfig::default();
+1417 // Setting this to false means that quinn will ignore packets that have the QUIC fixed bit
+1418 // set to 0. The fixed bit is the 3rd bit of the first byte of a packet.
+1419 // For performance reasons and to not rewrite buffers we pass non-QUIC UDP packets straight
+1420 // through to quinn. We set the first byte of the packet to zero, which makes quinn ignore
+1421 // the packet if grease_quic_bit is set to false.
+1422 endpoint_config.grease_quic_bit(false);
+1423
+1424 let sender = transports.create_sender(msock.clone());
+1425 let local_addrs_watch = transports.local_addrs_watch();
+1426 let network_change_sender = transports.create_network_change_sender();
+1427
+1428 let endpoint = quinn::Endpoint::new_with_abstract_socket(
+1429 endpoint_config,
+1430 Some(server_config),
+1431 Box::new(MagicUdpSocket {
+1432 socket: msock.clone(),
+1433 transports,
+1434 }),
+1435 #[cfg(not(wasm_browser))]
+1436 Arc::new(quinn::TokioRuntime),
+1437 #[cfg(wasm_browser)]
+1438 Arc::new(crate::web_runtime::WebRuntime),
+1439 )
+1440 .context(CreateQuinnEndpointSnafu)?;
+1441
+1442 let network_monitor = netmon::Monitor::new()
+1443 .await
+1444 .context(CreateNetmonMonitorSnafu)?;
+1445
+1446 let qad_endpoint = endpoint.clone();
+1447
+1448 #[cfg(any(test, feature = "test-utils"))]
+1449 let client_config = if insecure_skip_relay_cert_verify {
+1450 iroh_relay::client::make_dangerous_client_config()
+1451 } else {
+1452 default_quic_client_config()
+1453 };
+1454 #[cfg(not(any(test, feature = "test-utils")))]
+1455 let client_config = default_quic_client_config();
+1456
+1457 let net_report_config = net_report::Options::default();
+1458 #[cfg(not(wasm_browser))]
+1459 let net_report_config = net_report_config.quic_config(Some(QuicConfig {
+1460 ep: qad_endpoint,
+1461 client_config,
+1462 ipv4: true,
+1463 ipv6,
+1464 }));
+1465
+1466 #[cfg(any(test, feature = "test-utils"))]
+1467 let net_report_config =
+1468 net_report_config.insecure_skip_relay_cert_verify(insecure_skip_relay_cert_verify);
+1469
+1470 let net_reporter = net_report::Client::new(
+1471 #[cfg(not(wasm_browser))]
+1472 dns_resolver,
+1473 #[cfg(not(wasm_browser))]
+1474 Some(ip_mapped_addrs),
+1475 relay_map.clone(),
+1476 net_report_config,
+1477 metrics.net_report.clone(),
+1478 );
+1479
+1480 let (direct_addr_done_tx, direct_addr_done_rx) = mpsc::channel(8);
+1481 let direct_addr_update_state = DirectAddrUpdateState::new(
+1482 msock.clone(),
+1483 #[cfg(not(wasm_browser))]
+1484 port_mapper,
+1485 Arc::new(AsyncMutex::new(net_reporter)),
+1486 relay_map,
+1487 direct_addr_done_tx,
+1488 );
+1489
+1490 let netmon_watcher = network_monitor.interface_state();
+1491 let actor = Actor {
+1492 msg_receiver: actor_receiver,
+1493 msock: msock.clone(),
+1494 periodic_re_stun_timer: new_re_stun_timer(false),
+1495 network_monitor,
+1496 netmon_watcher,
+1497 direct_addr_update_state,
+1498 network_change_sender,
+1499 direct_addr_done_rx,
+1500 pending_call_me_maybes: Default::default(),
+1501 disco_receiver,
+1502 };
+1503
+1504 let actor_token = CancellationToken::new();
+1505 let token = actor_token.clone();
+1506 let actor_task = task::spawn(
+1507 actor
+1508 .run(token, local_addrs_watch, sender)
+1509 .instrument(info_span!("actor")),
+1510 );
+1511
+1512 let actor_task = Arc::new(Mutex::new(Some(AbortOnDropHandle::new(actor_task))));
+1513
+1514 Ok(Handle {
+1515 msock,
+1516 actor_task,
+1517 endpoint,
+1518 actor_token,
+1519 })
+1520 }
+1521
+1522 /// The underlying [`quinn::Endpoint`]
+1523 pub fn endpoint(&self) -> &quinn::Endpoint {
+1524 &self.endpoint
1525 }
1526
-1527 /// The underlying [`quinn::Endpoint`]
-1528 pub fn endpoint(&self) -> &quinn::Endpoint {
-1529 &self.endpoint
-1530 }
-1531
-1532 /// Closes the connection.
-1533 ///
-1534 /// Only the first close does anything. Any later closes return nil.
-1535 /// Polling the socket ([`AsyncUdpSocket::poll_recv`]) will return [`Poll::Pending`]
-1536 /// indefinitely after this call.
-1537 #[instrument(skip_all)]
-1538 pub(crate) async fn close(&self) {
-1539 trace!(me = ?self.public_key, "magicsock closing...");
-1540 // Initiate closing all connections, and refuse future connections.
-1541 self.endpoint.close(0u16.into(), b"");
-1542
-1543 // In the history of this code, this call had been
-1544 // - removed: https://github.com/n0-computer/iroh/pull/1753
-1545 // - then added back in: https://github.com/n0-computer/iroh/pull/2227/files#diff-ba27e40e2986a3919b20f6b412ad4fe63154af648610ea5d9ed0b5d5b0e2d780R573
-1546 // - then removed again: https://github.com/n0-computer/iroh/pull/3165
-1547 // and finally added back in together with this comment.
-1548 // So before removing this call, please consider carefully.
-1549 // Among other things, this call tries its best to make sure that any queued close frames
-1550 // (e.g. via the call to `endpoint.close(...)` above), are flushed out to the sockets
-1551 // *and acknowledged* (or time out with the "probe timeout" of usually 3 seconds).
-1552 // This allows the other endpoints for these connections to be notified to release
-1553 // their resources, or - depending on the protocol - that all data was received.
-1554 // With the current quinn API, this is the only way to ensure protocol code can use
-1555 // connection close codes, and close the endpoint properly.
-1556 // If this call is skipped, then connections that protocols close just shortly before the
-1557 // call to `Endpoint::close` will in most cases cause connection time-outs on remote ends.
-1558 self.endpoint.wait_idle().await;
-1559
-1560 if self.msock.is_closed() {
-1561 return;
-1562 }
-1563 self.msock.closing.store(true, Ordering::Relaxed);
-1564 self.actor_token.cancel();
-1565
-1566 // MutexGuard is not held across await points
-1567 let task = self.actor_task.lock().expect("poisoned").take();
-1568 if let Some(task) = task {
-1569 // give the tasks a moment to shutdown cleanly
-1570 let shutdown_done = time::timeout(Duration::from_millis(100), async move {
-1571 if let Err(err) = task.await {
-1572 warn!("unexpected error in task shutdown: {:?}", err);
-1573 }
-1574 })
-1575 .await;
-1576 match shutdown_done {
-1577 Ok(_) => trace!("tasks finished in time, shutdown complete"),
-1578 Err(time::Elapsed { .. }) => {
-1579 // Dropping the task will abort itt
-1580 warn!("tasks didn't finish in time, aborting");
-1581 }
-1582 }
-1583 }
-1584
-1585 self.msock.closed.store(true, Ordering::SeqCst);
-1586
-1587 trace!("magicsock closed");
-1588 }
-1589}
-1590
-1591fn default_quic_client_config() -> rustls::ClientConfig {
-1592 // create a client config for the endpoint to use for QUIC address discovery
-1593 let root_store =
-1594 rustls::RootCertStore::from_iter(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());
-1595 rustls::client::ClientConfig::builder_with_provider(Arc::new(
-1596 rustls::crypto::ring::default_provider(),
-1597 ))
-1598 .with_safe_default_protocol_versions()
-1599 .expect("ring supports these")
-1600 .with_root_certificates(root_store)
-1601 .with_no_client_auth()
-1602}
-1603
-1604#[derive(Debug)]
-1605struct DiscoState {
-1606 /// Encryption key for this node.
-1607 secret_encryption_key: crypto_box::SecretKey,
-1608 /// The state for an active DiscoKey.
-1609 secrets: Mutex<HashMap<PublicKey, SharedSecret>>,
-1610 /// Disco (ping) queue
-1611 sender: mpsc::Sender<(SendAddr, PublicKey, disco::Message)>,
-1612}
-1613
-1614impl DiscoState {
-1615 fn new(
-1616 secret_encryption_key: crypto_box::SecretKey,
-1617 ) -> (Self, mpsc::Receiver<(SendAddr, PublicKey, disco::Message)>) {
-1618 let (disco_sender, disco_receiver) = mpsc::channel(256);
-1619
-1620 (
-1621 Self {
-1622 secret_encryption_key,
-1623 secrets: Default::default(),
-1624 sender: disco_sender,
-1625 },
-1626 disco_receiver,
-1627 )
-1628 }
-1629
-1630 fn try_send(&self, dst: SendAddr, node_id: PublicKey, msg: disco::Message) -> bool {
-1631 self.sender.try_send((dst, node_id, msg)).is_ok()
-1632 }
-1633
-1634 fn encode_and_seal(
-1635 &self,
-1636 this_node_id: NodeId,
-1637 other_node_id: NodeId,
-1638 msg: &disco::Message,
-1639 ) -> Bytes {
-1640 let mut seal = msg.as_bytes();
-1641 self.get_secret(other_node_id, |secret| secret.seal(&mut seal));
-1642 disco::encode_message(&this_node_id, seal).into()
-1643 }
-1644
-1645 fn unseal_and_decode(
-1646 &self,
-1647 node_id: PublicKey,
-1648 sealed_box: &[u8],
-1649 ) -> Result<disco::Message, DiscoBoxError> {
-1650 let mut sealed_box = sealed_box.to_vec();
-1651 self.get_secret(node_id, |secret| secret.open(&mut sealed_box))
-1652 .context(OpenSnafu)?;
-1653 disco::Message::from_bytes(&sealed_box).context(ParseSnafu)
-1654 }
-1655
-1656 fn get_secret<F, T>(&self, node_id: PublicKey, cb: F) -> T
-1657 where
-1658 F: FnOnce(&mut SharedSecret) -> T,
-1659 {
-1660 let mut inner = self.secrets.lock().expect("poisoned");
-1661 let x = inner.entry(node_id).or_insert_with(|| {
-1662 let public_key = public_ed_box(&node_id.public());
-1663 SharedSecret::new(&self.secret_encryption_key, &public_key)
-1664 });
-1665 cb(x)
-1666 }
-1667}
-1668
-1669#[allow(missing_docs)]
-1670#[common_fields({
-1671 backtrace: Option<snafu::Backtrace>,
-1672 #[snafu(implicit)]
-1673 span_trace: n0_snafu::SpanTrace,
-1674})]
-1675#[derive(Debug, Snafu)]
-1676#[non_exhaustive]
-1677enum DiscoBoxError {
-1678 #[snafu(display("Failed to open crypto box"))]
-1679 Open {
-1680 #[snafu(source(from(DecryptionError, Box::new)))]
-1681 source: Box<DecryptionError>,
+1527 /// Closes the connection.
+1528 ///
+1529 /// Only the first close does anything. Any later closes return nil.
+1530 /// Polling the socket ([`AsyncUdpSocket::poll_recv`]) will return [`Poll::Pending`]
+1531 /// indefinitely after this call.
+1532 #[instrument(skip_all)]
+1533 pub(crate) async fn close(&self) {
+1534 trace!(me = ?self.public_key, "magicsock closing...");
+1535 // Initiate closing all connections, and refuse future connections.
+1536 self.endpoint.close(0u16.into(), b"");
+1537
+1538 // In the history of this code, this call had been
+1539 // - removed: https://github.com/n0-computer/iroh/pull/1753
+1540 // - then added back in: https://github.com/n0-computer/iroh/pull/2227/files#diff-ba27e40e2986a3919b20f6b412ad4fe63154af648610ea5d9ed0b5d5b0e2d780R573
+1541 // - then removed again: https://github.com/n0-computer/iroh/pull/3165
+1542 // and finally added back in together with this comment.
+1543 // So before removing this call, please consider carefully.
+1544 // Among other things, this call tries its best to make sure that any queued close frames
+1545 // (e.g. via the call to `endpoint.close(...)` above), are flushed out to the sockets
+1546 // *and acknowledged* (or time out with the "probe timeout" of usually 3 seconds).
+1547 // This allows the other endpoints for these connections to be notified to release
+1548 // their resources, or - depending on the protocol - that all data was received.
+1549 // With the current quinn API, this is the only way to ensure protocol code can use
+1550 // connection close codes, and close the endpoint properly.
+1551 // If this call is skipped, then connections that protocols close just shortly before the
+1552 // call to `Endpoint::close` will in most cases cause connection time-outs on remote ends.
+1553 self.endpoint.wait_idle().await;
+1554
+1555 if self.msock.is_closed() {
+1556 return;
+1557 }
+1558 self.msock.closing.store(true, Ordering::Relaxed);
+1559 self.actor_token.cancel();
+1560
+1561 // MutexGuard is not held across await points
+1562 let task = self.actor_task.lock().expect("poisoned").take();
+1563 if let Some(task) = task {
+1564 // give the tasks a moment to shutdown cleanly
+1565 let shutdown_done = time::timeout(Duration::from_millis(100), async move {
+1566 if let Err(err) = task.await {
+1567 warn!("unexpected error in task shutdown: {:?}", err);
+1568 }
+1569 })
+1570 .await;
+1571 match shutdown_done {
+1572 Ok(_) => trace!("tasks finished in time, shutdown complete"),
+1573 Err(time::Elapsed { .. }) => {
+1574 // Dropping the task will abort itt
+1575 warn!("tasks didn't finish in time, aborting");
+1576 }
+1577 }
+1578 }
+1579
+1580 self.msock.closed.store(true, Ordering::SeqCst);
+1581
+1582 trace!("magicsock closed");
+1583 }
+1584}
+1585
+1586fn default_quic_client_config() -> rustls::ClientConfig {
+1587 // create a client config for the endpoint to use for QUIC address discovery
+1588 let root_store =
+1589 rustls::RootCertStore::from_iter(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());
+1590 rustls::client::ClientConfig::builder_with_provider(Arc::new(
+1591 rustls::crypto::ring::default_provider(),
+1592 ))
+1593 .with_safe_default_protocol_versions()
+1594 .expect("ring supports these")
+1595 .with_root_certificates(root_store)
+1596 .with_no_client_auth()
+1597}
+1598
+1599#[derive(Debug)]
+1600struct DiscoState {
+1601 /// Encryption key for this node.
+1602 secret_encryption_key: crypto_box::SecretKey,
+1603 /// The state for an active DiscoKey.
+1604 secrets: Mutex<HashMap<PublicKey, SharedSecret>>,
+1605 /// Disco (ping) queue
+1606 sender: mpsc::Sender<(SendAddr, PublicKey, disco::Message)>,
+1607}
+1608
+1609impl DiscoState {
+1610 fn new(
+1611 secret_encryption_key: crypto_box::SecretKey,
+1612 ) -> (Self, mpsc::Receiver<(SendAddr, PublicKey, disco::Message)>) {
+1613 let (disco_sender, disco_receiver) = mpsc::channel(256);
+1614
+1615 (
+1616 Self {
+1617 secret_encryption_key,
+1618 secrets: Default::default(),
+1619 sender: disco_sender,
+1620 },
+1621 disco_receiver,
+1622 )
+1623 }
+1624
+1625 fn try_send(&self, dst: SendAddr, node_id: PublicKey, msg: disco::Message) -> bool {
+1626 self.sender.try_send((dst, node_id, msg)).is_ok()
+1627 }
+1628
+1629 fn encode_and_seal(
+1630 &self,
+1631 this_node_id: NodeId,
+1632 other_node_id: NodeId,
+1633 msg: &disco::Message,
+1634 ) -> Bytes {
+1635 let mut seal = msg.as_bytes();
+1636 self.get_secret(other_node_id, |secret| secret.seal(&mut seal));
+1637 disco::encode_message(&this_node_id, seal).into()
+1638 }
+1639
+1640 fn unseal_and_decode(
+1641 &self,
+1642 node_id: PublicKey,
+1643 sealed_box: &[u8],
+1644 ) -> Result<disco::Message, DiscoBoxError> {
+1645 let mut sealed_box = sealed_box.to_vec();
+1646 self.get_secret(node_id, |secret| secret.open(&mut sealed_box))
+1647 .context(OpenSnafu)?;
+1648 disco::Message::from_bytes(&sealed_box).context(ParseSnafu)
+1649 }
+1650
+1651 fn get_secret<F, T>(&self, node_id: PublicKey, cb: F) -> T
+1652 where
+1653 F: FnOnce(&mut SharedSecret) -> T,
+1654 {
+1655 let mut inner = self.secrets.lock().expect("poisoned");
+1656 let x = inner.entry(node_id).or_insert_with(|| {
+1657 let public_key = public_ed_box(&node_id.public());
+1658 SharedSecret::new(&self.secret_encryption_key, &public_key)
+1659 });
+1660 cb(x)
+1661 }
+1662}
+1663
+1664#[allow(missing_docs)]
+1665#[common_fields({
+1666 backtrace: Option<snafu::Backtrace>,
+1667 #[snafu(implicit)]
+1668 span_trace: n0_snafu::SpanTrace,
+1669})]
+1670#[derive(Debug, Snafu)]
+1671#[non_exhaustive]
+1672enum DiscoBoxError {
+1673 #[snafu(display("Failed to open crypto box"))]
+1674 Open {
+1675 #[snafu(source(from(DecryptionError, Box::new)))]
+1676 source: Box<DecryptionError>,
+1677 },
+1678 #[snafu(display("Failed to parse disco message"))]
+1679 Parse {
+1680 #[snafu(source(from(disco::ParseError, Box::new)))]
+1681 source: Box<disco::ParseError>,
1682 },
-1683 #[snafu(display("Failed to parse disco message"))]
-1684 Parse {
-1685 #[snafu(source(from(disco::ParseError, Box::new)))]
-1686 source: Box<disco::ParseError>,
-1687 },
-1688}
-1689
-1690#[derive(Debug)]
-1691struct MagicUdpSocket {
-1692 socket: Arc<MagicSock>,
-1693 transports: Transports,
-1694}
+1683}
+1684
+1685#[derive(Debug)]
+1686struct MagicUdpSocket {
+1687 socket: Arc<MagicSock>,
+1688 transports: Transports,
+1689}
+1690
+1691impl AsyncUdpSocket for MagicUdpSocket {
+1692 fn create_sender(&self) -> Pin<Box<dyn quinn::UdpSender>> {
+1693 Box::pin(self.transports.create_sender(self.socket.clone()))
+1694 }
1695
-1696impl AsyncUdpSocket for MagicUdpSocket {
-1697 fn create_sender(&self) -> Pin<Box<dyn quinn::UdpSender>> {
-1698 Box::pin(self.transports.create_sender(self.socket.clone()))
-1699 }
-1700
-1701 /// NOTE: Receiving on a closed socket will return [`Poll::Pending`] indefinitely.
-1702 fn poll_recv(
-1703 &mut self,
-1704 cx: &mut Context,
-1705 bufs: &mut [io::IoSliceMut<'_>],
-1706 metas: &mut [quinn_udp::RecvMeta],
-1707 ) -> Poll<io::Result<usize>> {
-1708 self.transports.poll_recv(cx, bufs, metas, &self.socket)
-1709 }
-1710
-1711 #[cfg(not(wasm_browser))]
-1712 fn local_addr(&self) -> io::Result<SocketAddr> {
-1713 let addrs: Vec<_> = self
-1714 .transports
-1715 .local_addrs()
-1716 .into_iter()
-1717 .filter_map(|addr| {
-1718 let addr: SocketAddr = addr.into_socket_addr()?;
-1719 Some(addr)
-1720 })
-1721 .collect();
-1722
-1723 if let Some(addr) = addrs.iter().find(|addr| addr.is_ipv6()) {
-1724 return Ok(*addr);
+1696 /// NOTE: Receiving on a closed socket will return [`Poll::Pending`] indefinitely.
+1697 fn poll_recv(
+1698 &mut self,
+1699 cx: &mut Context,
+1700 bufs: &mut [io::IoSliceMut<'_>],
+1701 metas: &mut [quinn_udp::RecvMeta],
+1702 ) -> Poll<io::Result<usize>> {
+1703 self.transports.poll_recv(cx, bufs, metas, &self.socket)
+1704 }
+1705
+1706 #[cfg(not(wasm_browser))]
+1707 fn local_addr(&self) -> io::Result<SocketAddr> {
+1708 let addrs: Vec<_> = self
+1709 .transports
+1710 .local_addrs()
+1711 .into_iter()
+1712 .filter_map(|addr| {
+1713 let addr: SocketAddr = addr.into_socket_addr()?;
+1714 Some(addr)
+1715 })
+1716 .collect();
+1717
+1718 if let Some(addr) = addrs.iter().find(|addr| addr.is_ipv6()) {
+1719 return Ok(*addr);
+1720 }
+1721 if let Some(SocketAddr::V4(addr)) = addrs.first() {
+1722 // Pretend to be IPv6, because our `MappedAddr`s need to be IPv6.
+1723 let ip = addr.ip().to_ipv6_mapped().into();
+1724 return Ok(SocketAddr::new(ip, addr.port()));
1725 }
-1726 if let Some(SocketAddr::V4(addr)) = addrs.first() {
-1727 // Pretend to be IPv6, because our `MappedAddr`s need to be IPv6.
-1728 let ip = addr.ip().to_ipv6_mapped().into();
-1729 return Ok(SocketAddr::new(ip, addr.port()));
-1730 }
-1731
-1732 Err(io::Error::other("no valid address available"))
-1733 }
-1734
-1735 #[cfg(wasm_browser)]
-1736 fn local_addr(&self) -> io::Result<SocketAddr> {
-1737 // Again, we need to pretend we're IPv6, because of our `MappedAddr`s.
-1738 Ok(SocketAddr::new(std::net::Ipv6Addr::LOCALHOST.into(), 0))
-1739 }
-1740
-1741 fn max_receive_segments(&self) -> usize {
-1742 self.transports.max_receive_segments()
-1743 }
+1726
+1727 Err(io::Error::other("no valid address available"))
+1728 }
+1729
+1730 #[cfg(wasm_browser)]
+1731 fn local_addr(&self) -> io::Result<SocketAddr> {
+1732 // Again, we need to pretend we're IPv6, because of our `MappedAddr`s.
+1733 Ok(SocketAddr::new(std::net::Ipv6Addr::LOCALHOST.into(), 0))
+1734 }
+1735
+1736 fn max_receive_segments(&self) -> usize {
+1737 self.transports.max_receive_segments()
+1738 }
+1739
+1740 fn may_fragment(&self) -> bool {
+1741 self.transports.may_fragment()
+1742 }
+1743}
1744
-1745 fn may_fragment(&self) -> bool {
-1746 self.transports.may_fragment()
-1747 }
-1748}
-1749
-1750#[derive(Debug)]
-1751enum ActorMessage {
-1752 PingActions(Vec<PingAction>),
-1753 EndpointPingExpired(usize, stun_rs::TransactionId),
-1754 NetworkChange,
-1755 ScheduleDirectAddrUpdate(UpdateReason, Option<(NodeId, RelayUrl)>),
-1756 #[cfg(test)]
-1757 ForceNetworkChange(bool),
-1758}
-1759
-1760struct Actor {
-1761 msock: Arc<MagicSock>,
-1762 msg_receiver: mpsc::Receiver<ActorMessage>,
-1763 /// When set, is an AfterFunc timer that will call MagicSock::do_periodic_stun.
-1764 periodic_re_stun_timer: time::Interval,
-1765
-1766 network_monitor: netmon::Monitor,
-1767 netmon_watcher: n0_watcher::Direct<netmon::State>,
-1768 network_change_sender: transports::NetworkChangeSender,
-1769 /// Indicates the direct addr update state.
-1770 direct_addr_update_state: DirectAddrUpdateState,
-1771 direct_addr_done_rx: mpsc::Receiver<()>,
-1772
-1773 /// List of CallMeMaybe disco messages that should be sent out after
-1774 /// the next endpoint update completes
-1775 pending_call_me_maybes: HashMap<PublicKey, RelayUrl>,
-1776 disco_receiver: mpsc::Receiver<(SendAddr, PublicKey, disco::Message)>,
-1777}
-1778
-1779#[cfg(not(wasm_browser))]
-1780fn bind_ip(
-1781 addr_v4: SocketAddrV4,
-1782 addr_v6: Option<SocketAddrV6>,
-1783 metrics: &EndpointMetrics,
-1784) -> io::Result<(Vec<IpTransport>, portmapper::Client)> {
-1785 let port_mapper =
-1786 portmapper::Client::with_metrics(Default::default(), metrics.portmapper.clone());
-1787
-1788 let v4 = Arc::new(bind_with_fallback(SocketAddr::V4(addr_v4))?);
-1789 let ip4_port = v4.local_addr()?.port();
-1790 let ip6_port = ip4_port.checked_add(1).unwrap_or(ip4_port - 1);
-1791
-1792 let addr_v6 =
-1793 addr_v6.unwrap_or_else(|| SocketAddrV6::new(Ipv6Addr::UNSPECIFIED, ip6_port, 0, 0));
-1794
-1795 let v6 = match bind_with_fallback(SocketAddr::V6(addr_v6)) {
-1796 Ok(sock) => Some(Arc::new(sock)),
-1797 Err(err) => {
-1798 info!("bind ignoring IPv6 bind failure: {:?}", err);
-1799 None
-1800 }
-1801 };
-1802
-1803 let port = v4.local_addr().map_or(0, |p| p.port());
-1804
-1805 let mut ip = vec![IpTransport::new(
-1806 addr_v4.into(),
-1807 v4,
-1808 metrics.magicsock.clone(),
-1809 )];
-1810 if let Some(v6) = v6 {
-1811 ip.push(IpTransport::new(
-1812 addr_v6.into(),
-1813 v6,
-1814 metrics.magicsock.clone(),
-1815 ))
-1816 }
-1817
-1818 // NOTE: we can end up with a zero port if `netwatch::UdpSocket::socket_addr` fails
-1819 match port.try_into() {
-1820 Ok(non_zero_port) => {
-1821 port_mapper.update_local_port(non_zero_port);
-1822 }
-1823 Err(_zero_port) => debug!("Skipping port mapping with zero local port"),
-1824 }
-1825
-1826 Ok((ip, port_mapper))
-1827}
-1828
-1829impl Actor {
-1830 async fn run(
-1831 mut self,
-1832 shutdown_token: CancellationToken,
-1833 mut watcher: impl Watcher<Value = Vec<transports::Addr>> + Send + Sync,
-1834 sender: UdpSender,
-1835 ) {
-1836 // Initialize addresses
-1837 #[cfg(not(wasm_browser))]
-1838 self.update_direct_addresses(None);
-1839
-1840 // Setup network monitoring
-1841 let mut current_netmon_state = self.netmon_watcher.get().expect("missing network state");
-1842
-1843 #[cfg(not(wasm_browser))]
-1844 let mut direct_addr_heartbeat_timer = time::interval(HEARTBEAT_INTERVAL);
-1845
-1846 #[cfg(not(wasm_browser))]
-1847 let mut portmap_watcher = self
-1848 .direct_addr_update_state
-1849 .port_mapper
-1850 .watch_external_address();
-1851
-1852 let mut discovery_events: BoxStream<DiscoveryItem> = Box::pin(n0_future::stream::empty());
-1853 if let Some(d) = self.msock.discovery() {
-1854 if let Some(events) = d.subscribe() {
-1855 discovery_events = events;
-1856 }
-1857 }
-1858
-1859 let mut receiver_closed = false;
-1860 #[cfg_attr(wasm_browser, allow(unused_mut))]
-1861 let mut portmap_watcher_closed = false;
-1862
-1863 let mut net_report_watcher = self.msock.net_report.watch();
-1864
-1865 loop {
-1866 self.msock.metrics.magicsock.actor_tick_main.inc();
+1745#[derive(Debug)]
+1746enum ActorMessage {
+1747 PingActions(Vec<PingAction>),
+1748 EndpointPingExpired(usize, stun_rs::TransactionId),
+1749 NetworkChange,
+1750 ScheduleDirectAddrUpdate(UpdateReason, Option<(NodeId, RelayUrl)>),
+1751 #[cfg(test)]
+1752 ForceNetworkChange(bool),
+1753}
+1754
+1755struct Actor {
+1756 msock: Arc<MagicSock>,
+1757 msg_receiver: mpsc::Receiver<ActorMessage>,
+1758 /// When set, is an AfterFunc timer that will call MagicSock::do_periodic_stun.
+1759 periodic_re_stun_timer: time::Interval,
+1760
+1761 network_monitor: netmon::Monitor,
+1762 netmon_watcher: n0_watcher::Direct<netmon::State>,
+1763 network_change_sender: transports::NetworkChangeSender,
+1764 /// Indicates the direct addr update state.
+1765 direct_addr_update_state: DirectAddrUpdateState,
+1766 direct_addr_done_rx: mpsc::Receiver<()>,
+1767
+1768 /// List of CallMeMaybe disco messages that should be sent out after
+1769 /// the next endpoint update completes
+1770 pending_call_me_maybes: HashMap<PublicKey, RelayUrl>,
+1771 disco_receiver: mpsc::Receiver<(SendAddr, PublicKey, disco::Message)>,
+1772}
+1773
+1774#[cfg(not(wasm_browser))]
+1775fn bind_ip(
+1776 addr_v4: SocketAddrV4,
+1777 addr_v6: Option<SocketAddrV6>,
+1778 metrics: &EndpointMetrics,
+1779) -> io::Result<(Vec<IpTransport>, portmapper::Client)> {
+1780 let port_mapper =
+1781 portmapper::Client::with_metrics(Default::default(), metrics.portmapper.clone());
+1782
+1783 let v4 = Arc::new(bind_with_fallback(SocketAddr::V4(addr_v4))?);
+1784 let ip4_port = v4.local_addr()?.port();
+1785 let ip6_port = ip4_port.checked_add(1).unwrap_or(ip4_port - 1);
+1786
+1787 let addr_v6 =
+1788 addr_v6.unwrap_or_else(|| SocketAddrV6::new(Ipv6Addr::UNSPECIFIED, ip6_port, 0, 0));
+1789
+1790 let v6 = match bind_with_fallback(SocketAddr::V6(addr_v6)) {
+1791 Ok(sock) => Some(Arc::new(sock)),
+1792 Err(err) => {
+1793 info!("bind ignoring IPv6 bind failure: {:?}", err);
+1794 None
+1795 }
+1796 };
+1797
+1798 let port = v4.local_addr().map_or(0, |p| p.port());
+1799
+1800 let mut ip = vec![IpTransport::new(
+1801 addr_v4.into(),
+1802 v4,
+1803 metrics.magicsock.clone(),
+1804 )];
+1805 if let Some(v6) = v6 {
+1806 ip.push(IpTransport::new(
+1807 addr_v6.into(),
+1808 v6,
+1809 metrics.magicsock.clone(),
+1810 ))
+1811 }
+1812
+1813 // NOTE: we can end up with a zero port if `netwatch::UdpSocket::socket_addr` fails
+1814 match port.try_into() {
+1815 Ok(non_zero_port) => {
+1816 port_mapper.update_local_port(non_zero_port);
+1817 }
+1818 Err(_zero_port) => debug!("Skipping port mapping with zero local port"),
+1819 }
+1820
+1821 Ok((ip, port_mapper))
+1822}
+1823
+1824impl Actor {
+1825 async fn run(
+1826 mut self,
+1827 shutdown_token: CancellationToken,
+1828 mut watcher: impl Watcher<Value = Vec<transports::Addr>> + Send + Sync,
+1829 sender: UdpSender,
+1830 ) {
+1831 // Initialize addresses
+1832 #[cfg(not(wasm_browser))]
+1833 self.update_direct_addresses(None);
+1834
+1835 // Setup network monitoring
+1836 let mut current_netmon_state = self.netmon_watcher.get().expect("missing network state");
+1837
+1838 #[cfg(not(wasm_browser))]
+1839 let mut direct_addr_heartbeat_timer = time::interval(HEARTBEAT_INTERVAL);
+1840
+1841 #[cfg(not(wasm_browser))]
+1842 let mut portmap_watcher = self
+1843 .direct_addr_update_state
+1844 .port_mapper
+1845 .watch_external_address();
+1846
+1847 let mut discovery_events: BoxStream<DiscoveryItem> = Box::pin(n0_future::stream::empty());
+1848 if let Some(d) = self.msock.discovery() {
+1849 if let Some(events) = d.subscribe() {
+1850 discovery_events = events;
+1851 }
+1852 }
+1853
+1854 let mut receiver_closed = false;
+1855 #[cfg_attr(wasm_browser, allow(unused_mut))]
+1856 let mut portmap_watcher_closed = false;
+1857
+1858 let mut net_report_watcher = self.msock.net_report.watch();
+1859
+1860 loop {
+1861 self.msock.metrics.magicsock.actor_tick_main.inc();
+1862 #[cfg(not(wasm_browser))]
+1863 let portmap_watcher_changed = portmap_watcher.changed();
+1864 #[cfg(wasm_browser)]
+1865 let portmap_watcher_changed = n0_future::future::pending();
+1866
1867 #[cfg(not(wasm_browser))]
-1868 let portmap_watcher_changed = portmap_watcher.changed();
+1868 let direct_addr_heartbeat_timer_tick = direct_addr_heartbeat_timer.tick();
1869 #[cfg(wasm_browser)]
-1870 let portmap_watcher_changed = n0_future::future::pending();
+1870 let direct_addr_heartbeat_timer_tick = n0_future::future::pending();
1871
-1872 #[cfg(not(wasm_browser))]
-1873 let direct_addr_heartbeat_timer_tick = direct_addr_heartbeat_timer.tick();
-1874 #[cfg(wasm_browser)]
-1875 let direct_addr_heartbeat_timer_tick = n0_future::future::pending();
-1876
-1877 tokio::select! {
-1878 _ = shutdown_token.cancelled() => {
-1879 debug!("shutting down");
-1880 return;
-1881 }
-1882 msg = self.msg_receiver.recv(), if !receiver_closed => {
-1883 let Some(msg) = msg else {
-1884 trace!("tick: magicsock receiver closed");
-1885 self.msock.metrics.magicsock.actor_tick_other.inc();
-1886
-1887 receiver_closed = true;
-1888 continue;
-1889 };
-1890
-1891 trace!(?msg, "tick: msg");
-1892 self.msock.metrics.magicsock.actor_tick_msg.inc();
-1893 self.handle_actor_message(msg, &sender).await;
+1872 tokio::select! {
+1873 _ = shutdown_token.cancelled() => {
+1874 debug!("shutting down");
+1875 return;
+1876 }
+1877 msg = self.msg_receiver.recv(), if !receiver_closed => {
+1878 let Some(msg) = msg else {
+1879 trace!("tick: magicsock receiver closed");
+1880 self.msock.metrics.magicsock.actor_tick_other.inc();
+1881
+1882 receiver_closed = true;
+1883 continue;
+1884 };
+1885
+1886 trace!(?msg, "tick: msg");
+1887 self.msock.metrics.magicsock.actor_tick_msg.inc();
+1888 self.handle_actor_message(msg, &sender).await;
+1889 }
+1890 tick = self.periodic_re_stun_timer.tick() => {
+1891 trace!("tick: re_stun {:?}", tick);
+1892 self.msock.metrics.magicsock.actor_tick_re_stun.inc();
+1893 self.re_stun(UpdateReason::Periodic);
1894 }
-1895 tick = self.periodic_re_stun_timer.tick() => {
-1896 trace!("tick: re_stun {:?}", tick);
-1897 self.msock.metrics.magicsock.actor_tick_re_stun.inc();
-1898 self.re_stun(UpdateReason::Periodic);
-1899 }
-1900 new_addr = watcher.updated() => {
-1901 match new_addr {
-1902 Ok(addrs) => {
-1903 if !addrs.is_empty() {
-1904 trace!(?addrs, "local addrs");
-1905 self.msock.publish_my_addr();
-1906 }
-1907 }
-1908 Err(_) => {
-1909 warn!("local addr watcher stopped");
-1910 }
-1911 }
-1912 }
-1913 report = net_report_watcher.updated() => {
-1914 match report {
-1915 Ok((report, _)) => {
-1916 self.handle_net_report_report(report);
-1917 #[cfg(not(wasm_browser))]
-1918 {
-1919 self.periodic_re_stun_timer = new_re_stun_timer(true);
-1920 }
-1921 }
-1922 Err(_) => {
-1923 warn!("net report watcher stopped");
-1924 }
-1925 }
-1926 }
-1927 reason = self.direct_addr_done_rx.recv() => {
-1928 match reason {
-1929 Some(()) => {
-1930 // check if a new run needs to be scheduled
-1931 let state = self.netmon_watcher.get().expect("disconnected");
-1932 self.direct_addr_update_state.try_run(state.into());
-1933 }
-1934 None => {
-1935 warn!("direct addr watcher died");
-1936 }
-1937 }
-1938 }
-1939 change = portmap_watcher_changed, if !portmap_watcher_closed => {
-1940 #[cfg(not(wasm_browser))]
-1941 {
-1942 if change.is_err() {
-1943 trace!("tick: portmap watcher closed");
-1944 self.msock.metrics.magicsock.actor_tick_other.inc();
-1945
-1946 portmap_watcher_closed = true;
-1947 continue;
-1948 }
-1949
-1950 trace!("tick: portmap changed");
-1951 self.msock.metrics.magicsock.actor_tick_portmap_changed.inc();
-1952 let new_external_address = *portmap_watcher.borrow();
-1953 debug!("external address updated: {new_external_address:?}");
-1954 self.re_stun(UpdateReason::PortmapUpdated);
-1955 }
-1956 #[cfg(wasm_browser)]
-1957 let _unused_in_browsers = change;
-1958 },
-1959 _ = direct_addr_heartbeat_timer_tick => {
-1960 #[cfg(not(wasm_browser))]
-1961 {
-1962 trace!(
-1963 "tick: direct addr heartbeat {} direct addrs",
-1964 self.msock.node_map.node_count(),
-1965 );
-1966 self.msock.metrics.magicsock.actor_tick_direct_addr_heartbeat.inc();
-1967 // TODO: this might trigger too many packets at once, pace this
-1968
-1969 self.msock.node_map.prune_inactive();
-1970 let msgs = self.msock.node_map.nodes_stayin_alive();
-1971 self.handle_ping_actions(&sender, msgs).await;
-1972 }
-1973 }
-1974 state = self.netmon_watcher.updated() => {
-1975 let Ok(state) = state else {
-1976 trace!("tick: link change receiver closed");
-1977 self.msock.metrics.magicsock.actor_tick_other.inc();
-1978 continue;
-1979 };
-1980 let is_major = state.is_major_change(¤t_netmon_state);
-1981 current_netmon_state = state;
-1982 trace!("tick: link change {}", is_major);
-1983 self.msock.metrics.magicsock.actor_link_change.inc();
-1984 self.handle_network_change(is_major).await;
-1985 }
-1986 // Even if `discovery_events` yields `None`, it could begin to yield
-1987 // `Some` again in the future, so we don't want to disable this branch
-1988 // forever like we do with the other branches that yield `Option`s
-1989 Some(discovery_item) = discovery_events.next() => {
-1990 trace!("tick: discovery event, address discovered: {discovery_item:?}");
-1991 let provenance = discovery_item.provenance();
-1992 let node_addr = discovery_item.to_node_addr();
-1993 if let Err(e) = self.msock.add_node_addr(
-1994 node_addr,
-1995 Source::Discovery {
-1996 name: provenance.to_string()
-1997 }) {
-1998 let node_addr = discovery_item.to_node_addr();
-1999 warn!(?node_addr, "unable to add discovered node address to the node map: {e:?}");
-2000 }
-2001 // Send the discovery item to the subscribers of the discovery broadcast stream.
-2002 self.msock.discovery_subscribers.send(discovery_item);
+1895 new_addr = watcher.updated() => {
+1896 match new_addr {
+1897 Ok(addrs) => {
+1898 if !addrs.is_empty() {
+1899 trace!(?addrs, "local addrs");
+1900 self.msock.publish_my_addr();
+1901 }
+1902 }
+1903 Err(_) => {
+1904 warn!("local addr watcher stopped");
+1905 }
+1906 }
+1907 }
+1908 report = net_report_watcher.updated() => {
+1909 match report {
+1910 Ok((report, _)) => {
+1911 self.handle_net_report_report(report);
+1912 #[cfg(not(wasm_browser))]
+1913 {
+1914 self.periodic_re_stun_timer = new_re_stun_timer(true);
+1915 }
+1916 }
+1917 Err(_) => {
+1918 warn!("net report watcher stopped");
+1919 }
+1920 }
+1921 }
+1922 reason = self.direct_addr_done_rx.recv() => {
+1923 match reason {
+1924 Some(()) => {
+1925 // check if a new run needs to be scheduled
+1926 let state = self.netmon_watcher.get().expect("disconnected");
+1927 self.direct_addr_update_state.try_run(state.into());
+1928 }
+1929 None => {
+1930 warn!("direct addr watcher died");
+1931 }
+1932 }
+1933 }
+1934 change = portmap_watcher_changed, if !portmap_watcher_closed => {
+1935 #[cfg(not(wasm_browser))]
+1936 {
+1937 if change.is_err() {
+1938 trace!("tick: portmap watcher closed");
+1939 self.msock.metrics.magicsock.actor_tick_other.inc();
+1940
+1941 portmap_watcher_closed = true;
+1942 continue;
+1943 }
+1944
+1945 trace!("tick: portmap changed");
+1946 self.msock.metrics.magicsock.actor_tick_portmap_changed.inc();
+1947 let new_external_address = *portmap_watcher.borrow();
+1948 debug!("external address updated: {new_external_address:?}");
+1949 self.re_stun(UpdateReason::PortmapUpdated);
+1950 }
+1951 #[cfg(wasm_browser)]
+1952 let _unused_in_browsers = change;
+1953 },
+1954 _ = direct_addr_heartbeat_timer_tick => {
+1955 #[cfg(not(wasm_browser))]
+1956 {
+1957 trace!(
+1958 "tick: direct addr heartbeat {} direct addrs",
+1959 self.msock.node_map.node_count(),
+1960 );
+1961 self.msock.metrics.magicsock.actor_tick_direct_addr_heartbeat.inc();
+1962 // TODO: this might trigger too many packets at once, pace this
+1963
+1964 self.msock.node_map.prune_inactive();
+1965 let msgs = self.msock.node_map.nodes_stayin_alive();
+1966 self.handle_ping_actions(&sender, msgs).await;
+1967 }
+1968 }
+1969 state = self.netmon_watcher.updated() => {
+1970 let Ok(state) = state else {
+1971 trace!("tick: link change receiver closed");
+1972 self.msock.metrics.magicsock.actor_tick_other.inc();
+1973 continue;
+1974 };
+1975 let is_major = state.is_major_change(¤t_netmon_state);
+1976 current_netmon_state = state;
+1977 trace!("tick: link change {}", is_major);
+1978 self.msock.metrics.magicsock.actor_link_change.inc();
+1979 self.handle_network_change(is_major).await;
+1980 }
+1981 // Even if `discovery_events` yields `None`, it could begin to yield
+1982 // `Some` again in the future, so we don't want to disable this branch
+1983 // forever like we do with the other branches that yield `Option`s
+1984 Some(discovery_item) = discovery_events.next() => {
+1985 trace!("tick: discovery event, address discovered: {discovery_item:?}");
+1986 let provenance = discovery_item.provenance();
+1987 let node_addr = discovery_item.to_node_addr();
+1988 if let Err(e) = self.msock.add_node_addr(
+1989 node_addr,
+1990 Source::Discovery {
+1991 name: provenance.to_string()
+1992 }) {
+1993 let node_addr = discovery_item.to_node_addr();
+1994 warn!(?node_addr, "unable to add discovered node address to the node map: {e:?}");
+1995 }
+1996 // Send the discovery item to the subscribers of the discovery broadcast stream.
+1997 self.msock.discovery_subscribers.send(discovery_item);
+1998 }
+1999 Some((dst, dst_key, msg)) = self.disco_receiver.recv() => {
+2000 if let Err(err) = self.msock.send_disco_message(&sender, dst.clone(), dst_key, msg).await {
+2001 warn!(%dst, node = %dst_key.fmt_short(), ?err, "failed to send disco message (UDP)");
+2002 }
2003 }
-2004 Some((dst, dst_key, msg)) = self.disco_receiver.recv() => {
-2005 if let Err(err) = self.msock.send_disco_message(&sender, dst.clone(), dst_key, msg).await {
-2006 warn!(%dst, node = %dst_key.fmt_short(), ?err, "failed to send disco message (UDP)");
-2007 }
-2008 }
-2009 }
-2010 }
-2011 }
-2012
-2013 async fn handle_network_change(&mut self, is_major: bool) {
-2014 debug!("link change detected: major? {}", is_major);
+2004 }
+2005 }
+2006 }
+2007
+2008 async fn handle_network_change(&mut self, is_major: bool) {
+2009 debug!("link change detected: major? {}", is_major);
+2010
+2011 if is_major {
+2012 if let Err(err) = self.network_change_sender.rebind() {
+2013 warn!("failed to rebind transports: {:?}", err);
+2014 }
2015
-2016 if is_major {
-2017 if let Err(err) = self.network_change_sender.rebind() {
-2018 warn!("failed to rebind transports: {:?}", err);
-2019 }
-2020
-2021 #[cfg(not(wasm_browser))]
-2022 self.msock.dns_resolver.reset().await;
-2023 self.re_stun(UpdateReason::LinkChangeMajor);
-2024 self.reset_endpoint_states();
-2025 } else {
-2026 self.re_stun(UpdateReason::LinkChangeMinor);
-2027 }
-2028 }
-2029
-2030 fn re_stun(&mut self, why: UpdateReason) {
-2031 let state = self.netmon_watcher.get().expect("disconnected");
-2032 self.direct_addr_update_state
-2033 .schedule_run(why, state.into());
-2034 }
-2035
-2036 #[instrument(skip_all)]
-2037 async fn handle_ping_actions(&mut self, sender: &UdpSender, msgs: Vec<PingAction>) {
-2038 if let Err(err) = self.msock.send_ping_actions(sender, msgs).await {
-2039 warn!("Failed to send ping actions: {err:#}");
-2040 }
-2041 }
-2042
-2043 /// Processes an incoming actor message.
-2044 ///
-2045 /// Returns `true` if it was a shutdown.
-2046 async fn handle_actor_message(&mut self, msg: ActorMessage, sender: &UdpSender) {
-2047 match msg {
-2048 ActorMessage::EndpointPingExpired(id, txid) => {
-2049 self.msock.node_map.notify_ping_timeout(id, txid);
-2050 }
-2051 ActorMessage::NetworkChange => {
-2052 self.network_monitor.network_change().await.ok();
-2053 }
-2054 ActorMessage::ScheduleDirectAddrUpdate(why, data) => {
-2055 if let Some((node, url)) = data {
-2056 self.pending_call_me_maybes.insert(node, url);
-2057 }
-2058 let state = self.netmon_watcher.get().expect("disconnected");
-2059 self.direct_addr_update_state
-2060 .schedule_run(why, state.into());
-2061 }
-2062 #[cfg(test)]
-2063 ActorMessage::ForceNetworkChange(is_major) => {
-2064 self.handle_network_change(is_major).await;
-2065 }
-2066 ActorMessage::PingActions(ping_actions) => {
-2067 self.handle_ping_actions(sender, ping_actions).await;
-2068 }
-2069 }
-2070 }
-2071
-2072 /// Updates the direct addresses of this magic socket.
-2073 ///
-2074 /// Updates the [`DiscoveredDirectAddrs`] of this [`MagicSock`] with the current set of
-2075 /// direct addresses from:
-2076 ///
-2077 /// - The portmapper.
-2078 /// - A net_report report.
-2079 /// - The local interfaces IP addresses.
-2080 #[cfg(not(wasm_browser))]
-2081 fn update_direct_addresses(&mut self, net_report_report: Option<&net_report::Report>) {
-2082 let portmap_watcher = self
-2083 .direct_addr_update_state
-2084 .port_mapper
-2085 .watch_external_address();
+2016 #[cfg(not(wasm_browser))]
+2017 self.msock.dns_resolver.reset().await;
+2018 self.re_stun(UpdateReason::LinkChangeMajor);
+2019 self.reset_endpoint_states();
+2020 } else {
+2021 self.re_stun(UpdateReason::LinkChangeMinor);
+2022 }
+2023 }
+2024
+2025 fn re_stun(&mut self, why: UpdateReason) {
+2026 let state = self.netmon_watcher.get().expect("disconnected");
+2027 self.direct_addr_update_state
+2028 .schedule_run(why, state.into());
+2029 }
+2030
+2031 #[instrument(skip_all)]
+2032 async fn handle_ping_actions(&mut self, sender: &UdpSender, msgs: Vec<PingAction>) {
+2033 if let Err(err) = self.msock.send_ping_actions(sender, msgs).await {
+2034 warn!("Failed to send ping actions: {err:#}");
+2035 }
+2036 }
+2037
+2038 /// Processes an incoming actor message.
+2039 ///
+2040 /// Returns `true` if it was a shutdown.
+2041 async fn handle_actor_message(&mut self, msg: ActorMessage, sender: &UdpSender) {
+2042 match msg {
+2043 ActorMessage::EndpointPingExpired(id, txid) => {
+2044 self.msock.node_map.notify_ping_timeout(id, txid);
+2045 }
+2046 ActorMessage::NetworkChange => {
+2047 self.network_monitor.network_change().await.ok();
+2048 }
+2049 ActorMessage::ScheduleDirectAddrUpdate(why, data) => {
+2050 if let Some((node, url)) = data {
+2051 self.pending_call_me_maybes.insert(node, url);
+2052 }
+2053 let state = self.netmon_watcher.get().expect("disconnected");
+2054 self.direct_addr_update_state
+2055 .schedule_run(why, state.into());
+2056 }
+2057 #[cfg(test)]
+2058 ActorMessage::ForceNetworkChange(is_major) => {
+2059 self.handle_network_change(is_major).await;
+2060 }
+2061 ActorMessage::PingActions(ping_actions) => {
+2062 self.handle_ping_actions(sender, ping_actions).await;
+2063 }
+2064 }
+2065 }
+2066
+2067 /// Updates the direct addresses of this magic socket.
+2068 ///
+2069 /// Updates the [`DiscoveredDirectAddrs`] of this [`MagicSock`] with the current set of
+2070 /// direct addresses from:
+2071 ///
+2072 /// - The portmapper.
+2073 /// - A net_report report.
+2074 /// - The local interfaces IP addresses.
+2075 #[cfg(not(wasm_browser))]
+2076 fn update_direct_addresses(&mut self, net_report_report: Option<&net_report::Report>) {
+2077 let portmap_watcher = self
+2078 .direct_addr_update_state
+2079 .port_mapper
+2080 .watch_external_address();
+2081
+2082 // We only want to have one DirectAddr for each SocketAddr we have. So we store
+2083 // this as a map of SocketAddr -> DirectAddrType. At the end we will construct a
+2084 // DirectAddr from each entry.
+2085 let mut addrs: BTreeMap<SocketAddr, DirectAddrType> = BTreeMap::new();
2086
-2087 // We only want to have one DirectAddr for each SocketAddr we have. So we store
-2088 // this as a map of SocketAddr -> DirectAddrType. At the end we will construct a
-2089 // DirectAddr from each entry.
-2090 let mut addrs: BTreeMap<SocketAddr, DirectAddrType> = BTreeMap::new();
-2091
-2092 // First add PortMapper provided addresses.
-2093 let maybe_port_mapped = *portmap_watcher.borrow();
-2094 if let Some(portmap_ext) = maybe_port_mapped.map(SocketAddr::V4) {
-2095 addrs
-2096 .entry(portmap_ext)
-2097 .or_insert(DirectAddrType::Portmapped);
-2098 }
+2087 // First add PortMapper provided addresses.
+2088 let maybe_port_mapped = *portmap_watcher.borrow();
+2089 if let Some(portmap_ext) = maybe_port_mapped.map(SocketAddr::V4) {
+2090 addrs
+2091 .entry(portmap_ext)
+2092 .or_insert(DirectAddrType::Portmapped);
+2093 }
+2094
+2095 // Next add STUN addresses from the net_report report.
+2096 if let Some(net_report_report) = net_report_report {
+2097 if let Some(global_v4) = net_report_report.global_v4 {
+2098 addrs.entry(global_v4.into()).or_insert(DirectAddrType::Qad);
2099
-2100 // Next add STUN addresses from the net_report report.
-2101 if let Some(net_report_report) = net_report_report {
-2102 if let Some(global_v4) = net_report_report.global_v4 {
-2103 addrs.entry(global_v4.into()).or_insert(DirectAddrType::Qad);
-2104
-2105 // If they're behind a hard NAT and are using a fixed
-2106 // port locally, assume they might've added a static
-2107 // port mapping on their router to the same explicit
-2108 // port that we are running with. Worst case it's an invalid candidate mapping.
-2109 let port = self.msock.ip_bind_addrs().iter().find_map(|addr| {
-2110 if addr.port() != 0 {
-2111 Some(addr.port())
-2112 } else {
-2113 None
-2114 }
-2115 });
-2116
-2117 if let Some(port) = port {
-2118 if net_report_report
-2119 .mapping_varies_by_dest()
-2120 .unwrap_or_default()
-2121 {
-2122 let mut addr = global_v4;
-2123 addr.set_port(port);
-2124 addrs
-2125 .entry(addr.into())
-2126 .or_insert(DirectAddrType::Qad4LocalPort);
-2127 }
-2128 }
-2129 }
-2130 if let Some(global_v6) = net_report_report.global_v6 {
-2131 addrs.entry(global_v6.into()).or_insert(DirectAddrType::Qad);
-2132 }
-2133 }
-2134
-2135 let local_addrs: Vec<(SocketAddr, SocketAddr)> = self
-2136 .msock
-2137 .ip_bind_addrs()
-2138 .iter()
-2139 .copied()
-2140 .zip(self.msock.ip_local_addrs())
-2141 .collect();
-2142
-2143 let has_ipv4_unspecified = local_addrs.iter().find_map(|(_, a)| {
-2144 if a.is_ipv4() && a.ip().is_unspecified() {
-2145 Some(a.port())
-2146 } else {
-2147 None
-2148 }
-2149 });
-2150 let has_ipv6_unspecified = local_addrs.iter().find_map(|(_, a)| {
-2151 if a.is_ipv6() && a.ip().is_unspecified() {
-2152 Some(a.port())
-2153 } else {
-2154 None
-2155 }
-2156 });
-2157
-2158 // If a socket is bound to the unspecified address, create SocketAddrs for
-2159 // each local IP address by pairing it with the port the socket is bound on.
-2160 if local_addrs
-2161 .iter()
-2162 .any(|(_, local)| local.ip().is_unspecified())
-2163 {
-2164 let LocalAddresses {
-2165 regular: mut ips,
-2166 loopback,
-2167 } = self
-2168 .netmon_watcher
-2169 .get()
-2170 .expect("netmon disconnected")
-2171 .local_addresses;
-2172 if ips.is_empty() && addrs.is_empty() {
-2173 // Include loopback addresses only if there are no other interfaces
-2174 // or public addresses, this allows testing offline.
-2175 ips = loopback;
-2176 }
-2177
-2178 for ip in ips {
-2179 let port_if_unspecified = match ip {
-2180 IpAddr::V4(_) => has_ipv4_unspecified,
-2181 IpAddr::V6(_) => has_ipv6_unspecified,
-2182 };
-2183 if let Some(port) = port_if_unspecified {
-2184 let addr = SocketAddr::new(ip, port);
-2185 addrs.entry(addr).or_insert(DirectAddrType::Local);
-2186 }
-2187 }
-2188 }
-2189
-2190 // If a socket is bound to a specific address, add it.
-2191 for (bound, local) in local_addrs {
-2192 if !bound.ip().is_unspecified() {
-2193 addrs.entry(local).or_insert(DirectAddrType::Local);
-2194 }
-2195 }
-2196
-2197 // Finally create and store store all these direct addresses and send any
-2198 // queued call-me-maybe messages.
-2199 self.msock.store_direct_addresses(
-2200 addrs
-2201 .iter()
-2202 .map(|(addr, typ)| DirectAddr {
-2203 addr: *addr,
-2204 typ: *typ,
-2205 })
-2206 .collect(),
-2207 );
-2208 self.send_queued_call_me_maybes();
-2209 }
+2100 // If they're behind a hard NAT and are using a fixed
+2101 // port locally, assume they might've added a static
+2102 // port mapping on their router to the same explicit
+2103 // port that we are running with. Worst case it's an invalid candidate mapping.
+2104 let port = self.msock.ip_bind_addrs().iter().find_map(|addr| {
+2105 if addr.port() != 0 {
+2106 Some(addr.port())
+2107 } else {
+2108 None
+2109 }
+2110 });
+2111
+2112 if let Some(port) = port {
+2113 if net_report_report
+2114 .mapping_varies_by_dest()
+2115 .unwrap_or_default()
+2116 {
+2117 let mut addr = global_v4;
+2118 addr.set_port(port);
+2119 addrs
+2120 .entry(addr.into())
+2121 .or_insert(DirectAddrType::Qad4LocalPort);
+2122 }
+2123 }
+2124 }
+2125 if let Some(global_v6) = net_report_report.global_v6 {
+2126 addrs.entry(global_v6.into()).or_insert(DirectAddrType::Qad);
+2127 }
+2128 }
+2129
+2130 let local_addrs: Vec<(SocketAddr, SocketAddr)> = self
+2131 .msock
+2132 .ip_bind_addrs()
+2133 .iter()
+2134 .copied()
+2135 .zip(self.msock.ip_local_addrs())
+2136 .collect();
+2137
+2138 let has_ipv4_unspecified = local_addrs.iter().find_map(|(_, a)| {
+2139 if a.is_ipv4() && a.ip().is_unspecified() {
+2140 Some(a.port())
+2141 } else {
+2142 None
+2143 }
+2144 });
+2145 let has_ipv6_unspecified = local_addrs.iter().find_map(|(_, a)| {
+2146 if a.is_ipv6() && a.ip().is_unspecified() {
+2147 Some(a.port())
+2148 } else {
+2149 None
+2150 }
+2151 });
+2152
+2153 // If a socket is bound to the unspecified address, create SocketAddrs for
+2154 // each local IP address by pairing it with the port the socket is bound on.
+2155 if local_addrs
+2156 .iter()
+2157 .any(|(_, local)| local.ip().is_unspecified())
+2158 {
+2159 let LocalAddresses {
+2160 regular: mut ips,
+2161 loopback,
+2162 } = self
+2163 .netmon_watcher
+2164 .get()
+2165 .expect("netmon disconnected")
+2166 .local_addresses;
+2167 if ips.is_empty() && addrs.is_empty() {
+2168 // Include loopback addresses only if there are no other interfaces
+2169 // or public addresses, this allows testing offline.
+2170 ips = loopback;
+2171 }
+2172
+2173 for ip in ips {
+2174 let port_if_unspecified = match ip {
+2175 IpAddr::V4(_) => has_ipv4_unspecified,
+2176 IpAddr::V6(_) => has_ipv6_unspecified,
+2177 };
+2178 if let Some(port) = port_if_unspecified {
+2179 let addr = SocketAddr::new(ip, port);
+2180 addrs.entry(addr).or_insert(DirectAddrType::Local);
+2181 }
+2182 }
+2183 }
+2184
+2185 // If a socket is bound to a specific address, add it.
+2186 for (bound, local) in local_addrs {
+2187 if !bound.ip().is_unspecified() {
+2188 addrs.entry(local).or_insert(DirectAddrType::Local);
+2189 }
+2190 }
+2191
+2192 // Finally create and store store all these direct addresses and send any
+2193 // queued call-me-maybe messages.
+2194 self.msock.store_direct_addresses(
+2195 addrs
+2196 .iter()
+2197 .map(|(addr, typ)| DirectAddr {
+2198 addr: *addr,
+2199 typ: *typ,
+2200 })
+2201 .collect(),
+2202 );
+2203 self.send_queued_call_me_maybes();
+2204 }
+2205
+2206 fn send_queued_call_me_maybes(&mut self) {
+2207 let msg = self.msock.direct_addrs.to_call_me_maybe_message();
+2208 let msg = disco::Message::CallMeMaybe(msg);
+2209 // allocate, to minimize locking duration
2210
-2211 fn send_queued_call_me_maybes(&mut self) {
-2212 let msg = self.msock.direct_addrs.to_call_me_maybe_message();
-2213 let msg = disco::Message::CallMeMaybe(msg);
-2214 // allocate, to minimize locking duration
-2215
-2216 for (public_key, url) in self.pending_call_me_maybes.drain() {
-2217 if !self
-2218 .msock
-2219 .disco
-2220 .try_send(SendAddr::Relay(url), public_key, msg.clone())
-2221 {
-2222 warn!(node = %public_key.fmt_short(), "relay channel full, dropping call-me-maybe");
-2223 }
-2224 }
-2225 }
-2226
-2227 fn handle_net_report_report(&mut self, mut report: Option<net_report::Report>) {
-2228 if let Some(ref mut r) = report {
-2229 self.msock.ipv6_reported.store(r.udp_v6, Ordering::Relaxed);
-2230 if r.preferred_relay.is_none() {
-2231 if let Some(my_relay) = self.msock.my_relay() {
-2232 r.preferred_relay.replace(my_relay);
-2233 }
-2234 }
-2235
-2236 // Notify all transports
-2237 self.network_change_sender.on_network_change(r);
-2238 }
-2239
-2240 #[cfg(not(wasm_browser))]
-2241 self.update_direct_addresses(report.as_ref());
-2242 }
-2243
-2244 /// Resets the preferred address for all nodes.
-2245 /// This is called when connectivity changes enough that we no longer trust the old routes.
-2246 #[instrument(skip_all)]
-2247 fn reset_endpoint_states(&mut self) {
-2248 self.msock.node_map.reset_node_states()
-2249 }
-2250}
-2251
-2252fn new_re_stun_timer(initial_delay: bool) -> time::Interval {
-2253 // Pick a random duration between 20 and 26 seconds (just under 30s,
-2254 // a common UDP NAT timeout on Linux,etc)
-2255 let mut rng = rand::thread_rng();
-2256 let d: Duration = rng.gen_range(Duration::from_secs(20)..=Duration::from_secs(26));
-2257 if initial_delay {
-2258 debug!("scheduling periodic_stun to run in {}s", d.as_secs());
-2259 time::interval_at(time::Instant::now() + d, d)
-2260 } else {
-2261 debug!(
-2262 "scheduling periodic_stun to run immediately and in {}s",
-2263 d.as_secs()
-2264 );
-2265 time::interval(d)
-2266 }
-2267}
-2268
-2269#[cfg(not(wasm_browser))]
-2270fn bind_with_fallback(mut addr: SocketAddr) -> io::Result<UdpSocket> {
-2271 debug!(%addr, "binding");
-2272
-2273 // First try binding a preferred port, if specified
-2274 match UdpSocket::bind_full(addr) {
-2275 Ok(socket) => {
-2276 let local_addr = socket.local_addr()?;
-2277 debug!(%addr, %local_addr, "successfully bound");
-2278 return Ok(socket);
-2279 }
-2280 Err(err) => {
-2281 debug!(%addr, "failed to bind: {err:#}");
-2282 // If that was already the fallback port, then error out
-2283 if addr.port() == 0 {
-2284 return Err(err);
-2285 }
-2286 }
-2287 }
+2211 for (public_key, url) in self.pending_call_me_maybes.drain() {
+2212 if !self
+2213 .msock
+2214 .disco
+2215 .try_send(SendAddr::Relay(url), public_key, msg.clone())
+2216 {
+2217 warn!(node = %public_key.fmt_short(), "relay channel full, dropping call-me-maybe");
+2218 }
+2219 }
+2220 }
+2221
+2222 fn handle_net_report_report(&mut self, mut report: Option<net_report::Report>) {
+2223 if let Some(ref mut r) = report {
+2224 self.msock.ipv6_reported.store(r.udp_v6, Ordering::Relaxed);
+2225 if r.preferred_relay.is_none() {
+2226 if let Some(my_relay) = self.msock.my_relay() {
+2227 r.preferred_relay.replace(my_relay);
+2228 }
+2229 }
+2230
+2231 // Notify all transports
+2232 self.network_change_sender.on_network_change(r);
+2233 }
+2234
+2235 #[cfg(not(wasm_browser))]
+2236 self.update_direct_addresses(report.as_ref());
+2237 }
+2238
+2239 /// Resets the preferred address for all nodes.
+2240 /// This is called when connectivity changes enough that we no longer trust the old routes.
+2241 #[instrument(skip_all)]
+2242 fn reset_endpoint_states(&mut self) {
+2243 self.msock.node_map.reset_node_states()
+2244 }
+2245}
+2246
+2247fn new_re_stun_timer(initial_delay: bool) -> time::Interval {
+2248 // Pick a random duration between 20 and 26 seconds (just under 30s,
+2249 // a common UDP NAT timeout on Linux,etc)
+2250 let mut rng = rand::thread_rng();
+2251 let d: Duration = rng.gen_range(Duration::from_secs(20)..=Duration::from_secs(26));
+2252 if initial_delay {
+2253 debug!("scheduling periodic_stun to run in {}s", d.as_secs());
+2254 time::interval_at(time::Instant::now() + d, d)
+2255 } else {
+2256 debug!(
+2257 "scheduling periodic_stun to run immediately and in {}s",
+2258 d.as_secs()
+2259 );
+2260 time::interval(d)
+2261 }
+2262}
+2263
+2264#[cfg(not(wasm_browser))]
+2265fn bind_with_fallback(mut addr: SocketAddr) -> io::Result<UdpSocket> {
+2266 debug!(%addr, "binding");
+2267
+2268 // First try binding a preferred port, if specified
+2269 match UdpSocket::bind_full(addr) {
+2270 Ok(socket) => {
+2271 let local_addr = socket.local_addr()?;
+2272 debug!(%addr, %local_addr, "successfully bound");
+2273 return Ok(socket);
+2274 }
+2275 Err(err) => {
+2276 debug!(%addr, "failed to bind: {err:#}");
+2277 // If that was already the fallback port, then error out
+2278 if addr.port() == 0 {
+2279 return Err(err);
+2280 }
+2281 }
+2282 }
+2283
+2284 // Otherwise, try binding with port 0
+2285 addr.set_port(0);
+2286 UdpSocket::bind_full(addr)
+2287}
2288
-2289 // Otherwise, try binding with port 0
-2290 addr.set_port(0);
-2291 UdpSocket::bind_full(addr)
-2292}
-2293
-2294/// The discovered direct addresses of this [`MagicSock`].
-2295///
-2296/// These are all the [`DirectAddr`]s that this [`MagicSock`] is aware of for itself.
-2297/// They include all locally bound ones as well as those discovered by other mechanisms like
-2298/// QAD.
-2299#[derive(derive_more::Debug, Default, Clone)]
-2300struct DiscoveredDirectAddrs {
-2301 /// The last set of discovered direct addresses.
-2302 addrs: Watchable<Option<BTreeSet<DirectAddr>>>,
-2303
-2304 /// The last time the direct addresses were updated, even if there was no change.
-2305 ///
-2306 /// This is only ever None at startup.
-2307 updated_at: Arc<RwLock<Option<Instant>>>,
-2308}
-2309
-2310impl DiscoveredDirectAddrs {
-2311 /// Updates the direct addresses, returns `true` if they changed, `false` if not.
-2312 fn update(&self, addrs: BTreeSet<DirectAddr>) -> bool {
-2313 *self.updated_at.write().expect("poisoned") = Some(Instant::now());
-2314 let updated = self.addrs.set(Some(addrs)).is_ok();
-2315 if updated {
-2316 event!(
-2317 target: "iroh::_events::direct_addrs",
-2318 Level::DEBUG,
-2319 addrs = ?self.addrs.get(),
-2320 );
-2321 }
-2322 updated
-2323 }
-2324
-2325 fn sockaddrs(&self) -> BTreeSet<SocketAddr> {
-2326 self.addrs
-2327 .get()
-2328 .unwrap_or_default()
-2329 .into_iter()
-2330 .map(|da| da.addr)
-2331 .collect()
-2332 }
-2333
-2334 /// Whether the direct addr information is considered "fresh".
+2289/// The discovered direct addresses of this [`MagicSock`].
+2290///
+2291/// These are all the [`DirectAddr`]s that this [`MagicSock`] is aware of for itself.
+2292/// They include all locally bound ones as well as those discovered by other mechanisms like
+2293/// QAD.
+2294#[derive(derive_more::Debug, Default, Clone)]
+2295struct DiscoveredDirectAddrs {
+2296 /// The last set of discovered direct addresses.
+2297 addrs: Watchable<Option<BTreeSet<DirectAddr>>>,
+2298
+2299 /// The last time the direct addresses were updated, even if there was no change.
+2300 ///
+2301 /// This is only ever None at startup.
+2302 updated_at: Arc<RwLock<Option<Instant>>>,
+2303}
+2304
+2305impl DiscoveredDirectAddrs {
+2306 /// Updates the direct addresses, returns `true` if they changed, `false` if not.
+2307 fn update(&self, addrs: BTreeSet<DirectAddr>) -> bool {
+2308 *self.updated_at.write().expect("poisoned") = Some(Instant::now());
+2309 let updated = self.addrs.set(Some(addrs)).is_ok();
+2310 if updated {
+2311 event!(
+2312 target: "iroh::_events::direct_addrs",
+2313 Level::DEBUG,
+2314 addrs = ?self.addrs.get(),
+2315 );
+2316 }
+2317 updated
+2318 }
+2319
+2320 fn sockaddrs(&self) -> BTreeSet<SocketAddr> {
+2321 self.addrs
+2322 .get()
+2323 .unwrap_or_default()
+2324 .into_iter()
+2325 .map(|da| da.addr)
+2326 .collect()
+2327 }
+2328
+2329 /// Whether the direct addr information is considered "fresh".
+2330 ///
+2331 /// If not fresh you should probably update the direct addresses before using this info.
+2332 ///
+2333 /// Returns `Ok(())` if fresh enough and `Err(elapsed)` if not fresh enough.
+2334 /// `elapsed` is the time elapsed since the direct addresses were last updated.
2335 ///
-2336 /// If not fresh you should probably update the direct addresses before using this info.
-2337 ///
-2338 /// Returns `Ok(())` if fresh enough and `Err(elapsed)` if not fresh enough.
-2339 /// `elapsed` is the time elapsed since the direct addresses were last updated.
-2340 ///
-2341 /// If there is no direct address information `Err(Duration::ZERO)` is returned.
-2342 fn fresh_enough(&self) -> Result<(), Duration> {
-2343 match *self.updated_at.read().expect("poisoned") {
-2344 None => Err(Duration::ZERO),
-2345 Some(time) => {
-2346 let elapsed = time.elapsed();
-2347 if elapsed <= ENDPOINTS_FRESH_ENOUGH_DURATION {
-2348 Ok(())
-2349 } else {
-2350 Err(elapsed)
-2351 }
-2352 }
-2353 }
-2354 }
-2355
-2356 fn to_call_me_maybe_message(&self) -> disco::CallMeMaybe {
-2357 let my_numbers = self
-2358 .addrs
-2359 .get()
-2360 .unwrap_or_default()
-2361 .into_iter()
-2362 .map(|da| da.addr)
-2363 .collect();
-2364 disco::CallMeMaybe { my_numbers }
-2365 }
-2366}
-2367
-2368/// The fake address used by the QUIC layer to address a node.
-2369///
-2370/// You can consider this as nothing more than a lookup key for a node the [`MagicSock`] knows
-2371/// about.
+2336 /// If there is no direct address information `Err(Duration::ZERO)` is returned.
+2337 fn fresh_enough(&self) -> Result<(), Duration> {
+2338 match *self.updated_at.read().expect("poisoned") {
+2339 None => Err(Duration::ZERO),
+2340 Some(time) => {
+2341 let elapsed = time.elapsed();
+2342 if elapsed <= ENDPOINTS_FRESH_ENOUGH_DURATION {
+2343 Ok(())
+2344 } else {
+2345 Err(elapsed)
+2346 }
+2347 }
+2348 }
+2349 }
+2350
+2351 fn to_call_me_maybe_message(&self) -> disco::CallMeMaybe {
+2352 let my_numbers = self
+2353 .addrs
+2354 .get()
+2355 .unwrap_or_default()
+2356 .into_iter()
+2357 .map(|da| da.addr)
+2358 .collect();
+2359 disco::CallMeMaybe { my_numbers }
+2360 }
+2361}
+2362
+2363/// The fake address used by the QUIC layer to address a node.
+2364///
+2365/// You can consider this as nothing more than a lookup key for a node the [`MagicSock`] knows
+2366/// about.
+2367///
+2368/// [`MagicSock`] can reach a node by several real socket addresses, or maybe even via the relay
+2369/// node. The QUIC layer however needs to address a node by a stable [`SocketAddr`] so
+2370/// that normal socket APIs can function. Thus when a new node is introduced to a [`MagicSock`]
+2371/// it is given a new fake address. This is the type of that address.
2372///
-2373/// [`MagicSock`] can reach a node by several real socket addresses, or maybe even via the relay
-2374/// node. The QUIC layer however needs to address a node by a stable [`SocketAddr`] so
-2375/// that normal socket APIs can function. Thus when a new node is introduced to a [`MagicSock`]
-2376/// it is given a new fake address. This is the type of that address.
-2377///
-2378/// It is but a newtype. And in our QUIC-facing socket APIs like [`AsyncUdpSocket`] it
-2379/// comes in as the inner [`Ipv6Addr`], in those interfaces we have to be careful to do
-2380/// the conversion to this type.
-2381#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
-2382pub(crate) struct NodeIdMappedAddr(Ipv6Addr);
+2373/// It is but a newtype. And in our QUIC-facing socket APIs like [`AsyncUdpSocket`] it
+2374/// comes in as the inner [`Ipv6Addr`], in those interfaces we have to be careful to do
+2375/// the conversion to this type.
+2376#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
+2377pub(crate) struct NodeIdMappedAddr(Ipv6Addr);
+2378
+2379/// Can occur when converting a [`SocketAddr`] to an [`NodeIdMappedAddr`]
+2380#[derive(Debug, Snafu)]
+2381#[snafu(display("Failed to convert"))]
+2382pub struct NodeIdMappedAddrError;
2383
-2384/// Can occur when converting a [`SocketAddr`] to an [`NodeIdMappedAddr`]
-2385#[derive(Debug, Snafu)]
-2386#[snafu(display("Failed to convert"))]
-2387pub struct NodeIdMappedAddrError;
-2388
-2389/// Counter to always generate unique addresses for [`NodeIdMappedAddr`].
-2390static NODE_ID_ADDR_COUNTER: AtomicU64 = AtomicU64::new(1);
-2391
-2392impl NodeIdMappedAddr {
-2393 /// The Prefix/L of our Unique Local Addresses.
-2394 const ADDR_PREFIXL: u8 = 0xfd;
-2395 /// The Global ID used in our Unique Local Addresses.
-2396 const ADDR_GLOBAL_ID: [u8; 5] = [21, 7, 10, 81, 11];
-2397 /// The Subnet ID used in our Unique Local Addresses.
-2398 const ADDR_SUBNET: [u8; 2] = [0; 2];
-2399
-2400 /// The dummy port used for all [`NodeIdMappedAddr`]s.
-2401 const NODE_ID_MAPPED_PORT: u16 = 12345;
-2402
-2403 /// Generates a globally unique fake UDP address.
-2404 ///
-2405 /// This generates and IPv6 Unique Local Address according to RFC 4193.
-2406 pub(crate) fn generate() -> Self {
-2407 let mut addr = [0u8; 16];
-2408 addr[0] = Self::ADDR_PREFIXL;
-2409 addr[1..6].copy_from_slice(&Self::ADDR_GLOBAL_ID);
-2410 addr[6..8].copy_from_slice(&Self::ADDR_SUBNET);
-2411
-2412 let counter = NODE_ID_ADDR_COUNTER.fetch_add(1, Ordering::Relaxed);
-2413 addr[8..16].copy_from_slice(&counter.to_be_bytes());
-2414
-2415 Self(Ipv6Addr::from(addr))
-2416 }
-2417
-2418 /// Returns a consistent [`SocketAddr`] for the [`NodeIdMappedAddr`].
-2419 ///
-2420 /// This socket address does not have a routable IP address.
-2421 ///
-2422 /// This uses a made-up port number, since the port does not play a role in looking up
-2423 /// the node in the [`NodeMap`]. This socket address is only to be used to pass into
-2424 /// Quinn.
-2425 pub(crate) fn private_socket_addr(&self) -> SocketAddr {
-2426 SocketAddr::new(IpAddr::from(self.0), Self::NODE_ID_MAPPED_PORT)
-2427 }
-2428}
-2429
-2430impl TryFrom<Ipv6Addr> for NodeIdMappedAddr {
-2431 type Error = NodeIdMappedAddrError;
-2432
-2433 fn try_from(value: Ipv6Addr) -> Result<Self, Self::Error> {
-2434 let octets = value.octets();
-2435 if octets[0] == Self::ADDR_PREFIXL
-2436 && octets[1..6] == Self::ADDR_GLOBAL_ID
-2437 && octets[6..8] == Self::ADDR_SUBNET
-2438 {
-2439 return Ok(Self(value));
-2440 }
-2441 Err(NodeIdMappedAddrError)
-2442 }
-2443}
-2444
-2445impl std::fmt::Display for NodeIdMappedAddr {
-2446 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
-2447 write!(f, "NodeIdMappedAddr({})", self.0)
-2448 }
-2449}
-2450
-2451fn disco_message_sent(msg: &disco::Message, metrics: &MagicsockMetrics) {
-2452 match msg {
-2453 disco::Message::Ping(_) => {
-2454 metrics.sent_disco_ping.inc();
-2455 }
-2456 disco::Message::Pong(_) => {
-2457 metrics.sent_disco_pong.inc();
-2458 }
-2459 disco::Message::CallMeMaybe(_) => {
-2460 metrics.sent_disco_call_me_maybe.inc();
-2461 }
-2462 }
-2463}
-2464
-2465/// A *direct address* on which an iroh-node might be contactable.
-2466///
-2467/// Direct addresses are UDP socket addresses on which an iroh node could potentially be
-2468/// contacted. These can come from various sources depending on the network topology of the
-2469/// iroh node, see [`DirectAddrType`] for the several kinds of sources.
-2470#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
-2471pub struct DirectAddr {
-2472 /// The address.
-2473 pub addr: SocketAddr,
-2474 /// The origin of this direct address.
-2475 pub typ: DirectAddrType,
-2476}
-2477
-2478/// The type of direct address.
-2479///
-2480/// These are the various sources or origins from which an iroh node might have found a
-2481/// possible [`DirectAddr`].
-2482#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
-2483pub enum DirectAddrType {
-2484 /// Not yet determined..
-2485 Unknown,
-2486 /// A locally bound socket address.
-2487 Local,
-2488 /// Public internet address discovered via QAD.
-2489 ///
-2490 /// When possible an iroh node will perform QAD to discover which is the address
-2491 /// from which it sends data on the public internet. This can be different from locally
-2492 /// bound addresses when the node is on a local network which performs NAT or similar.
-2493 Qad,
-2494 /// An address assigned by the router using port mapping.
+2384/// Counter to always generate unique addresses for [`NodeIdMappedAddr`].
+2385static NODE_ID_ADDR_COUNTER: AtomicU64 = AtomicU64::new(1);
+2386
+2387impl NodeIdMappedAddr {
+2388 /// The Prefix/L of our Unique Local Addresses.
+2389 const ADDR_PREFIXL: u8 = 0xfd;
+2390 /// The Global ID used in our Unique Local Addresses.
+2391 const ADDR_GLOBAL_ID: [u8; 5] = [21, 7, 10, 81, 11];
+2392 /// The Subnet ID used in our Unique Local Addresses.
+2393 const ADDR_SUBNET: [u8; 2] = [0; 2];
+2394
+2395 /// The dummy port used for all [`NodeIdMappedAddr`]s.
+2396 const NODE_ID_MAPPED_PORT: u16 = 12345;
+2397
+2398 /// Generates a globally unique fake UDP address.
+2399 ///
+2400 /// This generates and IPv6 Unique Local Address according to RFC 4193.
+2401 pub(crate) fn generate() -> Self {
+2402 let mut addr = [0u8; 16];
+2403 addr[0] = Self::ADDR_PREFIXL;
+2404 addr[1..6].copy_from_slice(&Self::ADDR_GLOBAL_ID);
+2405 addr[6..8].copy_from_slice(&Self::ADDR_SUBNET);
+2406
+2407 let counter = NODE_ID_ADDR_COUNTER.fetch_add(1, Ordering::Relaxed);
+2408 addr[8..16].copy_from_slice(&counter.to_be_bytes());
+2409
+2410 Self(Ipv6Addr::from(addr))
+2411 }
+2412
+2413 /// Returns a consistent [`SocketAddr`] for the [`NodeIdMappedAddr`].
+2414 ///
+2415 /// This socket address does not have a routable IP address.
+2416 ///
+2417 /// This uses a made-up port number, since the port does not play a role in looking up
+2418 /// the node in the [`NodeMap`]. This socket address is only to be used to pass into
+2419 /// Quinn.
+2420 pub(crate) fn private_socket_addr(&self) -> SocketAddr {
+2421 SocketAddr::new(IpAddr::from(self.0), Self::NODE_ID_MAPPED_PORT)
+2422 }
+2423}
+2424
+2425impl TryFrom<Ipv6Addr> for NodeIdMappedAddr {
+2426 type Error = NodeIdMappedAddrError;
+2427
+2428 fn try_from(value: Ipv6Addr) -> Result<Self, Self::Error> {
+2429 let octets = value.octets();
+2430 if octets[0] == Self::ADDR_PREFIXL
+2431 && octets[1..6] == Self::ADDR_GLOBAL_ID
+2432 && octets[6..8] == Self::ADDR_SUBNET
+2433 {
+2434 return Ok(Self(value));
+2435 }
+2436 Err(NodeIdMappedAddrError)
+2437 }
+2438}
+2439
+2440impl std::fmt::Display for NodeIdMappedAddr {
+2441 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
+2442 write!(f, "NodeIdMappedAddr({})", self.0)
+2443 }
+2444}
+2445
+2446fn disco_message_sent(msg: &disco::Message, metrics: &MagicsockMetrics) {
+2447 match msg {
+2448 disco::Message::Ping(_) => {
+2449 metrics.sent_disco_ping.inc();
+2450 }
+2451 disco::Message::Pong(_) => {
+2452 metrics.sent_disco_pong.inc();
+2453 }
+2454 disco::Message::CallMeMaybe(_) => {
+2455 metrics.sent_disco_call_me_maybe.inc();
+2456 }
+2457 }
+2458}
+2459
+2460/// A *direct address* on which an iroh-node might be contactable.
+2461///
+2462/// Direct addresses are UDP socket addresses on which an iroh node could potentially be
+2463/// contacted. These can come from various sources depending on the network topology of the
+2464/// iroh node, see [`DirectAddrType`] for the several kinds of sources.
+2465#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
+2466pub struct DirectAddr {
+2467 /// The address.
+2468 pub addr: SocketAddr,
+2469 /// The origin of this direct address.
+2470 pub typ: DirectAddrType,
+2471}
+2472
+2473/// The type of direct address.
+2474///
+2475/// These are the various sources or origins from which an iroh node might have found a
+2476/// possible [`DirectAddr`].
+2477#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
+2478pub enum DirectAddrType {
+2479 /// Not yet determined..
+2480 Unknown,
+2481 /// A locally bound socket address.
+2482 Local,
+2483 /// Public internet address discovered via QAD.
+2484 ///
+2485 /// When possible an iroh node will perform QAD to discover which is the address
+2486 /// from which it sends data on the public internet. This can be different from locally
+2487 /// bound addresses when the node is on a local network which performs NAT or similar.
+2488 Qad,
+2489 /// An address assigned by the router using port mapping.
+2490 ///
+2491 /// When possible an iroh node will request a port mapping from the local router to
+2492 /// get a publicly routable direct address.
+2493 Portmapped,
+2494 /// Hard NAT: QAD'ed IPv4 address + local fixed port.
2495 ///
-2496 /// When possible an iroh node will request a port mapping from the local router to
-2497 /// get a publicly routable direct address.
-2498 Portmapped,
-2499 /// Hard NAT: QAD'ed IPv4 address + local fixed port.
-2500 ///
-2501 /// It is possible to configure iroh to bound to a specific port and independently
-2502 /// configure the router to forward this port to the iroh node. This indicates a
-2503 /// situation like this, which still uses QAD to discover the public address.
-2504 Qad4LocalPort,
-2505}
-2506
-2507impl Display for DirectAddrType {
-2508 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
-2509 match self {
-2510 DirectAddrType::Unknown => write!(f, "?"),
-2511 DirectAddrType::Local => write!(f, "local"),
-2512 DirectAddrType::Qad => write!(f, "qad"),
-2513 DirectAddrType::Portmapped => write!(f, "portmap"),
-2514 DirectAddrType::Qad4LocalPort => write!(f, "qad4localport"),
-2515 }
-2516 }
-2517}
-2518
-2519#[cfg(test)]
-2520mod tests {
-2521 use std::{collections::BTreeSet, sync::Arc, time::Duration};
-2522
-2523 use data_encoding::HEXLOWER;
-2524 use iroh_base::{NodeAddr, NodeId, PublicKey};
-2525 use n0_future::{time, StreamExt};
-2526 use n0_snafu::{Result, ResultExt};
-2527 use n0_watcher::Watcher;
-2528 use quinn::ServerConfig;
-2529 use rand::{Rng, RngCore};
-2530 use tokio::task::JoinSet;
-2531 use tokio_util::task::AbortOnDropHandle;
-2532 use tracing::{error, info, info_span, instrument, Instrument};
-2533 use tracing_test::traced_test;
-2534
-2535 use super::{NodeIdMappedAddr, Options};
-2536 use crate::{
-2537 dns::DnsResolver,
-2538 endpoint::{DirectAddr, PathSelection, Source},
-2539 magicsock::{node_map, Handle, MagicSock},
-2540 tls, Endpoint, RelayMap, RelayMode, SecretKey,
-2541 };
-2542
-2543 const ALPN: &[u8] = b"n0/test/1";
-2544
-2545 impl Default for Options {
-2546 fn default() -> Self {
-2547 let secret_key = SecretKey::generate(rand::rngs::OsRng);
-2548 let server_config = make_default_server_config(&secret_key);
-2549 Options {
-2550 addr_v4: None,
-2551 addr_v6: None,
-2552 secret_key,
-2553 relay_map: RelayMap::empty(),
-2554 relay_protocol: iroh_relay::http::Protocol::default(),
-2555 node_map: None,
-2556 discovery: None,
-2557 proxy_url: None,
-2558 dns_resolver: DnsResolver::new(),
-2559 server_config,
-2560 #[cfg(any(test, feature = "test-utils"))]
-2561 insecure_skip_relay_cert_verify: false,
-2562 #[cfg(any(test, feature = "test-utils"))]
-2563 path_selection: PathSelection::default(),
-2564 discovery_user_data: None,
-2565 metrics: Default::default(),
-2566 }
-2567 }
-2568 }
-2569
-2570 /// Generate a server config with no ALPNS and a default transport configuration
-2571 fn make_default_server_config(secret_key: &SecretKey) -> ServerConfig {
-2572 let quic_server_config =
-2573 crate::tls::TlsConfig::new(secret_key.clone()).make_server_config(vec![], false);
-2574 let mut server_config = ServerConfig::with_crypto(Arc::new(quic_server_config));
-2575 server_config.transport_config(Arc::new(quinn::TransportConfig::default()));
-2576 server_config
-2577 }
-2578
-2579 impl MagicSock {
-2580 #[track_caller]
-2581 pub fn add_test_addr(&self, node_addr: NodeAddr) {
-2582 self.add_node_addr(
-2583 node_addr,
-2584 Source::NamedApp {
-2585 name: "test".into(),
-2586 },
-2587 )
-2588 .unwrap()
-2589 }
-2590 }
-2591
-2592 /// Magicsock plus wrappers for sending packets
-2593 #[derive(Clone)]
-2594 struct MagicStack {
-2595 secret_key: SecretKey,
-2596 endpoint: Endpoint,
-2597 }
-2598
-2599 impl MagicStack {
-2600 async fn new(relay_mode: RelayMode) -> Self {
-2601 let secret_key = SecretKey::generate(rand::thread_rng());
-2602
-2603 let mut transport_config = quinn::TransportConfig::default();
-2604 transport_config.max_idle_timeout(Some(Duration::from_secs(10).try_into().unwrap()));
-2605
-2606 let endpoint = Endpoint::builder()
-2607 .secret_key(secret_key.clone())
-2608 .transport_config(transport_config)
-2609 .relay_mode(relay_mode)
-2610 .alpns(vec![ALPN.to_vec()])
-2611 .bind()
-2612 .await
-2613 .unwrap();
-2614
-2615 Self {
-2616 secret_key,
-2617 endpoint,
-2618 }
-2619 }
-2620
-2621 fn tracked_endpoints(&self) -> Vec<PublicKey> {
-2622 self.endpoint
-2623 .magic_sock()
-2624 .list_remote_infos()
-2625 .into_iter()
-2626 .map(|ep| ep.node_id)
-2627 .collect()
-2628 }
+2496 /// It is possible to configure iroh to bound to a specific port and independently
+2497 /// configure the router to forward this port to the iroh node. This indicates a
+2498 /// situation like this, which still uses QAD to discover the public address.
+2499 Qad4LocalPort,
+2500}
+2501
+2502impl Display for DirectAddrType {
+2503 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+2504 match self {
+2505 DirectAddrType::Unknown => write!(f, "?"),
+2506 DirectAddrType::Local => write!(f, "local"),
+2507 DirectAddrType::Qad => write!(f, "qad"),
+2508 DirectAddrType::Portmapped => write!(f, "portmap"),
+2509 DirectAddrType::Qad4LocalPort => write!(f, "qad4localport"),
+2510 }
+2511 }
+2512}
+2513
+2514#[cfg(test)]
+2515mod tests {
+2516 use std::{collections::BTreeSet, sync::Arc, time::Duration};
+2517
+2518 use data_encoding::HEXLOWER;
+2519 use iroh_base::{NodeAddr, NodeId, PublicKey};
+2520 use n0_future::{time, StreamExt};
+2521 use n0_snafu::{Result, ResultExt};
+2522 use n0_watcher::Watcher;
+2523 use quinn::ServerConfig;
+2524 use rand::{Rng, RngCore};
+2525 use tokio::task::JoinSet;
+2526 use tokio_util::task::AbortOnDropHandle;
+2527 use tracing::{error, info, info_span, instrument, Instrument};
+2528 use tracing_test::traced_test;
+2529
+2530 use super::{NodeIdMappedAddr, Options};
+2531 use crate::{
+2532 dns::DnsResolver,
+2533 endpoint::{DirectAddr, PathSelection, Source},
+2534 magicsock::{node_map, Handle, MagicSock},
+2535 tls, Endpoint, RelayMap, RelayMode, SecretKey,
+2536 };
+2537
+2538 const ALPN: &[u8] = b"n0/test/1";
+2539
+2540 impl Default for Options {
+2541 fn default() -> Self {
+2542 let secret_key = SecretKey::generate(rand::rngs::OsRng);
+2543 let server_config = make_default_server_config(&secret_key);
+2544 Options {
+2545 addr_v4: None,
+2546 addr_v6: None,
+2547 secret_key,
+2548 relay_map: RelayMap::empty(),
+2549 relay_protocol: iroh_relay::http::Protocol::default(),
+2550 node_map: None,
+2551 discovery: None,
+2552 proxy_url: None,
+2553 dns_resolver: DnsResolver::new(),
+2554 server_config,
+2555 #[cfg(any(test, feature = "test-utils"))]
+2556 insecure_skip_relay_cert_verify: false,
+2557 #[cfg(any(test, feature = "test-utils"))]
+2558 path_selection: PathSelection::default(),
+2559 discovery_user_data: None,
+2560 metrics: Default::default(),
+2561 }
+2562 }
+2563 }
+2564
+2565 /// Generate a server config with no ALPNS and a default transport configuration
+2566 fn make_default_server_config(secret_key: &SecretKey) -> ServerConfig {
+2567 let quic_server_config =
+2568 crate::tls::TlsConfig::new(secret_key.clone()).make_server_config(vec![], false);
+2569 let mut server_config = ServerConfig::with_crypto(Arc::new(quic_server_config));
+2570 server_config.transport_config(Arc::new(quinn::TransportConfig::default()));
+2571 server_config
+2572 }
+2573
+2574 impl MagicSock {
+2575 #[track_caller]
+2576 pub fn add_test_addr(&self, node_addr: NodeAddr) {
+2577 self.add_node_addr(
+2578 node_addr,
+2579 Source::NamedApp {
+2580 name: "test".into(),
+2581 },
+2582 )
+2583 .unwrap()
+2584 }
+2585 }
+2586
+2587 /// Magicsock plus wrappers for sending packets
+2588 #[derive(Clone)]
+2589 struct MagicStack {
+2590 secret_key: SecretKey,
+2591 endpoint: Endpoint,
+2592 }
+2593
+2594 impl MagicStack {
+2595 async fn new(relay_mode: RelayMode) -> Self {
+2596 let secret_key = SecretKey::generate(rand::thread_rng());
+2597
+2598 let mut transport_config = quinn::TransportConfig::default();
+2599 transport_config.max_idle_timeout(Some(Duration::from_secs(10).try_into().unwrap()));
+2600
+2601 let endpoint = Endpoint::builder()
+2602 .secret_key(secret_key.clone())
+2603 .transport_config(transport_config)
+2604 .relay_mode(relay_mode)
+2605 .alpns(vec![ALPN.to_vec()])
+2606 .bind()
+2607 .await
+2608 .unwrap();
+2609
+2610 Self {
+2611 secret_key,
+2612 endpoint,
+2613 }
+2614 }
+2615
+2616 fn tracked_endpoints(&self) -> Vec<PublicKey> {
+2617 self.endpoint
+2618 .magic_sock()
+2619 .list_remote_infos()
+2620 .into_iter()
+2621 .map(|ep| ep.node_id)
+2622 .collect()
+2623 }
+2624
+2625 fn public(&self) -> PublicKey {
+2626 self.secret_key.public()
+2627 }
+2628 }
2629
-2630 fn public(&self) -> PublicKey {
-2631 self.secret_key.public()
-2632 }
-2633 }
-2634
-2635 /// Monitors endpoint changes and plumbs things together.
+2630 /// Monitors endpoint changes and plumbs things together.
+2631 ///
+2632 /// This is a way of connecting endpoints without a relay server. Whenever the local
+2633 /// endpoints of a magic endpoint change this address is added to the other magic
+2634 /// sockets. This function will await until the endpoints are connected the first time
+2635 /// before returning.
2636 ///
-2637 /// This is a way of connecting endpoints without a relay server. Whenever the local
-2638 /// endpoints of a magic endpoint change this address is added to the other magic
-2639 /// sockets. This function will await until the endpoints are connected the first time
-2640 /// before returning.
-2641 ///
-2642 /// When the returned drop guard is dropped, the tasks doing this updating are stopped.
-2643 #[instrument(skip_all)]
-2644 async fn mesh_stacks(stacks: Vec<MagicStack>) -> Result<JoinSet<()>> {
-2645 /// Registers endpoint addresses of a node to all other nodes.
-2646 fn update_direct_addrs(
-2647 stacks: &[MagicStack],
-2648 my_idx: usize,
-2649 new_addrs: BTreeSet<DirectAddr>,
-2650 ) {
-2651 let me = &stacks[my_idx];
-2652 for (i, m) in stacks.iter().enumerate() {
-2653 if i == my_idx {
-2654 continue;
-2655 }
-2656
-2657 let addr = NodeAddr {
-2658 node_id: me.public(),
-2659 relay_url: None,
-2660 direct_addresses: new_addrs.iter().map(|ep| ep.addr).collect(),
-2661 };
-2662 m.endpoint.magic_sock().add_test_addr(addr);
-2663 }
-2664 }
-2665
-2666 // For each node, start a task which monitors its local endpoints and registers them
-2667 // with the other nodes as local endpoints become known.
-2668 let mut tasks = JoinSet::new();
-2669 for (my_idx, m) in stacks.iter().enumerate() {
-2670 let m = m.clone();
-2671 let stacks = stacks.clone();
-2672 tasks.spawn(async move {
-2673 let me = m.endpoint.node_id().fmt_short();
-2674 let mut stream = m.endpoint.direct_addresses().stream().filter_map(|i| i);
-2675 while let Some(new_eps) = stream.next().await {
-2676 info!(%me, "conn{} endpoints update: {:?}", my_idx + 1, new_eps);
-2677 update_direct_addrs(&stacks, my_idx, new_eps);
-2678 }
-2679 });
-2680 }
-2681
-2682 // Wait for all nodes to be registered with each other.
-2683 time::timeout(Duration::from_secs(10), async move {
-2684 let all_node_ids: Vec<_> = stacks.iter().map(|ms| ms.endpoint.node_id()).collect();
-2685 loop {
-2686 let mut ready = Vec::with_capacity(stacks.len());
-2687 for ms in stacks.iter() {
-2688 let endpoints = ms.tracked_endpoints();
-2689 let my_node_id = ms.endpoint.node_id();
-2690 let all_nodes_meshed = all_node_ids
-2691 .iter()
-2692 .filter(|node_id| **node_id != my_node_id)
-2693 .all(|node_id| endpoints.contains(node_id));
-2694 ready.push(all_nodes_meshed);
-2695 }
-2696 if ready.iter().all(|meshed| *meshed) {
-2697 break;
-2698 }
-2699 time::sleep(Duration::from_millis(200)).await;
-2700 }
-2701 })
-2702 .await
-2703 .context("timeout")?;
-2704 info!("all nodes meshed");
-2705 Ok(tasks)
-2706 }
+2637 /// When the returned drop guard is dropped, the tasks doing this updating are stopped.
+2638 #[instrument(skip_all)]
+2639 async fn mesh_stacks(stacks: Vec<MagicStack>) -> Result<JoinSet<()>> {
+2640 /// Registers endpoint addresses of a node to all other nodes.
+2641 fn update_direct_addrs(
+2642 stacks: &[MagicStack],
+2643 my_idx: usize,
+2644 new_addrs: BTreeSet<DirectAddr>,
+2645 ) {
+2646 let me = &stacks[my_idx];
+2647 for (i, m) in stacks.iter().enumerate() {
+2648 if i == my_idx {
+2649 continue;
+2650 }
+2651
+2652 let addr = NodeAddr {
+2653 node_id: me.public(),
+2654 relay_url: None,
+2655 direct_addresses: new_addrs.iter().map(|ep| ep.addr).collect(),
+2656 };
+2657 m.endpoint.magic_sock().add_test_addr(addr);
+2658 }
+2659 }
+2660
+2661 // For each node, start a task which monitors its local endpoints and registers them
+2662 // with the other nodes as local endpoints become known.
+2663 let mut tasks = JoinSet::new();
+2664 for (my_idx, m) in stacks.iter().enumerate() {
+2665 let m = m.clone();
+2666 let stacks = stacks.clone();
+2667 tasks.spawn(async move {
+2668 let me = m.endpoint.node_id().fmt_short();
+2669 let mut stream = m.endpoint.direct_addresses().stream().filter_map(|i| i);
+2670 while let Some(new_eps) = stream.next().await {
+2671 info!(%me, "conn{} endpoints update: {:?}", my_idx + 1, new_eps);
+2672 update_direct_addrs(&stacks, my_idx, new_eps);
+2673 }
+2674 });
+2675 }
+2676
+2677 // Wait for all nodes to be registered with each other.
+2678 time::timeout(Duration::from_secs(10), async move {
+2679 let all_node_ids: Vec<_> = stacks.iter().map(|ms| ms.endpoint.node_id()).collect();
+2680 loop {
+2681 let mut ready = Vec::with_capacity(stacks.len());
+2682 for ms in stacks.iter() {
+2683 let endpoints = ms.tracked_endpoints();
+2684 let my_node_id = ms.endpoint.node_id();
+2685 let all_nodes_meshed = all_node_ids
+2686 .iter()
+2687 .filter(|node_id| **node_id != my_node_id)
+2688 .all(|node_id| endpoints.contains(node_id));
+2689 ready.push(all_nodes_meshed);
+2690 }
+2691 if ready.iter().all(|meshed| *meshed) {
+2692 break;
+2693 }
+2694 time::sleep(Duration::from_millis(200)).await;
+2695 }
+2696 })
+2697 .await
+2698 .context("timeout")?;
+2699 info!("all nodes meshed");
+2700 Ok(tasks)
+2701 }
+2702
+2703 #[instrument(skip_all, fields(me = %ep.endpoint.node_id().fmt_short()))]
+2704 async fn echo_receiver(ep: MagicStack, loss: ExpectedLoss) -> Result {
+2705 info!("accepting conn");
+2706 let conn = ep.endpoint.accept().await.expect("no conn");
2707
-2708 #[instrument(skip_all, fields(me = %ep.endpoint.node_id().fmt_short()))]
-2709 async fn echo_receiver(ep: MagicStack, loss: ExpectedLoss) -> Result {
-2710 info!("accepting conn");
-2711 let conn = ep.endpoint.accept().await.expect("no conn");
+2708 info!("connecting");
+2709 let conn = conn.await.context("connecting")?;
+2710 info!("accepting bi");
+2711 let (mut send_bi, mut recv_bi) = conn.accept_bi().await.context("accept bi")?;
2712
-2713 info!("connecting");
-2714 let conn = conn.await.context("connecting")?;
-2715 info!("accepting bi");
-2716 let (mut send_bi, mut recv_bi) = conn.accept_bi().await.context("accept bi")?;
-2717
-2718 info!("reading");
-2719 let val = recv_bi
-2720 .read_to_end(usize::MAX)
-2721 .await
-2722 .context("read to end")?;
+2713 info!("reading");
+2714 let val = recv_bi
+2715 .read_to_end(usize::MAX)
+2716 .await
+2717 .context("read to end")?;
+2718
+2719 info!("replying");
+2720 for chunk in val.chunks(12) {
+2721 send_bi.write_all(chunk).await.context("write all")?;
+2722 }
2723
-2724 info!("replying");
-2725 for chunk in val.chunks(12) {
-2726 send_bi.write_all(chunk).await.context("write all")?;
-2727 }
-2728
-2729 info!("finishing");
-2730 send_bi.finish().context("finish")?;
-2731 send_bi.stopped().await.context("stopped")?;
-2732
-2733 let stats = conn.stats();
-2734 info!("stats: {:#?}", stats);
-2735 // TODO: ensure panics in this function are reported ok
-2736 if matches!(loss, ExpectedLoss::AlmostNone) {
-2737 for (id, path) in &stats.paths {
-2738 assert!(
-2739 path.lost_packets < 10,
-2740 "[receiver] path {id:?} should not loose many packets",
-2741 );
-2742 }
-2743 }
+2724 info!("finishing");
+2725 send_bi.finish().context("finish")?;
+2726 send_bi.stopped().await.context("stopped")?;
+2727
+2728 let stats = conn.stats();
+2729 info!("stats: {:#?}", stats);
+2730 // TODO: ensure panics in this function are reported ok
+2731 if matches!(loss, ExpectedLoss::AlmostNone) {
+2732 for (id, path) in &stats.paths {
+2733 assert!(
+2734 path.lost_packets < 10,
+2735 "[receiver] path {id:?} should not loose many packets",
+2736 );
+2737 }
+2738 }
+2739
+2740 info!("close");
+2741 conn.close(0u32.into(), b"done");
+2742 info!("wait idle");
+2743 ep.endpoint.endpoint().wait_idle().await;
2744
-2745 info!("close");
-2746 conn.close(0u32.into(), b"done");
-2747 info!("wait idle");
-2748 ep.endpoint.endpoint().wait_idle().await;
-2749
-2750 Ok(())
-2751 }
-2752
-2753 #[instrument(skip_all, fields(me = %ep.endpoint.node_id().fmt_short()))]
-2754 async fn echo_sender(
-2755 ep: MagicStack,
-2756 dest_id: PublicKey,
-2757 msg: &[u8],
-2758 loss: ExpectedLoss,
-2759 ) -> Result {
-2760 info!("connecting to {}", dest_id.fmt_short());
-2761 let dest = NodeAddr::new(dest_id);
-2762 let conn = ep.endpoint.connect(dest, ALPN).await?;
-2763
-2764 info!("opening bi");
-2765 let (mut send_bi, mut recv_bi) = conn.open_bi().await.context("open bi")?;
-2766
-2767 info!("writing message");
-2768 send_bi.write_all(msg).await.context("write all")?;
-2769
-2770 info!("finishing");
-2771 send_bi.finish().context("finish")?;
-2772 send_bi.stopped().await.context("stopped")?;
-2773
-2774 info!("reading_to_end");
-2775 let val = recv_bi
-2776 .read_to_end(usize::MAX)
-2777 .await
-2778 .context("read to end")?;
-2779 assert_eq!(
-2780 val,
-2781 msg,
-2782 "[sender] expected {}, got {}",
-2783 HEXLOWER.encode(msg),
-2784 HEXLOWER.encode(&val)
-2785 );
-2786
-2787 let stats = conn.stats();
-2788 info!("stats: {:#?}", stats);
-2789 if matches!(loss, ExpectedLoss::AlmostNone) {
-2790 for (id, path) in &stats.paths {
-2791 assert!(
-2792 path.lost_packets < 10,
-2793 "[sender] path {id:?} should not loose many packets",
-2794 );
-2795 }
-2796 }
-2797
-2798 info!("close");
-2799 conn.close(0u32.into(), b"done");
-2800 info!("wait idle");
-2801 ep.endpoint.endpoint().wait_idle().await;
-2802 Ok(())
-2803 }
-2804
-2805 #[derive(Debug, Copy, Clone)]
-2806 enum ExpectedLoss {
-2807 AlmostNone,
-2808 YeahSure,
-2809 }
-2810
-2811 /// Runs a roundtrip between the [`echo_sender`] and [`echo_receiver`].
-2812 async fn run_roundtrip(
-2813 sender: MagicStack,
-2814 receiver: MagicStack,
-2815 payload: &[u8],
-2816 loss: ExpectedLoss,
-2817 ) {
-2818 let send_node_id = sender.endpoint.node_id();
-2819 let recv_node_id = receiver.endpoint.node_id();
-2820 info!("\nroundtrip: {send_node_id:#} -> {recv_node_id:#}");
-2821
-2822 let receiver_task = tokio::spawn(echo_receiver(receiver, loss));
-2823 let sender_res = echo_sender(sender, recv_node_id, payload, loss).await;
-2824 let sender_is_err = match sender_res {
-2825 Ok(()) => false,
-2826 Err(err) => {
-2827 eprintln!("[sender] Error:\n{err:#?}");
-2828 true
-2829 }
-2830 };
-2831 let receiver_is_err = match receiver_task.await {
-2832 Ok(Ok(())) => false,
-2833 Ok(Err(err)) => {
-2834 eprintln!("[receiver] Error:\n{err:#?}");
-2835 true
-2836 }
-2837 Err(joinerr) => {
-2838 if joinerr.is_panic() {
-2839 std::panic::resume_unwind(joinerr.into_panic());
-2840 } else {
-2841 eprintln!("[receiver] Error:\n{joinerr:#?}");
-2842 }
-2843 true
-2844 }
-2845 };
-2846 if sender_is_err || receiver_is_err {
-2847 panic!("Sender or receiver errored");
-2848 }
-2849 }
-2850
-2851 #[tokio::test(flavor = "multi_thread")]
-2852 #[traced_test]
-2853 async fn test_two_devices_roundtrip_quinn_magic() -> Result {
-2854 let m1 = MagicStack::new(RelayMode::Disabled).await;
-2855 let m2 = MagicStack::new(RelayMode::Disabled).await;
-2856
-2857 let _guard = mesh_stacks(vec![m1.clone(), m2.clone()]).await?;
-2858
-2859 for i in 0..5 {
-2860 info!("\n-- round {i}");
-2861 run_roundtrip(
-2862 m1.clone(),
-2863 m2.clone(),
-2864 b"hello m1",
-2865 ExpectedLoss::AlmostNone,
-2866 )
-2867 .await;
-2868 run_roundtrip(
-2869 m2.clone(),
-2870 m1.clone(),
-2871 b"hello m2",
-2872 ExpectedLoss::AlmostNone,
-2873 )
-2874 .await;
-2875
-2876 info!("\n-- larger data");
-2877 let mut data = vec![0u8; 10 * 1024];
-2878 rand::thread_rng().fill_bytes(&mut data);
-2879 run_roundtrip(m1.clone(), m2.clone(), &data, ExpectedLoss::AlmostNone).await;
-2880 run_roundtrip(m2.clone(), m1.clone(), &data, ExpectedLoss::AlmostNone).await;
-2881 }
-2882
-2883 Ok(())
-2884 }
-2885
-2886 #[tokio::test]
-2887 #[traced_test]
-2888 async fn test_regression_network_change_rebind_wakes_connection_driver() -> n0_snafu::Result {
-2889 let m1 = MagicStack::new(RelayMode::Disabled).await;
-2890 let m2 = MagicStack::new(RelayMode::Disabled).await;
-2891
-2892 println!("Net change");
-2893 m1.endpoint.magic_sock().force_network_change(true).await;
-2894 tokio::time::sleep(Duration::from_secs(1)).await; // wait for socket rebinding
-2895
-2896 let _guard = mesh_stacks(vec![m1.clone(), m2.clone()]).await?;
-2897
-2898 let _handle = AbortOnDropHandle::new(tokio::spawn({
-2899 let endpoint = m2.endpoint.clone();
-2900 async move {
-2901 while let Some(incoming) = endpoint.accept().await {
-2902 println!("Incoming first conn!");
-2903 let conn = incoming.await.e()?;
-2904 conn.closed().await;
-2905 }
-2906
-2907 Ok::<_, n0_snafu::Error>(())
-2908 }
-2909 }));
-2910
-2911 println!("first conn!");
-2912 let conn = m1
-2913 .endpoint
-2914 .connect(m2.endpoint.node_addr().initialized().await?, ALPN)
-2915 .await?;
-2916 println!("Closing first conn");
-2917 conn.close(0u32.into(), b"bye lolz");
-2918 conn.closed().await;
-2919 println!("Closed first conn");
-2920
-2921 Ok(())
-2922 }
-2923
-2924 #[tokio::test(flavor = "multi_thread")]
-2925 #[traced_test]
-2926 async fn test_two_devices_roundtrip_network_change() -> Result {
-2927 time::timeout(
-2928 Duration::from_secs(90),
-2929 test_two_devices_roundtrip_network_change_impl(),
-2930 )
-2931 .await
-2932 .context("timeout")?
-2933 }
-2934
-2935 /// Same structure as `test_two_devices_roundtrip_quinn_magic`, but interrupts regularly
-2936 /// with (simulated) network changes.
-2937 async fn test_two_devices_roundtrip_network_change_impl() -> Result {
-2938 let m1 = MagicStack::new(RelayMode::Disabled).await;
-2939 let m2 = MagicStack::new(RelayMode::Disabled).await;
-2940
-2941 let _guard = mesh_stacks(vec![m1.clone(), m2.clone()]).await?;
-2942
-2943 let offset = || {
-2944 let delay = rand::thread_rng().gen_range(10..=500);
-2945 Duration::from_millis(delay)
-2946 };
-2947 let rounds = 5;
-2948
-2949 // Regular network changes to m1 only.
-2950 let m1_network_change_guard = {
-2951 let m1 = m1.clone();
-2952 let task = tokio::spawn(async move {
-2953 loop {
-2954 println!("[m1] network change");
-2955 m1.endpoint.magic_sock().force_network_change(true).await;
-2956 time::sleep(offset()).await;
-2957 }
-2958 });
-2959 AbortOnDropHandle::new(task)
-2960 };
+2745 Ok(())
+2746 }
+2747
+2748 #[instrument(skip_all, fields(me = %ep.endpoint.node_id().fmt_short()))]
+2749 async fn echo_sender(
+2750 ep: MagicStack,
+2751 dest_id: PublicKey,
+2752 msg: &[u8],
+2753 loss: ExpectedLoss,
+2754 ) -> Result {
+2755 info!("connecting to {}", dest_id.fmt_short());
+2756 let dest = NodeAddr::new(dest_id);
+2757 let conn = ep.endpoint.connect(dest, ALPN).await?;
+2758
+2759 info!("opening bi");
+2760 let (mut send_bi, mut recv_bi) = conn.open_bi().await.context("open bi")?;
+2761
+2762 info!("writing message");
+2763 send_bi.write_all(msg).await.context("write all")?;
+2764
+2765 info!("finishing");
+2766 send_bi.finish().context("finish")?;
+2767 send_bi.stopped().await.context("stopped")?;
+2768
+2769 info!("reading_to_end");
+2770 let val = recv_bi
+2771 .read_to_end(usize::MAX)
+2772 .await
+2773 .context("read to end")?;
+2774 assert_eq!(
+2775 val,
+2776 msg,
+2777 "[sender] expected {}, got {}",
+2778 HEXLOWER.encode(msg),
+2779 HEXLOWER.encode(&val)
+2780 );
+2781
+2782 let stats = conn.stats();
+2783 info!("stats: {:#?}", stats);
+2784 if matches!(loss, ExpectedLoss::AlmostNone) {
+2785 for (id, path) in &stats.paths {
+2786 assert!(
+2787 path.lost_packets < 10,
+2788 "[sender] path {id:?} should not loose many packets",
+2789 );
+2790 }
+2791 }
+2792
+2793 info!("close");
+2794 conn.close(0u32.into(), b"done");
+2795 info!("wait idle");
+2796 ep.endpoint.endpoint().wait_idle().await;
+2797 Ok(())
+2798 }
+2799
+2800 #[derive(Debug, Copy, Clone)]
+2801 enum ExpectedLoss {
+2802 AlmostNone,
+2803 YeahSure,
+2804 }
+2805
+2806 /// Runs a roundtrip between the [`echo_sender`] and [`echo_receiver`].
+2807 async fn run_roundtrip(
+2808 sender: MagicStack,
+2809 receiver: MagicStack,
+2810 payload: &[u8],
+2811 loss: ExpectedLoss,
+2812 ) {
+2813 let send_node_id = sender.endpoint.node_id();
+2814 let recv_node_id = receiver.endpoint.node_id();
+2815 info!("\nroundtrip: {send_node_id:#} -> {recv_node_id:#}");
+2816
+2817 let receiver_task = tokio::spawn(echo_receiver(receiver, loss));
+2818 let sender_res = echo_sender(sender, recv_node_id, payload, loss).await;
+2819 let sender_is_err = match sender_res {
+2820 Ok(()) => false,
+2821 Err(err) => {
+2822 eprintln!("[sender] Error:\n{err:#?}");
+2823 true
+2824 }
+2825 };
+2826 let receiver_is_err = match receiver_task.await {
+2827 Ok(Ok(())) => false,
+2828 Ok(Err(err)) => {
+2829 eprintln!("[receiver] Error:\n{err:#?}");
+2830 true
+2831 }
+2832 Err(joinerr) => {
+2833 if joinerr.is_panic() {
+2834 std::panic::resume_unwind(joinerr.into_panic());
+2835 } else {
+2836 eprintln!("[receiver] Error:\n{joinerr:#?}");
+2837 }
+2838 true
+2839 }
+2840 };
+2841 if sender_is_err || receiver_is_err {
+2842 panic!("Sender or receiver errored");
+2843 }
+2844 }
+2845
+2846 #[tokio::test(flavor = "multi_thread")]
+2847 #[traced_test]
+2848 async fn test_two_devices_roundtrip_quinn_magic() -> Result {
+2849 let m1 = MagicStack::new(RelayMode::Disabled).await;
+2850 let m2 = MagicStack::new(RelayMode::Disabled).await;
+2851
+2852 let _guard = mesh_stacks(vec![m1.clone(), m2.clone()]).await?;
+2853
+2854 for i in 0..5 {
+2855 info!("\n-- round {i}");
+2856 run_roundtrip(
+2857 m1.clone(),
+2858 m2.clone(),
+2859 b"hello m1",
+2860 ExpectedLoss::AlmostNone,
+2861 )
+2862 .await;
+2863 run_roundtrip(
+2864 m2.clone(),
+2865 m1.clone(),
+2866 b"hello m2",
+2867 ExpectedLoss::AlmostNone,
+2868 )
+2869 .await;
+2870
+2871 info!("\n-- larger data");
+2872 let mut data = vec![0u8; 10 * 1024];
+2873 rand::thread_rng().fill_bytes(&mut data);
+2874 run_roundtrip(m1.clone(), m2.clone(), &data, ExpectedLoss::AlmostNone).await;
+2875 run_roundtrip(m2.clone(), m1.clone(), &data, ExpectedLoss::AlmostNone).await;
+2876 }
+2877
+2878 Ok(())
+2879 }
+2880
+2881 #[tokio::test]
+2882 #[traced_test]
+2883 async fn test_regression_network_change_rebind_wakes_connection_driver() -> n0_snafu::Result {
+2884 let m1 = MagicStack::new(RelayMode::Disabled).await;
+2885 let m2 = MagicStack::new(RelayMode::Disabled).await;
+2886
+2887 println!("Net change");
+2888 m1.endpoint.magic_sock().force_network_change(true).await;
+2889 tokio::time::sleep(Duration::from_secs(1)).await; // wait for socket rebinding
+2890
+2891 let _guard = mesh_stacks(vec![m1.clone(), m2.clone()]).await?;
+2892
+2893 let _handle = AbortOnDropHandle::new(tokio::spawn({
+2894 let endpoint = m2.endpoint.clone();
+2895 async move {
+2896 while let Some(incoming) = endpoint.accept().await {
+2897 println!("Incoming first conn!");
+2898 let conn = incoming.await.e()?;
+2899 conn.closed().await;
+2900 }
+2901
+2902 Ok::<_, n0_snafu::Error>(())
+2903 }
+2904 }));
+2905
+2906 println!("first conn!");
+2907 let conn = m1
+2908 .endpoint
+2909 .connect(m2.endpoint.node_addr().initialized().await?, ALPN)
+2910 .await?;
+2911 println!("Closing first conn");
+2912 conn.close(0u32.into(), b"bye lolz");
+2913 conn.closed().await;
+2914 println!("Closed first conn");
+2915
+2916 Ok(())
+2917 }
+2918
+2919 #[tokio::test(flavor = "multi_thread")]
+2920 #[traced_test]
+2921 async fn test_two_devices_roundtrip_network_change() -> Result {
+2922 time::timeout(
+2923 Duration::from_secs(90),
+2924 test_two_devices_roundtrip_network_change_impl(),
+2925 )
+2926 .await
+2927 .context("timeout")?
+2928 }
+2929
+2930 /// Same structure as `test_two_devices_roundtrip_quinn_magic`, but interrupts regularly
+2931 /// with (simulated) network changes.
+2932 async fn test_two_devices_roundtrip_network_change_impl() -> Result {
+2933 let m1 = MagicStack::new(RelayMode::Disabled).await;
+2934 let m2 = MagicStack::new(RelayMode::Disabled).await;
+2935
+2936 let _guard = mesh_stacks(vec![m1.clone(), m2.clone()]).await?;
+2937
+2938 let offset = || {
+2939 let delay = rand::thread_rng().gen_range(10..=500);
+2940 Duration::from_millis(delay)
+2941 };
+2942 let rounds = 5;
+2943
+2944 // Regular network changes to m1 only.
+2945 let m1_network_change_guard = {
+2946 let m1 = m1.clone();
+2947 let task = tokio::spawn(async move {
+2948 loop {
+2949 println!("[m1] network change");
+2950 m1.endpoint.magic_sock().force_network_change(true).await;
+2951 time::sleep(offset()).await;
+2952 }
+2953 });
+2954 AbortOnDropHandle::new(task)
+2955 };
+2956
+2957 for i in 0..rounds {
+2958 println!("-- [m1 changes] round {}", i + 1);
+2959 run_roundtrip(m1.clone(), m2.clone(), b"hello m1", ExpectedLoss::YeahSure).await;
+2960 run_roundtrip(m2.clone(), m1.clone(), b"hello m2", ExpectedLoss::YeahSure).await;
2961
-2962 for i in 0..rounds {
-2963 println!("-- [m1 changes] round {}", i + 1);
-2964 run_roundtrip(m1.clone(), m2.clone(), b"hello m1", ExpectedLoss::YeahSure).await;
-2965 run_roundtrip(m2.clone(), m1.clone(), b"hello m2", ExpectedLoss::YeahSure).await;
-2966
-2967 println!("-- [m1 changes] larger data");
-2968 let mut data = vec![0u8; 10 * 1024];
-2969 rand::thread_rng().fill_bytes(&mut data);
-2970 run_roundtrip(m1.clone(), m2.clone(), &data, ExpectedLoss::YeahSure).await;
-2971 run_roundtrip(m2.clone(), m1.clone(), &data, ExpectedLoss::YeahSure).await;
-2972 }
-2973
-2974 std::mem::drop(m1_network_change_guard);
-2975
-2976 // Regular network changes to m2 only.
-2977 let m2_network_change_guard = {
-2978 let m2 = m2.clone();
-2979 let task = tokio::spawn(async move {
-2980 loop {
-2981 println!("[m2] network change");
-2982 m2.endpoint.magic_sock().force_network_change(true).await;
-2983 time::sleep(offset()).await;
-2984 }
-2985 });
-2986 AbortOnDropHandle::new(task)
-2987 };
+2962 println!("-- [m1 changes] larger data");
+2963 let mut data = vec![0u8; 10 * 1024];
+2964 rand::thread_rng().fill_bytes(&mut data);
+2965 run_roundtrip(m1.clone(), m2.clone(), &data, ExpectedLoss::YeahSure).await;
+2966 run_roundtrip(m2.clone(), m1.clone(), &data, ExpectedLoss::YeahSure).await;
+2967 }
+2968
+2969 std::mem::drop(m1_network_change_guard);
+2970
+2971 // Regular network changes to m2 only.
+2972 let m2_network_change_guard = {
+2973 let m2 = m2.clone();
+2974 let task = tokio::spawn(async move {
+2975 loop {
+2976 println!("[m2] network change");
+2977 m2.endpoint.magic_sock().force_network_change(true).await;
+2978 time::sleep(offset()).await;
+2979 }
+2980 });
+2981 AbortOnDropHandle::new(task)
+2982 };
+2983
+2984 for i in 0..rounds {
+2985 println!("-- [m2 changes] round {}", i + 1);
+2986 run_roundtrip(m1.clone(), m2.clone(), b"hello m1", ExpectedLoss::YeahSure).await;
+2987 run_roundtrip(m2.clone(), m1.clone(), b"hello m2", ExpectedLoss::YeahSure).await;
2988
-2989 for i in 0..rounds {
-2990 println!("-- [m2 changes] round {}", i + 1);
-2991 run_roundtrip(m1.clone(), m2.clone(), b"hello m1", ExpectedLoss::YeahSure).await;
-2992 run_roundtrip(m2.clone(), m1.clone(), b"hello m2", ExpectedLoss::YeahSure).await;
-2993
-2994 println!("-- [m2 changes] larger data");
-2995 let mut data = vec![0u8; 10 * 1024];
-2996 rand::thread_rng().fill_bytes(&mut data);
-2997 run_roundtrip(m1.clone(), m2.clone(), &data, ExpectedLoss::YeahSure).await;
-2998 run_roundtrip(m2.clone(), m1.clone(), &data, ExpectedLoss::YeahSure).await;
-2999 }
-3000
-3001 std::mem::drop(m2_network_change_guard);
-3002
-3003 // Regular network changes to both m1 and m2 only.
-3004 let m1_m2_network_change_guard = {
-3005 let m1 = m1.clone();
-3006 let m2 = m2.clone();
-3007 let task = tokio::spawn(async move {
-3008 println!("-- [m1] network change");
-3009 m1.endpoint.magic_sock().force_network_change(true).await;
-3010 println!("-- [m2] network change");
-3011 m2.endpoint.magic_sock().force_network_change(true).await;
-3012 time::sleep(offset()).await;
-3013 });
-3014 AbortOnDropHandle::new(task)
-3015 };
+2989 println!("-- [m2 changes] larger data");
+2990 let mut data = vec![0u8; 10 * 1024];
+2991 rand::thread_rng().fill_bytes(&mut data);
+2992 run_roundtrip(m1.clone(), m2.clone(), &data, ExpectedLoss::YeahSure).await;
+2993 run_roundtrip(m2.clone(), m1.clone(), &data, ExpectedLoss::YeahSure).await;
+2994 }
+2995
+2996 std::mem::drop(m2_network_change_guard);
+2997
+2998 // Regular network changes to both m1 and m2 only.
+2999 let m1_m2_network_change_guard = {
+3000 let m1 = m1.clone();
+3001 let m2 = m2.clone();
+3002 let task = tokio::spawn(async move {
+3003 println!("-- [m1] network change");
+3004 m1.endpoint.magic_sock().force_network_change(true).await;
+3005 println!("-- [m2] network change");
+3006 m2.endpoint.magic_sock().force_network_change(true).await;
+3007 time::sleep(offset()).await;
+3008 });
+3009 AbortOnDropHandle::new(task)
+3010 };
+3011
+3012 for i in 0..rounds {
+3013 println!("-- [m1 & m2 changes] round {}", i + 1);
+3014 run_roundtrip(m1.clone(), m2.clone(), b"hello m1", ExpectedLoss::YeahSure).await;
+3015 run_roundtrip(m2.clone(), m1.clone(), b"hello m2", ExpectedLoss::YeahSure).await;
3016
-3017 for i in 0..rounds {
-3018 println!("-- [m1 & m2 changes] round {}", i + 1);
-3019 run_roundtrip(m1.clone(), m2.clone(), b"hello m1", ExpectedLoss::YeahSure).await;
-3020 run_roundtrip(m2.clone(), m1.clone(), b"hello m2", ExpectedLoss::YeahSure).await;
-3021
-3022 println!("-- [m1 & m2 changes] larger data");
-3023 let mut data = vec![0u8; 10 * 1024];
-3024 rand::thread_rng().fill_bytes(&mut data);
-3025 run_roundtrip(m1.clone(), m2.clone(), &data, ExpectedLoss::YeahSure).await;
-3026 run_roundtrip(m2.clone(), m1.clone(), &data, ExpectedLoss::YeahSure).await;
-3027 }
-3028
-3029 std::mem::drop(m1_m2_network_change_guard);
-3030 Ok(())
-3031 }
-3032
-3033 #[tokio::test(flavor = "multi_thread")]
-3034 #[traced_test]
-3035 async fn test_two_devices_setup_teardown() -> Result {
-3036 for i in 0..10 {
-3037 println!("-- round {i}");
-3038 println!("setting up magic stack");
-3039 let m1 = MagicStack::new(RelayMode::Disabled).await;
-3040 let m2 = MagicStack::new(RelayMode::Disabled).await;
-3041
-3042 let _guard = mesh_stacks(vec![m1.clone(), m2.clone()]).await?;
-3043
-3044 println!("closing endpoints");
-3045 let msock1 = m1.endpoint.magic_sock();
-3046 let msock2 = m2.endpoint.magic_sock();
-3047 m1.endpoint.close().await;
-3048 m2.endpoint.close().await;
-3049
-3050 assert!(msock1.msock.is_closed());
-3051 assert!(msock2.msock.is_closed());
-3052 }
-3053 Ok(())
-3054 }
+3017 println!("-- [m1 & m2 changes] larger data");
+3018 let mut data = vec![0u8; 10 * 1024];
+3019 rand::thread_rng().fill_bytes(&mut data);
+3020 run_roundtrip(m1.clone(), m2.clone(), &data, ExpectedLoss::YeahSure).await;
+3021 run_roundtrip(m2.clone(), m1.clone(), &data, ExpectedLoss::YeahSure).await;
+3022 }
+3023
+3024 std::mem::drop(m1_m2_network_change_guard);
+3025 Ok(())
+3026 }
+3027
+3028 #[tokio::test(flavor = "multi_thread")]
+3029 #[traced_test]
+3030 async fn test_two_devices_setup_teardown() -> Result {
+3031 for i in 0..10 {
+3032 println!("-- round {i}");
+3033 println!("setting up magic stack");
+3034 let m1 = MagicStack::new(RelayMode::Disabled).await;
+3035 let m2 = MagicStack::new(RelayMode::Disabled).await;
+3036
+3037 let _guard = mesh_stacks(vec![m1.clone(), m2.clone()]).await?;
+3038
+3039 println!("closing endpoints");
+3040 let msock1 = m1.endpoint.magic_sock();
+3041 let msock2 = m2.endpoint.magic_sock();
+3042 m1.endpoint.close().await;
+3043 m2.endpoint.close().await;
+3044
+3045 assert!(msock1.msock.is_closed());
+3046 assert!(msock2.msock.is_closed());
+3047 }
+3048 Ok(())
+3049 }
+3050
+3051 #[tokio::test]
+3052 #[traced_test]
+3053 async fn test_local_endpoints() {
+3054 let ms = Handle::new(Default::default()).await.unwrap();
3055
-3056 #[tokio::test]
-3057 #[traced_test]
-3058 async fn test_local_endpoints() {
-3059 let ms = Handle::new(Default::default()).await.unwrap();
+3056 // See if we can get endpoints.
+3057 let eps0 = ms.direct_addresses().initialized().await.unwrap();
+3058 println!("{eps0:?}");
+3059 assert!(!eps0.is_empty());
3060
-3061 // See if we can get endpoints.
-3062 let eps0 = ms.direct_addresses().initialized().await.unwrap();
-3063 println!("{eps0:?}");
-3064 assert!(!eps0.is_empty());
-3065
-3066 // Getting the endpoints again immediately should give the same results.
-3067 let eps1 = ms.direct_addresses().initialized().await.unwrap();
-3068 println!("{eps1:?}");
-3069 assert_eq!(eps0, eps1);
-3070 }
-3071
-3072 /// Creates a new [`quinn::Endpoint`] hooked up to a [`MagicSock`].
-3073 ///
-3074 /// This is without involving [`crate::endpoint::Endpoint`]. The socket will accept
-3075 /// connections using [`ALPN`].
-3076 ///
-3077 /// Use [`magicsock_connect`] to establish connections.
-3078 #[instrument(name = "ep", skip_all, fields(me = secret_key.public().fmt_short()))]
-3079 async fn magicsock_ep(secret_key: SecretKey) -> Result<Handle> {
-3080 let quic_server_config =
-3081 tls::TlsConfig::new(secret_key.clone()).make_server_config(vec![ALPN.to_vec()], true);
-3082 let mut server_config = ServerConfig::with_crypto(Arc::new(quic_server_config));
-3083 server_config.transport_config(Arc::new(quinn::TransportConfig::default()));
-3084
-3085 let dns_resolver = DnsResolver::new();
-3086 let opts = Options {
-3087 addr_v4: None,
-3088 addr_v6: None,
-3089 secret_key: secret_key.clone(),
-3090 relay_map: RelayMap::empty(),
-3091 relay_protocol: iroh_relay::http::Protocol::default(),
-3092 node_map: None,
-3093 discovery: None,
-3094 discovery_user_data: None,
-3095 dns_resolver,
-3096 proxy_url: None,
-3097 server_config,
-3098 insecure_skip_relay_cert_verify: false,
-3099 path_selection: PathSelection::default(),
-3100 metrics: Default::default(),
-3101 };
-3102 let msock = MagicSock::spawn(opts).await?;
-3103 Ok(msock)
-3104 }
-3105
-3106 /// Connects from `ep` returned by [`magicsock_ep`] to the `node_id`.
-3107 ///
-3108 /// Uses [`ALPN`], `node_id`, must match `addr`.
-3109 #[instrument(name = "connect", skip_all, fields(me = ep_secret_key.public().fmt_short()))]
-3110 async fn magicsock_connect(
-3111 ep: &quinn::Endpoint,
-3112 ep_secret_key: SecretKey,
-3113 addr: NodeIdMappedAddr,
-3114 node_id: NodeId,
-3115 ) -> Result<quinn::Connection> {
-3116 // Endpoint::connect sets this, do the same to have similar behaviour.
-3117 let mut transport_config = quinn::TransportConfig::default();
-3118 transport_config.keep_alive_interval(Some(Duration::from_secs(1)));
-3119
-3120 magicsock_connect_with_transport_config(
-3121 ep,
-3122 ep_secret_key,
-3123 addr,
-3124 node_id,
-3125 Arc::new(transport_config),
-3126 )
-3127 .await
-3128 }
-3129
-3130 /// Connects from `ep` returned by [`magicsock_ep`] to the `node_id`.
-3131 ///
-3132 /// This version allows customising the transport config.
-3133 ///
-3134 /// Uses [`ALPN`], `node_id`, must match `addr`.
-3135 #[instrument(name = "connect", skip_all, fields(me = ep_secret_key.public().fmt_short()))]
-3136 async fn magicsock_connect_with_transport_config(
-3137 ep: &quinn::Endpoint,
-3138 ep_secret_key: SecretKey,
-3139 mapped_addr: NodeIdMappedAddr,
-3140 node_id: NodeId,
-3141 transport_config: Arc<quinn::TransportConfig>,
-3142 ) -> Result<quinn::Connection> {
-3143 let alpns = vec![ALPN.to_vec()];
-3144 let quic_client_config =
-3145 tls::TlsConfig::new(ep_secret_key.clone()).make_client_config(alpns, true);
-3146 let mut client_config = quinn::ClientConfig::new(Arc::new(quic_client_config));
-3147 client_config.transport_config(transport_config);
-3148 let connect = ep
-3149 .connect_with(
-3150 client_config,
-3151 mapped_addr.private_socket_addr(),
-3152 &tls::name::encode(node_id),
-3153 )
-3154 .context("connect")?;
-3155 let connection = connect.await.e()?;
-3156 Ok(connection)
-3157 }
-3158
-3159 #[tokio::test]
-3160 #[traced_test]
-3161 async fn test_try_send_no_send_addr() {
-3162 // Regression test: if there is no send_addr we should keep being able to use the
-3163 // Endpoint.
-3164
-3165 let secret_key_1 = SecretKey::from_bytes(&[1u8; 32]);
-3166 let secret_key_2 = SecretKey::from_bytes(&[2u8; 32]);
-3167 let node_id_2 = secret_key_2.public();
-3168 let secret_key_missing_node = SecretKey::from_bytes(&[255u8; 32]);
-3169 let node_id_missing_node = secret_key_missing_node.public();
+3061 // Getting the endpoints again immediately should give the same results.
+3062 let eps1 = ms.direct_addresses().initialized().await.unwrap();
+3063 println!("{eps1:?}");
+3064 assert_eq!(eps0, eps1);
+3065 }
+3066
+3067 /// Creates a new [`quinn::Endpoint`] hooked up to a [`MagicSock`].
+3068 ///
+3069 /// This is without involving [`crate::endpoint::Endpoint`]. The socket will accept
+3070 /// connections using [`ALPN`].
+3071 ///
+3072 /// Use [`magicsock_connect`] to establish connections.
+3073 #[instrument(name = "ep", skip_all, fields(me = secret_key.public().fmt_short()))]
+3074 async fn magicsock_ep(secret_key: SecretKey) -> Result<Handle> {
+3075 let quic_server_config =
+3076 tls::TlsConfig::new(secret_key.clone()).make_server_config(vec![ALPN.to_vec()], true);
+3077 let mut server_config = ServerConfig::with_crypto(Arc::new(quic_server_config));
+3078 server_config.transport_config(Arc::new(quinn::TransportConfig::default()));
+3079
+3080 let dns_resolver = DnsResolver::new();
+3081 let opts = Options {
+3082 addr_v4: None,
+3083 addr_v6: None,
+3084 secret_key: secret_key.clone(),
+3085 relay_map: RelayMap::empty(),
+3086 relay_protocol: iroh_relay::http::Protocol::default(),
+3087 node_map: None,
+3088 discovery: None,
+3089 discovery_user_data: None,
+3090 dns_resolver,
+3091 proxy_url: None,
+3092 server_config,
+3093 insecure_skip_relay_cert_verify: false,
+3094 path_selection: PathSelection::default(),
+3095 metrics: Default::default(),
+3096 };
+3097 let msock = MagicSock::spawn(opts).await?;
+3098 Ok(msock)
+3099 }
+3100
+3101 /// Connects from `ep` returned by [`magicsock_ep`] to the `node_id`.
+3102 ///
+3103 /// Uses [`ALPN`], `node_id`, must match `addr`.
+3104 #[instrument(name = "connect", skip_all, fields(me = ep_secret_key.public().fmt_short()))]
+3105 async fn magicsock_connect(
+3106 ep: &quinn::Endpoint,
+3107 ep_secret_key: SecretKey,
+3108 addr: NodeIdMappedAddr,
+3109 node_id: NodeId,
+3110 ) -> Result<quinn::Connection> {
+3111 // Endpoint::connect sets this, do the same to have similar behaviour.
+3112 let mut transport_config = quinn::TransportConfig::default();
+3113 transport_config.keep_alive_interval(Some(Duration::from_secs(1)));
+3114
+3115 magicsock_connect_with_transport_config(
+3116 ep,
+3117 ep_secret_key,
+3118 addr,
+3119 node_id,
+3120 Arc::new(transport_config),
+3121 )
+3122 .await
+3123 }
+3124
+3125 /// Connects from `ep` returned by [`magicsock_ep`] to the `node_id`.
+3126 ///
+3127 /// This version allows customising the transport config.
+3128 ///
+3129 /// Uses [`ALPN`], `node_id`, must match `addr`.
+3130 #[instrument(name = "connect", skip_all, fields(me = ep_secret_key.public().fmt_short()))]
+3131 async fn magicsock_connect_with_transport_config(
+3132 ep: &quinn::Endpoint,
+3133 ep_secret_key: SecretKey,
+3134 mapped_addr: NodeIdMappedAddr,
+3135 node_id: NodeId,
+3136 transport_config: Arc<quinn::TransportConfig>,
+3137 ) -> Result<quinn::Connection> {
+3138 let alpns = vec![ALPN.to_vec()];
+3139 let quic_client_config =
+3140 tls::TlsConfig::new(ep_secret_key.clone()).make_client_config(alpns, true);
+3141 let mut client_config = quinn::ClientConfig::new(Arc::new(quic_client_config));
+3142 client_config.transport_config(transport_config);
+3143 let connect = ep
+3144 .connect_with(
+3145 client_config,
+3146 mapped_addr.private_socket_addr(),
+3147 &tls::name::encode(node_id),
+3148 )
+3149 .context("connect")?;
+3150 let connection = connect.await.e()?;
+3151 Ok(connection)
+3152 }
+3153
+3154 #[tokio::test]
+3155 #[traced_test]
+3156 async fn test_try_send_no_send_addr() {
+3157 // Regression test: if there is no send_addr we should keep being able to use the
+3158 // Endpoint.
+3159
+3160 let secret_key_1 = SecretKey::from_bytes(&[1u8; 32]);
+3161 let secret_key_2 = SecretKey::from_bytes(&[2u8; 32]);
+3162 let node_id_2 = secret_key_2.public();
+3163 let secret_key_missing_node = SecretKey::from_bytes(&[255u8; 32]);
+3164 let node_id_missing_node = secret_key_missing_node.public();
+3165
+3166 let msock_1 = magicsock_ep(secret_key_1.clone()).await.unwrap();
+3167
+3168 // Generate an address not present in the NodeMap.
+3169 let bad_addr = NodeIdMappedAddr::generate();
3170
-3171 let msock_1 = magicsock_ep(secret_key_1.clone()).await.unwrap();
-3172
-3173 // Generate an address not present in the NodeMap.
-3174 let bad_addr = NodeIdMappedAddr::generate();
-3175
-3176 // 500ms is rather fast here. Running this locally it should always be the correct
-3177 // timeout. If this is too slow however the test will not become flaky as we are
-3178 // expecting the timeout, we might just get the timeout for the wrong reason. But
-3179 // this speeds up the test.
-3180 let res = tokio::time::timeout(
-3181 Duration::from_millis(500),
-3182 magicsock_connect(
-3183 msock_1.endpoint(),
-3184 secret_key_1.clone(),
-3185 bad_addr,
-3186 node_id_missing_node,
-3187 ),
-3188 )
-3189 .await;
-3190 assert!(res.is_err(), "expecting timeout");
-3191
-3192 // Now check we can still create another connection with this endpoint.
-3193 let msock_2 = magicsock_ep(secret_key_2.clone()).await.unwrap();
-3194
-3195 // This needs an accept task
-3196 let accept_task = tokio::spawn({
-3197 async fn accept(ep: quinn::Endpoint) -> Result<()> {
-3198 let incoming = ep.accept().await.context("no incoming")?;
-3199 let _conn = incoming
-3200 .accept()
-3201 .context("accept")?
-3202 .await
-3203 .context("connecting")?;
-3204
-3205 // Keep this connection alive for a while
-3206 tokio::time::sleep(Duration::from_secs(10)).await;
-3207 info!("accept finished");
-3208 Ok(())
-3209 }
-3210 let ep = msock_2.endpoint().clone();
-3211 async move {
-3212 if let Err(err) = accept(ep).await {
-3213 error!("{err:#}");
-3214 }
-3215 }
-3216 .instrument(info_span!("ep2.accept, me = node_id_2.fmt_short()"))
-3217 });
-3218 let _accept_task = AbortOnDropHandle::new(accept_task);
-3219
-3220 let node_addr_2 = NodeAddr {
-3221 node_id: node_id_2,
-3222 relay_url: None,
-3223 direct_addresses: msock_2
-3224 .direct_addresses()
-3225 .initialized()
-3226 .await
-3227 .expect("no direct addrs")
-3228 .into_iter()
-3229 .map(|x| x.addr)
-3230 .collect(),
-3231 };
-3232 msock_1
-3233 .add_node_addr(
-3234 node_addr_2,
-3235 Source::NamedApp {
-3236 name: "test".into(),
-3237 },
-3238 )
-3239 .unwrap();
-3240 let addr = msock_1.get_mapping_addr(node_id_2).unwrap();
-3241 let res = tokio::time::timeout(
-3242 Duration::from_secs(10),
-3243 magicsock_connect(msock_1.endpoint(), secret_key_1.clone(), addr, node_id_2),
-3244 )
-3245 .await
-3246 .expect("timeout while connecting");
-3247
-3248 // aka assert!(res.is_ok()) but with nicer error reporting.
-3249 res.unwrap();
-3250
-3251 // TODO: Now check if we can connect to a repaired ep_3, but we can't modify that
-3252 // much internal state for now.
-3253 }
-3254
-3255 #[tokio::test]
-3256 #[traced_test]
-3257 async fn test_try_send_no_udp_addr_or_relay_url() {
-3258 // This specifically tests the `if udp_addr.is_none() && relay_url.is_none()`
-3259 // behaviour of MagicSock::try_send.
-3260
-3261 let secret_key_1 = SecretKey::from_bytes(&[1u8; 32]);
-3262 let secret_key_2 = SecretKey::from_bytes(&[2u8; 32]);
-3263 let node_id_2 = secret_key_2.public();
-3264
-3265 let msock_1 = magicsock_ep(secret_key_1.clone()).await.unwrap();
-3266 let msock_2 = magicsock_ep(secret_key_2.clone()).await.unwrap();
-3267 let ep_2 = msock_2.endpoint().clone();
-3268
-3269 // We need a task to accept the connection.
-3270 let accept_task = tokio::spawn({
-3271 async fn accept(ep: quinn::Endpoint) -> Result<()> {
-3272 let incoming = ep.accept().await.context("no incoming")?;
-3273 let conn = incoming
-3274 .accept()
-3275 .context("accept")?
-3276 .await
-3277 .context("connecting")?;
-3278 let mut stream = conn.accept_uni().await.context("accept uni")?;
-3279 stream.read_to_end(1 << 16).await.context("read to end")?;
-3280 info!("accept finished");
-3281 Ok(())
+3171 // 500ms is rather fast here. Running this locally it should always be the correct
+3172 // timeout. If this is too slow however the test will not become flaky as we are
+3173 // expecting the timeout, we might just get the timeout for the wrong reason. But
+3174 // this speeds up the test.
+3175 let res = tokio::time::timeout(
+3176 Duration::from_millis(500),
+3177 magicsock_connect(
+3178 msock_1.endpoint(),
+3179 secret_key_1.clone(),
+3180 bad_addr,
+3181 node_id_missing_node,
+3182 ),
+3183 )
+3184 .await;
+3185 assert!(res.is_err(), "expecting timeout");
+3186
+3187 // Now check we can still create another connection with this endpoint.
+3188 let msock_2 = magicsock_ep(secret_key_2.clone()).await.unwrap();
+3189
+3190 // This needs an accept task
+3191 let accept_task = tokio::spawn({
+3192 async fn accept(ep: quinn::Endpoint) -> Result<()> {
+3193 let incoming = ep.accept().await.context("no incoming")?;
+3194 let _conn = incoming
+3195 .accept()
+3196 .context("accept")?
+3197 .await
+3198 .context("connecting")?;
+3199
+3200 // Keep this connection alive for a while
+3201 tokio::time::sleep(Duration::from_secs(10)).await;
+3202 info!("accept finished");
+3203 Ok(())
+3204 }
+3205 let ep = msock_2.endpoint().clone();
+3206 async move {
+3207 if let Err(err) = accept(ep).await {
+3208 error!("{err:#}");
+3209 }
+3210 }
+3211 .instrument(info_span!("ep2.accept, me = node_id_2.fmt_short()"))
+3212 });
+3213 let _accept_task = AbortOnDropHandle::new(accept_task);
+3214
+3215 let node_addr_2 = NodeAddr {
+3216 node_id: node_id_2,
+3217 relay_url: None,
+3218 direct_addresses: msock_2
+3219 .direct_addresses()
+3220 .initialized()
+3221 .await
+3222 .expect("no direct addrs")
+3223 .into_iter()
+3224 .map(|x| x.addr)
+3225 .collect(),
+3226 };
+3227 msock_1
+3228 .add_node_addr(
+3229 node_addr_2,
+3230 Source::NamedApp {
+3231 name: "test".into(),
+3232 },
+3233 )
+3234 .unwrap();
+3235 let addr = msock_1.get_mapping_addr(node_id_2).unwrap();
+3236 let res = tokio::time::timeout(
+3237 Duration::from_secs(10),
+3238 magicsock_connect(msock_1.endpoint(), secret_key_1.clone(), addr, node_id_2),
+3239 )
+3240 .await
+3241 .expect("timeout while connecting");
+3242
+3243 // aka assert!(res.is_ok()) but with nicer error reporting.
+3244 res.unwrap();
+3245
+3246 // TODO: Now check if we can connect to a repaired ep_3, but we can't modify that
+3247 // much internal state for now.
+3248 }
+3249
+3250 #[tokio::test]
+3251 #[traced_test]
+3252 async fn test_try_send_no_udp_addr_or_relay_url() {
+3253 // This specifically tests the `if udp_addr.is_none() && relay_url.is_none()`
+3254 // behaviour of MagicSock::try_send.
+3255
+3256 let secret_key_1 = SecretKey::from_bytes(&[1u8; 32]);
+3257 let secret_key_2 = SecretKey::from_bytes(&[2u8; 32]);
+3258 let node_id_2 = secret_key_2.public();
+3259
+3260 let msock_1 = magicsock_ep(secret_key_1.clone()).await.unwrap();
+3261 let msock_2 = magicsock_ep(secret_key_2.clone()).await.unwrap();
+3262 let ep_2 = msock_2.endpoint().clone();
+3263
+3264 // We need a task to accept the connection.
+3265 let accept_task = tokio::spawn({
+3266 async fn accept(ep: quinn::Endpoint) -> Result<()> {
+3267 let incoming = ep.accept().await.context("no incoming")?;
+3268 let conn = incoming
+3269 .accept()
+3270 .context("accept")?
+3271 .await
+3272 .context("connecting")?;
+3273 let mut stream = conn.accept_uni().await.context("accept uni")?;
+3274 stream.read_to_end(1 << 16).await.context("read to end")?;
+3275 info!("accept finished");
+3276 Ok(())
+3277 }
+3278 async move {
+3279 if let Err(err) = accept(ep_2).await {
+3280 error!("{err:#}");
+3281 }
3282 }
-3283 async move {
-3284 if let Err(err) = accept(ep_2).await {
-3285 error!("{err:#}");
-3286 }
-3287 }
-3288 .instrument(info_span!("ep2.accept", me = node_id_2.fmt_short()))
-3289 });
-3290 let _accept_task = AbortOnDropHandle::new(accept_task);
-3291
-3292 // Add an empty entry in the NodeMap of ep_1
-3293 msock_1.node_map.add_node_addr(
-3294 NodeAddr {
-3295 node_id: node_id_2,
-3296 relay_url: None,
-3297 direct_addresses: Default::default(),
-3298 },
-3299 Source::NamedApp {
-3300 name: "test".into(),
-3301 },
-3302 &msock_1.metrics.magicsock,
-3303 );
-3304 let addr_2 = msock_1.get_mapping_addr(node_id_2).unwrap();
-3305
-3306 // Set a low max_idle_timeout so quinn gives up on this quickly and our test does
-3307 // not take forever. You need to check the log output to verify this is really
-3308 // triggering the correct error.
-3309 // In test_try_send_no_send_addr() above you may have noticed we used
-3310 // tokio::time::timeout() on the connection attempt instead. Here however we want
-3311 // Quinn itself to have fully given up on the connection attempt because we will
-3312 // later connect to **the same** node. If Quinn did not give up on the connection
-3313 // we'd close it on drop, and the retransmits of the close packets would interfere
-3314 // with the next handshake, closing it during the handshake. This makes the test a
-3315 // little slower though.
-3316 let mut transport_config = quinn::TransportConfig::default();
-3317 transport_config.max_idle_timeout(Some(Duration::from_millis(200).try_into().unwrap()));
-3318 let res = magicsock_connect_with_transport_config(
-3319 msock_1.endpoint(),
-3320 secret_key_1.clone(),
-3321 addr_2,
-3322 node_id_2,
-3323 Arc::new(transport_config),
-3324 )
-3325 .await;
-3326 assert!(res.is_err(), "expected timeout");
-3327 info!("first connect timed out as expected");
-3328
-3329 // Provide correct addressing information
-3330 msock_1.node_map.add_node_addr(
-3331 NodeAddr {
-3332 node_id: node_id_2,
-3333 relay_url: None,
-3334 direct_addresses: msock_2
-3335 .direct_addresses()
-3336 .initialized()
-3337 .await
-3338 .expect("no direct addrs")
-3339 .into_iter()
-3340 .map(|x| x.addr)
-3341 .collect(),
-3342 },
-3343 Source::NamedApp {
-3344 name: "test".into(),
-3345 },
-3346 &msock_1.metrics.magicsock,
-3347 );
-3348
-3349 // We can now connect
-3350 tokio::time::timeout(Duration::from_secs(10), async move {
-3351 info!("establishing new connection");
-3352 let conn =
-3353 magicsock_connect(msock_1.endpoint(), secret_key_1.clone(), addr_2, node_id_2)
-3354 .await
-3355 .unwrap();
-3356 info!("have connection");
-3357 let mut stream = conn.open_uni().await.unwrap();
-3358 stream.write_all(b"hello").await.unwrap();
-3359 stream.finish().unwrap();
-3360 stream.stopped().await.unwrap();
-3361 info!("finished stream");
-3362 })
-3363 .await
-3364 .expect("connection timed out");
-3365
-3366 // TODO: could remove the addresses again, send, add it back and see it recover.
-3367 // But we don't have that much private access to the NodeMap. This will do for now.
-3368 }
+3283 .instrument(info_span!("ep2.accept", me = node_id_2.fmt_short()))
+3284 });
+3285 let _accept_task = AbortOnDropHandle::new(accept_task);
+3286
+3287 // Add an empty entry in the NodeMap of ep_1
+3288 msock_1.node_map.add_node_addr(
+3289 NodeAddr {
+3290 node_id: node_id_2,
+3291 relay_url: None,
+3292 direct_addresses: Default::default(),
+3293 },
+3294 Source::NamedApp {
+3295 name: "test".into(),
+3296 },
+3297 &msock_1.metrics.magicsock,
+3298 );
+3299 let addr_2 = msock_1.get_mapping_addr(node_id_2).unwrap();
+3300
+3301 // Set a low max_idle_timeout so quinn gives up on this quickly and our test does
+3302 // not take forever. You need to check the log output to verify this is really
+3303 // triggering the correct error.
+3304 // In test_try_send_no_send_addr() above you may have noticed we used
+3305 // tokio::time::timeout() on the connection attempt instead. Here however we want
+3306 // Quinn itself to have fully given up on the connection attempt because we will
+3307 // later connect to **the same** node. If Quinn did not give up on the connection
+3308 // we'd close it on drop, and the retransmits of the close packets would interfere
+3309 // with the next handshake, closing it during the handshake. This makes the test a
+3310 // little slower though.
+3311 let mut transport_config = quinn::TransportConfig::default();
+3312 transport_config.max_idle_timeout(Some(Duration::from_millis(200).try_into().unwrap()));
+3313 let res = magicsock_connect_with_transport_config(
+3314 msock_1.endpoint(),
+3315 secret_key_1.clone(),
+3316 addr_2,
+3317 node_id_2,
+3318 Arc::new(transport_config),
+3319 )
+3320 .await;
+3321 assert!(res.is_err(), "expected timeout");
+3322 info!("first connect timed out as expected");
+3323
+3324 // Provide correct addressing information
+3325 msock_1.node_map.add_node_addr(
+3326 NodeAddr {
+3327 node_id: node_id_2,
+3328 relay_url: None,
+3329 direct_addresses: msock_2
+3330 .direct_addresses()
+3331 .initialized()
+3332 .await
+3333 .expect("no direct addrs")
+3334 .into_iter()
+3335 .map(|x| x.addr)
+3336 .collect(),
+3337 },
+3338 Source::NamedApp {
+3339 name: "test".into(),
+3340 },
+3341 &msock_1.metrics.magicsock,
+3342 );
+3343
+3344 // We can now connect
+3345 tokio::time::timeout(Duration::from_secs(10), async move {
+3346 info!("establishing new connection");
+3347 let conn =
+3348 magicsock_connect(msock_1.endpoint(), secret_key_1.clone(), addr_2, node_id_2)
+3349 .await
+3350 .unwrap();
+3351 info!("have connection");
+3352 let mut stream = conn.open_uni().await.unwrap();
+3353 stream.write_all(b"hello").await.unwrap();
+3354 stream.finish().unwrap();
+3355 stream.stopped().await.unwrap();
+3356 info!("finished stream");
+3357 })
+3358 .await
+3359 .expect("connection timed out");
+3360
+3361 // TODO: could remove the addresses again, send, add it back and see it recover.
+3362 // But we don't have that much private access to the NodeMap. This will do for now.
+3363 }
+3364
+3365 #[tokio::test]
+3366 async fn test_add_node_addr() -> Result {
+3367 let stack = MagicStack::new(RelayMode::Default).await;
+3368 let mut rng = rand::thread_rng();
3369
-3370 #[tokio::test]
-3371 async fn test_add_node_addr() -> Result {
-3372 let stack = MagicStack::new(RelayMode::Default).await;
-3373 let mut rng = rand::thread_rng();
-3374
-3375 assert_eq!(stack.endpoint.magic_sock().node_map.node_count(), 0);
-3376
-3377 // Empty
-3378 let empty_addr = NodeAddr {
-3379 node_id: SecretKey::generate(&mut rng).public(),
-3380 relay_url: None,
-3381 direct_addresses: Default::default(),
-3382 };
-3383 let err = stack
-3384 .endpoint
-3385 .magic_sock()
-3386 .add_node_addr(empty_addr, node_map::Source::App)
-3387 .unwrap_err();
-3388 assert!(err
-3389 .to_string()
-3390 .to_lowercase()
-3391 .contains("empty addressing info"));
-3392
-3393 // relay url only
-3394 let addr = NodeAddr {
-3395 node_id: SecretKey::generate(&mut rng).public(),
-3396 relay_url: Some("http://my-relay.com".parse().unwrap()),
-3397 direct_addresses: Default::default(),
-3398 };
-3399 stack
-3400 .endpoint
-3401 .magic_sock()
-3402 .add_node_addr(addr, node_map::Source::App)?;
-3403 assert_eq!(stack.endpoint.magic_sock().node_map.node_count(), 1);
-3404
-3405 // addrs only
-3406 let addr = NodeAddr {
-3407 node_id: SecretKey::generate(&mut rng).public(),
-3408 relay_url: None,
-3409 direct_addresses: ["127.0.0.1:1234".parse().unwrap()].into_iter().collect(),
-3410 };
-3411 stack
-3412 .endpoint
-3413 .magic_sock()
-3414 .add_node_addr(addr, node_map::Source::App)?;
-3415 assert_eq!(stack.endpoint.magic_sock().node_map.node_count(), 2);
-3416
-3417 // both
-3418 let addr = NodeAddr {
-3419 node_id: SecretKey::generate(&mut rng).public(),
-3420 relay_url: Some("http://my-relay.com".parse().unwrap()),
-3421 direct_addresses: ["127.0.0.1:1234".parse().unwrap()].into_iter().collect(),
-3422 };
-3423 stack
-3424 .endpoint
-3425 .magic_sock()
-3426 .add_node_addr(addr, node_map::Source::App)?;
-3427 assert_eq!(stack.endpoint.magic_sock().node_map.node_count(), 3);
-3428
-3429 Ok(())
-3430 }
-3431}
\ No newline at end of file
+3370 assert_eq!(stack.endpoint.magic_sock().node_map.node_count(), 0);
+3371
+3372 // Empty
+3373 let empty_addr = NodeAddr {
+3374 node_id: SecretKey::generate(&mut rng).public(),
+3375 relay_url: None,
+3376 direct_addresses: Default::default(),
+3377 };
+3378 let err = stack
+3379 .endpoint
+3380 .magic_sock()
+3381 .add_node_addr(empty_addr, node_map::Source::App)
+3382 .unwrap_err();
+3383 assert!(err
+3384 .to_string()
+3385 .to_lowercase()
+3386 .contains("empty addressing info"));
+3387
+3388 // relay url only
+3389 let addr = NodeAddr {
+3390 node_id: SecretKey::generate(&mut rng).public(),
+3391 relay_url: Some("http://my-relay.com".parse().unwrap()),
+3392 direct_addresses: Default::default(),
+3393 };
+3394 stack
+3395 .endpoint
+3396 .magic_sock()
+3397 .add_node_addr(addr, node_map::Source::App)?;
+3398 assert_eq!(stack.endpoint.magic_sock().node_map.node_count(), 1);
+3399
+3400 // addrs only
+3401 let addr = NodeAddr {
+3402 node_id: SecretKey::generate(&mut rng).public(),
+3403 relay_url: None,
+3404 direct_addresses: ["127.0.0.1:1234".parse().unwrap()].into_iter().collect(),
+3405 };
+3406 stack
+3407 .endpoint
+3408 .magic_sock()
+3409 .add_node_addr(addr, node_map::Source::App)?;
+3410 assert_eq!(stack.endpoint.magic_sock().node_map.node_count(), 2);
+3411
+3412 // both
+3413 let addr = NodeAddr {
+3414 node_id: SecretKey::generate(&mut rng).public(),
+3415 relay_url: Some("http://my-relay.com".parse().unwrap()),
+3416 direct_addresses: ["127.0.0.1:1234".parse().unwrap()].into_iter().collect(),
+3417 };
+3418 stack
+3419 .endpoint
+3420 .magic_sock()
+3421 .add_node_addr(addr, node_map::Source::App)?;
+3422 assert_eq!(stack.endpoint.magic_sock().node_map.node_count(), 3);
+3423
+3424 Ok(())
+3425 }
+3426}
\ No newline at end of file
diff --git a/pr/3381/docs/trait.impl/core/convert/trait.From.js b/pr/3381/docs/trait.impl/core/convert/trait.From.js
index 301235bb2d..2ae75d6be2 100644
--- a/pr/3381/docs/trait.impl/core/convert/trait.From.js
+++ b/pr/3381/docs/trait.impl/core/convert/trait.From.js
@@ -1,9 +1,9 @@
(function() {
- var implementors = Object.fromEntries([["iroh",[["impl From<IntoDiscoveryError> for BindError"],["impl From<PkarrError> for DiscoveryError"],["impl From<AddNodeAddrError> for ConnectWithOptsError"],["impl From<ConnectWithOptsError> for ConnectError"],["impl From<ConnectionError> for AlpnError"],["impl From<ConnectionError> for ConnectError"],["impl From<ConnectionError> for AcceptError"],["impl From<Box<dyn Error + Send + Sync>> for AcceptError"],["impl From<Error> for AcceptError"],["impl From<DiscoveryItem> for NodeInfo"],["impl From<ClosedStream> for AcceptError"],["impl From<RemoteInfo> for NodeAddr"],["impl From<RemoteNodeIdError> for AcceptError"],["impl<T> From<T> for ConcurrentDiscovery"],["impl<T: ProtocolHandler> From<T> for Box<dyn DynProtocolHandler>"]]],["iroh_base",[["impl From<(PublicKey, Option<RelayUrl>, &[SocketAddr])> for NodeAddr"],["impl From<Url> for RelayUrl"],["impl From<NodeAddr> for NodeTicket"],["impl From<PublicKey> for NodeAddr"],["impl From<RelayUrl> for Url"],["impl From<NodeTicket> for NodeAddr"],["impl From<DecodeError> for KeyParsingError"],["impl From<DecodeError> for ParseError"],["impl From<Error> for KeyParsingError"],["impl From<Error> for ParseError"],["impl From<SigningKey> for SecretKey"],["impl From<VerifyingKey> for PublicKey"],["impl From<[u8; 32]> for SecretKey"]]],["iroh_relay",[["impl From<DialError> for ConnectError"],["impl From<SendError> for SendError"],["impl From<DnsError> for DialError"],["impl From<DecodingError> for ParseError"],["impl From<FrameType> for u8"],["impl From<RecvError> for RecvError"],["impl From<SendError> for ConnectError"],["impl From<SendError> for RecvError"],["impl From<u8> for FrameType"],["impl From<Error> for DialError"],["impl From<Error> for RecvError"],["impl From<Error> for SendError"],["impl From<Error> for RecvError"],["impl From<Error> for SendError"],["impl From<NodeAddr> for NodeData"],["impl From<NodeAddr> for NodeInfo"],["impl From<RelayUrl> for RelayMap"],["impl From<RelayUrl> for RelayNode"],["impl From<NodeInfo> for NodeAddr"],["impl From<RelayNode> for RelayMap"],["impl From<ConnectError> for Error"],["impl From<ConnectionError> for Error"],["impl From<Elapsed> for DialError"],["impl From<Elapsed> for DnsError"],["impl From<Elapsed> for RecvError"],["impl From<Elapsed> for SendError"],["impl From<Error> for ConnectError"],["impl From<Error> for RecvError"],["impl From<Error> for SendError"],["impl From<Error> for RecvError"],["impl From<Error> for RecvError"],["impl From<Error> for SendError"],["impl From<JoinError> for SupervisorError"],["impl From<RecvError> for Error"],["impl From<ResolveError> for DnsError"],["impl From<Resolver<GenericConnector<TokioRuntimeProvider>>> for DnsResolver"],["impl From<SignedPacketBuildError> for EncodingError"],["impl From<TxtLookup> for TxtLookup"]]]]);
+ var implementors = Object.fromEntries([["iroh",[["impl From<IntoDiscoveryError> for BindError"],["impl From<PkarrError> for DiscoveryError"],["impl From<AddNodeAddrError> for ConnectWithOptsError"],["impl From<ConnectWithOptsError> for ConnectError"],["impl From<ConnectionError> for AlpnError"],["impl From<ConnectionError> for ConnectError"],["impl From<ConnectionError> for AcceptError"],["impl From<Box<dyn Error + Send + Sync>> for AcceptError"],["impl From<Error> for AcceptError"],["impl From<DiscoveryItem> for NodeInfo"],["impl From<ClosedStream> for AcceptError"],["impl From<RemoteInfo> for NodeAddr"],["impl From<RemoteNodeIdError> for AcceptError"],["impl<T> From<T> for ConcurrentDiscovery"],["impl<T: ProtocolHandler> From<T> for Box<dyn DynProtocolHandler>"]]],["iroh_base",[["impl From<(PublicKey, Option<RelayUrl>, &[SocketAddr])> for NodeAddr"],["impl From<Url> for RelayUrl"],["impl From<NodeAddr> for NodeTicket"],["impl From<PublicKey> for NodeAddr"],["impl From<RelayUrl> for Url"],["impl From<NodeTicket> for NodeAddr"],["impl From<DecodeError> for KeyParsingError"],["impl From<DecodeError> for ParseError"],["impl From<Error> for KeyParsingError"],["impl From<Error> for ParseError"],["impl From<SigningKey> for SecretKey"],["impl From<VerifyingKey> for PublicKey"],["impl From<[u8; 32]> for SecretKey"]]],["iroh_relay",[["impl From<DialError> for ConnectError"],["impl From<SendError> for SendError"],["impl From<DnsError> for DialError"],["impl From<DecodingError> for ParseError"],["impl From<FrameType> for u8"],["impl From<RecvError> for RecvError"],["impl From<SendError> for ConnectError"],["impl From<SendError> for RecvError"],["impl From<u8> for FrameType"],["impl From<Error> for DialError"],["impl From<Error> for RecvError"],["impl From<Error> for SendError"],["impl From<Error> for RecvError"],["impl From<Error> for SendError"],["impl From<NodeInfo> for NodeAddr"],["impl From<RelayNode> for RelayMap"],["impl From<ConnectError> for Error"],["impl From<ConnectionError> for Error"],["impl From<Elapsed> for DialError"],["impl From<Elapsed> for DnsError"],["impl From<Elapsed> for RecvError"],["impl From<Elapsed> for SendError"],["impl From<Error> for ConnectError"],["impl From<Error> for RecvError"],["impl From<Error> for SendError"],["impl From<Error> for RecvError"],["impl From<Error> for RecvError"],["impl From<Error> for SendError"],["impl From<JoinError> for SupervisorError"],["impl From<NodeAddr> for NodeData"],["impl From<NodeAddr> for NodeInfo"],["impl From<RecvError> for Error"],["impl From<RelayUrl> for RelayMap"],["impl From<RelayUrl> for RelayNode"],["impl From<ResolveError> for DnsError"],["impl From<Resolver<GenericConnector<TokioRuntimeProvider>>> for DnsResolver"],["impl From<SignedPacketBuildError> for EncodingError"],["impl From<TxtLookup> for TxtLookup"]]]]);
if (window.register_implementors) {
window.register_implementors(implementors);
} else {
window.pending_implementors = implementors;
}
})()
-//{"start":57,"fragment_lengths":[7257,4938,13608]}
\ No newline at end of file
+//{"start":57,"fragment_lengths":[7257,4938,12998]}
\ No newline at end of file
diff --git a/pr/3381/docs/trait.impl/core/iter/traits/collect/trait.FromIterator.js b/pr/3381/docs/trait.impl/core/iter/traits/collect/trait.FromIterator.js
index 8cd585bc9e..d104c409e3 100644
--- a/pr/3381/docs/trait.impl/core/iter/traits/collect/trait.FromIterator.js
+++ b/pr/3381/docs/trait.impl/core/iter/traits/collect/trait.FromIterator.js
@@ -1,9 +1,9 @@
(function() {
- var implementors = Object.fromEntries([["iroh_relay",[["impl FromIterator<RelayUrl> for RelayMap"],["impl FromIterator<RelayNode> for RelayMap"]]]]);
+ var implementors = Object.fromEntries([["iroh_relay",[["impl FromIterator<RelayNode> for RelayMap"],["impl FromIterator<RelayUrl> for RelayMap"]]]]);
if (window.register_implementors) {
window.register_implementors(implementors);
} else {
window.pending_implementors = implementors;
}
})()
-//{"start":57,"fragment_lengths":[898]}
\ No newline at end of file
+//{"start":57,"fragment_lengths":[776]}
\ No newline at end of file
pub struct DirectAddr {
+DirectAddr in iroh::endpoint - Rust 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: SocketAddrThe address.
§typ: DirectAddrTypeThe origin of this direct address.
-Trait Implementations§
Source§impl Clone for DirectAddr
Source§fn clone(&self) -> DirectAddr
Returns a copy of the value. Read more1.0.0 · Source§fn clone_from(&mut self, source: &Self)
Performs copy-assignment from source. Read moreSource§impl Debug for DirectAddr
Source§impl Hash for DirectAddr
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 more1.0.0 · Source§fn clone_from(&mut self, source: &Self)
Performs copy-assignment from source. Read moreSource§impl Debug for DirectAddr
Source§impl Hash for DirectAddr
Source§impl Ord for DirectAddr
Source§impl Ord for DirectAddr
Source§fn cmp(&self, other: &DirectAddr) -> Ordering
1.21.0 · Source§fn max(self, other: Self) -> Selfwhere
Self: Sized,
Compares and returns the maximum of two values. Read moreSource§impl PartialEq for DirectAddr
Source§impl PartialOrd for DirectAddr
Source§impl PartialEq for DirectAddr
Source§impl PartialOrd for DirectAddr
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 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§
§impl<'a, T, E> AsTaggedExplicit<'a, E> for Twhere
T: 'a,
§impl<'a, T, E> AsTaggedImplicit<'a, E> for Twhere
T: 'a,
§fn implicit(
diff --git a/pr/3381/docs/iroh_relay/client/enum.ReceivedMessage.html b/pr/3381/docs/iroh_relay/client/enum.ReceivedMessage.html
index d67f15652a..d204d79567 100644
--- a/pr/3381/docs/iroh_relay/client/enum.ReceivedMessage.html
+++ b/pr/3381/docs/iroh_relay/client/enum.ReceivedMessage.html
@@ -1,9 +1,9 @@
ReceivedMessage in iroh_relay::client - Rust pub enum ReceivedMessage {
ReceivedPacket {
- remote_node_id: NodeId,
+ remote_node_id: NodeId,
data: Bytes,
},
- NodeGone(NodeId),
+ NodeGone(NodeId),
Ping([u8; 8]),
Pong([u8; 8]),
KeepAlive,
@@ -17,9 +17,9 @@
}
Expand description
The messages received from a framed relay stream.
This is a type-validated version of the Frames on the RelayCodec.
Variants§
§ReceivedPacket
Represents an incoming packet.
-Fields
§NodeGone(NodeId)
Indicates that the client identified by the underlying public key had previously sent you a
packet but has now disconnected from the server.
§Ping([u8; 8])
Request from a client or server to reply to the
other side with a ReceivedMessage::Pong with the given payload.
diff --git a/pr/3381/docs/iroh_relay/client/enum.SendMessage.html b/pr/3381/docs/iroh_relay/client/enum.SendMessage.html
index 1efae8feee..b6279d244c 100644
--- a/pr/3381/docs/iroh_relay/client/enum.SendMessage.html
+++ b/pr/3381/docs/iroh_relay/client/enum.SendMessage.html
@@ -1,9 +1,9 @@
SendMessage in iroh_relay::client - Rust pub enum SendMessage {
- SendPacket(NodeId, Bytes),
+ SendPacket(NodeId, Bytes),
Ping([u8; 8]),
Pong([u8; 8]),
}
Expand description
Messages we can send to a relay server.
-Variants§
§SendPacket(NodeId, Bytes)
Send a packet of data to the NodeId.
+Variants§
§SendPacket(NodeId, Bytes)
Send a packet of data to the [NodeId].
§Ping([u8; 8])
Sends a ping message to the connected relay server.
§Pong([u8; 8])
Sends a pong message to the connected relay server.
Trait Implementations§
Source§impl Debug for SendMessage
Source§impl Sink<SendMessage> for Client
Source§fn poll_ready(
diff --git a/pr/3381/docs/iroh_relay/client/struct.ClientBuilder.html b/pr/3381/docs/iroh_relay/client/struct.ClientBuilder.html
index 26ccff11ea..bfafcd37c8 100644
--- a/pr/3381/docs/iroh_relay/client/struct.ClientBuilder.html
+++ b/pr/3381/docs/iroh_relay/client/struct.ClientBuilder.html
@@ -1,7 +1,7 @@
ClientBuilder in iroh_relay::client - Rust pub struct ClientBuilder { /* private fields */ }
Expand description
Build a Client.
Implementations§
Source§impl ClientBuilder
Sourcepub fn new(
- url: impl Into<RelayUrl>,
- secret_key: SecretKey,
+ url: impl Into<RelayUrl>,
+ secret_key: SecretKey,
dns_resolver: DnsResolver,
) -> Self
Create a new ClientBuilder
Sourcepub fn protocol(self, protocol: Protocol) -> Self
Sets whether to connect to the relay via websockets or not.
diff --git a/pr/3381/docs/iroh_relay/dns/struct.DnsResolver.html b/pr/3381/docs/iroh_relay/dns/struct.DnsResolver.html
index f9da8945f9..f83d48fca0 100644
--- a/pr/3381/docs/iroh_relay/dns/struct.DnsResolver.html
+++ b/pr/3381/docs/iroh_relay/dns/struct.DnsResolver.html
@@ -68,9 +68,9 @@ at T+0ms, T+200ms and T+300ms. The timeout is applied as stated in
summary of all errors otherwise.
Sourcepub async fn lookup_node_by_id(
&self,
- node_id: &NodeId,
+ node_id: &NodeId,
origin: &str,
-) -> Result<NodeInfo, LookupError>
Looks up node info by NodeId and origin domain name.
+) -> Result<NodeInfo, LookupError>Looks up node info by [NodeId] and origin domain name.
To lookup nodes that published their node info to the DNS servers run by n0,
pass N0_DNS_NODE_ORIGIN_PROD as origin.
Sourcepub async fn lookup_node_by_domain_name(
@@ -88,10 +88,10 @@ at T+0ms, T+200ms and T+300ms. The result of the first successful call is return
summary of all errors otherwise.
Sourcepub async fn lookup_node_by_id_staggered(
&self,
- node_id: &NodeId,
+ node_id: &NodeId,
origin: &str,
delays_ms: &[u64],
-) -> Result<NodeInfo, StaggeredError<LookupError>>
Looks up node info by NodeId and origin domain name.
+) -> Result<NodeInfo, StaggeredError<LookupError>>Looks up node info by [NodeId] and origin domain name.
From the moment this function is called, each lookup is scheduled after the delays in
delays_ms with the first call being done immediately. [200ms, 300ms] results in calls
at T+0ms, T+200ms and T+300ms. The result of the first successful call is returned, or a
diff --git a/pr/3381/docs/iroh_relay/index.html b/pr/3381/docs/iroh_relay/index.html
index 0dffafd7bb..a95da1d81a 100644
--- a/pr/3381/docs/iroh_relay/index.html
+++ b/pr/3381/docs/iroh_relay/index.html
@@ -25,6 +25,6 @@ Tailscale.
QAD support and expose metrics.
-Re-exports§
pub use protos::relay::MAX_PACKET_SIZE;
Modules§
- client
- Exposes
Client, which allows to establish connections to a relay server. - defaults
- Default values used in the relay.
- dns
Non-wasm_browser - DNS resolver
- http
- HTTP-specific constants for the relay server and client.
- node_
info - Support for handling DNS resource records for dialing by
NodeId. - protos
- Protocols used by the iroh-relay
- quic
- Create a QUIC server that accepts connections
+
Re-exports§
pub use protos::relay::MAX_PACKET_SIZE;
Modules§
- client
- Exposes
Client, which allows to establish connections to a relay server. - defaults
- Default values used in the relay.
- dns
Non-wasm_browser - DNS resolver
- http
- HTTP-specific constants for the relay server and client.
- node_
info - Support for handling DNS resource records for dialing by [
NodeId]. - protos
- Protocols used by the iroh-relay
- quic
- Create a QUIC server that accepts connections
for QUIC address discovery.
- server
server - A fully-fledged iroh-relay server over HTTP or HTTPS.
Structs§
- Ping
Tracker - Tracks pings on a single relay connection.
- Relay
Map - Configuration of all the relay servers that can be used.
- Relay
Node - Information on a specific relay server.
- Relay
QuicConfig - Configuration for speaking to the QUIC endpoint on the relay
server to do QUIC address discovery.
\ No newline at end of file
diff --git a/pr/3381/docs/iroh_relay/node_info/index.html b/pr/3381/docs/iroh_relay/node_info/index.html
index 35bc283b6f..48e4910fda 100644
--- a/pr/3381/docs/iroh_relay/node_info/index.html
+++ b/pr/3381/docs/iroh_relay/node_info/index.html
@@ -1,5 +1,5 @@
-iroh_relay::node_info - Rust Expand description
Support for handling DNS resource records for dialing by NodeId.
-Dialing by NodeId is supported by iroh nodes publishing Pkarr records to DNS
+
iroh_relay::node_info - Rust Expand description
Support for handling DNS resource records for dialing by [NodeId].
+Dialing by [NodeId] is supported by iroh nodes publishing Pkarr records to DNS
servers or the Mainline DHT. This module supports creating and parsing these records.
DNS records are published under the following names:
_iroh.<z32-node-id>.<origin-domain> TXT
@@ -8,7 +8,7 @@ servers or the Mainline DHT. This module supports creating and parsing these re
_iroh is the record name as defined by IROH_TXT_NAME.
-<z32-node-id> is the z-base-32 encoding of the NodeId.
+<z32-node-id> is the z-base-32 encoding of the [NodeId].
<origin-domain> is the domain name of the publishing DNS server,
@@ -23,12 +23,12 @@ servers or the Mainline DHT. This module supports creating and parsing these re
in RFC1464. The following attributes are defined:
- Structs§
- MaxLength
ExceededError - Error returned when an input value is too long for
UserData. - Node
Data - Data about a node that may be published to and resolved from discovery services.
- Node
Info - Information about a node that may be published to and resolved from discovery services.
- User
Data - Under the hood this is a UTF-8 String is no longer than
UserData::MAX_LENGTH bytes.
Enums§
- Decoding
Error - Encoding
Error - Lookup
Error Non-wasm_browser - Parse
Error
Constants§
- IROH_
TXT_NAME - The DNS name for the iroh TXT record.
Traits§
Structs§
- MaxLength
ExceededError - Error returned when an input value is too long for
UserData. - Node
Data - Data about a node that may be published to and resolved from discovery services.
- Node
Info - Information about a node that may be published to and resolved from discovery services.
- User
Data - Under the hood this is a UTF-8 String is no longer than
UserData::MAX_LENGTH bytes.
Enums§
- Decoding
Error - Encoding
Error - Lookup
Error Non-wasm_browser - Parse
Error
Constants§
- IROH_
TXT_NAME - The DNS name for the iroh TXT record.
Traits§
- Node
IdExt - Extension methods for [
NodeId] to encode to and decode from [z32],
which is the encoding used in [pkarr] domain names.
\ No newline at end of file
diff --git a/pr/3381/docs/iroh_relay/node_info/struct.NodeData.html b/pr/3381/docs/iroh_relay/node_info/struct.NodeData.html
index c0ab566f79..5e8b8f53c0 100644
--- a/pr/3381/docs/iroh_relay/node_info/struct.NodeData.html
+++ b/pr/3381/docs/iroh_relay/node_info/struct.NodeData.html
@@ -1,20 +1,20 @@
NodeData in iroh_relay::node_info - Rust pub struct NodeData { /* private fields */ }
Expand description
Data about a node that may be published to and resolved from discovery services.
-This includes an optional RelayUrl, a set of direct addresses, and the optional
+
This includes an optional [RelayUrl], a set of direct addresses, and the optional
UserData, a string that can be set by applications and is not parsed or used by iroh
itself.
-This struct does not include the node’s NodeId, only the data about a certain
-node. See NodeInfo for a struct that contains a NodeId with associated NodeData.
+This struct does not include the node’s [NodeId], only the data about a certain
+node. See NodeInfo for a struct that contains a [NodeId] with associated NodeData.
Implementations§
Source§impl NodeData
Sourcepub fn new(
- relay_url: Option<RelayUrl>,
+ relay_url: Option<RelayUrl>,
direct_addresses: BTreeSet<SocketAddr>,
) -> Self
Creates a new NodeData with a relay URL and a set of direct addresses.
-Sourcepub fn with_relay_url(self, relay_url: Option<RelayUrl>) -> Self
Sets the relay URL and returns the updated node data.
+Sourcepub fn with_relay_url(self, relay_url: Option<RelayUrl>) -> Self
Sets the relay URL and returns the updated node data.
Sourcepub fn with_direct_addresses(
self,
direct_addresses: BTreeSet<SocketAddr>,
) -> Self
Sets the direct addresses and returns the updated node data.
Sourcepub fn with_user_data(self, user_data: Option<UserData>) -> Self
Sets the user-defined data and returns the updated node data.
-Sourcepub fn user_data(&self) -> Option<&UserData>
Returns the optional user-defined data of the node.
Sourcepub fn direct_addresses(&self) -> &BTreeSet<SocketAddr>
Returns the direct addresses of the node.
Sourcepub fn clear_direct_addresses(&mut self)
Removes all direct addresses from the node data.
@@ -22,9 +22,9 @@ node. See IntoIterator<Item = SocketAddr>,
)Adds direct addresses to the node data.
-Sourcepub fn set_relay_url(&mut self, relay_url: Option<RelayUrl>)
Sets the relay URL of the node data.
+Sourcepub fn set_relay_url(&mut self, relay_url: Option<RelayUrl>)
Sets the relay URL of the node data.
Sourcepub fn set_user_data(&mut self, user_data: Option<UserData>)
Sets the user-defined data of the node data.
-Trait Implementations§
Trait Implementations§
Source§impl Eq for NodeData
Source§impl StructuralPartialEq for NodeData
Auto Trait Implementations§
§impl Freeze for NodeData
§impl RefUnwindSafe for NodeData
§impl Send for NodeData
§impl Sync for NodeData
§impl Unpin for NodeData
§impl UnwindSafe for NodeData
Blanket Implementations§
§impl<'a, T, E> AsTaggedExplicit<'a, E> for Twhere
T: 'a,
§impl<'a, T, E> AsTaggedImplicit<'a, E> for Twhere
diff --git a/pr/3381/docs/iroh_relay/node_info/struct.NodeInfo.html b/pr/3381/docs/iroh_relay/node_info/struct.NodeInfo.html
index 6b5ba1f068..28fba3c4c9 100644
--- a/pr/3381/docs/iroh_relay/node_info/struct.NodeInfo.html
+++ b/pr/3381/docs/iroh_relay/node_info/struct.NodeInfo.html
@@ -1,32 +1,32 @@
NodeInfo in iroh_relay::node_info - Rust pub struct NodeInfo {
- pub node_id: NodeId,
+ pub node_id: NodeId,
pub data: NodeData,
}
Expand description
Fields§
§node_id: NodeIdThe NodeId of the node this is about.
+This struct couples a [NodeId] with its associated NodeData.
+Fields§
§node_id: NodeIdThe [NodeId] of the node this is about.
§data: NodeDataThe information published about the node.
-Implementations§
Source§impl NodeInfo
Sourcepub fn from_parts(node_id: NodeId, data: NodeData) -> Self
Creates a new NodeInfo from its parts.
-Sourcepub fn with_relay_url(self, relay_url: Option<RelayUrl>) -> Self
Sets the relay URL and returns the updated node info.
+Implementations§
Source§impl NodeInfo
Sourcepub fn from_parts(node_id: NodeId, data: NodeData) -> Self
Creates a new NodeInfo from its parts.
+Sourcepub fn with_relay_url(self, relay_url: Option<RelayUrl>) -> Self
Sets the relay URL and returns the updated node info.
Sourcepub fn with_direct_addresses(
self,
direct_addresses: BTreeSet<SocketAddr>,
) -> Self
Sets the direct addresses and returns the updated node info.
Sourcepub fn with_user_data(self, user_data: Option<UserData>) -> Self
Sets the user-defined data and returns the updated node info.
-Sourcepub fn to_node_addr(&self) -> NodeAddr
Converts into a NodeAddr by cloning the needed fields.
-Sourcepub fn into_node_addr(self) -> NodeAddr
Converts into a NodeAddr without cloning.
+Sourcepub fn to_node_addr(&self) -> NodeAddr
Converts into a [NodeAddr] by cloning the needed fields.
+Sourcepub fn into_node_addr(self) -> NodeAddr
Converts into a [NodeAddr] without cloning.
Sourcepub fn from_txt_lookup(lookup: TxtLookup) -> Result<Self, ParseError>
Available on non-wasm_browser only.
Parses a NodeInfo from a TXT records lookup.
Sourcepub fn from_pkarr_signed_packet(
packet: &SignedPacket,
) -> Result<Self, ParseError>
Parses a NodeInfo from a [pkarr::SignedPacket].
Sourcepub fn to_pkarr_signed_packet(
&self,
- secret_key: &SecretKey,
+ secret_key: &SecretKey,
ttl: u32,
) -> Result<SignedPacket, EncodingError>
Creates a [pkarr::SignedPacket].
-This constructs a DNS packet and signs it with a SecretKey.
+This constructs a DNS packet and signs it with a [SecretKey].
Sourcepub fn to_txt_strings(&self) -> Vec<String>
Converts into a list of {key}={value} strings.
-Methods from Deref<Target = NodeData>§
Sourcepub fn user_data(&self) -> Option<&UserData>
Returns the optional user-defined data of the node.
Sourcepub fn direct_addresses(&self) -> &BTreeSet<SocketAddr>
Returns the direct addresses of the node.
Sourcepub fn clear_direct_addresses(&mut self)
Removes all direct addresses from the node data.
@@ -34,9 +34,9 @@
&mut self,
addrs: impl IntoIterator<Item = SocketAddr>,
)Adds direct addresses to the node data.
-Sourcepub fn set_relay_url(&mut self, relay_url: Option<RelayUrl>)
Sets the relay URL of the node data.
+Sourcepub fn set_relay_url(&mut self, relay_url: Option<RelayUrl>)
Sets the relay URL of the node data.
Sourcepub fn set_user_data(&mut self, user_data: Option<UserData>)
Sets the user-defined data of the node data.
-Trait Implementations§
Trait Implementations§
Source§impl Eq for NodeInfo
Source§impl StructuralPartialEq for NodeInfo
Auto Trait Implementations§
§impl Freeze for NodeInfo
§impl RefUnwindSafe for NodeInfo
§impl Send for NodeInfo
§impl Sync for NodeInfo
§impl Unpin for NodeInfo
§impl UnwindSafe for NodeInfo
Blanket Implementations§
§impl<'a, T, E> AsTaggedExplicit<'a, E> for Twhere
T: 'a,
§impl<'a, T, E> AsTaggedImplicit<'a, E> for Twhere
diff --git a/pr/3381/docs/iroh_relay/node_info/trait.NodeIdExt.html b/pr/3381/docs/iroh_relay/node_info/trait.NodeIdExt.html
index b4a8808135..d668a07cef 100644
--- a/pr/3381/docs/iroh_relay/node_info/trait.NodeIdExt.html
+++ b/pr/3381/docs/iroh_relay/node_info/trait.NodeIdExt.html
@@ -1,9 +1,9 @@
NodeIdExt in iroh_relay::node_info - Rust pub trait NodeIdExt {
// Required methods
fn to_z32(&self) -> String;
- fn from_z32(s: &str) -> Result<NodeId, DecodingError>;
-}
Expand description
Extension methods for NodeId to encode to and decode from [z32],
+ fn from_z32(s: &str) -> Result<NodeId, DecodingError>;
+}Expand description
Extension methods for [NodeId] to encode to and decode from [z32],
which is the encoding used in [pkarr] domain names.
-
Required Methods§
Dyn Compatibility§
This trait is not dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.
Implementations on Foreign Types§
Implementors§
\ No newline at end of file
+Required Methods§
Sourcefn from_z32(s: &str) -> Result<NodeId, DecodingError>
Parses a [NodeId] from [z-base-32] encoding.
+Dyn Compatibility§
This trait is not dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.
Implementations on Foreign Types§
Implementors§
\ No newline at end of file
diff --git a/pr/3381/docs/iroh_relay/server/enum.AccessConfig.html b/pr/3381/docs/iroh_relay/server/enum.AccessConfig.html
index c318e01200..9c6c400b3e 100644
--- a/pr/3381/docs/iroh_relay/server/enum.AccessConfig.html
+++ b/pr/3381/docs/iroh_relay/server/enum.AccessConfig.html
@@ -1,10 +1,10 @@
AccessConfig in iroh_relay::server - Rust pub enum AccessConfig {
Everyone,
- Restricted(Box<dyn Fn(NodeId) -> Boxed<Access> + Send + Sync + 'static>),
+ Restricted(Box<dyn Fn(NodeId) -> Boxed<Access> + Send + Sync + 'static>),
}
Available on crate feature server only.Expand description
Controls which nodes are allowed to use the relay.
Variants§
§Everyone
Everyone
-§Restricted(Box<dyn Fn(NodeId) -> Boxed<Access> + Send + Sync + 'static>)
Only nodes for which the function returns Access::Allow.
-Implementations§
Source§impl AccessConfig
Implementations§
Source§impl AccessConfig
Sourcepub async fn is_allowed(&self, node: NodeId) -> bool
Is this node allowed?
Trait Implementations§
Auto Trait Implementations§
§impl Freeze for AccessConfig
§impl !RefUnwindSafe for AccessConfig
§impl Send for AccessConfig
§impl Sync for AccessConfig
§impl Unpin for AccessConfig
§impl !UnwindSafe for AccessConfig
Blanket Implementations§
§impl<'a, T, E> AsTaggedExplicit<'a, E> for Twhere
T: 'a,
§impl<'a, T, E> AsTaggedImplicit<'a, E> for Twhere
diff --git a/pr/3381/docs/iroh_relay/server/struct.Server.html b/pr/3381/docs/iroh_relay/server/struct.Server.html
index 33a6a8b24f..1d0dc22b7b 100644
--- a/pr/3381/docs/iroh_relay/server/struct.Server.html
+++ b/pr/3381/docs/iroh_relay/server/struct.Server.html
@@ -17,9 +17,9 @@ case there is an error in the server before it is shut down.
Sourcepub fn http_addr(&self) -> Option<SocketAddr>
The socket address the HTTP server is listening on.
Sourcepub fn quic_addr(&self) -> Option<SocketAddr>
The socket address the QUIC server is listening on.
Sourcepub fn certificates(&self) -> Option<Vec<CertificateDer<'static>>>
The certificates chain if configured with manual TLS certificates.
-Sourcepub fn https_url(&self) -> Option<RelayUrl>
Available on crate feature test-utils only.
Get the server’s https RelayUrl.
+Sourcepub fn https_url(&self) -> Option<RelayUrl>
Available on crate feature test-utils only.
Get the server’s https [RelayUrl].
This uses Self::https_addr so it’s mostly useful for local development.
-Sourcepub fn http_url(&self) -> Option<RelayUrl>
Available on crate feature test-utils only.
Get the server’s http RelayUrl.
+Sourcepub fn http_url(&self) -> Option<RelayUrl>
Available on crate feature test-utils only.
Get the server’s http [RelayUrl].
This uses Self::http_addr so it’s mostly useful for local development.
Sourcepub fn metrics(&self) -> &RelayMetrics
Returns the metrics collected in the relay server.
Trait Implementations§
Auto Trait Implementations§
§impl Freeze for Server
§impl RefUnwindSafe for Server
§impl Send for Server
§impl Sync for Server
§impl Unpin for Server
§impl UnwindSafe for Server
Blanket Implementations§
Source§impl<T> Any for Twhere
diff --git a/pr/3381/docs/iroh_relay/struct.RelayMap.html b/pr/3381/docs/iroh_relay/struct.RelayMap.html
index b284268144..8ab9e60978 100644
--- a/pr/3381/docs/iroh_relay/struct.RelayMap.html
+++ b/pr/3381/docs/iroh_relay/struct.RelayMap.html
@@ -1,15 +1,15 @@
RelayMap in iroh_relay - Rust pub struct RelayMap { /* private fields */ }
Expand description
Configuration of all the relay servers that can be used.
-Implementations§
Source§impl RelayMap
Implementations§
Trait Implementations§
Trait Implementations§
Source§impl FromIterator<RelayNode> for RelayMap
Source§impl FromIterator<RelayUrl> for RelayMap
Source§impl FromIterator<RelayNode> for RelayMap
Source§impl FromIterator<RelayUrl> for RelayMap
Source§impl PartialEq for RelayMap
Source§fn eq(&self, other: &RelayMap) -> 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,
diff --git a/pr/3381/docs/iroh_relay/struct.RelayNode.html b/pr/3381/docs/iroh_relay/struct.RelayNode.html
index 2c5ac7dc6c..588d10e2b3 100644
--- a/pr/3381/docs/iroh_relay/struct.RelayNode.html
+++ b/pr/3381/docs/iroh_relay/struct.RelayNode.html
@@ -1,14 +1,14 @@
RelayNode in iroh_relay - Rust pub struct RelayNode {
- pub url: RelayUrl,
+ pub url: RelayUrl,
pub quic: Option<RelayQuicConfig>,
}
Expand description
Information on a specific relay server.
Includes the Url where it can be dialed.
-Fields§
§url: RelayUrlThe RelayUrl where this relay server can be dialed.
+Fields§
§url: RelayUrlThe [RelayUrl] where this relay server can be dialed.
§quic: Option<RelayQuicConfig>Configuration to speak to the QUIC endpoint on the relay server.
When None, we will not attempt to do QUIC address discovery
with this relay server.
Trait Implementations§
Source§impl<'de> Deserialize<'de> for RelayNode
Source§fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>where
- __D: Deserializer<'de>,
Deserialize this value from the given Serde deserializer. Read moreSource§impl FromIterator<RelayNode> for RelayMap
Source§impl FromIterator<RelayNode> for RelayMap
Source§impl Ord for RelayNode
Source§impl PartialEq for RelayNode
Source§fn eq(&self, other: &RelayNode) -> 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,
diff --git a/pr/3381/docs/src/iroh/magicsock.rs.html b/pr/3381/docs/src/iroh/magicsock.rs.html
index 5dabf264a0..f2d76f1aad 100644
--- a/pr/3381/docs/src/iroh/magicsock.rs.html
+++ b/pr/3381/docs/src/iroh/magicsock.rs.html
@@ -471,2961 +471,2956 @@
471 let conn = conn.clone();
472 let addr = addr.private_socket_addr();
473 task::spawn(async move {
-474 match conn
-475 .open_path(addr, quinn_proto::PathStatus::Available)
-476 .await
-477 {
-478 Ok(path) => {
-479 path.set_max_idle_timeout(Some(
-480 ENDPOINTS_FRESH_ENOUGH_DURATION,
-481 ))
-482 .ok();
-483 path.set_keep_alive_interval(Some(HEARTBEAT_INTERVAL)).ok();
-484 }
-485 Err(err) => {
-486 warn!("failed to open path {:?}", err);
-487 }
-488 }
-489 });
-490 }
-491 } else {
-492 to_delete.push(i);
-493 }
-494 }
-495 // cleanup dead connections
-496 let mut i = 0;
-497 conns.retain(|_| {
-498 let remove = to_delete.contains(&i);
-499 i += 1;
+474 match conn.open_path(addr, quinn_proto::PathStatus::Backup).await {
+475 Ok(path) => {
+476 // Keep the relay path open
+477 path.set_max_idle_timeout(None).ok();
+478 path.set_keep_alive_interval(None).ok();
+479 }
+480 Err(err) => {
+481 warn!("failed to open path {:?}", err);
+482 }
+483 }
+484 });
+485 }
+486 } else {
+487 to_delete.push(i);
+488 }
+489 }
+490 // cleanup dead connections
+491 let mut i = 0;
+492 conns.retain(|_| {
+493 let remove = to_delete.contains(&i);
+494 i += 1;
+495
+496 !remove
+497 });
+498 }
+499 }
500
-501 !remove
-502 });
-503 }
-504 }
-505
-506 /// Stores a new set of direct addresses.
-507 ///
-508 /// If the direct addresses have changed from the previous set, they are published to
-509 /// discovery.
-510 pub(super) fn store_direct_addresses(&self, addrs: BTreeSet<DirectAddr>) {
-511 let updated = self.direct_addrs.update(addrs);
-512 if updated {
-513 self.node_map
-514 .on_direct_addr_discovered(self.direct_addrs.sockaddrs());
-515 self.publish_my_addr();
-516 }
-517 }
-518
-519 /// Get a reference to the DNS resolver used in this [`MagicSock`].
-520 #[cfg(not(wasm_browser))]
-521 pub(crate) fn dns_resolver(&self) -> &DnsResolver {
-522 &self.dns_resolver
+501 /// Stores a new set of direct addresses.
+502 ///
+503 /// If the direct addresses have changed from the previous set, they are published to
+504 /// discovery.
+505 pub(super) fn store_direct_addresses(&self, addrs: BTreeSet<DirectAddr>) {
+506 let updated = self.direct_addrs.update(addrs);
+507 if updated {
+508 self.node_map
+509 .on_direct_addr_discovered(self.direct_addrs.sockaddrs());
+510 self.publish_my_addr();
+511 }
+512 }
+513
+514 /// Get a reference to the DNS resolver used in this [`MagicSock`].
+515 #[cfg(not(wasm_browser))]
+516 pub(crate) fn dns_resolver(&self) -> &DnsResolver {
+517 &self.dns_resolver
+518 }
+519
+520 /// Reference to optional discovery service
+521 pub(crate) fn discovery(&self) -> Option<&dyn Discovery> {
+522 self.discovery.as_ref().map(Box::as_ref)
523 }
524
-525 /// Reference to optional discovery service
-526 pub(crate) fn discovery(&self) -> Option<&dyn Discovery> {
-527 self.discovery.as_ref().map(Box::as_ref)
-528 }
-529
-530 /// Updates the user-defined discovery data for this node.
-531 pub(crate) fn set_user_data_for_discovery(&self, user_data: Option<UserData>) {
-532 let mut guard = self.discovery_user_data.write().expect("lock poisened");
-533 if *guard != user_data {
-534 *guard = user_data;
-535 drop(guard);
-536 self.publish_my_addr();
-537 }
-538 }
-539
-540 /// Call to notify the system of potential network changes.
-541 pub(crate) async fn network_change(&self) {
-542 self.actor_sender
-543 .send(ActorMessage::NetworkChange)
-544 .await
-545 .ok();
+525 /// Updates the user-defined discovery data for this node.
+526 pub(crate) fn set_user_data_for_discovery(&self, user_data: Option<UserData>) {
+527 let mut guard = self.discovery_user_data.write().expect("lock poisened");
+528 if *guard != user_data {
+529 *guard = user_data;
+530 drop(guard);
+531 self.publish_my_addr();
+532 }
+533 }
+534
+535 /// Call to notify the system of potential network changes.
+536 pub(crate) async fn network_change(&self) {
+537 self.actor_sender
+538 .send(ActorMessage::NetworkChange)
+539 .await
+540 .ok();
+541 }
+542
+543 /// Returns a reference to the subscribers channel for discovery events.
+544 pub(crate) fn discovery_subscribers(&self) -> &DiscoverySubscribers {
+545 &self.discovery_subscribers
546 }
547
-548 /// Returns a reference to the subscribers channel for discovery events.
-549 pub(crate) fn discovery_subscribers(&self) -> &DiscoverySubscribers {
-550 &self.discovery_subscribers
-551 }
-552
-553 #[cfg(test)]
-554 async fn force_network_change(&self, is_major: bool) {
-555 self.actor_sender
-556 .send(ActorMessage::ForceNetworkChange(is_major))
-557 .await
-558 .ok();
-559 }
-560
-561 #[cfg_attr(windows, allow(dead_code))]
-562 fn normalized_local_addr(&self) -> io::Result<SocketAddr> {
-563 let addrs = self.local_addrs_watch.get().expect("disconnected");
-564
-565 let mut ipv4_addr = None;
-566 for addr in addrs {
-567 let Some(addr) = addr.into_socket_addr() else {
-568 continue;
-569 };
-570 if addr.is_ipv6() {
-571 return Ok(addr);
-572 }
-573 if addr.is_ipv4() && ipv4_addr.is_none() {
-574 ipv4_addr.replace(addr);
-575 }
-576 }
-577 match ipv4_addr {
-578 Some(addr) => Ok(addr),
-579 None => Err(io::Error::other("no valid socket available")),
-580 }
-581 }
-582
-583 /// Searches the `node_map` to determine the current transports to be used.
-584 #[instrument(skip_all)]
-585 fn prepare_send(
-586 &self,
-587 transmit: &quinn_udp::Transmit,
-588 ) -> io::Result<SmallVec<[transports::Addr; 3]>> {
-589 self.metrics
-590 .magicsock
-591 .send_data
-592 .inc_by(transmit.contents.len() as _);
-593
-594 if self.is_closed() {
-595 self.metrics
-596 .magicsock
-597 .send_data_network_down
-598 .inc_by(transmit.contents.len() as _);
-599 return Err(io::Error::new(
-600 io::ErrorKind::NotConnected,
-601 "connection closed",
-602 ));
-603 }
-604
-605 let mut active_paths = SmallVec::<[_; 3]>::new();
-606
-607 match MappedAddr::from(transmit.destination) {
-608 MappedAddr::None(addr) => {
-609 active_paths.push(transports::Addr::from(addr));
-610 }
-611 MappedAddr::NodeId(dest) => {
-612 trace!(
-613 dst = %dest,
-614 src = ?transmit.src_ip,
-615 len = %transmit.contents.len(),
-616 "sending",
-617 );
-618
-619 // Get the node's relay address and best direct address, as well
-620 // as any pings that need to be sent for hole-punching purposes.
-621 match self.node_map.get_send_addrs(
-622 dest,
-623 self.ipv6_reported.load(Ordering::Relaxed),
-624 &self.metrics.magicsock,
-625 ) {
-626 Some((node_id, _udp_addr, relay_url, ping_actions)) => {
-627 if !ping_actions.is_empty() {
-628 self.actor_sender
-629 .try_send(ActorMessage::PingActions(ping_actions))
-630 .ok();
+548 #[cfg(test)]
+549 async fn force_network_change(&self, is_major: bool) {
+550 self.actor_sender
+551 .send(ActorMessage::ForceNetworkChange(is_major))
+552 .await
+553 .ok();
+554 }
+555
+556 #[cfg_attr(windows, allow(dead_code))]
+557 fn normalized_local_addr(&self) -> io::Result<SocketAddr> {
+558 let addrs = self.local_addrs_watch.get().expect("disconnected");
+559
+560 let mut ipv4_addr = None;
+561 for addr in addrs {
+562 let Some(addr) = addr.into_socket_addr() else {
+563 continue;
+564 };
+565 if addr.is_ipv6() {
+566 return Ok(addr);
+567 }
+568 if addr.is_ipv4() && ipv4_addr.is_none() {
+569 ipv4_addr.replace(addr);
+570 }
+571 }
+572 match ipv4_addr {
+573 Some(addr) => Ok(addr),
+574 None => Err(io::Error::other("no valid socket available")),
+575 }
+576 }
+577
+578 /// Searches the `node_map` to determine the current transports to be used.
+579 #[instrument(skip_all)]
+580 fn prepare_send(
+581 &self,
+582 transmit: &quinn_udp::Transmit,
+583 ) -> io::Result<SmallVec<[transports::Addr; 3]>> {
+584 self.metrics
+585 .magicsock
+586 .send_data
+587 .inc_by(transmit.contents.len() as _);
+588
+589 if self.is_closed() {
+590 self.metrics
+591 .magicsock
+592 .send_data_network_down
+593 .inc_by(transmit.contents.len() as _);
+594 return Err(io::Error::new(
+595 io::ErrorKind::NotConnected,
+596 "connection closed",
+597 ));
+598 }
+599
+600 let mut active_paths = SmallVec::<[_; 3]>::new();
+601
+602 match MappedAddr::from(transmit.destination) {
+603 MappedAddr::None(addr) => {
+604 active_paths.push(transports::Addr::from(addr));
+605 }
+606 MappedAddr::NodeId(dest) => {
+607 trace!(
+608 dst = %dest,
+609 src = ?transmit.src_ip,
+610 len = %transmit.contents.len(),
+611 "sending",
+612 );
+613
+614 // Get the node's relay address and best direct address, as well
+615 // as any pings that need to be sent for hole-punching purposes.
+616 match self.node_map.get_send_addrs(
+617 dest,
+618 self.ipv6_reported.load(Ordering::Relaxed),
+619 &self.metrics.magicsock,
+620 ) {
+621 Some((node_id, _udp_addr, relay_url, ping_actions)) => {
+622 if !ping_actions.is_empty() {
+623 self.actor_sender
+624 .try_send(ActorMessage::PingActions(ping_actions))
+625 .ok();
+626 }
+627 // NodeId mapped addrs are only used for relays, currently.
+628 // IP based addrs will have been added as individual paths
+629 if let Some(url) = relay_url {
+630 active_paths.push(transports::Addr::Relay(url, node_id));
631 }
-632 // NodeId mapped addrs are only used for relays, currently.
-633 // IP based addrs will have been added as individual paths
-634 if let Some(url) = relay_url {
-635 active_paths.push(transports::Addr::Relay(url, node_id));
-636 }
-637 }
-638 None => {
-639 error!(%dest, "no NodeState for mapped address");
-640 }
-641 }
-642 }
-643 #[cfg(not(wasm_browser))]
-644 MappedAddr::Ip(dest) => {
-645 trace!(
-646 dst = %dest,
-647 src = ?transmit.src_ip,
-648 len = %transmit.contents.len(),
-649 "sending",
-650 );
-651
-652 // Check if this is a known IpMappedAddr, and if so, send over UDP
-653 // Get the socket addr
-654 match self.ip_mapped_addrs.get_ip_addr(&dest) {
-655 Some(addr) => {
-656 active_paths.push(transports::Addr::from(addr));
-657 }
-658 None => {
-659 error!(%dest, "unknown mapped address");
-660 }
-661 }
-662 }
-663 }
-664
-665 Ok(active_paths)
-666 }
-667
-668 /// Process datagrams received from UDP sockets.
-669 ///
-670 /// All the `bufs` and `metas` should have initialized packets in them.
-671 ///
-672 /// This fixes up the datagrams to use the correct [`NodeIdMappedAddr`] and extracts DISCO
-673 /// packets, processing them inside the magic socket.
-674 fn process_datagrams(
-675 &self,
-676 bufs: &mut [io::IoSliceMut<'_>],
-677 metas: &mut [quinn_udp::RecvMeta],
-678 source_addrs: &[transports::Addr],
-679 ) {
-680 debug_assert_eq!(bufs.len(), metas.len(), "non matching bufs & metas");
-681 debug_assert_eq!(
-682 bufs.len(),
-683 source_addrs.len(),
-684 "non matching bufs & source_addrs"
-685 );
-686
-687 // Adding the IP address we received something on results in Quinn using this
-688 // address on the send path to send from. However we let Quinn use a
-689 // NodeIdMappedAddress, not a real address. So we used to substitute our bind address
-690 // here so that Quinn would send on the right address. But that would sometimes
-691 // result in the wrong address family and Windows trips up on that.
-692 //
-693 // What should be done is that this dst_ip from the RecvMeta is stored in the
-694 // NodeState/PathState. Then on the send path it should be retrieved from the
-695 // NodeState/PathSate together with the send address and substituted at send time.
-696 // This is relevant for IPv6 link-local addresses where the OS otherwise does not
-697 // know which interface to send from.
-698 #[cfg(not(windows))]
-699 let dst_ip = self.normalized_local_addr().ok().map(|addr| addr.ip());
-700 // Reasoning for this here:
-701 // https://github.com/n0-computer/iroh/pull/2595#issuecomment-2290947319
-702 #[cfg(windows)]
-703 let dst_ip = None;
-704
-705 let mut quic_packets_total = 0;
-706
-707 for ((quinn_meta, buf), source_addr) in metas
-708 .iter_mut()
-709 .zip(bufs.iter_mut())
-710 .zip(source_addrs.iter())
-711 {
-712 let mut buf_contains_quic_datagrams = false;
-713 let mut quic_datagram_count = 0;
-714 if quinn_meta.len > quinn_meta.stride {
-715 trace!(%quinn_meta.len, %quinn_meta.stride, "GRO datagram received");
-716 self.metrics.magicsock.recv_gro_datagrams.inc();
-717 }
-718
-719 // Chunk through the datagrams in this GRO payload to find disco
-720 // packets and forward them to the actor
-721 for datagram in buf[..quinn_meta.len].chunks_mut(quinn_meta.stride) {
-722 if datagram.len() < quinn_meta.stride {
-723 trace!(
-724 len = %datagram.len(),
-725 %quinn_meta.stride,
-726 "Last GRO datagram smaller than stride",
-727 );
-728 }
-729
-730 // Detect DISCO datagrams and process them. Overwrite the first
-731 // byte of those packets with zero to make Quinn ignore the packet. This
-732 // relies on quinn::EndpointConfig::grease_quic_bit being set to `false`,
-733 // which we do in Endpoint::bind.
-734 if let Some((sender, sealed_box)) = disco::source_and_box(datagram) {
-735 trace!(src = ?source_addr, len = %quinn_meta.stride, "UDP recv: disco packet");
-736 self.handle_disco_message(sender, sealed_box, source_addr);
-737 datagram[0] = 0u8;
-738 } else {
-739 trace!(src = ?source_addr, len = %quinn_meta.stride, "UDP recv: quic packet");
-740 match source_addr {
-741 transports::Addr::Ip(SocketAddr::V4(..)) => {
-742 self.metrics
-743 .magicsock
-744 .recv_data_ipv4
-745 .inc_by(datagram.len() as _);
-746 }
-747 transports::Addr::Ip(SocketAddr::V6(..)) => {
-748 self.metrics
-749 .magicsock
-750 .recv_data_ipv6
-751 .inc_by(datagram.len() as _);
-752 }
-753 transports::Addr::Relay(..) => {
-754 self.metrics
-755 .magicsock
-756 .recv_data_relay
-757 .inc_by(datagram.len() as _);
-758 }
-759 }
+632 }
+633 None => {
+634 error!(%dest, "no NodeState for mapped address");
+635 }
+636 }
+637 }
+638 #[cfg(not(wasm_browser))]
+639 MappedAddr::Ip(dest) => {
+640 trace!(
+641 dst = %dest,
+642 src = ?transmit.src_ip,
+643 len = %transmit.contents.len(),
+644 "sending",
+645 );
+646
+647 // Check if this is a known IpMappedAddr, and if so, send over UDP
+648 // Get the socket addr
+649 match self.ip_mapped_addrs.get_ip_addr(&dest) {
+650 Some(addr) => {
+651 active_paths.push(transports::Addr::from(addr));
+652 }
+653 None => {
+654 error!(%dest, "unknown mapped address");
+655 }
+656 }
+657 }
+658 }
+659
+660 Ok(active_paths)
+661 }
+662
+663 /// Process datagrams received from UDP sockets.
+664 ///
+665 /// All the `bufs` and `metas` should have initialized packets in them.
+666 ///
+667 /// This fixes up the datagrams to use the correct [`NodeIdMappedAddr`] and extracts DISCO
+668 /// packets, processing them inside the magic socket.
+669 fn process_datagrams(
+670 &self,
+671 bufs: &mut [io::IoSliceMut<'_>],
+672 metas: &mut [quinn_udp::RecvMeta],
+673 source_addrs: &[transports::Addr],
+674 ) {
+675 debug_assert_eq!(bufs.len(), metas.len(), "non matching bufs & metas");
+676 debug_assert_eq!(
+677 bufs.len(),
+678 source_addrs.len(),
+679 "non matching bufs & source_addrs"
+680 );
+681
+682 // Adding the IP address we received something on results in Quinn using this
+683 // address on the send path to send from. However we let Quinn use a
+684 // NodeIdMappedAddress, not a real address. So we used to substitute our bind address
+685 // here so that Quinn would send on the right address. But that would sometimes
+686 // result in the wrong address family and Windows trips up on that.
+687 //
+688 // What should be done is that this dst_ip from the RecvMeta is stored in the
+689 // NodeState/PathState. Then on the send path it should be retrieved from the
+690 // NodeState/PathSate together with the send address and substituted at send time.
+691 // This is relevant for IPv6 link-local addresses where the OS otherwise does not
+692 // know which interface to send from.
+693 #[cfg(not(windows))]
+694 let dst_ip = self.normalized_local_addr().ok().map(|addr| addr.ip());
+695 // Reasoning for this here:
+696 // https://github.com/n0-computer/iroh/pull/2595#issuecomment-2290947319
+697 #[cfg(windows)]
+698 let dst_ip = None;
+699
+700 let mut quic_packets_total = 0;
+701
+702 for ((quinn_meta, buf), source_addr) in metas
+703 .iter_mut()
+704 .zip(bufs.iter_mut())
+705 .zip(source_addrs.iter())
+706 {
+707 let mut buf_contains_quic_datagrams = false;
+708 let mut quic_datagram_count = 0;
+709 if quinn_meta.len > quinn_meta.stride {
+710 trace!(%quinn_meta.len, %quinn_meta.stride, "GRO datagram received");
+711 self.metrics.magicsock.recv_gro_datagrams.inc();
+712 }
+713
+714 // Chunk through the datagrams in this GRO payload to find disco
+715 // packets and forward them to the actor
+716 for datagram in buf[..quinn_meta.len].chunks_mut(quinn_meta.stride) {
+717 if datagram.len() < quinn_meta.stride {
+718 trace!(
+719 len = %datagram.len(),
+720 %quinn_meta.stride,
+721 "Last GRO datagram smaller than stride",
+722 );
+723 }
+724
+725 // Detect DISCO datagrams and process them. Overwrite the first
+726 // byte of those packets with zero to make Quinn ignore the packet. This
+727 // relies on quinn::EndpointConfig::grease_quic_bit being set to `false`,
+728 // which we do in Endpoint::bind.
+729 if let Some((sender, sealed_box)) = disco::source_and_box(datagram) {
+730 trace!(src = ?source_addr, len = %quinn_meta.stride, "UDP recv: disco packet");
+731 self.handle_disco_message(sender, sealed_box, source_addr);
+732 datagram[0] = 0u8;
+733 } else {
+734 trace!(src = ?source_addr, len = %quinn_meta.stride, "UDP recv: quic packet");
+735 match source_addr {
+736 transports::Addr::Ip(SocketAddr::V4(..)) => {
+737 self.metrics
+738 .magicsock
+739 .recv_data_ipv4
+740 .inc_by(datagram.len() as _);
+741 }
+742 transports::Addr::Ip(SocketAddr::V6(..)) => {
+743 self.metrics
+744 .magicsock
+745 .recv_data_ipv6
+746 .inc_by(datagram.len() as _);
+747 }
+748 transports::Addr::Relay(..) => {
+749 self.metrics
+750 .magicsock
+751 .recv_data_relay
+752 .inc_by(datagram.len() as _);
+753 }
+754 }
+755
+756 quic_datagram_count += 1;
+757 buf_contains_quic_datagrams = true;
+758 }
+759 }
760
-761 quic_datagram_count += 1;
-762 buf_contains_quic_datagrams = true;
-763 }
-764 }
-765
-766 if buf_contains_quic_datagrams {
-767 match source_addr {
-768 #[cfg(wasm_browser)]
-769 transports::Addr::Ip(_addr) => {
-770 panic!("cannot use IP based addressing in the browser");
-771 }
-772 #[cfg(not(wasm_browser))]
-773 transports::Addr::Ip(addr) => {
-774 // UDP
-775
-776 // Update the NodeMap and remap RecvMeta to the NodeIdMappedAddr.
-777 match self.node_map.receive_udp(*addr) {
-778 None => {
-779 // Check if this address is mapped to an IpMappedAddr
-780 if let Some(ip_mapped_addr) =
-781 self.ip_mapped_addrs.get_mapped_addr(addr)
-782 {
-783 trace!(
-784 src = %addr,
-785 count = %quic_datagram_count,
-786 len = quinn_meta.len,
-787 "UDP recv QUIC address discovery packets",
-788 );
-789 quic_packets_total += quic_datagram_count;
-790 quinn_meta.addr = ip_mapped_addr.private_socket_addr();
-791 } else {
-792 warn!(
-793 src = %addr,
-794 count = %quic_datagram_count,
-795 len = quinn_meta.len,
-796 "UDP recv quic packets: no node state found, skipping",
-797 );
-798 // If we have no node state for the from addr, set len to 0 to make
-799 // quinn skip the buf completely.
-800 quinn_meta.len = 0;
-801 }
-802 }
-803 Some((node_id, quic_mapped_addr)) => {
-804 trace!(
-805 src = %addr,
-806 node = %node_id.fmt_short(),
-807 count = %quic_datagram_count,
-808 len = quinn_meta.len,
-809 "UDP recv quic packets",
-810 );
-811 quic_packets_total += quic_datagram_count;
-812 quinn_meta.addr = quic_mapped_addr.private_socket_addr();
-813 }
-814 }
+761 if buf_contains_quic_datagrams {
+762 match source_addr {
+763 #[cfg(wasm_browser)]
+764 transports::Addr::Ip(_addr) => {
+765 panic!("cannot use IP based addressing in the browser");
+766 }
+767 #[cfg(not(wasm_browser))]
+768 transports::Addr::Ip(addr) => {
+769 // UDP
+770
+771 // Update the NodeMap and remap RecvMeta to the NodeIdMappedAddr.
+772 match self.node_map.receive_udp(*addr) {
+773 None => {
+774 // Check if this address is mapped to an IpMappedAddr
+775 if let Some(ip_mapped_addr) =
+776 self.ip_mapped_addrs.get_mapped_addr(addr)
+777 {
+778 trace!(
+779 src = %addr,
+780 count = %quic_datagram_count,
+781 len = quinn_meta.len,
+782 "UDP recv QUIC address discovery packets",
+783 );
+784 quic_packets_total += quic_datagram_count;
+785 quinn_meta.addr = ip_mapped_addr.private_socket_addr();
+786 } else {
+787 warn!(
+788 src = %addr,
+789 count = %quic_datagram_count,
+790 len = quinn_meta.len,
+791 "UDP recv quic packets: no node state found, skipping",
+792 );
+793 // If we have no node state for the from addr, set len to 0 to make
+794 // quinn skip the buf completely.
+795 quinn_meta.len = 0;
+796 }
+797 }
+798 Some((node_id, quic_mapped_addr)) => {
+799 trace!(
+800 src = %addr,
+801 node = %node_id.fmt_short(),
+802 count = %quic_datagram_count,
+803 len = quinn_meta.len,
+804 "UDP recv quic packets",
+805 );
+806 quic_packets_total += quic_datagram_count;
+807 quinn_meta.addr = quic_mapped_addr.private_socket_addr();
+808 }
+809 }
+810 }
+811 transports::Addr::Relay(src_url, src_node) => {
+812 // Relay
+813 let quic_mapped_addr = self.node_map.receive_relay(src_url, *src_node);
+814 quinn_meta.addr = quic_mapped_addr.private_socket_addr();
815 }
-816 transports::Addr::Relay(src_url, src_node) => {
-817 // Relay
-818 let quic_mapped_addr = self.node_map.receive_relay(src_url, *src_node);
-819 quinn_meta.addr = quic_mapped_addr.private_socket_addr();
-820 }
-821 }
-822 } else {
-823 // If all datagrams in this buf are DISCO, set len to zero to make
-824 // Quinn skip the buf completely.
-825 quinn_meta.len = 0;
-826 }
-827 // Normalize local_ip
-828 quinn_meta.dst_ip = dst_ip;
-829 }
-830
-831 if quic_packets_total > 0 {
-832 self.metrics
-833 .magicsock
-834 .recv_datagrams
-835 .inc_by(quic_packets_total as _);
-836 trace!("UDP recv: {} packets", quic_packets_total);
-837 }
-838 }
-839
-840 /// Handles a discovery message.
-841 #[instrument("disco_in", skip_all, fields(node = %sender.fmt_short(), ?src))]
-842 fn handle_disco_message(&self, sender: PublicKey, sealed_box: &[u8], src: &transports::Addr) {
-843 trace!("handle_disco_message start");
-844 if self.is_closed() {
-845 return;
-846 }
-847
-848 if let transports::Addr::Relay(_, node_id) = src {
-849 if node_id != &sender {
-850 // TODO: return here?
-851 warn!(
-852 "Received relay disco message from connection for {}, but with message from {}",
-853 node_id.fmt_short(),
-854 sender.fmt_short()
-855 );
-856 }
-857 }
-858
-859 // We're now reasonably sure we're expecting communication from
-860 // this node, do the heavy crypto lifting to see what they want.
-861 let dm = match self.disco.unseal_and_decode(sender, sealed_box) {
-862 Ok(dm) => dm,
-863 Err(DiscoBoxError::Open { source, .. }) => {
-864 warn!(?source, "failed to open disco box");
-865 self.metrics.magicsock.recv_disco_bad_key.inc();
-866 return;
-867 }
-868 Err(DiscoBoxError::Parse { source, .. }) => {
-869 // Couldn't parse it, but it was inside a correctly
-870 // signed box, so just ignore it, assuming it's from a
-871 // newer version of Tailscale that we don't
-872 // understand. Not even worth logging about, lest it
-873 // be too spammy for old clients.
-874
-875 self.metrics.magicsock.recv_disco_bad_parse.inc();
-876 debug!(?source, "failed to parse disco message");
-877 return;
-878 }
-879 };
-880
-881 if src.is_relay() {
-882 self.metrics.magicsock.recv_disco_relay.inc();
-883 } else {
-884 self.metrics.magicsock.recv_disco_udp.inc();
-885 }
-886
-887 let span = trace_span!("handle_disco", ?dm);
-888 let _guard = span.enter();
-889 trace!("receive disco message");
-890 match dm {
-891 disco::Message::Ping(ping) => {
-892 self.metrics.magicsock.recv_disco_ping.inc();
-893 self.handle_ping(ping, sender, src);
-894 }
-895 disco::Message::Pong(pong) => {
-896 self.metrics.magicsock.recv_disco_pong.inc();
-897 self.node_map.handle_pong(sender, src, pong);
-898 }
-899 disco::Message::CallMeMaybe(cm) => {
-900 self.metrics.magicsock.recv_disco_call_me_maybe.inc();
-901 match src {
-902 transports::Addr::Relay(url, _) => {
-903 event!(
-904 target: "iroh::_events::call-me-maybe::recv",
-905 Level::DEBUG,
-906 remote_node = sender.fmt_short(),
-907 via = ?url,
-908 their_addrs = ?cm.my_numbers,
-909 );
-910 }
-911 _ => {
-912 warn!("call-me-maybe packets should only come via relay");
-913 return;
-914 }
-915 }
-916
-917 // Add new addresses as paths
-918 self.add_paths(NodeAddr {
-919 node_id: sender,
-920 relay_url: None,
-921 direct_addresses: cm.my_numbers.iter().copied().collect(),
-922 });
-923
-924 let ping_actions =
-925 self.node_map
-926 .handle_call_me_maybe(sender, cm, &self.metrics.magicsock);
-927
-928 for action in ping_actions {
-929 match action {
-930 PingAction::SendCallMeMaybe { .. } => {
-931 warn!("Unexpected CallMeMaybe as response of handling a CallMeMaybe");
-932 }
-933 PingAction::SendPing(ping) => {
-934 self.send_ping_queued(ping);
-935 }
-936 }
-937 }
-938 }
-939 }
-940 trace!("disco message handled");
-941 }
-942
-943 /// Handle a ping message.
-944 fn handle_ping(&self, dm: disco::Ping, sender: NodeId, src: &transports::Addr) {
-945 // Insert the ping into the node map, and return whether a ping with this tx_id was already
-946 // received.
-947 let addr: SendAddr = src.clone().into();
-948 let handled = self.node_map.handle_ping(sender, addr.clone(), dm.tx_id);
-949 match handled.role {
-950 PingRole::Duplicate => {
-951 debug!(?src, tx = %HEXLOWER.encode(&dm.tx_id), "received ping: path already confirmed, skip");
-952 return;
-953 }
-954 PingRole::LikelyHeartbeat => {}
-955 PingRole::NewPath => {
-956 debug!(?src, tx = %HEXLOWER.encode(&dm.tx_id), "received ping: new path");
-957 }
-958 PingRole::Activate => {
-959 debug!(?src, tx = %HEXLOWER.encode(&dm.tx_id), "received ping: path active");
-960 }
-961 }
-962
-963 // Send a pong.
-964 debug!(tx = %HEXLOWER.encode(&dm.tx_id), %addr, dstkey = %sender.fmt_short(),
-965 "sending pong");
-966 let pong = disco::Message::Pong(disco::Pong {
-967 tx_id: dm.tx_id,
-968 ping_observed_addr: addr.clone(),
-969 });
-970 event!(
-971 target: "iroh::_events::pong::sent",
-972 Level::DEBUG,
-973 remote_node = %sender.fmt_short(),
-974 dst = ?addr,
-975 txn = ?dm.tx_id,
-976 );
-977
-978 if !self.disco.try_send(addr.clone(), sender, pong) {
-979 warn!(%addr, "failed to queue pong");
-980 }
-981
-982 if let Some(ping) = handled.needs_ping_back {
-983 debug!(
-984 %addr,
-985 dstkey = %sender.fmt_short(),
-986 "sending direct ping back",
-987 );
-988 self.send_ping_queued(ping);
-989 }
-990 }
-991
-992 fn send_ping_queued(&self, ping: SendPing) {
-993 let SendPing {
-994 id,
-995 dst,
-996 dst_node,
-997 tx_id,
-998 purpose,
-999 } = ping;
-1000 let msg = disco::Message::Ping(disco::Ping {
-1001 tx_id,
-1002 node_key: self.public_key,
-1003 });
-1004 let sent = self.disco.try_send(dst.clone(), dst_node, msg);
-1005 if sent {
-1006 let msg_sender = self.actor_sender.clone();
-1007 trace!(%dst, tx = %HEXLOWER.encode(&tx_id), ?purpose, "ping sent (queued)");
-1008 self.node_map
-1009 .notify_ping_sent(id, dst, tx_id, purpose, msg_sender);
-1010 } else {
-1011 warn!(dst = ?dst, tx = %HEXLOWER.encode(&tx_id), ?purpose, "failed to send ping: queues full");
-1012 }
-1013 }
-1014
-1015 /// Send the given ping actions out.
-1016 async fn send_ping_actions(&self, sender: &UdpSender, msgs: Vec<PingAction>) -> io::Result<()> {
-1017 for msg in msgs {
-1018 // Abort sending as soon as we know we are shutting down.
-1019 if self.is_closing() || self.is_closed() {
-1020 return Ok(());
-1021 }
-1022 match msg {
-1023 PingAction::SendCallMeMaybe {
-1024 relay_url,
-1025 dst_node,
-1026 } => {
-1027 // Sends the call-me-maybe DISCO message, queuing if addresses are too stale.
-1028 //
-1029 // To send the call-me-maybe message, we need to know our current direct addresses. If
-1030 // this information is too stale, the call-me-maybe is queued while a net_report run is
-1031 // scheduled. Once this run finishes, the call-me-maybe will be sent.
-1032 match self.direct_addrs.fresh_enough() {
-1033 Ok(()) => {
-1034 let msg = disco::Message::CallMeMaybe(
-1035 self.direct_addrs.to_call_me_maybe_message(),
-1036 );
-1037 if !self.disco.try_send(
-1038 SendAddr::Relay(relay_url.clone()),
-1039 dst_node,
-1040 msg.clone(),
-1041 ) {
-1042 warn!(dstkey = %dst_node.fmt_short(), %relay_url, "relay channel full, dropping call-me-maybe");
-1043 } else {
-1044 debug!(dstkey = %dst_node.fmt_short(), %relay_url, "call-me-maybe sent");
-1045 }
-1046 }
-1047 Err(last_refresh_ago) => {
-1048 debug!(
-1049 ?last_refresh_ago,
-1050 "want call-me-maybe but direct addrs stale; queuing after restun",
-1051 );
-1052 self.actor_sender
-1053 .try_send(ActorMessage::ScheduleDirectAddrUpdate(
-1054 UpdateReason::RefreshForPeering,
-1055 Some((dst_node, relay_url)),
-1056 ))
-1057 .ok();
-1058 }
-1059 }
-1060 }
-1061 PingAction::SendPing(SendPing {
-1062 id,
-1063 dst,
-1064 dst_node,
-1065 tx_id,
-1066 purpose,
-1067 }) => {
-1068 let msg = disco::Message::Ping(disco::Ping {
-1069 tx_id,
-1070 node_key: self.public_key,
-1071 });
-1072
-1073 self.send_disco_message(sender, dst.clone(), dst_node, msg)
-1074 .await?;
-1075 debug!(%dst, tx = %HEXLOWER.encode(&tx_id), ?purpose, "ping sent");
-1076 let msg_sender = self.actor_sender.clone();
-1077 self.node_map
-1078 .notify_ping_sent(id, dst, tx_id, purpose, msg_sender);
-1079 }
-1080 }
-1081 }
-1082 Ok(())
-1083 }
-1084
-1085 /// Sends out a disco message.
-1086 async fn send_disco_message(
-1087 &self,
-1088 sender: &UdpSender,
-1089 dst: SendAddr,
-1090 dst_key: PublicKey,
-1091 msg: disco::Message,
-1092 ) -> io::Result<()> {
-1093 let dst = match dst {
-1094 SendAddr::Udp(addr) => transports::Addr::Ip(addr),
-1095 SendAddr::Relay(url) => transports::Addr::Relay(url, dst_key),
-1096 };
-1097
-1098 trace!(?dst, %msg, "send disco message (UDP)");
-1099 if self.is_closed() {
-1100 return Err(io::Error::new(
-1101 io::ErrorKind::NotConnected,
-1102 "connection closed",
-1103 ));
-1104 }
-1105
-1106 let pkt = self.disco.encode_and_seal(self.public_key, dst_key, &msg);
-1107
-1108 let transmit = transports::Transmit {
-1109 contents: &pkt,
-1110 ecn: None,
-1111 segment_size: None,
-1112 };
-1113
-1114 let dst2 = dst.clone();
-1115 match sender.send(&dst2, None, &transmit).await {
-1116 Ok(()) => {
-1117 trace!(?dst, %msg, "sent disco message");
-1118 self.metrics.magicsock.sent_disco_udp.inc();
-1119 disco_message_sent(&msg, &self.metrics.magicsock);
-1120 Ok(())
-1121 }
-1122 Err(err) => {
-1123 warn!(?dst, ?msg, ?err, "failed to send disco message");
-1124 Err(err)
-1125 }
-1126 }
-1127 }
-1128
-1129 /// Publishes our address to a discovery service, if configured.
-1130 ///
-1131 /// Called whenever our addresses or home relay node changes.
-1132 fn publish_my_addr(&self) {
-1133 if let Some(ref discovery) = self.discovery {
-1134 let relay_url = self.my_relay();
-1135 let direct_addrs = self.direct_addrs.sockaddrs();
-1136
-1137 let user_data = self
-1138 .discovery_user_data
-1139 .read()
-1140 .expect("lock poisened")
-1141 .clone();
-1142 if relay_url.is_none() && direct_addrs.is_empty() && user_data.is_none() {
-1143 // do not bother publishing if we don't have any information
-1144 return;
-1145 }
-1146
-1147 let data = NodeData::new(relay_url, direct_addrs).with_user_data(user_data);
-1148 discovery.publish(&data);
-1149 }
-1150 }
-1151}
-1152
-1153#[derive(Clone, Debug)]
-1154enum MappedAddr {
-1155 NodeId(NodeIdMappedAddr),
-1156 #[cfg(not(wasm_browser))]
-1157 Ip(IpMappedAddr),
-1158 None(SocketAddr),
-1159}
-1160
-1161impl From<SocketAddr> for MappedAddr {
-1162 fn from(value: SocketAddr) -> Self {
-1163 match value.ip() {
-1164 IpAddr::V4(_) => MappedAddr::None(value),
-1165 IpAddr::V6(addr) => {
-1166 if let Ok(node_id_mapped_addr) = NodeIdMappedAddr::try_from(addr) {
-1167 return MappedAddr::NodeId(node_id_mapped_addr);
-1168 }
-1169 #[cfg(not(wasm_browser))]
-1170 if let Ok(ip_mapped_addr) = IpMappedAddr::try_from(addr) {
-1171 return MappedAddr::Ip(ip_mapped_addr);
-1172 }
-1173 MappedAddr::None(value)
-1174 }
-1175 }
-1176 }
-1177}
-1178
-1179/// Manages currently running direct addr discovery, aka net_report runs.
-1180///
-1181/// Invariants:
-1182/// - only one direct addr update must be running at a time
-1183/// - if an update is scheduled while another one is running, remember that
-1184/// and start a new one when the current one has finished
-1185#[derive(Debug)]
-1186struct DirectAddrUpdateState {
-1187 /// If set, start a new update as soon as the current one is finished.
-1188 want_update: Option<UpdateReason>,
-1189 msock: Arc<MagicSock>,
-1190 #[cfg(not(wasm_browser))]
-1191 port_mapper: portmapper::Client,
-1192 /// The prober that discovers local network conditions, including the closest relay relay and NAT mappings.
-1193 net_reporter: Arc<AsyncMutex<net_report::Client>>,
-1194 relay_map: RelayMap,
-1195 run_done: mpsc::Sender<()>,
-1196}
-1197
-1198#[derive(Default, Debug, PartialEq, Eq, Clone, Copy)]
-1199enum UpdateReason {
-1200 /// Initial state
-1201 #[default]
-1202 None,
-1203 RefreshForPeering,
-1204 Periodic,
-1205 PortmapUpdated,
-1206 LinkChangeMajor,
-1207 LinkChangeMinor,
-1208}
-1209
-1210impl UpdateReason {
-1211 fn is_major(self) -> bool {
-1212 matches!(self, Self::LinkChangeMajor)
-1213 }
-1214}
-1215
-1216impl DirectAddrUpdateState {
-1217 fn new(
-1218 msock: Arc<MagicSock>,
-1219 #[cfg(not(wasm_browser))] port_mapper: portmapper::Client,
-1220 net_reporter: Arc<AsyncMutex<net_report::Client>>,
-1221 relay_map: RelayMap,
-1222 run_done: mpsc::Sender<()>,
-1223 ) -> Self {
-1224 DirectAddrUpdateState {
-1225 want_update: Default::default(),
-1226 #[cfg(not(wasm_browser))]
-1227 port_mapper,
-1228 net_reporter,
-1229 msock,
-1230 relay_map,
-1231 run_done,
-1232 }
-1233 }
-1234
-1235 /// Schedules a new run, either starting it immediately if none is running or
-1236 /// scheduling it for later.
-1237 fn schedule_run(&mut self, why: UpdateReason, if_state: IfStateDetails) {
-1238 match self.net_reporter.clone().try_lock_owned() {
-1239 Ok(net_reporter) => {
-1240 self.run(why, if_state, net_reporter);
-1241 }
-1242 Err(_) => {
-1243 let _ = self.want_update.insert(why);
-1244 }
-1245 }
-1246 }
-1247
-1248 /// If another run is needed, triggers this run, otherwise does nothing.
-1249 fn try_run(&mut self, if_state: IfStateDetails) {
-1250 match self.net_reporter.clone().try_lock_owned() {
-1251 Ok(net_reporter) => {
-1252 if let Some(why) = self.want_update.take() {
-1253 self.run(why, if_state, net_reporter);
-1254 }
-1255 }
-1256 Err(_) => {
-1257 // do nothing
-1258 }
-1259 }
-1260 }
-1261
-1262 /// Trigger a new run.
-1263 fn run(
-1264 &mut self,
-1265 why: UpdateReason,
-1266 if_state: IfStateDetails,
-1267 mut net_reporter: tokio::sync::OwnedMutexGuard<net_report::Client>,
-1268 ) {
-1269 debug!("starting direct addr update ({:?})", why);
-1270 #[cfg(not(wasm_browser))]
-1271 self.port_mapper.procure_mapping();
-1272 // Don't start a net report probe if we know
-1273 // we are shutting down
-1274 if self.msock.is_closing() || self.msock.is_closed() {
-1275 debug!("skipping net_report, socket is shutting down");
+816 }
+817 } else {
+818 // If all datagrams in this buf are DISCO, set len to zero to make
+819 // Quinn skip the buf completely.
+820 quinn_meta.len = 0;
+821 }
+822 // Normalize local_ip
+823 quinn_meta.dst_ip = dst_ip;
+824 }
+825
+826 if quic_packets_total > 0 {
+827 self.metrics
+828 .magicsock
+829 .recv_datagrams
+830 .inc_by(quic_packets_total as _);
+831 trace!("UDP recv: {} packets", quic_packets_total);
+832 }
+833 }
+834
+835 /// Handles a discovery message.
+836 #[instrument("disco_in", skip_all, fields(node = %sender.fmt_short(), ?src))]
+837 fn handle_disco_message(&self, sender: PublicKey, sealed_box: &[u8], src: &transports::Addr) {
+838 trace!("handle_disco_message start");
+839 if self.is_closed() {
+840 return;
+841 }
+842
+843 if let transports::Addr::Relay(_, node_id) = src {
+844 if node_id != &sender {
+845 // TODO: return here?
+846 warn!(
+847 "Received relay disco message from connection for {}, but with message from {}",
+848 node_id.fmt_short(),
+849 sender.fmt_short()
+850 );
+851 }
+852 }
+853
+854 // We're now reasonably sure we're expecting communication from
+855 // this node, do the heavy crypto lifting to see what they want.
+856 let dm = match self.disco.unseal_and_decode(sender, sealed_box) {
+857 Ok(dm) => dm,
+858 Err(DiscoBoxError::Open { source, .. }) => {
+859 warn!(?source, "failed to open disco box");
+860 self.metrics.magicsock.recv_disco_bad_key.inc();
+861 return;
+862 }
+863 Err(DiscoBoxError::Parse { source, .. }) => {
+864 // Couldn't parse it, but it was inside a correctly
+865 // signed box, so just ignore it, assuming it's from a
+866 // newer version of Tailscale that we don't
+867 // understand. Not even worth logging about, lest it
+868 // be too spammy for old clients.
+869
+870 self.metrics.magicsock.recv_disco_bad_parse.inc();
+871 debug!(?source, "failed to parse disco message");
+872 return;
+873 }
+874 };
+875
+876 if src.is_relay() {
+877 self.metrics.magicsock.recv_disco_relay.inc();
+878 } else {
+879 self.metrics.magicsock.recv_disco_udp.inc();
+880 }
+881
+882 let span = trace_span!("handle_disco", ?dm);
+883 let _guard = span.enter();
+884 trace!("receive disco message");
+885 match dm {
+886 disco::Message::Ping(ping) => {
+887 self.metrics.magicsock.recv_disco_ping.inc();
+888 self.handle_ping(ping, sender, src);
+889 }
+890 disco::Message::Pong(pong) => {
+891 self.metrics.magicsock.recv_disco_pong.inc();
+892 self.node_map.handle_pong(sender, src, pong);
+893 }
+894 disco::Message::CallMeMaybe(cm) => {
+895 self.metrics.magicsock.recv_disco_call_me_maybe.inc();
+896 match src {
+897 transports::Addr::Relay(url, _) => {
+898 event!(
+899 target: "iroh::_events::call-me-maybe::recv",
+900 Level::DEBUG,
+901 remote_node = sender.fmt_short(),
+902 via = ?url,
+903 their_addrs = ?cm.my_numbers,
+904 );
+905 }
+906 _ => {
+907 warn!("call-me-maybe packets should only come via relay");
+908 return;
+909 }
+910 }
+911
+912 // Add new addresses as paths
+913 self.add_paths(NodeAddr {
+914 node_id: sender,
+915 relay_url: None,
+916 direct_addresses: cm.my_numbers.iter().copied().collect(),
+917 });
+918
+919 let ping_actions =
+920 self.node_map
+921 .handle_call_me_maybe(sender, cm, &self.metrics.magicsock);
+922
+923 for action in ping_actions {
+924 match action {
+925 PingAction::SendCallMeMaybe { .. } => {
+926 warn!("Unexpected CallMeMaybe as response of handling a CallMeMaybe");
+927 }
+928 PingAction::SendPing(ping) => {
+929 self.send_ping_queued(ping);
+930 }
+931 }
+932 }
+933 }
+934 }
+935 trace!("disco message handled");
+936 }
+937
+938 /// Handle a ping message.
+939 fn handle_ping(&self, dm: disco::Ping, sender: NodeId, src: &transports::Addr) {
+940 // Insert the ping into the node map, and return whether a ping with this tx_id was already
+941 // received.
+942 let addr: SendAddr = src.clone().into();
+943 let handled = self.node_map.handle_ping(sender, addr.clone(), dm.tx_id);
+944 match handled.role {
+945 PingRole::Duplicate => {
+946 debug!(?src, tx = %HEXLOWER.encode(&dm.tx_id), "received ping: path already confirmed, skip");
+947 return;
+948 }
+949 PingRole::LikelyHeartbeat => {}
+950 PingRole::NewPath => {
+951 debug!(?src, tx = %HEXLOWER.encode(&dm.tx_id), "received ping: new path");
+952 }
+953 PingRole::Activate => {
+954 debug!(?src, tx = %HEXLOWER.encode(&dm.tx_id), "received ping: path active");
+955 }
+956 }
+957
+958 // Send a pong.
+959 debug!(tx = %HEXLOWER.encode(&dm.tx_id), %addr, dstkey = %sender.fmt_short(),
+960 "sending pong");
+961 let pong = disco::Message::Pong(disco::Pong {
+962 tx_id: dm.tx_id,
+963 ping_observed_addr: addr.clone(),
+964 });
+965 event!(
+966 target: "iroh::_events::pong::sent",
+967 Level::DEBUG,
+968 remote_node = %sender.fmt_short(),
+969 dst = ?addr,
+970 txn = ?dm.tx_id,
+971 );
+972
+973 if !self.disco.try_send(addr.clone(), sender, pong) {
+974 warn!(%addr, "failed to queue pong");
+975 }
+976
+977 if let Some(ping) = handled.needs_ping_back {
+978 debug!(
+979 %addr,
+980 dstkey = %sender.fmt_short(),
+981 "sending direct ping back",
+982 );
+983 self.send_ping_queued(ping);
+984 }
+985 }
+986
+987 fn send_ping_queued(&self, ping: SendPing) {
+988 let SendPing {
+989 id,
+990 dst,
+991 dst_node,
+992 tx_id,
+993 purpose,
+994 } = ping;
+995 let msg = disco::Message::Ping(disco::Ping {
+996 tx_id,
+997 node_key: self.public_key,
+998 });
+999 let sent = self.disco.try_send(dst.clone(), dst_node, msg);
+1000 if sent {
+1001 let msg_sender = self.actor_sender.clone();
+1002 trace!(%dst, tx = %HEXLOWER.encode(&tx_id), ?purpose, "ping sent (queued)");
+1003 self.node_map
+1004 .notify_ping_sent(id, dst, tx_id, purpose, msg_sender);
+1005 } else {
+1006 warn!(dst = ?dst, tx = %HEXLOWER.encode(&tx_id), ?purpose, "failed to send ping: queues full");
+1007 }
+1008 }
+1009
+1010 /// Send the given ping actions out.
+1011 async fn send_ping_actions(&self, sender: &UdpSender, msgs: Vec<PingAction>) -> io::Result<()> {
+1012 for msg in msgs {
+1013 // Abort sending as soon as we know we are shutting down.
+1014 if self.is_closing() || self.is_closed() {
+1015 return Ok(());
+1016 }
+1017 match msg {
+1018 PingAction::SendCallMeMaybe {
+1019 relay_url,
+1020 dst_node,
+1021 } => {
+1022 // Sends the call-me-maybe DISCO message, queuing if addresses are too stale.
+1023 //
+1024 // To send the call-me-maybe message, we need to know our current direct addresses. If
+1025 // this information is too stale, the call-me-maybe is queued while a net_report run is
+1026 // scheduled. Once this run finishes, the call-me-maybe will be sent.
+1027 match self.direct_addrs.fresh_enough() {
+1028 Ok(()) => {
+1029 let msg = disco::Message::CallMeMaybe(
+1030 self.direct_addrs.to_call_me_maybe_message(),
+1031 );
+1032 if !self.disco.try_send(
+1033 SendAddr::Relay(relay_url.clone()),
+1034 dst_node,
+1035 msg.clone(),
+1036 ) {
+1037 warn!(dstkey = %dst_node.fmt_short(), %relay_url, "relay channel full, dropping call-me-maybe");
+1038 } else {
+1039 debug!(dstkey = %dst_node.fmt_short(), %relay_url, "call-me-maybe sent");
+1040 }
+1041 }
+1042 Err(last_refresh_ago) => {
+1043 debug!(
+1044 ?last_refresh_ago,
+1045 "want call-me-maybe but direct addrs stale; queuing after restun",
+1046 );
+1047 self.actor_sender
+1048 .try_send(ActorMessage::ScheduleDirectAddrUpdate(
+1049 UpdateReason::RefreshForPeering,
+1050 Some((dst_node, relay_url)),
+1051 ))
+1052 .ok();
+1053 }
+1054 }
+1055 }
+1056 PingAction::SendPing(SendPing {
+1057 id,
+1058 dst,
+1059 dst_node,
+1060 tx_id,
+1061 purpose,
+1062 }) => {
+1063 let msg = disco::Message::Ping(disco::Ping {
+1064 tx_id,
+1065 node_key: self.public_key,
+1066 });
+1067
+1068 self.send_disco_message(sender, dst.clone(), dst_node, msg)
+1069 .await?;
+1070 debug!(%dst, tx = %HEXLOWER.encode(&tx_id), ?purpose, "ping sent");
+1071 let msg_sender = self.actor_sender.clone();
+1072 self.node_map
+1073 .notify_ping_sent(id, dst, tx_id, purpose, msg_sender);
+1074 }
+1075 }
+1076 }
+1077 Ok(())
+1078 }
+1079
+1080 /// Sends out a disco message.
+1081 async fn send_disco_message(
+1082 &self,
+1083 sender: &UdpSender,
+1084 dst: SendAddr,
+1085 dst_key: PublicKey,
+1086 msg: disco::Message,
+1087 ) -> io::Result<()> {
+1088 let dst = match dst {
+1089 SendAddr::Udp(addr) => transports::Addr::Ip(addr),
+1090 SendAddr::Relay(url) => transports::Addr::Relay(url, dst_key),
+1091 };
+1092
+1093 trace!(?dst, %msg, "send disco message (UDP)");
+1094 if self.is_closed() {
+1095 return Err(io::Error::new(
+1096 io::ErrorKind::NotConnected,
+1097 "connection closed",
+1098 ));
+1099 }
+1100
+1101 let pkt = self.disco.encode_and_seal(self.public_key, dst_key, &msg);
+1102
+1103 let transmit = transports::Transmit {
+1104 contents: &pkt,
+1105 ecn: None,
+1106 segment_size: None,
+1107 };
+1108
+1109 let dst2 = dst.clone();
+1110 match sender.send(&dst2, None, &transmit).await {
+1111 Ok(()) => {
+1112 trace!(?dst, %msg, "sent disco message");
+1113 self.metrics.magicsock.sent_disco_udp.inc();
+1114 disco_message_sent(&msg, &self.metrics.magicsock);
+1115 Ok(())
+1116 }
+1117 Err(err) => {
+1118 warn!(?dst, ?msg, ?err, "failed to send disco message");
+1119 Err(err)
+1120 }
+1121 }
+1122 }
+1123
+1124 /// Publishes our address to a discovery service, if configured.
+1125 ///
+1126 /// Called whenever our addresses or home relay node changes.
+1127 fn publish_my_addr(&self) {
+1128 if let Some(ref discovery) = self.discovery {
+1129 let relay_url = self.my_relay();
+1130 let direct_addrs = self.direct_addrs.sockaddrs();
+1131
+1132 let user_data = self
+1133 .discovery_user_data
+1134 .read()
+1135 .expect("lock poisened")
+1136 .clone();
+1137 if relay_url.is_none() && direct_addrs.is_empty() && user_data.is_none() {
+1138 // do not bother publishing if we don't have any information
+1139 return;
+1140 }
+1141
+1142 let data = NodeData::new(relay_url, direct_addrs).with_user_data(user_data);
+1143 discovery.publish(&data);
+1144 }
+1145 }
+1146}
+1147
+1148#[derive(Clone, Debug)]
+1149enum MappedAddr {
+1150 NodeId(NodeIdMappedAddr),
+1151 #[cfg(not(wasm_browser))]
+1152 Ip(IpMappedAddr),
+1153 None(SocketAddr),
+1154}
+1155
+1156impl From<SocketAddr> for MappedAddr {
+1157 fn from(value: SocketAddr) -> Self {
+1158 match value.ip() {
+1159 IpAddr::V4(_) => MappedAddr::None(value),
+1160 IpAddr::V6(addr) => {
+1161 if let Ok(node_id_mapped_addr) = NodeIdMappedAddr::try_from(addr) {
+1162 return MappedAddr::NodeId(node_id_mapped_addr);
+1163 }
+1164 #[cfg(not(wasm_browser))]
+1165 if let Ok(ip_mapped_addr) = IpMappedAddr::try_from(addr) {
+1166 return MappedAddr::Ip(ip_mapped_addr);
+1167 }
+1168 MappedAddr::None(value)
+1169 }
+1170 }
+1171 }
+1172}
+1173
+1174/// Manages currently running direct addr discovery, aka net_report runs.
+1175///
+1176/// Invariants:
+1177/// - only one direct addr update must be running at a time
+1178/// - if an update is scheduled while another one is running, remember that
+1179/// and start a new one when the current one has finished
+1180#[derive(Debug)]
+1181struct DirectAddrUpdateState {
+1182 /// If set, start a new update as soon as the current one is finished.
+1183 want_update: Option<UpdateReason>,
+1184 msock: Arc<MagicSock>,
+1185 #[cfg(not(wasm_browser))]
+1186 port_mapper: portmapper::Client,
+1187 /// The prober that discovers local network conditions, including the closest relay relay and NAT mappings.
+1188 net_reporter: Arc<AsyncMutex<net_report::Client>>,
+1189 relay_map: RelayMap,
+1190 run_done: mpsc::Sender<()>,
+1191}
+1192
+1193#[derive(Default, Debug, PartialEq, Eq, Clone, Copy)]
+1194enum UpdateReason {
+1195 /// Initial state
+1196 #[default]
+1197 None,
+1198 RefreshForPeering,
+1199 Periodic,
+1200 PortmapUpdated,
+1201 LinkChangeMajor,
+1202 LinkChangeMinor,
+1203}
+1204
+1205impl UpdateReason {
+1206 fn is_major(self) -> bool {
+1207 matches!(self, Self::LinkChangeMajor)
+1208 }
+1209}
+1210
+1211impl DirectAddrUpdateState {
+1212 fn new(
+1213 msock: Arc<MagicSock>,
+1214 #[cfg(not(wasm_browser))] port_mapper: portmapper::Client,
+1215 net_reporter: Arc<AsyncMutex<net_report::Client>>,
+1216 relay_map: RelayMap,
+1217 run_done: mpsc::Sender<()>,
+1218 ) -> Self {
+1219 DirectAddrUpdateState {
+1220 want_update: Default::default(),
+1221 #[cfg(not(wasm_browser))]
+1222 port_mapper,
+1223 net_reporter,
+1224 msock,
+1225 relay_map,
+1226 run_done,
+1227 }
+1228 }
+1229
+1230 /// Schedules a new run, either starting it immediately if none is running or
+1231 /// scheduling it for later.
+1232 fn schedule_run(&mut self, why: UpdateReason, if_state: IfStateDetails) {
+1233 match self.net_reporter.clone().try_lock_owned() {
+1234 Ok(net_reporter) => {
+1235 self.run(why, if_state, net_reporter);
+1236 }
+1237 Err(_) => {
+1238 let _ = self.want_update.insert(why);
+1239 }
+1240 }
+1241 }
+1242
+1243 /// If another run is needed, triggers this run, otherwise does nothing.
+1244 fn try_run(&mut self, if_state: IfStateDetails) {
+1245 match self.net_reporter.clone().try_lock_owned() {
+1246 Ok(net_reporter) => {
+1247 if let Some(why) = self.want_update.take() {
+1248 self.run(why, if_state, net_reporter);
+1249 }
+1250 }
+1251 Err(_) => {
+1252 // do nothing
+1253 }
+1254 }
+1255 }
+1256
+1257 /// Trigger a new run.
+1258 fn run(
+1259 &mut self,
+1260 why: UpdateReason,
+1261 if_state: IfStateDetails,
+1262 mut net_reporter: tokio::sync::OwnedMutexGuard<net_report::Client>,
+1263 ) {
+1264 debug!("starting direct addr update ({:?})", why);
+1265 #[cfg(not(wasm_browser))]
+1266 self.port_mapper.procure_mapping();
+1267 // Don't start a net report probe if we know
+1268 // we are shutting down
+1269 if self.msock.is_closing() || self.msock.is_closed() {
+1270 debug!("skipping net_report, socket is shutting down");
+1271 return;
+1272 }
+1273 if self.relay_map.is_empty() {
+1274 debug!("skipping net_report, empty RelayMap");
+1275 self.msock.net_report.set((None, why)).ok();
1276 return;
1277 }
-1278 if self.relay_map.is_empty() {
-1279 debug!("skipping net_report, empty RelayMap");
-1280 self.msock.net_report.set((None, why)).ok();
-1281 return;
-1282 }
-1283
-1284 debug!("requesting net_report report");
-1285 let msock = self.msock.clone();
-1286
-1287 let run_done = self.run_done.clone();
-1288 task::spawn(async move {
-1289 let fut = time::timeout(
-1290 NET_REPORT_TIMEOUT,
-1291 net_reporter.get_report(if_state, why.is_major()),
-1292 );
-1293 match fut.await {
-1294 Ok(report) => {
-1295 msock.net_report.set((Some(report), why)).ok();
-1296 }
-1297 Err(time::Elapsed { .. }) => {
-1298 warn!("net_report report timed out");
-1299 }
-1300 }
-1301
-1302 // mark run as finished
-1303 debug!("direct addr update done ({:?})", why);
-1304 run_done.send(()).await.ok();
-1305 });
-1306 }
-1307}
-1308
-1309#[allow(missing_docs)]
-1310#[common_fields({
-1311 backtrace: Option<snafu::Backtrace>,
-1312 #[snafu(implicit)]
-1313 span_trace: n0_snafu::SpanTrace,
-1314})]
-1315#[derive(Debug, Snafu)]
-1316#[non_exhaustive]
-1317pub enum CreateHandleError {
-1318 #[snafu(display("Failed to create bind sockets"))]
-1319 BindSockets { source: io::Error },
-1320 #[snafu(display("Failed to create internal quinn endpoint"))]
-1321 CreateQuinnEndpoint { source: io::Error },
-1322 #[snafu(display("Failed to create socket state"))]
-1323 CreateSocketState { source: io::Error },
-1324 #[snafu(display("Failed to create netmon monitor"))]
-1325 CreateNetmonMonitor { source: netmon::Error },
-1326 #[snafu(display("Failed to subscribe netmon monitor"))]
-1327 SubscribeNetmonMonitor { source: netmon::Error },
-1328}
-1329
-1330impl Handle {
-1331 /// Creates a magic [`MagicSock`] listening on [`Options::addr_v4`] and [`Options::addr_v6`].
-1332 async fn new(opts: Options) -> Result<Self, CreateHandleError> {
-1333 let Options {
-1334 addr_v4,
-1335 addr_v6,
-1336 secret_key,
-1337 relay_map,
-1338 relay_protocol,
-1339 node_map,
-1340 discovery,
-1341 discovery_user_data,
-1342 #[cfg(not(wasm_browser))]
-1343 dns_resolver,
-1344 proxy_url,
-1345 server_config,
-1346 #[cfg(any(test, feature = "test-utils"))]
-1347 insecure_skip_relay_cert_verify,
-1348 #[cfg(any(test, feature = "test-utils"))]
-1349 path_selection,
-1350 metrics,
-1351 } = opts;
-1352
-1353 let addr_v4 = addr_v4.unwrap_or_else(|| SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0));
-1354
-1355 #[cfg(not(wasm_browser))]
-1356 let (ip_transports, port_mapper) =
-1357 bind_ip(addr_v4, addr_v6, &metrics).context(BindSocketsSnafu)?;
-1358
-1359 let ip_mapped_addrs = IpMappedAddresses::default();
-1360
-1361 let (actor_sender, actor_receiver) = mpsc::channel(256);
-1362
-1363 // load the node data
-1364 let node_map = node_map.unwrap_or_default();
-1365 #[cfg(any(test, feature = "test-utils"))]
-1366 let node_map = NodeMap::load_from_vec(node_map, path_selection, &metrics.magicsock);
-1367 #[cfg(not(any(test, feature = "test-utils")))]
-1368 let node_map = NodeMap::load_from_vec(node_map, &metrics.magicsock);
-1369
-1370 let my_relay = Watchable::new(None);
-1371 let ipv6_reported = Arc::new(AtomicBool::new(false));
-1372
-1373 let relay_transport = RelayTransport::new(RelayActorConfig {
-1374 my_relay: my_relay.clone(),
-1375 secret_key: secret_key.clone(),
-1376 #[cfg(not(wasm_browser))]
-1377 dns_resolver: dns_resolver.clone(),
-1378 proxy_url: proxy_url.clone(),
-1379 ipv6_reported: ipv6_reported.clone(),
-1380 #[cfg(any(test, feature = "test-utils"))]
-1381 insecure_skip_relay_cert_verify,
-1382 metrics: metrics.magicsock.clone(),
-1383 protocol: relay_protocol,
-1384 });
-1385 let relay_transports = vec![relay_transport];
-1386
-1387 let secret_encryption_key = secret_ed_box(secret_key.secret());
-1388 #[cfg(not(wasm_browser))]
-1389 let ipv6 = ip_transports.iter().any(|t| t.bind_addr().is_ipv6());
+1278
+1279 debug!("requesting net_report report");
+1280 let msock = self.msock.clone();
+1281
+1282 let run_done = self.run_done.clone();
+1283 task::spawn(async move {
+1284 let fut = time::timeout(
+1285 NET_REPORT_TIMEOUT,
+1286 net_reporter.get_report(if_state, why.is_major()),
+1287 );
+1288 match fut.await {
+1289 Ok(report) => {
+1290 msock.net_report.set((Some(report), why)).ok();
+1291 }
+1292 Err(time::Elapsed { .. }) => {
+1293 warn!("net_report report timed out");
+1294 }
+1295 }
+1296
+1297 // mark run as finished
+1298 debug!("direct addr update done ({:?})", why);
+1299 run_done.send(()).await.ok();
+1300 });
+1301 }
+1302}
+1303
+1304#[allow(missing_docs)]
+1305#[common_fields({
+1306 backtrace: Option<snafu::Backtrace>,
+1307 #[snafu(implicit)]
+1308 span_trace: n0_snafu::SpanTrace,
+1309})]
+1310#[derive(Debug, Snafu)]
+1311#[non_exhaustive]
+1312pub enum CreateHandleError {
+1313 #[snafu(display("Failed to create bind sockets"))]
+1314 BindSockets { source: io::Error },
+1315 #[snafu(display("Failed to create internal quinn endpoint"))]
+1316 CreateQuinnEndpoint { source: io::Error },
+1317 #[snafu(display("Failed to create socket state"))]
+1318 CreateSocketState { source: io::Error },
+1319 #[snafu(display("Failed to create netmon monitor"))]
+1320 CreateNetmonMonitor { source: netmon::Error },
+1321 #[snafu(display("Failed to subscribe netmon monitor"))]
+1322 SubscribeNetmonMonitor { source: netmon::Error },
+1323}
+1324
+1325impl Handle {
+1326 /// Creates a magic [`MagicSock`] listening on [`Options::addr_v4`] and [`Options::addr_v6`].
+1327 async fn new(opts: Options) -> Result<Self, CreateHandleError> {
+1328 let Options {
+1329 addr_v4,
+1330 addr_v6,
+1331 secret_key,
+1332 relay_map,
+1333 relay_protocol,
+1334 node_map,
+1335 discovery,
+1336 discovery_user_data,
+1337 #[cfg(not(wasm_browser))]
+1338 dns_resolver,
+1339 proxy_url,
+1340 server_config,
+1341 #[cfg(any(test, feature = "test-utils"))]
+1342 insecure_skip_relay_cert_verify,
+1343 #[cfg(any(test, feature = "test-utils"))]
+1344 path_selection,
+1345 metrics,
+1346 } = opts;
+1347
+1348 let addr_v4 = addr_v4.unwrap_or_else(|| SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0));
+1349
+1350 #[cfg(not(wasm_browser))]
+1351 let (ip_transports, port_mapper) =
+1352 bind_ip(addr_v4, addr_v6, &metrics).context(BindSocketsSnafu)?;
+1353
+1354 let ip_mapped_addrs = IpMappedAddresses::default();
+1355
+1356 let (actor_sender, actor_receiver) = mpsc::channel(256);
+1357
+1358 // load the node data
+1359 let node_map = node_map.unwrap_or_default();
+1360 #[cfg(any(test, feature = "test-utils"))]
+1361 let node_map = NodeMap::load_from_vec(node_map, path_selection, &metrics.magicsock);
+1362 #[cfg(not(any(test, feature = "test-utils")))]
+1363 let node_map = NodeMap::load_from_vec(node_map, &metrics.magicsock);
+1364
+1365 let my_relay = Watchable::new(None);
+1366 let ipv6_reported = Arc::new(AtomicBool::new(false));
+1367
+1368 let relay_transport = RelayTransport::new(RelayActorConfig {
+1369 my_relay: my_relay.clone(),
+1370 secret_key: secret_key.clone(),
+1371 #[cfg(not(wasm_browser))]
+1372 dns_resolver: dns_resolver.clone(),
+1373 proxy_url: proxy_url.clone(),
+1374 ipv6_reported: ipv6_reported.clone(),
+1375 #[cfg(any(test, feature = "test-utils"))]
+1376 insecure_skip_relay_cert_verify,
+1377 metrics: metrics.magicsock.clone(),
+1378 protocol: relay_protocol,
+1379 });
+1380 let relay_transports = vec![relay_transport];
+1381
+1382 let secret_encryption_key = secret_ed_box(secret_key.secret());
+1383 #[cfg(not(wasm_browser))]
+1384 let ipv6 = ip_transports.iter().any(|t| t.bind_addr().is_ipv6());
+1385
+1386 #[cfg(not(wasm_browser))]
+1387 let transports = Transports::new(ip_transports, relay_transports);
+1388 #[cfg(wasm_browser)]
+1389 let transports = Transports::new(relay_transports);
1390
-1391 #[cfg(not(wasm_browser))]
-1392 let transports = Transports::new(ip_transports, relay_transports);
-1393 #[cfg(wasm_browser)]
-1394 let transports = Transports::new(relay_transports);
-1395
-1396 let (disco, disco_receiver) = DiscoState::new(secret_encryption_key);
-1397
-1398 let msock = Arc::new(MagicSock {
-1399 public_key: secret_key.public(),
-1400 closing: AtomicBool::new(false),
-1401 closed: AtomicBool::new(false),
-1402 disco,
-1403 actor_sender: actor_sender.clone(),
-1404 ipv6_reported,
-1405 node_map,
-1406 connection_map: Default::default(),
-1407 ip_mapped_addrs: ip_mapped_addrs.clone(),
-1408 discovery,
-1409 discovery_user_data: RwLock::new(discovery_user_data),
-1410 direct_addrs: Default::default(),
-1411 net_report: Watchable::new((None, UpdateReason::None)),
+1391 let (disco, disco_receiver) = DiscoState::new(secret_encryption_key);
+1392
+1393 let msock = Arc::new(MagicSock {
+1394 public_key: secret_key.public(),
+1395 closing: AtomicBool::new(false),
+1396 closed: AtomicBool::new(false),
+1397 disco,
+1398 actor_sender: actor_sender.clone(),
+1399 ipv6_reported,
+1400 node_map,
+1401 connection_map: Default::default(),
+1402 ip_mapped_addrs: ip_mapped_addrs.clone(),
+1403 discovery,
+1404 discovery_user_data: RwLock::new(discovery_user_data),
+1405 direct_addrs: Default::default(),
+1406 net_report: Watchable::new((None, UpdateReason::None)),
+1407 #[cfg(not(wasm_browser))]
+1408 dns_resolver: dns_resolver.clone(),
+1409 discovery_subscribers: DiscoverySubscribers::new(),
+1410 metrics: metrics.clone(),
+1411 local_addrs_watch: transports.local_addrs_watch(),
1412 #[cfg(not(wasm_browser))]
-1413 dns_resolver: dns_resolver.clone(),
-1414 discovery_subscribers: DiscoverySubscribers::new(),
-1415 metrics: metrics.clone(),
-1416 local_addrs_watch: transports.local_addrs_watch(),
-1417 #[cfg(not(wasm_browser))]
-1418 ip_bind_addrs: transports.ip_bind_addrs(),
-1419 });
-1420
-1421 let mut endpoint_config = quinn::EndpointConfig::default();
-1422 // Setting this to false means that quinn will ignore packets that have the QUIC fixed bit
-1423 // set to 0. The fixed bit is the 3rd bit of the first byte of a packet.
-1424 // For performance reasons and to not rewrite buffers we pass non-QUIC UDP packets straight
-1425 // through to quinn. We set the first byte of the packet to zero, which makes quinn ignore
-1426 // the packet if grease_quic_bit is set to false.
-1427 endpoint_config.grease_quic_bit(false);
-1428
-1429 let sender = transports.create_sender(msock.clone());
-1430 let local_addrs_watch = transports.local_addrs_watch();
-1431 let network_change_sender = transports.create_network_change_sender();
-1432
-1433 let endpoint = quinn::Endpoint::new_with_abstract_socket(
-1434 endpoint_config,
-1435 Some(server_config),
-1436 Box::new(MagicUdpSocket {
-1437 socket: msock.clone(),
-1438 transports,
-1439 }),
-1440 #[cfg(not(wasm_browser))]
-1441 Arc::new(quinn::TokioRuntime),
-1442 #[cfg(wasm_browser)]
-1443 Arc::new(crate::web_runtime::WebRuntime),
-1444 )
-1445 .context(CreateQuinnEndpointSnafu)?;
-1446
-1447 let network_monitor = netmon::Monitor::new()
-1448 .await
-1449 .context(CreateNetmonMonitorSnafu)?;
-1450
-1451 let qad_endpoint = endpoint.clone();
-1452
-1453 #[cfg(any(test, feature = "test-utils"))]
-1454 let client_config = if insecure_skip_relay_cert_verify {
-1455 iroh_relay::client::make_dangerous_client_config()
-1456 } else {
-1457 default_quic_client_config()
-1458 };
-1459 #[cfg(not(any(test, feature = "test-utils")))]
-1460 let client_config = default_quic_client_config();
-1461
-1462 let net_report_config = net_report::Options::default();
-1463 #[cfg(not(wasm_browser))]
-1464 let net_report_config = net_report_config.quic_config(Some(QuicConfig {
-1465 ep: qad_endpoint,
-1466 client_config,
-1467 ipv4: true,
-1468 ipv6,
-1469 }));
-1470
-1471 #[cfg(any(test, feature = "test-utils"))]
-1472 let net_report_config =
-1473 net_report_config.insecure_skip_relay_cert_verify(insecure_skip_relay_cert_verify);
-1474
-1475 let net_reporter = net_report::Client::new(
-1476 #[cfg(not(wasm_browser))]
-1477 dns_resolver,
-1478 #[cfg(not(wasm_browser))]
-1479 Some(ip_mapped_addrs),
-1480 relay_map.clone(),
-1481 net_report_config,
-1482 metrics.net_report.clone(),
-1483 );
-1484
-1485 let (direct_addr_done_tx, direct_addr_done_rx) = mpsc::channel(8);
-1486 let direct_addr_update_state = DirectAddrUpdateState::new(
-1487 msock.clone(),
-1488 #[cfg(not(wasm_browser))]
-1489 port_mapper,
-1490 Arc::new(AsyncMutex::new(net_reporter)),
-1491 relay_map,
-1492 direct_addr_done_tx,
-1493 );
-1494
-1495 let netmon_watcher = network_monitor.interface_state();
-1496 let actor = Actor {
-1497 msg_receiver: actor_receiver,
-1498 msock: msock.clone(),
-1499 periodic_re_stun_timer: new_re_stun_timer(false),
-1500 network_monitor,
-1501 netmon_watcher,
-1502 direct_addr_update_state,
-1503 network_change_sender,
-1504 direct_addr_done_rx,
-1505 pending_call_me_maybes: Default::default(),
-1506 disco_receiver,
-1507 };
-1508
-1509 let actor_token = CancellationToken::new();
-1510 let token = actor_token.clone();
-1511 let actor_task = task::spawn(
-1512 actor
-1513 .run(token, local_addrs_watch, sender)
-1514 .instrument(info_span!("actor")),
-1515 );
-1516
-1517 let actor_task = Arc::new(Mutex::new(Some(AbortOnDropHandle::new(actor_task))));
-1518
-1519 Ok(Handle {
-1520 msock,
-1521 actor_task,
-1522 endpoint,
-1523 actor_token,
-1524 })
+1413 ip_bind_addrs: transports.ip_bind_addrs(),
+1414 });
+1415
+1416 let mut endpoint_config = quinn::EndpointConfig::default();
+1417 // Setting this to false means that quinn will ignore packets that have the QUIC fixed bit
+1418 // set to 0. The fixed bit is the 3rd bit of the first byte of a packet.
+1419 // For performance reasons and to not rewrite buffers we pass non-QUIC UDP packets straight
+1420 // through to quinn. We set the first byte of the packet to zero, which makes quinn ignore
+1421 // the packet if grease_quic_bit is set to false.
+1422 endpoint_config.grease_quic_bit(false);
+1423
+1424 let sender = transports.create_sender(msock.clone());
+1425 let local_addrs_watch = transports.local_addrs_watch();
+1426 let network_change_sender = transports.create_network_change_sender();
+1427
+1428 let endpoint = quinn::Endpoint::new_with_abstract_socket(
+1429 endpoint_config,
+1430 Some(server_config),
+1431 Box::new(MagicUdpSocket {
+1432 socket: msock.clone(),
+1433 transports,
+1434 }),
+1435 #[cfg(not(wasm_browser))]
+1436 Arc::new(quinn::TokioRuntime),
+1437 #[cfg(wasm_browser)]
+1438 Arc::new(crate::web_runtime::WebRuntime),
+1439 )
+1440 .context(CreateQuinnEndpointSnafu)?;
+1441
+1442 let network_monitor = netmon::Monitor::new()
+1443 .await
+1444 .context(CreateNetmonMonitorSnafu)?;
+1445
+1446 let qad_endpoint = endpoint.clone();
+1447
+1448 #[cfg(any(test, feature = "test-utils"))]
+1449 let client_config = if insecure_skip_relay_cert_verify {
+1450 iroh_relay::client::make_dangerous_client_config()
+1451 } else {
+1452 default_quic_client_config()
+1453 };
+1454 #[cfg(not(any(test, feature = "test-utils")))]
+1455 let client_config = default_quic_client_config();
+1456
+1457 let net_report_config = net_report::Options::default();
+1458 #[cfg(not(wasm_browser))]
+1459 let net_report_config = net_report_config.quic_config(Some(QuicConfig {
+1460 ep: qad_endpoint,
+1461 client_config,
+1462 ipv4: true,
+1463 ipv6,
+1464 }));
+1465
+1466 #[cfg(any(test, feature = "test-utils"))]
+1467 let net_report_config =
+1468 net_report_config.insecure_skip_relay_cert_verify(insecure_skip_relay_cert_verify);
+1469
+1470 let net_reporter = net_report::Client::new(
+1471 #[cfg(not(wasm_browser))]
+1472 dns_resolver,
+1473 #[cfg(not(wasm_browser))]
+1474 Some(ip_mapped_addrs),
+1475 relay_map.clone(),
+1476 net_report_config,
+1477 metrics.net_report.clone(),
+1478 );
+1479
+1480 let (direct_addr_done_tx, direct_addr_done_rx) = mpsc::channel(8);
+1481 let direct_addr_update_state = DirectAddrUpdateState::new(
+1482 msock.clone(),
+1483 #[cfg(not(wasm_browser))]
+1484 port_mapper,
+1485 Arc::new(AsyncMutex::new(net_reporter)),
+1486 relay_map,
+1487 direct_addr_done_tx,
+1488 );
+1489
+1490 let netmon_watcher = network_monitor.interface_state();
+1491 let actor = Actor {
+1492 msg_receiver: actor_receiver,
+1493 msock: msock.clone(),
+1494 periodic_re_stun_timer: new_re_stun_timer(false),
+1495 network_monitor,
+1496 netmon_watcher,
+1497 direct_addr_update_state,
+1498 network_change_sender,
+1499 direct_addr_done_rx,
+1500 pending_call_me_maybes: Default::default(),
+1501 disco_receiver,
+1502 };
+1503
+1504 let actor_token = CancellationToken::new();
+1505 let token = actor_token.clone();
+1506 let actor_task = task::spawn(
+1507 actor
+1508 .run(token, local_addrs_watch, sender)
+1509 .instrument(info_span!("actor")),
+1510 );
+1511
+1512 let actor_task = Arc::new(Mutex::new(Some(AbortOnDropHandle::new(actor_task))));
+1513
+1514 Ok(Handle {
+1515 msock,
+1516 actor_task,
+1517 endpoint,
+1518 actor_token,
+1519 })
+1520 }
+1521
+1522 /// The underlying [`quinn::Endpoint`]
+1523 pub fn endpoint(&self) -> &quinn::Endpoint {
+1524 &self.endpoint
1525 }
1526
-1527 /// The underlying [`quinn::Endpoint`]
-1528 pub fn endpoint(&self) -> &quinn::Endpoint {
-1529 &self.endpoint
-1530 }
-1531
-1532 /// Closes the connection.
-1533 ///
-1534 /// Only the first close does anything. Any later closes return nil.
-1535 /// Polling the socket ([`AsyncUdpSocket::poll_recv`]) will return [`Poll::Pending`]
-1536 /// indefinitely after this call.
-1537 #[instrument(skip_all)]
-1538 pub(crate) async fn close(&self) {
-1539 trace!(me = ?self.public_key, "magicsock closing...");
-1540 // Initiate closing all connections, and refuse future connections.
-1541 self.endpoint.close(0u16.into(), b"");
-1542
-1543 // In the history of this code, this call had been
-1544 // - removed: https://github.com/n0-computer/iroh/pull/1753
-1545 // - then added back in: https://github.com/n0-computer/iroh/pull/2227/files#diff-ba27e40e2986a3919b20f6b412ad4fe63154af648610ea5d9ed0b5d5b0e2d780R573
-1546 // - then removed again: https://github.com/n0-computer/iroh/pull/3165
-1547 // and finally added back in together with this comment.
-1548 // So before removing this call, please consider carefully.
-1549 // Among other things, this call tries its best to make sure that any queued close frames
-1550 // (e.g. via the call to `endpoint.close(...)` above), are flushed out to the sockets
-1551 // *and acknowledged* (or time out with the "probe timeout" of usually 3 seconds).
-1552 // This allows the other endpoints for these connections to be notified to release
-1553 // their resources, or - depending on the protocol - that all data was received.
-1554 // With the current quinn API, this is the only way to ensure protocol code can use
-1555 // connection close codes, and close the endpoint properly.
-1556 // If this call is skipped, then connections that protocols close just shortly before the
-1557 // call to `Endpoint::close` will in most cases cause connection time-outs on remote ends.
-1558 self.endpoint.wait_idle().await;
-1559
-1560 if self.msock.is_closed() {
-1561 return;
-1562 }
-1563 self.msock.closing.store(true, Ordering::Relaxed);
-1564 self.actor_token.cancel();
-1565
-1566 // MutexGuard is not held across await points
-1567 let task = self.actor_task.lock().expect("poisoned").take();
-1568 if let Some(task) = task {
-1569 // give the tasks a moment to shutdown cleanly
-1570 let shutdown_done = time::timeout(Duration::from_millis(100), async move {
-1571 if let Err(err) = task.await {
-1572 warn!("unexpected error in task shutdown: {:?}", err);
-1573 }
-1574 })
-1575 .await;
-1576 match shutdown_done {
-1577 Ok(_) => trace!("tasks finished in time, shutdown complete"),
-1578 Err(time::Elapsed { .. }) => {
-1579 // Dropping the task will abort itt
-1580 warn!("tasks didn't finish in time, aborting");
-1581 }
-1582 }
-1583 }
-1584
-1585 self.msock.closed.store(true, Ordering::SeqCst);
-1586
-1587 trace!("magicsock closed");
-1588 }
-1589}
-1590
-1591fn default_quic_client_config() -> rustls::ClientConfig {
-1592 // create a client config for the endpoint to use for QUIC address discovery
-1593 let root_store =
-1594 rustls::RootCertStore::from_iter(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());
-1595 rustls::client::ClientConfig::builder_with_provider(Arc::new(
-1596 rustls::crypto::ring::default_provider(),
-1597 ))
-1598 .with_safe_default_protocol_versions()
-1599 .expect("ring supports these")
-1600 .with_root_certificates(root_store)
-1601 .with_no_client_auth()
-1602}
-1603
-1604#[derive(Debug)]
-1605struct DiscoState {
-1606 /// Encryption key for this node.
-1607 secret_encryption_key: crypto_box::SecretKey,
-1608 /// The state for an active DiscoKey.
-1609 secrets: Mutex<HashMap<PublicKey, SharedSecret>>,
-1610 /// Disco (ping) queue
-1611 sender: mpsc::Sender<(SendAddr, PublicKey, disco::Message)>,
-1612}
-1613
-1614impl DiscoState {
-1615 fn new(
-1616 secret_encryption_key: crypto_box::SecretKey,
-1617 ) -> (Self, mpsc::Receiver<(SendAddr, PublicKey, disco::Message)>) {
-1618 let (disco_sender, disco_receiver) = mpsc::channel(256);
-1619
-1620 (
-1621 Self {
-1622 secret_encryption_key,
-1623 secrets: Default::default(),
-1624 sender: disco_sender,
-1625 },
-1626 disco_receiver,
-1627 )
-1628 }
-1629
-1630 fn try_send(&self, dst: SendAddr, node_id: PublicKey, msg: disco::Message) -> bool {
-1631 self.sender.try_send((dst, node_id, msg)).is_ok()
-1632 }
-1633
-1634 fn encode_and_seal(
-1635 &self,
-1636 this_node_id: NodeId,
-1637 other_node_id: NodeId,
-1638 msg: &disco::Message,
-1639 ) -> Bytes {
-1640 let mut seal = msg.as_bytes();
-1641 self.get_secret(other_node_id, |secret| secret.seal(&mut seal));
-1642 disco::encode_message(&this_node_id, seal).into()
-1643 }
-1644
-1645 fn unseal_and_decode(
-1646 &self,
-1647 node_id: PublicKey,
-1648 sealed_box: &[u8],
-1649 ) -> Result<disco::Message, DiscoBoxError> {
-1650 let mut sealed_box = sealed_box.to_vec();
-1651 self.get_secret(node_id, |secret| secret.open(&mut sealed_box))
-1652 .context(OpenSnafu)?;
-1653 disco::Message::from_bytes(&sealed_box).context(ParseSnafu)
-1654 }
-1655
-1656 fn get_secret<F, T>(&self, node_id: PublicKey, cb: F) -> T
-1657 where
-1658 F: FnOnce(&mut SharedSecret) -> T,
-1659 {
-1660 let mut inner = self.secrets.lock().expect("poisoned");
-1661 let x = inner.entry(node_id).or_insert_with(|| {
-1662 let public_key = public_ed_box(&node_id.public());
-1663 SharedSecret::new(&self.secret_encryption_key, &public_key)
-1664 });
-1665 cb(x)
-1666 }
-1667}
-1668
-1669#[allow(missing_docs)]
-1670#[common_fields({
-1671 backtrace: Option<snafu::Backtrace>,
-1672 #[snafu(implicit)]
-1673 span_trace: n0_snafu::SpanTrace,
-1674})]
-1675#[derive(Debug, Snafu)]
-1676#[non_exhaustive]
-1677enum DiscoBoxError {
-1678 #[snafu(display("Failed to open crypto box"))]
-1679 Open {
-1680 #[snafu(source(from(DecryptionError, Box::new)))]
-1681 source: Box<DecryptionError>,
+1527 /// Closes the connection.
+1528 ///
+1529 /// Only the first close does anything. Any later closes return nil.
+1530 /// Polling the socket ([`AsyncUdpSocket::poll_recv`]) will return [`Poll::Pending`]
+1531 /// indefinitely after this call.
+1532 #[instrument(skip_all)]
+1533 pub(crate) async fn close(&self) {
+1534 trace!(me = ?self.public_key, "magicsock closing...");
+1535 // Initiate closing all connections, and refuse future connections.
+1536 self.endpoint.close(0u16.into(), b"");
+1537
+1538 // In the history of this code, this call had been
+1539 // - removed: https://github.com/n0-computer/iroh/pull/1753
+1540 // - then added back in: https://github.com/n0-computer/iroh/pull/2227/files#diff-ba27e40e2986a3919b20f6b412ad4fe63154af648610ea5d9ed0b5d5b0e2d780R573
+1541 // - then removed again: https://github.com/n0-computer/iroh/pull/3165
+1542 // and finally added back in together with this comment.
+1543 // So before removing this call, please consider carefully.
+1544 // Among other things, this call tries its best to make sure that any queued close frames
+1545 // (e.g. via the call to `endpoint.close(...)` above), are flushed out to the sockets
+1546 // *and acknowledged* (or time out with the "probe timeout" of usually 3 seconds).
+1547 // This allows the other endpoints for these connections to be notified to release
+1548 // their resources, or - depending on the protocol - that all data was received.
+1549 // With the current quinn API, this is the only way to ensure protocol code can use
+1550 // connection close codes, and close the endpoint properly.
+1551 // If this call is skipped, then connections that protocols close just shortly before the
+1552 // call to `Endpoint::close` will in most cases cause connection time-outs on remote ends.
+1553 self.endpoint.wait_idle().await;
+1554
+1555 if self.msock.is_closed() {
+1556 return;
+1557 }
+1558 self.msock.closing.store(true, Ordering::Relaxed);
+1559 self.actor_token.cancel();
+1560
+1561 // MutexGuard is not held across await points
+1562 let task = self.actor_task.lock().expect("poisoned").take();
+1563 if let Some(task) = task {
+1564 // give the tasks a moment to shutdown cleanly
+1565 let shutdown_done = time::timeout(Duration::from_millis(100), async move {
+1566 if let Err(err) = task.await {
+1567 warn!("unexpected error in task shutdown: {:?}", err);
+1568 }
+1569 })
+1570 .await;
+1571 match shutdown_done {
+1572 Ok(_) => trace!("tasks finished in time, shutdown complete"),
+1573 Err(time::Elapsed { .. }) => {
+1574 // Dropping the task will abort itt
+1575 warn!("tasks didn't finish in time, aborting");
+1576 }
+1577 }
+1578 }
+1579
+1580 self.msock.closed.store(true, Ordering::SeqCst);
+1581
+1582 trace!("magicsock closed");
+1583 }
+1584}
+1585
+1586fn default_quic_client_config() -> rustls::ClientConfig {
+1587 // create a client config for the endpoint to use for QUIC address discovery
+1588 let root_store =
+1589 rustls::RootCertStore::from_iter(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());
+1590 rustls::client::ClientConfig::builder_with_provider(Arc::new(
+1591 rustls::crypto::ring::default_provider(),
+1592 ))
+1593 .with_safe_default_protocol_versions()
+1594 .expect("ring supports these")
+1595 .with_root_certificates(root_store)
+1596 .with_no_client_auth()
+1597}
+1598
+1599#[derive(Debug)]
+1600struct DiscoState {
+1601 /// Encryption key for this node.
+1602 secret_encryption_key: crypto_box::SecretKey,
+1603 /// The state for an active DiscoKey.
+1604 secrets: Mutex<HashMap<PublicKey, SharedSecret>>,
+1605 /// Disco (ping) queue
+1606 sender: mpsc::Sender<(SendAddr, PublicKey, disco::Message)>,
+1607}
+1608
+1609impl DiscoState {
+1610 fn new(
+1611 secret_encryption_key: crypto_box::SecretKey,
+1612 ) -> (Self, mpsc::Receiver<(SendAddr, PublicKey, disco::Message)>) {
+1613 let (disco_sender, disco_receiver) = mpsc::channel(256);
+1614
+1615 (
+1616 Self {
+1617 secret_encryption_key,
+1618 secrets: Default::default(),
+1619 sender: disco_sender,
+1620 },
+1621 disco_receiver,
+1622 )
+1623 }
+1624
+1625 fn try_send(&self, dst: SendAddr, node_id: PublicKey, msg: disco::Message) -> bool {
+1626 self.sender.try_send((dst, node_id, msg)).is_ok()
+1627 }
+1628
+1629 fn encode_and_seal(
+1630 &self,
+1631 this_node_id: NodeId,
+1632 other_node_id: NodeId,
+1633 msg: &disco::Message,
+1634 ) -> Bytes {
+1635 let mut seal = msg.as_bytes();
+1636 self.get_secret(other_node_id, |secret| secret.seal(&mut seal));
+1637 disco::encode_message(&this_node_id, seal).into()
+1638 }
+1639
+1640 fn unseal_and_decode(
+1641 &self,
+1642 node_id: PublicKey,
+1643 sealed_box: &[u8],
+1644 ) -> Result<disco::Message, DiscoBoxError> {
+1645 let mut sealed_box = sealed_box.to_vec();
+1646 self.get_secret(node_id, |secret| secret.open(&mut sealed_box))
+1647 .context(OpenSnafu)?;
+1648 disco::Message::from_bytes(&sealed_box).context(ParseSnafu)
+1649 }
+1650
+1651 fn get_secret<F, T>(&self, node_id: PublicKey, cb: F) -> T
+1652 where
+1653 F: FnOnce(&mut SharedSecret) -> T,
+1654 {
+1655 let mut inner = self.secrets.lock().expect("poisoned");
+1656 let x = inner.entry(node_id).or_insert_with(|| {
+1657 let public_key = public_ed_box(&node_id.public());
+1658 SharedSecret::new(&self.secret_encryption_key, &public_key)
+1659 });
+1660 cb(x)
+1661 }
+1662}
+1663
+1664#[allow(missing_docs)]
+1665#[common_fields({
+1666 backtrace: Option<snafu::Backtrace>,
+1667 #[snafu(implicit)]
+1668 span_trace: n0_snafu::SpanTrace,
+1669})]
+1670#[derive(Debug, Snafu)]
+1671#[non_exhaustive]
+1672enum DiscoBoxError {
+1673 #[snafu(display("Failed to open crypto box"))]
+1674 Open {
+1675 #[snafu(source(from(DecryptionError, Box::new)))]
+1676 source: Box<DecryptionError>,
+1677 },
+1678 #[snafu(display("Failed to parse disco message"))]
+1679 Parse {
+1680 #[snafu(source(from(disco::ParseError, Box::new)))]
+1681 source: Box<disco::ParseError>,
1682 },
-1683 #[snafu(display("Failed to parse disco message"))]
-1684 Parse {
-1685 #[snafu(source(from(disco::ParseError, Box::new)))]
-1686 source: Box<disco::ParseError>,
-1687 },
-1688}
-1689
-1690#[derive(Debug)]
-1691struct MagicUdpSocket {
-1692 socket: Arc<MagicSock>,
-1693 transports: Transports,
-1694}
+1683}
+1684
+1685#[derive(Debug)]
+1686struct MagicUdpSocket {
+1687 socket: Arc<MagicSock>,
+1688 transports: Transports,
+1689}
+1690
+1691impl AsyncUdpSocket for MagicUdpSocket {
+1692 fn create_sender(&self) -> Pin<Box<dyn quinn::UdpSender>> {
+1693 Box::pin(self.transports.create_sender(self.socket.clone()))
+1694 }
1695
-1696impl AsyncUdpSocket for MagicUdpSocket {
-1697 fn create_sender(&self) -> Pin<Box<dyn quinn::UdpSender>> {
-1698 Box::pin(self.transports.create_sender(self.socket.clone()))
-1699 }
-1700
-1701 /// NOTE: Receiving on a closed socket will return [`Poll::Pending`] indefinitely.
-1702 fn poll_recv(
-1703 &mut self,
-1704 cx: &mut Context,
-1705 bufs: &mut [io::IoSliceMut<'_>],
-1706 metas: &mut [quinn_udp::RecvMeta],
-1707 ) -> Poll<io::Result<usize>> {
-1708 self.transports.poll_recv(cx, bufs, metas, &self.socket)
-1709 }
-1710
-1711 #[cfg(not(wasm_browser))]
-1712 fn local_addr(&self) -> io::Result<SocketAddr> {
-1713 let addrs: Vec<_> = self
-1714 .transports
-1715 .local_addrs()
-1716 .into_iter()
-1717 .filter_map(|addr| {
-1718 let addr: SocketAddr = addr.into_socket_addr()?;
-1719 Some(addr)
-1720 })
-1721 .collect();
-1722
-1723 if let Some(addr) = addrs.iter().find(|addr| addr.is_ipv6()) {
-1724 return Ok(*addr);
+1696 /// NOTE: Receiving on a closed socket will return [`Poll::Pending`] indefinitely.
+1697 fn poll_recv(
+1698 &mut self,
+1699 cx: &mut Context,
+1700 bufs: &mut [io::IoSliceMut<'_>],
+1701 metas: &mut [quinn_udp::RecvMeta],
+1702 ) -> Poll<io::Result<usize>> {
+1703 self.transports.poll_recv(cx, bufs, metas, &self.socket)
+1704 }
+1705
+1706 #[cfg(not(wasm_browser))]
+1707 fn local_addr(&self) -> io::Result<SocketAddr> {
+1708 let addrs: Vec<_> = self
+1709 .transports
+1710 .local_addrs()
+1711 .into_iter()
+1712 .filter_map(|addr| {
+1713 let addr: SocketAddr = addr.into_socket_addr()?;
+1714 Some(addr)
+1715 })
+1716 .collect();
+1717
+1718 if let Some(addr) = addrs.iter().find(|addr| addr.is_ipv6()) {
+1719 return Ok(*addr);
+1720 }
+1721 if let Some(SocketAddr::V4(addr)) = addrs.first() {
+1722 // Pretend to be IPv6, because our `MappedAddr`s need to be IPv6.
+1723 let ip = addr.ip().to_ipv6_mapped().into();
+1724 return Ok(SocketAddr::new(ip, addr.port()));
1725 }
-1726 if let Some(SocketAddr::V4(addr)) = addrs.first() {
-1727 // Pretend to be IPv6, because our `MappedAddr`s need to be IPv6.
-1728 let ip = addr.ip().to_ipv6_mapped().into();
-1729 return Ok(SocketAddr::new(ip, addr.port()));
-1730 }
-1731
-1732 Err(io::Error::other("no valid address available"))
-1733 }
-1734
-1735 #[cfg(wasm_browser)]
-1736 fn local_addr(&self) -> io::Result<SocketAddr> {
-1737 // Again, we need to pretend we're IPv6, because of our `MappedAddr`s.
-1738 Ok(SocketAddr::new(std::net::Ipv6Addr::LOCALHOST.into(), 0))
-1739 }
-1740
-1741 fn max_receive_segments(&self) -> usize {
-1742 self.transports.max_receive_segments()
-1743 }
+1726
+1727 Err(io::Error::other("no valid address available"))
+1728 }
+1729
+1730 #[cfg(wasm_browser)]
+1731 fn local_addr(&self) -> io::Result<SocketAddr> {
+1732 // Again, we need to pretend we're IPv6, because of our `MappedAddr`s.
+1733 Ok(SocketAddr::new(std::net::Ipv6Addr::LOCALHOST.into(), 0))
+1734 }
+1735
+1736 fn max_receive_segments(&self) -> usize {
+1737 self.transports.max_receive_segments()
+1738 }
+1739
+1740 fn may_fragment(&self) -> bool {
+1741 self.transports.may_fragment()
+1742 }
+1743}
1744
-1745 fn may_fragment(&self) -> bool {
-1746 self.transports.may_fragment()
-1747 }
-1748}
-1749
-1750#[derive(Debug)]
-1751enum ActorMessage {
-1752 PingActions(Vec<PingAction>),
-1753 EndpointPingExpired(usize, stun_rs::TransactionId),
-1754 NetworkChange,
-1755 ScheduleDirectAddrUpdate(UpdateReason, Option<(NodeId, RelayUrl)>),
-1756 #[cfg(test)]
-1757 ForceNetworkChange(bool),
-1758}
-1759
-1760struct Actor {
-1761 msock: Arc<MagicSock>,
-1762 msg_receiver: mpsc::Receiver<ActorMessage>,
-1763 /// When set, is an AfterFunc timer that will call MagicSock::do_periodic_stun.
-1764 periodic_re_stun_timer: time::Interval,
-1765
-1766 network_monitor: netmon::Monitor,
-1767 netmon_watcher: n0_watcher::Direct<netmon::State>,
-1768 network_change_sender: transports::NetworkChangeSender,
-1769 /// Indicates the direct addr update state.
-1770 direct_addr_update_state: DirectAddrUpdateState,
-1771 direct_addr_done_rx: mpsc::Receiver<()>,
-1772
-1773 /// List of CallMeMaybe disco messages that should be sent out after
-1774 /// the next endpoint update completes
-1775 pending_call_me_maybes: HashMap<PublicKey, RelayUrl>,
-1776 disco_receiver: mpsc::Receiver<(SendAddr, PublicKey, disco::Message)>,
-1777}
-1778
-1779#[cfg(not(wasm_browser))]
-1780fn bind_ip(
-1781 addr_v4: SocketAddrV4,
-1782 addr_v6: Option<SocketAddrV6>,
-1783 metrics: &EndpointMetrics,
-1784) -> io::Result<(Vec<IpTransport>, portmapper::Client)> {
-1785 let port_mapper =
-1786 portmapper::Client::with_metrics(Default::default(), metrics.portmapper.clone());
-1787
-1788 let v4 = Arc::new(bind_with_fallback(SocketAddr::V4(addr_v4))?);
-1789 let ip4_port = v4.local_addr()?.port();
-1790 let ip6_port = ip4_port.checked_add(1).unwrap_or(ip4_port - 1);
-1791
-1792 let addr_v6 =
-1793 addr_v6.unwrap_or_else(|| SocketAddrV6::new(Ipv6Addr::UNSPECIFIED, ip6_port, 0, 0));
-1794
-1795 let v6 = match bind_with_fallback(SocketAddr::V6(addr_v6)) {
-1796 Ok(sock) => Some(Arc::new(sock)),
-1797 Err(err) => {
-1798 info!("bind ignoring IPv6 bind failure: {:?}", err);
-1799 None
-1800 }
-1801 };
-1802
-1803 let port = v4.local_addr().map_or(0, |p| p.port());
-1804
-1805 let mut ip = vec![IpTransport::new(
-1806 addr_v4.into(),
-1807 v4,
-1808 metrics.magicsock.clone(),
-1809 )];
-1810 if let Some(v6) = v6 {
-1811 ip.push(IpTransport::new(
-1812 addr_v6.into(),
-1813 v6,
-1814 metrics.magicsock.clone(),
-1815 ))
-1816 }
-1817
-1818 // NOTE: we can end up with a zero port if `netwatch::UdpSocket::socket_addr` fails
-1819 match port.try_into() {
-1820 Ok(non_zero_port) => {
-1821 port_mapper.update_local_port(non_zero_port);
-1822 }
-1823 Err(_zero_port) => debug!("Skipping port mapping with zero local port"),
-1824 }
-1825
-1826 Ok((ip, port_mapper))
-1827}
-1828
-1829impl Actor {
-1830 async fn run(
-1831 mut self,
-1832 shutdown_token: CancellationToken,
-1833 mut watcher: impl Watcher<Value = Vec<transports::Addr>> + Send + Sync,
-1834 sender: UdpSender,
-1835 ) {
-1836 // Initialize addresses
-1837 #[cfg(not(wasm_browser))]
-1838 self.update_direct_addresses(None);
-1839
-1840 // Setup network monitoring
-1841 let mut current_netmon_state = self.netmon_watcher.get().expect("missing network state");
-1842
-1843 #[cfg(not(wasm_browser))]
-1844 let mut direct_addr_heartbeat_timer = time::interval(HEARTBEAT_INTERVAL);
-1845
-1846 #[cfg(not(wasm_browser))]
-1847 let mut portmap_watcher = self
-1848 .direct_addr_update_state
-1849 .port_mapper
-1850 .watch_external_address();
-1851
-1852 let mut discovery_events: BoxStream<DiscoveryItem> = Box::pin(n0_future::stream::empty());
-1853 if let Some(d) = self.msock.discovery() {
-1854 if let Some(events) = d.subscribe() {
-1855 discovery_events = events;
-1856 }
-1857 }
-1858
-1859 let mut receiver_closed = false;
-1860 #[cfg_attr(wasm_browser, allow(unused_mut))]
-1861 let mut portmap_watcher_closed = false;
-1862
-1863 let mut net_report_watcher = self.msock.net_report.watch();
-1864
-1865 loop {
-1866 self.msock.metrics.magicsock.actor_tick_main.inc();
+1745#[derive(Debug)]
+1746enum ActorMessage {
+1747 PingActions(Vec<PingAction>),
+1748 EndpointPingExpired(usize, stun_rs::TransactionId),
+1749 NetworkChange,
+1750 ScheduleDirectAddrUpdate(UpdateReason, Option<(NodeId, RelayUrl)>),
+1751 #[cfg(test)]
+1752 ForceNetworkChange(bool),
+1753}
+1754
+1755struct Actor {
+1756 msock: Arc<MagicSock>,
+1757 msg_receiver: mpsc::Receiver<ActorMessage>,
+1758 /// When set, is an AfterFunc timer that will call MagicSock::do_periodic_stun.
+1759 periodic_re_stun_timer: time::Interval,
+1760
+1761 network_monitor: netmon::Monitor,
+1762 netmon_watcher: n0_watcher::Direct<netmon::State>,
+1763 network_change_sender: transports::NetworkChangeSender,
+1764 /// Indicates the direct addr update state.
+1765 direct_addr_update_state: DirectAddrUpdateState,
+1766 direct_addr_done_rx: mpsc::Receiver<()>,
+1767
+1768 /// List of CallMeMaybe disco messages that should be sent out after
+1769 /// the next endpoint update completes
+1770 pending_call_me_maybes: HashMap<PublicKey, RelayUrl>,
+1771 disco_receiver: mpsc::Receiver<(SendAddr, PublicKey, disco::Message)>,
+1772}
+1773
+1774#[cfg(not(wasm_browser))]
+1775fn bind_ip(
+1776 addr_v4: SocketAddrV4,
+1777 addr_v6: Option<SocketAddrV6>,
+1778 metrics: &EndpointMetrics,
+1779) -> io::Result<(Vec<IpTransport>, portmapper::Client)> {
+1780 let port_mapper =
+1781 portmapper::Client::with_metrics(Default::default(), metrics.portmapper.clone());
+1782
+1783 let v4 = Arc::new(bind_with_fallback(SocketAddr::V4(addr_v4))?);
+1784 let ip4_port = v4.local_addr()?.port();
+1785 let ip6_port = ip4_port.checked_add(1).unwrap_or(ip4_port - 1);
+1786
+1787 let addr_v6 =
+1788 addr_v6.unwrap_or_else(|| SocketAddrV6::new(Ipv6Addr::UNSPECIFIED, ip6_port, 0, 0));
+1789
+1790 let v6 = match bind_with_fallback(SocketAddr::V6(addr_v6)) {
+1791 Ok(sock) => Some(Arc::new(sock)),
+1792 Err(err) => {
+1793 info!("bind ignoring IPv6 bind failure: {:?}", err);
+1794 None
+1795 }
+1796 };
+1797
+1798 let port = v4.local_addr().map_or(0, |p| p.port());
+1799
+1800 let mut ip = vec![IpTransport::new(
+1801 addr_v4.into(),
+1802 v4,
+1803 metrics.magicsock.clone(),
+1804 )];
+1805 if let Some(v6) = v6 {
+1806 ip.push(IpTransport::new(
+1807 addr_v6.into(),
+1808 v6,
+1809 metrics.magicsock.clone(),
+1810 ))
+1811 }
+1812
+1813 // NOTE: we can end up with a zero port if `netwatch::UdpSocket::socket_addr` fails
+1814 match port.try_into() {
+1815 Ok(non_zero_port) => {
+1816 port_mapper.update_local_port(non_zero_port);
+1817 }
+1818 Err(_zero_port) => debug!("Skipping port mapping with zero local port"),
+1819 }
+1820
+1821 Ok((ip, port_mapper))
+1822}
+1823
+1824impl Actor {
+1825 async fn run(
+1826 mut self,
+1827 shutdown_token: CancellationToken,
+1828 mut watcher: impl Watcher<Value = Vec<transports::Addr>> + Send + Sync,
+1829 sender: UdpSender,
+1830 ) {
+1831 // Initialize addresses
+1832 #[cfg(not(wasm_browser))]
+1833 self.update_direct_addresses(None);
+1834
+1835 // Setup network monitoring
+1836 let mut current_netmon_state = self.netmon_watcher.get().expect("missing network state");
+1837
+1838 #[cfg(not(wasm_browser))]
+1839 let mut direct_addr_heartbeat_timer = time::interval(HEARTBEAT_INTERVAL);
+1840
+1841 #[cfg(not(wasm_browser))]
+1842 let mut portmap_watcher = self
+1843 .direct_addr_update_state
+1844 .port_mapper
+1845 .watch_external_address();
+1846
+1847 let mut discovery_events: BoxStream<DiscoveryItem> = Box::pin(n0_future::stream::empty());
+1848 if let Some(d) = self.msock.discovery() {
+1849 if let Some(events) = d.subscribe() {
+1850 discovery_events = events;
+1851 }
+1852 }
+1853
+1854 let mut receiver_closed = false;
+1855 #[cfg_attr(wasm_browser, allow(unused_mut))]
+1856 let mut portmap_watcher_closed = false;
+1857
+1858 let mut net_report_watcher = self.msock.net_report.watch();
+1859
+1860 loop {
+1861 self.msock.metrics.magicsock.actor_tick_main.inc();
+1862 #[cfg(not(wasm_browser))]
+1863 let portmap_watcher_changed = portmap_watcher.changed();
+1864 #[cfg(wasm_browser)]
+1865 let portmap_watcher_changed = n0_future::future::pending();
+1866
1867 #[cfg(not(wasm_browser))]
-1868 let portmap_watcher_changed = portmap_watcher.changed();
+1868 let direct_addr_heartbeat_timer_tick = direct_addr_heartbeat_timer.tick();
1869 #[cfg(wasm_browser)]
-1870 let portmap_watcher_changed = n0_future::future::pending();
+1870 let direct_addr_heartbeat_timer_tick = n0_future::future::pending();
1871
-1872 #[cfg(not(wasm_browser))]
-1873 let direct_addr_heartbeat_timer_tick = direct_addr_heartbeat_timer.tick();
-1874 #[cfg(wasm_browser)]
-1875 let direct_addr_heartbeat_timer_tick = n0_future::future::pending();
-1876
-1877 tokio::select! {
-1878 _ = shutdown_token.cancelled() => {
-1879 debug!("shutting down");
-1880 return;
-1881 }
-1882 msg = self.msg_receiver.recv(), if !receiver_closed => {
-1883 let Some(msg) = msg else {
-1884 trace!("tick: magicsock receiver closed");
-1885 self.msock.metrics.magicsock.actor_tick_other.inc();
-1886
-1887 receiver_closed = true;
-1888 continue;
-1889 };
-1890
-1891 trace!(?msg, "tick: msg");
-1892 self.msock.metrics.magicsock.actor_tick_msg.inc();
-1893 self.handle_actor_message(msg, &sender).await;
+1872 tokio::select! {
+1873 _ = shutdown_token.cancelled() => {
+1874 debug!("shutting down");
+1875 return;
+1876 }
+1877 msg = self.msg_receiver.recv(), if !receiver_closed => {
+1878 let Some(msg) = msg else {
+1879 trace!("tick: magicsock receiver closed");
+1880 self.msock.metrics.magicsock.actor_tick_other.inc();
+1881
+1882 receiver_closed = true;
+1883 continue;
+1884 };
+1885
+1886 trace!(?msg, "tick: msg");
+1887 self.msock.metrics.magicsock.actor_tick_msg.inc();
+1888 self.handle_actor_message(msg, &sender).await;
+1889 }
+1890 tick = self.periodic_re_stun_timer.tick() => {
+1891 trace!("tick: re_stun {:?}", tick);
+1892 self.msock.metrics.magicsock.actor_tick_re_stun.inc();
+1893 self.re_stun(UpdateReason::Periodic);
1894 }
-1895 tick = self.periodic_re_stun_timer.tick() => {
-1896 trace!("tick: re_stun {:?}", tick);
-1897 self.msock.metrics.magicsock.actor_tick_re_stun.inc();
-1898 self.re_stun(UpdateReason::Periodic);
-1899 }
-1900 new_addr = watcher.updated() => {
-1901 match new_addr {
-1902 Ok(addrs) => {
-1903 if !addrs.is_empty() {
-1904 trace!(?addrs, "local addrs");
-1905 self.msock.publish_my_addr();
-1906 }
-1907 }
-1908 Err(_) => {
-1909 warn!("local addr watcher stopped");
-1910 }
-1911 }
-1912 }
-1913 report = net_report_watcher.updated() => {
-1914 match report {
-1915 Ok((report, _)) => {
-1916 self.handle_net_report_report(report);
-1917 #[cfg(not(wasm_browser))]
-1918 {
-1919 self.periodic_re_stun_timer = new_re_stun_timer(true);
-1920 }
-1921 }
-1922 Err(_) => {
-1923 warn!("net report watcher stopped");
-1924 }
-1925 }
-1926 }
-1927 reason = self.direct_addr_done_rx.recv() => {
-1928 match reason {
-1929 Some(()) => {
-1930 // check if a new run needs to be scheduled
-1931 let state = self.netmon_watcher.get().expect("disconnected");
-1932 self.direct_addr_update_state.try_run(state.into());
-1933 }
-1934 None => {
-1935 warn!("direct addr watcher died");
-1936 }
-1937 }
-1938 }
-1939 change = portmap_watcher_changed, if !portmap_watcher_closed => {
-1940 #[cfg(not(wasm_browser))]
-1941 {
-1942 if change.is_err() {
-1943 trace!("tick: portmap watcher closed");
-1944 self.msock.metrics.magicsock.actor_tick_other.inc();
-1945
-1946 portmap_watcher_closed = true;
-1947 continue;
-1948 }
-1949
-1950 trace!("tick: portmap changed");
-1951 self.msock.metrics.magicsock.actor_tick_portmap_changed.inc();
-1952 let new_external_address = *portmap_watcher.borrow();
-1953 debug!("external address updated: {new_external_address:?}");
-1954 self.re_stun(UpdateReason::PortmapUpdated);
-1955 }
-1956 #[cfg(wasm_browser)]
-1957 let _unused_in_browsers = change;
-1958 },
-1959 _ = direct_addr_heartbeat_timer_tick => {
-1960 #[cfg(not(wasm_browser))]
-1961 {
-1962 trace!(
-1963 "tick: direct addr heartbeat {} direct addrs",
-1964 self.msock.node_map.node_count(),
-1965 );
-1966 self.msock.metrics.magicsock.actor_tick_direct_addr_heartbeat.inc();
-1967 // TODO: this might trigger too many packets at once, pace this
-1968
-1969 self.msock.node_map.prune_inactive();
-1970 let msgs = self.msock.node_map.nodes_stayin_alive();
-1971 self.handle_ping_actions(&sender, msgs).await;
-1972 }
-1973 }
-1974 state = self.netmon_watcher.updated() => {
-1975 let Ok(state) = state else {
-1976 trace!("tick: link change receiver closed");
-1977 self.msock.metrics.magicsock.actor_tick_other.inc();
-1978 continue;
-1979 };
-1980 let is_major = state.is_major_change(¤t_netmon_state);
-1981 current_netmon_state = state;
-1982 trace!("tick: link change {}", is_major);
-1983 self.msock.metrics.magicsock.actor_link_change.inc();
-1984 self.handle_network_change(is_major).await;
-1985 }
-1986 // Even if `discovery_events` yields `None`, it could begin to yield
-1987 // `Some` again in the future, so we don't want to disable this branch
-1988 // forever like we do with the other branches that yield `Option`s
-1989 Some(discovery_item) = discovery_events.next() => {
-1990 trace!("tick: discovery event, address discovered: {discovery_item:?}");
-1991 let provenance = discovery_item.provenance();
-1992 let node_addr = discovery_item.to_node_addr();
-1993 if let Err(e) = self.msock.add_node_addr(
-1994 node_addr,
-1995 Source::Discovery {
-1996 name: provenance.to_string()
-1997 }) {
-1998 let node_addr = discovery_item.to_node_addr();
-1999 warn!(?node_addr, "unable to add discovered node address to the node map: {e:?}");
-2000 }
-2001 // Send the discovery item to the subscribers of the discovery broadcast stream.
-2002 self.msock.discovery_subscribers.send(discovery_item);
+1895 new_addr = watcher.updated() => {
+1896 match new_addr {
+1897 Ok(addrs) => {
+1898 if !addrs.is_empty() {
+1899 trace!(?addrs, "local addrs");
+1900 self.msock.publish_my_addr();
+1901 }
+1902 }
+1903 Err(_) => {
+1904 warn!("local addr watcher stopped");
+1905 }
+1906 }
+1907 }
+1908 report = net_report_watcher.updated() => {
+1909 match report {
+1910 Ok((report, _)) => {
+1911 self.handle_net_report_report(report);
+1912 #[cfg(not(wasm_browser))]
+1913 {
+1914 self.periodic_re_stun_timer = new_re_stun_timer(true);
+1915 }
+1916 }
+1917 Err(_) => {
+1918 warn!("net report watcher stopped");
+1919 }
+1920 }
+1921 }
+1922 reason = self.direct_addr_done_rx.recv() => {
+1923 match reason {
+1924 Some(()) => {
+1925 // check if a new run needs to be scheduled
+1926 let state = self.netmon_watcher.get().expect("disconnected");
+1927 self.direct_addr_update_state.try_run(state.into());
+1928 }
+1929 None => {
+1930 warn!("direct addr watcher died");
+1931 }
+1932 }
+1933 }
+1934 change = portmap_watcher_changed, if !portmap_watcher_closed => {
+1935 #[cfg(not(wasm_browser))]
+1936 {
+1937 if change.is_err() {
+1938 trace!("tick: portmap watcher closed");
+1939 self.msock.metrics.magicsock.actor_tick_other.inc();
+1940
+1941 portmap_watcher_closed = true;
+1942 continue;
+1943 }
+1944
+1945 trace!("tick: portmap changed");
+1946 self.msock.metrics.magicsock.actor_tick_portmap_changed.inc();
+1947 let new_external_address = *portmap_watcher.borrow();
+1948 debug!("external address updated: {new_external_address:?}");
+1949 self.re_stun(UpdateReason::PortmapUpdated);
+1950 }
+1951 #[cfg(wasm_browser)]
+1952 let _unused_in_browsers = change;
+1953 },
+1954 _ = direct_addr_heartbeat_timer_tick => {
+1955 #[cfg(not(wasm_browser))]
+1956 {
+1957 trace!(
+1958 "tick: direct addr heartbeat {} direct addrs",
+1959 self.msock.node_map.node_count(),
+1960 );
+1961 self.msock.metrics.magicsock.actor_tick_direct_addr_heartbeat.inc();
+1962 // TODO: this might trigger too many packets at once, pace this
+1963
+1964 self.msock.node_map.prune_inactive();
+1965 let msgs = self.msock.node_map.nodes_stayin_alive();
+1966 self.handle_ping_actions(&sender, msgs).await;
+1967 }
+1968 }
+1969 state = self.netmon_watcher.updated() => {
+1970 let Ok(state) = state else {
+1971 trace!("tick: link change receiver closed");
+1972 self.msock.metrics.magicsock.actor_tick_other.inc();
+1973 continue;
+1974 };
+1975 let is_major = state.is_major_change(¤t_netmon_state);
+1976 current_netmon_state = state;
+1977 trace!("tick: link change {}", is_major);
+1978 self.msock.metrics.magicsock.actor_link_change.inc();
+1979 self.handle_network_change(is_major).await;
+1980 }
+1981 // Even if `discovery_events` yields `None`, it could begin to yield
+1982 // `Some` again in the future, so we don't want to disable this branch
+1983 // forever like we do with the other branches that yield `Option`s
+1984 Some(discovery_item) = discovery_events.next() => {
+1985 trace!("tick: discovery event, address discovered: {discovery_item:?}");
+1986 let provenance = discovery_item.provenance();
+1987 let node_addr = discovery_item.to_node_addr();
+1988 if let Err(e) = self.msock.add_node_addr(
+1989 node_addr,
+1990 Source::Discovery {
+1991 name: provenance.to_string()
+1992 }) {
+1993 let node_addr = discovery_item.to_node_addr();
+1994 warn!(?node_addr, "unable to add discovered node address to the node map: {e:?}");
+1995 }
+1996 // Send the discovery item to the subscribers of the discovery broadcast stream.
+1997 self.msock.discovery_subscribers.send(discovery_item);
+1998 }
+1999 Some((dst, dst_key, msg)) = self.disco_receiver.recv() => {
+2000 if let Err(err) = self.msock.send_disco_message(&sender, dst.clone(), dst_key, msg).await {
+2001 warn!(%dst, node = %dst_key.fmt_short(), ?err, "failed to send disco message (UDP)");
+2002 }
2003 }
-2004 Some((dst, dst_key, msg)) = self.disco_receiver.recv() => {
-2005 if let Err(err) = self.msock.send_disco_message(&sender, dst.clone(), dst_key, msg).await {
-2006 warn!(%dst, node = %dst_key.fmt_short(), ?err, "failed to send disco message (UDP)");
-2007 }
-2008 }
-2009 }
-2010 }
-2011 }
-2012
-2013 async fn handle_network_change(&mut self, is_major: bool) {
-2014 debug!("link change detected: major? {}", is_major);
+2004 }
+2005 }
+2006 }
+2007
+2008 async fn handle_network_change(&mut self, is_major: bool) {
+2009 debug!("link change detected: major? {}", is_major);
+2010
+2011 if is_major {
+2012 if let Err(err) = self.network_change_sender.rebind() {
+2013 warn!("failed to rebind transports: {:?}", err);
+2014 }
2015
-2016 if is_major {
-2017 if let Err(err) = self.network_change_sender.rebind() {
-2018 warn!("failed to rebind transports: {:?}", err);
-2019 }
-2020
-2021 #[cfg(not(wasm_browser))]
-2022 self.msock.dns_resolver.reset().await;
-2023 self.re_stun(UpdateReason::LinkChangeMajor);
-2024 self.reset_endpoint_states();
-2025 } else {
-2026 self.re_stun(UpdateReason::LinkChangeMinor);
-2027 }
-2028 }
-2029
-2030 fn re_stun(&mut self, why: UpdateReason) {
-2031 let state = self.netmon_watcher.get().expect("disconnected");
-2032 self.direct_addr_update_state
-2033 .schedule_run(why, state.into());
-2034 }
-2035
-2036 #[instrument(skip_all)]
-2037 async fn handle_ping_actions(&mut self, sender: &UdpSender, msgs: Vec<PingAction>) {
-2038 if let Err(err) = self.msock.send_ping_actions(sender, msgs).await {
-2039 warn!("Failed to send ping actions: {err:#}");
-2040 }
-2041 }
-2042
-2043 /// Processes an incoming actor message.
-2044 ///
-2045 /// Returns `true` if it was a shutdown.
-2046 async fn handle_actor_message(&mut self, msg: ActorMessage, sender: &UdpSender) {
-2047 match msg {
-2048 ActorMessage::EndpointPingExpired(id, txid) => {
-2049 self.msock.node_map.notify_ping_timeout(id, txid);
-2050 }
-2051 ActorMessage::NetworkChange => {
-2052 self.network_monitor.network_change().await.ok();
-2053 }
-2054 ActorMessage::ScheduleDirectAddrUpdate(why, data) => {
-2055 if let Some((node, url)) = data {
-2056 self.pending_call_me_maybes.insert(node, url);
-2057 }
-2058 let state = self.netmon_watcher.get().expect("disconnected");
-2059 self.direct_addr_update_state
-2060 .schedule_run(why, state.into());
-2061 }
-2062 #[cfg(test)]
-2063 ActorMessage::ForceNetworkChange(is_major) => {
-2064 self.handle_network_change(is_major).await;
-2065 }
-2066 ActorMessage::PingActions(ping_actions) => {
-2067 self.handle_ping_actions(sender, ping_actions).await;
-2068 }
-2069 }
-2070 }
-2071
-2072 /// Updates the direct addresses of this magic socket.
-2073 ///
-2074 /// Updates the [`DiscoveredDirectAddrs`] of this [`MagicSock`] with the current set of
-2075 /// direct addresses from:
-2076 ///
-2077 /// - The portmapper.
-2078 /// - A net_report report.
-2079 /// - The local interfaces IP addresses.
-2080 #[cfg(not(wasm_browser))]
-2081 fn update_direct_addresses(&mut self, net_report_report: Option<&net_report::Report>) {
-2082 let portmap_watcher = self
-2083 .direct_addr_update_state
-2084 .port_mapper
-2085 .watch_external_address();
+2016 #[cfg(not(wasm_browser))]
+2017 self.msock.dns_resolver.reset().await;
+2018 self.re_stun(UpdateReason::LinkChangeMajor);
+2019 self.reset_endpoint_states();
+2020 } else {
+2021 self.re_stun(UpdateReason::LinkChangeMinor);
+2022 }
+2023 }
+2024
+2025 fn re_stun(&mut self, why: UpdateReason) {
+2026 let state = self.netmon_watcher.get().expect("disconnected");
+2027 self.direct_addr_update_state
+2028 .schedule_run(why, state.into());
+2029 }
+2030
+2031 #[instrument(skip_all)]
+2032 async fn handle_ping_actions(&mut self, sender: &UdpSender, msgs: Vec<PingAction>) {
+2033 if let Err(err) = self.msock.send_ping_actions(sender, msgs).await {
+2034 warn!("Failed to send ping actions: {err:#}");
+2035 }
+2036 }
+2037
+2038 /// Processes an incoming actor message.
+2039 ///
+2040 /// Returns `true` if it was a shutdown.
+2041 async fn handle_actor_message(&mut self, msg: ActorMessage, sender: &UdpSender) {
+2042 match msg {
+2043 ActorMessage::EndpointPingExpired(id, txid) => {
+2044 self.msock.node_map.notify_ping_timeout(id, txid);
+2045 }
+2046 ActorMessage::NetworkChange => {
+2047 self.network_monitor.network_change().await.ok();
+2048 }
+2049 ActorMessage::ScheduleDirectAddrUpdate(why, data) => {
+2050 if let Some((node, url)) = data {
+2051 self.pending_call_me_maybes.insert(node, url);
+2052 }
+2053 let state = self.netmon_watcher.get().expect("disconnected");
+2054 self.direct_addr_update_state
+2055 .schedule_run(why, state.into());
+2056 }
+2057 #[cfg(test)]
+2058 ActorMessage::ForceNetworkChange(is_major) => {
+2059 self.handle_network_change(is_major).await;
+2060 }
+2061 ActorMessage::PingActions(ping_actions) => {
+2062 self.handle_ping_actions(sender, ping_actions).await;
+2063 }
+2064 }
+2065 }
+2066
+2067 /// Updates the direct addresses of this magic socket.
+2068 ///
+2069 /// Updates the [`DiscoveredDirectAddrs`] of this [`MagicSock`] with the current set of
+2070 /// direct addresses from:
+2071 ///
+2072 /// - The portmapper.
+2073 /// - A net_report report.
+2074 /// - The local interfaces IP addresses.
+2075 #[cfg(not(wasm_browser))]
+2076 fn update_direct_addresses(&mut self, net_report_report: Option<&net_report::Report>) {
+2077 let portmap_watcher = self
+2078 .direct_addr_update_state
+2079 .port_mapper
+2080 .watch_external_address();
+2081
+2082 // We only want to have one DirectAddr for each SocketAddr we have. So we store
+2083 // this as a map of SocketAddr -> DirectAddrType. At the end we will construct a
+2084 // DirectAddr from each entry.
+2085 let mut addrs: BTreeMap<SocketAddr, DirectAddrType> = BTreeMap::new();
2086
-2087 // We only want to have one DirectAddr for each SocketAddr we have. So we store
-2088 // this as a map of SocketAddr -> DirectAddrType. At the end we will construct a
-2089 // DirectAddr from each entry.
-2090 let mut addrs: BTreeMap<SocketAddr, DirectAddrType> = BTreeMap::new();
-2091
-2092 // First add PortMapper provided addresses.
-2093 let maybe_port_mapped = *portmap_watcher.borrow();
-2094 if let Some(portmap_ext) = maybe_port_mapped.map(SocketAddr::V4) {
-2095 addrs
-2096 .entry(portmap_ext)
-2097 .or_insert(DirectAddrType::Portmapped);
-2098 }
+2087 // First add PortMapper provided addresses.
+2088 let maybe_port_mapped = *portmap_watcher.borrow();
+2089 if let Some(portmap_ext) = maybe_port_mapped.map(SocketAddr::V4) {
+2090 addrs
+2091 .entry(portmap_ext)
+2092 .or_insert(DirectAddrType::Portmapped);
+2093 }
+2094
+2095 // Next add STUN addresses from the net_report report.
+2096 if let Some(net_report_report) = net_report_report {
+2097 if let Some(global_v4) = net_report_report.global_v4 {
+2098 addrs.entry(global_v4.into()).or_insert(DirectAddrType::Qad);
2099
-2100 // Next add STUN addresses from the net_report report.
-2101 if let Some(net_report_report) = net_report_report {
-2102 if let Some(global_v4) = net_report_report.global_v4 {
-2103 addrs.entry(global_v4.into()).or_insert(DirectAddrType::Qad);
-2104
-2105 // If they're behind a hard NAT and are using a fixed
-2106 // port locally, assume they might've added a static
-2107 // port mapping on their router to the same explicit
-2108 // port that we are running with. Worst case it's an invalid candidate mapping.
-2109 let port = self.msock.ip_bind_addrs().iter().find_map(|addr| {
-2110 if addr.port() != 0 {
-2111 Some(addr.port())
-2112 } else {
-2113 None
-2114 }
-2115 });
-2116
-2117 if let Some(port) = port {
-2118 if net_report_report
-2119 .mapping_varies_by_dest()
-2120 .unwrap_or_default()
-2121 {
-2122 let mut addr = global_v4;
-2123 addr.set_port(port);
-2124 addrs
-2125 .entry(addr.into())
-2126 .or_insert(DirectAddrType::Qad4LocalPort);
-2127 }
-2128 }
-2129 }
-2130 if let Some(global_v6) = net_report_report.global_v6 {
-2131 addrs.entry(global_v6.into()).or_insert(DirectAddrType::Qad);
-2132 }
-2133 }
-2134
-2135 let local_addrs: Vec<(SocketAddr, SocketAddr)> = self
-2136 .msock
-2137 .ip_bind_addrs()
-2138 .iter()
-2139 .copied()
-2140 .zip(self.msock.ip_local_addrs())
-2141 .collect();
-2142
-2143 let has_ipv4_unspecified = local_addrs.iter().find_map(|(_, a)| {
-2144 if a.is_ipv4() && a.ip().is_unspecified() {
-2145 Some(a.port())
-2146 } else {
-2147 None
-2148 }
-2149 });
-2150 let has_ipv6_unspecified = local_addrs.iter().find_map(|(_, a)| {
-2151 if a.is_ipv6() && a.ip().is_unspecified() {
-2152 Some(a.port())
-2153 } else {
-2154 None
-2155 }
-2156 });
-2157
-2158 // If a socket is bound to the unspecified address, create SocketAddrs for
-2159 // each local IP address by pairing it with the port the socket is bound on.
-2160 if local_addrs
-2161 .iter()
-2162 .any(|(_, local)| local.ip().is_unspecified())
-2163 {
-2164 let LocalAddresses {
-2165 regular: mut ips,
-2166 loopback,
-2167 } = self
-2168 .netmon_watcher
-2169 .get()
-2170 .expect("netmon disconnected")
-2171 .local_addresses;
-2172 if ips.is_empty() && addrs.is_empty() {
-2173 // Include loopback addresses only if there are no other interfaces
-2174 // or public addresses, this allows testing offline.
-2175 ips = loopback;
-2176 }
-2177
-2178 for ip in ips {
-2179 let port_if_unspecified = match ip {
-2180 IpAddr::V4(_) => has_ipv4_unspecified,
-2181 IpAddr::V6(_) => has_ipv6_unspecified,
-2182 };
-2183 if let Some(port) = port_if_unspecified {
-2184 let addr = SocketAddr::new(ip, port);
-2185 addrs.entry(addr).or_insert(DirectAddrType::Local);
-2186 }
-2187 }
-2188 }
-2189
-2190 // If a socket is bound to a specific address, add it.
-2191 for (bound, local) in local_addrs {
-2192 if !bound.ip().is_unspecified() {
-2193 addrs.entry(local).or_insert(DirectAddrType::Local);
-2194 }
-2195 }
-2196
-2197 // Finally create and store store all these direct addresses and send any
-2198 // queued call-me-maybe messages.
-2199 self.msock.store_direct_addresses(
-2200 addrs
-2201 .iter()
-2202 .map(|(addr, typ)| DirectAddr {
-2203 addr: *addr,
-2204 typ: *typ,
-2205 })
-2206 .collect(),
-2207 );
-2208 self.send_queued_call_me_maybes();
-2209 }
+2100 // If they're behind a hard NAT and are using a fixed
+2101 // port locally, assume they might've added a static
+2102 // port mapping on their router to the same explicit
+2103 // port that we are running with. Worst case it's an invalid candidate mapping.
+2104 let port = self.msock.ip_bind_addrs().iter().find_map(|addr| {
+2105 if addr.port() != 0 {
+2106 Some(addr.port())
+2107 } else {
+2108 None
+2109 }
+2110 });
+2111
+2112 if let Some(port) = port {
+2113 if net_report_report
+2114 .mapping_varies_by_dest()
+2115 .unwrap_or_default()
+2116 {
+2117 let mut addr = global_v4;
+2118 addr.set_port(port);
+2119 addrs
+2120 .entry(addr.into())
+2121 .or_insert(DirectAddrType::Qad4LocalPort);
+2122 }
+2123 }
+2124 }
+2125 if let Some(global_v6) = net_report_report.global_v6 {
+2126 addrs.entry(global_v6.into()).or_insert(DirectAddrType::Qad);
+2127 }
+2128 }
+2129
+2130 let local_addrs: Vec<(SocketAddr, SocketAddr)> = self
+2131 .msock
+2132 .ip_bind_addrs()
+2133 .iter()
+2134 .copied()
+2135 .zip(self.msock.ip_local_addrs())
+2136 .collect();
+2137
+2138 let has_ipv4_unspecified = local_addrs.iter().find_map(|(_, a)| {
+2139 if a.is_ipv4() && a.ip().is_unspecified() {
+2140 Some(a.port())
+2141 } else {
+2142 None
+2143 }
+2144 });
+2145 let has_ipv6_unspecified = local_addrs.iter().find_map(|(_, a)| {
+2146 if a.is_ipv6() && a.ip().is_unspecified() {
+2147 Some(a.port())
+2148 } else {
+2149 None
+2150 }
+2151 });
+2152
+2153 // If a socket is bound to the unspecified address, create SocketAddrs for
+2154 // each local IP address by pairing it with the port the socket is bound on.
+2155 if local_addrs
+2156 .iter()
+2157 .any(|(_, local)| local.ip().is_unspecified())
+2158 {
+2159 let LocalAddresses {
+2160 regular: mut ips,
+2161 loopback,
+2162 } = self
+2163 .netmon_watcher
+2164 .get()
+2165 .expect("netmon disconnected")
+2166 .local_addresses;
+2167 if ips.is_empty() && addrs.is_empty() {
+2168 // Include loopback addresses only if there are no other interfaces
+2169 // or public addresses, this allows testing offline.
+2170 ips = loopback;
+2171 }
+2172
+2173 for ip in ips {
+2174 let port_if_unspecified = match ip {
+2175 IpAddr::V4(_) => has_ipv4_unspecified,
+2176 IpAddr::V6(_) => has_ipv6_unspecified,
+2177 };
+2178 if let Some(port) = port_if_unspecified {
+2179 let addr = SocketAddr::new(ip, port);
+2180 addrs.entry(addr).or_insert(DirectAddrType::Local);
+2181 }
+2182 }
+2183 }
+2184
+2185 // If a socket is bound to a specific address, add it.
+2186 for (bound, local) in local_addrs {
+2187 if !bound.ip().is_unspecified() {
+2188 addrs.entry(local).or_insert(DirectAddrType::Local);
+2189 }
+2190 }
+2191
+2192 // Finally create and store store all these direct addresses and send any
+2193 // queued call-me-maybe messages.
+2194 self.msock.store_direct_addresses(
+2195 addrs
+2196 .iter()
+2197 .map(|(addr, typ)| DirectAddr {
+2198 addr: *addr,
+2199 typ: *typ,
+2200 })
+2201 .collect(),
+2202 );
+2203 self.send_queued_call_me_maybes();
+2204 }
+2205
+2206 fn send_queued_call_me_maybes(&mut self) {
+2207 let msg = self.msock.direct_addrs.to_call_me_maybe_message();
+2208 let msg = disco::Message::CallMeMaybe(msg);
+2209 // allocate, to minimize locking duration
2210
-2211 fn send_queued_call_me_maybes(&mut self) {
-2212 let msg = self.msock.direct_addrs.to_call_me_maybe_message();
-2213 let msg = disco::Message::CallMeMaybe(msg);
-2214 // allocate, to minimize locking duration
-2215
-2216 for (public_key, url) in self.pending_call_me_maybes.drain() {
-2217 if !self
-2218 .msock
-2219 .disco
-2220 .try_send(SendAddr::Relay(url), public_key, msg.clone())
-2221 {
-2222 warn!(node = %public_key.fmt_short(), "relay channel full, dropping call-me-maybe");
-2223 }
-2224 }
-2225 }
-2226
-2227 fn handle_net_report_report(&mut self, mut report: Option<net_report::Report>) {
-2228 if let Some(ref mut r) = report {
-2229 self.msock.ipv6_reported.store(r.udp_v6, Ordering::Relaxed);
-2230 if r.preferred_relay.is_none() {
-2231 if let Some(my_relay) = self.msock.my_relay() {
-2232 r.preferred_relay.replace(my_relay);
-2233 }
-2234 }
-2235
-2236 // Notify all transports
-2237 self.network_change_sender.on_network_change(r);
-2238 }
-2239
-2240 #[cfg(not(wasm_browser))]
-2241 self.update_direct_addresses(report.as_ref());
-2242 }
-2243
-2244 /// Resets the preferred address for all nodes.
-2245 /// This is called when connectivity changes enough that we no longer trust the old routes.
-2246 #[instrument(skip_all)]
-2247 fn reset_endpoint_states(&mut self) {
-2248 self.msock.node_map.reset_node_states()
-2249 }
-2250}
-2251
-2252fn new_re_stun_timer(initial_delay: bool) -> time::Interval {
-2253 // Pick a random duration between 20 and 26 seconds (just under 30s,
-2254 // a common UDP NAT timeout on Linux,etc)
-2255 let mut rng = rand::thread_rng();
-2256 let d: Duration = rng.gen_range(Duration::from_secs(20)..=Duration::from_secs(26));
-2257 if initial_delay {
-2258 debug!("scheduling periodic_stun to run in {}s", d.as_secs());
-2259 time::interval_at(time::Instant::now() + d, d)
-2260 } else {
-2261 debug!(
-2262 "scheduling periodic_stun to run immediately and in {}s",
-2263 d.as_secs()
-2264 );
-2265 time::interval(d)
-2266 }
-2267}
-2268
-2269#[cfg(not(wasm_browser))]
-2270fn bind_with_fallback(mut addr: SocketAddr) -> io::Result<UdpSocket> {
-2271 debug!(%addr, "binding");
-2272
-2273 // First try binding a preferred port, if specified
-2274 match UdpSocket::bind_full(addr) {
-2275 Ok(socket) => {
-2276 let local_addr = socket.local_addr()?;
-2277 debug!(%addr, %local_addr, "successfully bound");
-2278 return Ok(socket);
-2279 }
-2280 Err(err) => {
-2281 debug!(%addr, "failed to bind: {err:#}");
-2282 // If that was already the fallback port, then error out
-2283 if addr.port() == 0 {
-2284 return Err(err);
-2285 }
-2286 }
-2287 }
+2211 for (public_key, url) in self.pending_call_me_maybes.drain() {
+2212 if !self
+2213 .msock
+2214 .disco
+2215 .try_send(SendAddr::Relay(url), public_key, msg.clone())
+2216 {
+2217 warn!(node = %public_key.fmt_short(), "relay channel full, dropping call-me-maybe");
+2218 }
+2219 }
+2220 }
+2221
+2222 fn handle_net_report_report(&mut self, mut report: Option<net_report::Report>) {
+2223 if let Some(ref mut r) = report {
+2224 self.msock.ipv6_reported.store(r.udp_v6, Ordering::Relaxed);
+2225 if r.preferred_relay.is_none() {
+2226 if let Some(my_relay) = self.msock.my_relay() {
+2227 r.preferred_relay.replace(my_relay);
+2228 }
+2229 }
+2230
+2231 // Notify all transports
+2232 self.network_change_sender.on_network_change(r);
+2233 }
+2234
+2235 #[cfg(not(wasm_browser))]
+2236 self.update_direct_addresses(report.as_ref());
+2237 }
+2238
+2239 /// Resets the preferred address for all nodes.
+2240 /// This is called when connectivity changes enough that we no longer trust the old routes.
+2241 #[instrument(skip_all)]
+2242 fn reset_endpoint_states(&mut self) {
+2243 self.msock.node_map.reset_node_states()
+2244 }
+2245}
+2246
+2247fn new_re_stun_timer(initial_delay: bool) -> time::Interval {
+2248 // Pick a random duration between 20 and 26 seconds (just under 30s,
+2249 // a common UDP NAT timeout on Linux,etc)
+2250 let mut rng = rand::thread_rng();
+2251 let d: Duration = rng.gen_range(Duration::from_secs(20)..=Duration::from_secs(26));
+2252 if initial_delay {
+2253 debug!("scheduling periodic_stun to run in {}s", d.as_secs());
+2254 time::interval_at(time::Instant::now() + d, d)
+2255 } else {
+2256 debug!(
+2257 "scheduling periodic_stun to run immediately and in {}s",
+2258 d.as_secs()
+2259 );
+2260 time::interval(d)
+2261 }
+2262}
+2263
+2264#[cfg(not(wasm_browser))]
+2265fn bind_with_fallback(mut addr: SocketAddr) -> io::Result<UdpSocket> {
+2266 debug!(%addr, "binding");
+2267
+2268 // First try binding a preferred port, if specified
+2269 match UdpSocket::bind_full(addr) {
+2270 Ok(socket) => {
+2271 let local_addr = socket.local_addr()?;
+2272 debug!(%addr, %local_addr, "successfully bound");
+2273 return Ok(socket);
+2274 }
+2275 Err(err) => {
+2276 debug!(%addr, "failed to bind: {err:#}");
+2277 // If that was already the fallback port, then error out
+2278 if addr.port() == 0 {
+2279 return Err(err);
+2280 }
+2281 }
+2282 }
+2283
+2284 // Otherwise, try binding with port 0
+2285 addr.set_port(0);
+2286 UdpSocket::bind_full(addr)
+2287}
2288
-2289 // Otherwise, try binding with port 0
-2290 addr.set_port(0);
-2291 UdpSocket::bind_full(addr)
-2292}
-2293
-2294/// The discovered direct addresses of this [`MagicSock`].
-2295///
-2296/// These are all the [`DirectAddr`]s that this [`MagicSock`] is aware of for itself.
-2297/// They include all locally bound ones as well as those discovered by other mechanisms like
-2298/// QAD.
-2299#[derive(derive_more::Debug, Default, Clone)]
-2300struct DiscoveredDirectAddrs {
-2301 /// The last set of discovered direct addresses.
-2302 addrs: Watchable<Option<BTreeSet<DirectAddr>>>,
-2303
-2304 /// The last time the direct addresses were updated, even if there was no change.
-2305 ///
-2306 /// This is only ever None at startup.
-2307 updated_at: Arc<RwLock<Option<Instant>>>,
-2308}
-2309
-2310impl DiscoveredDirectAddrs {
-2311 /// Updates the direct addresses, returns `true` if they changed, `false` if not.
-2312 fn update(&self, addrs: BTreeSet<DirectAddr>) -> bool {
-2313 *self.updated_at.write().expect("poisoned") = Some(Instant::now());
-2314 let updated = self.addrs.set(Some(addrs)).is_ok();
-2315 if updated {
-2316 event!(
-2317 target: "iroh::_events::direct_addrs",
-2318 Level::DEBUG,
-2319 addrs = ?self.addrs.get(),
-2320 );
-2321 }
-2322 updated
-2323 }
-2324
-2325 fn sockaddrs(&self) -> BTreeSet<SocketAddr> {
-2326 self.addrs
-2327 .get()
-2328 .unwrap_or_default()
-2329 .into_iter()
-2330 .map(|da| da.addr)
-2331 .collect()
-2332 }
-2333
-2334 /// Whether the direct addr information is considered "fresh".
+2289/// The discovered direct addresses of this [`MagicSock`].
+2290///
+2291/// These are all the [`DirectAddr`]s that this [`MagicSock`] is aware of for itself.
+2292/// They include all locally bound ones as well as those discovered by other mechanisms like
+2293/// QAD.
+2294#[derive(derive_more::Debug, Default, Clone)]
+2295struct DiscoveredDirectAddrs {
+2296 /// The last set of discovered direct addresses.
+2297 addrs: Watchable<Option<BTreeSet<DirectAddr>>>,
+2298
+2299 /// The last time the direct addresses were updated, even if there was no change.
+2300 ///
+2301 /// This is only ever None at startup.
+2302 updated_at: Arc<RwLock<Option<Instant>>>,
+2303}
+2304
+2305impl DiscoveredDirectAddrs {
+2306 /// Updates the direct addresses, returns `true` if they changed, `false` if not.
+2307 fn update(&self, addrs: BTreeSet<DirectAddr>) -> bool {
+2308 *self.updated_at.write().expect("poisoned") = Some(Instant::now());
+2309 let updated = self.addrs.set(Some(addrs)).is_ok();
+2310 if updated {
+2311 event!(
+2312 target: "iroh::_events::direct_addrs",
+2313 Level::DEBUG,
+2314 addrs = ?self.addrs.get(),
+2315 );
+2316 }
+2317 updated
+2318 }
+2319
+2320 fn sockaddrs(&self) -> BTreeSet<SocketAddr> {
+2321 self.addrs
+2322 .get()
+2323 .unwrap_or_default()
+2324 .into_iter()
+2325 .map(|da| da.addr)
+2326 .collect()
+2327 }
+2328
+2329 /// Whether the direct addr information is considered "fresh".
+2330 ///
+2331 /// If not fresh you should probably update the direct addresses before using this info.
+2332 ///
+2333 /// Returns `Ok(())` if fresh enough and `Err(elapsed)` if not fresh enough.
+2334 /// `elapsed` is the time elapsed since the direct addresses were last updated.
2335 ///
-2336 /// If not fresh you should probably update the direct addresses before using this info.
-2337 ///
-2338 /// Returns `Ok(())` if fresh enough and `Err(elapsed)` if not fresh enough.
-2339 /// `elapsed` is the time elapsed since the direct addresses were last updated.
-2340 ///
-2341 /// If there is no direct address information `Err(Duration::ZERO)` is returned.
-2342 fn fresh_enough(&self) -> Result<(), Duration> {
-2343 match *self.updated_at.read().expect("poisoned") {
-2344 None => Err(Duration::ZERO),
-2345 Some(time) => {
-2346 let elapsed = time.elapsed();
-2347 if elapsed <= ENDPOINTS_FRESH_ENOUGH_DURATION {
-2348 Ok(())
-2349 } else {
-2350 Err(elapsed)
-2351 }
-2352 }
-2353 }
-2354 }
-2355
-2356 fn to_call_me_maybe_message(&self) -> disco::CallMeMaybe {
-2357 let my_numbers = self
-2358 .addrs
-2359 .get()
-2360 .unwrap_or_default()
-2361 .into_iter()
-2362 .map(|da| da.addr)
-2363 .collect();
-2364 disco::CallMeMaybe { my_numbers }
-2365 }
-2366}
-2367
-2368/// The fake address used by the QUIC layer to address a node.
-2369///
-2370/// You can consider this as nothing more than a lookup key for a node the [`MagicSock`] knows
-2371/// about.
+2336 /// If there is no direct address information `Err(Duration::ZERO)` is returned.
+2337 fn fresh_enough(&self) -> Result<(), Duration> {
+2338 match *self.updated_at.read().expect("poisoned") {
+2339 None => Err(Duration::ZERO),
+2340 Some(time) => {
+2341 let elapsed = time.elapsed();
+2342 if elapsed <= ENDPOINTS_FRESH_ENOUGH_DURATION {
+2343 Ok(())
+2344 } else {
+2345 Err(elapsed)
+2346 }
+2347 }
+2348 }
+2349 }
+2350
+2351 fn to_call_me_maybe_message(&self) -> disco::CallMeMaybe {
+2352 let my_numbers = self
+2353 .addrs
+2354 .get()
+2355 .unwrap_or_default()
+2356 .into_iter()
+2357 .map(|da| da.addr)
+2358 .collect();
+2359 disco::CallMeMaybe { my_numbers }
+2360 }
+2361}
+2362
+2363/// The fake address used by the QUIC layer to address a node.
+2364///
+2365/// You can consider this as nothing more than a lookup key for a node the [`MagicSock`] knows
+2366/// about.
+2367///
+2368/// [`MagicSock`] can reach a node by several real socket addresses, or maybe even via the relay
+2369/// node. The QUIC layer however needs to address a node by a stable [`SocketAddr`] so
+2370/// that normal socket APIs can function. Thus when a new node is introduced to a [`MagicSock`]
+2371/// it is given a new fake address. This is the type of that address.
2372///
-2373/// [`MagicSock`] can reach a node by several real socket addresses, or maybe even via the relay
-2374/// node. The QUIC layer however needs to address a node by a stable [`SocketAddr`] so
-2375/// that normal socket APIs can function. Thus when a new node is introduced to a [`MagicSock`]
-2376/// it is given a new fake address. This is the type of that address.
-2377///
-2378/// It is but a newtype. And in our QUIC-facing socket APIs like [`AsyncUdpSocket`] it
-2379/// comes in as the inner [`Ipv6Addr`], in those interfaces we have to be careful to do
-2380/// the conversion to this type.
-2381#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
-2382pub(crate) struct NodeIdMappedAddr(Ipv6Addr);
+2373/// It is but a newtype. And in our QUIC-facing socket APIs like [`AsyncUdpSocket`] it
+2374/// comes in as the inner [`Ipv6Addr`], in those interfaces we have to be careful to do
+2375/// the conversion to this type.
+2376#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
+2377pub(crate) struct NodeIdMappedAddr(Ipv6Addr);
+2378
+2379/// Can occur when converting a [`SocketAddr`] to an [`NodeIdMappedAddr`]
+2380#[derive(Debug, Snafu)]
+2381#[snafu(display("Failed to convert"))]
+2382pub struct NodeIdMappedAddrError;
2383
-2384/// Can occur when converting a [`SocketAddr`] to an [`NodeIdMappedAddr`]
-2385#[derive(Debug, Snafu)]
-2386#[snafu(display("Failed to convert"))]
-2387pub struct NodeIdMappedAddrError;
-2388
-2389/// Counter to always generate unique addresses for [`NodeIdMappedAddr`].
-2390static NODE_ID_ADDR_COUNTER: AtomicU64 = AtomicU64::new(1);
-2391
-2392impl NodeIdMappedAddr {
-2393 /// The Prefix/L of our Unique Local Addresses.
-2394 const ADDR_PREFIXL: u8 = 0xfd;
-2395 /// The Global ID used in our Unique Local Addresses.
-2396 const ADDR_GLOBAL_ID: [u8; 5] = [21, 7, 10, 81, 11];
-2397 /// The Subnet ID used in our Unique Local Addresses.
-2398 const ADDR_SUBNET: [u8; 2] = [0; 2];
-2399
-2400 /// The dummy port used for all [`NodeIdMappedAddr`]s.
-2401 const NODE_ID_MAPPED_PORT: u16 = 12345;
-2402
-2403 /// Generates a globally unique fake UDP address.
-2404 ///
-2405 /// This generates and IPv6 Unique Local Address according to RFC 4193.
-2406 pub(crate) fn generate() -> Self {
-2407 let mut addr = [0u8; 16];
-2408 addr[0] = Self::ADDR_PREFIXL;
-2409 addr[1..6].copy_from_slice(&Self::ADDR_GLOBAL_ID);
-2410 addr[6..8].copy_from_slice(&Self::ADDR_SUBNET);
-2411
-2412 let counter = NODE_ID_ADDR_COUNTER.fetch_add(1, Ordering::Relaxed);
-2413 addr[8..16].copy_from_slice(&counter.to_be_bytes());
-2414
-2415 Self(Ipv6Addr::from(addr))
-2416 }
-2417
-2418 /// Returns a consistent [`SocketAddr`] for the [`NodeIdMappedAddr`].
-2419 ///
-2420 /// This socket address does not have a routable IP address.
-2421 ///
-2422 /// This uses a made-up port number, since the port does not play a role in looking up
-2423 /// the node in the [`NodeMap`]. This socket address is only to be used to pass into
-2424 /// Quinn.
-2425 pub(crate) fn private_socket_addr(&self) -> SocketAddr {
-2426 SocketAddr::new(IpAddr::from(self.0), Self::NODE_ID_MAPPED_PORT)
-2427 }
-2428}
-2429
-2430impl TryFrom<Ipv6Addr> for NodeIdMappedAddr {
-2431 type Error = NodeIdMappedAddrError;
-2432
-2433 fn try_from(value: Ipv6Addr) -> Result<Self, Self::Error> {
-2434 let octets = value.octets();
-2435 if octets[0] == Self::ADDR_PREFIXL
-2436 && octets[1..6] == Self::ADDR_GLOBAL_ID
-2437 && octets[6..8] == Self::ADDR_SUBNET
-2438 {
-2439 return Ok(Self(value));
-2440 }
-2441 Err(NodeIdMappedAddrError)
-2442 }
-2443}
-2444
-2445impl std::fmt::Display for NodeIdMappedAddr {
-2446 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
-2447 write!(f, "NodeIdMappedAddr({})", self.0)
-2448 }
-2449}
-2450
-2451fn disco_message_sent(msg: &disco::Message, metrics: &MagicsockMetrics) {
-2452 match msg {
-2453 disco::Message::Ping(_) => {
-2454 metrics.sent_disco_ping.inc();
-2455 }
-2456 disco::Message::Pong(_) => {
-2457 metrics.sent_disco_pong.inc();
-2458 }
-2459 disco::Message::CallMeMaybe(_) => {
-2460 metrics.sent_disco_call_me_maybe.inc();
-2461 }
-2462 }
-2463}
-2464
-2465/// A *direct address* on which an iroh-node might be contactable.
-2466///
-2467/// Direct addresses are UDP socket addresses on which an iroh node could potentially be
-2468/// contacted. These can come from various sources depending on the network topology of the
-2469/// iroh node, see [`DirectAddrType`] for the several kinds of sources.
-2470#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
-2471pub struct DirectAddr {
-2472 /// The address.
-2473 pub addr: SocketAddr,
-2474 /// The origin of this direct address.
-2475 pub typ: DirectAddrType,
-2476}
-2477
-2478/// The type of direct address.
-2479///
-2480/// These are the various sources or origins from which an iroh node might have found a
-2481/// possible [`DirectAddr`].
-2482#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
-2483pub enum DirectAddrType {
-2484 /// Not yet determined..
-2485 Unknown,
-2486 /// A locally bound socket address.
-2487 Local,
-2488 /// Public internet address discovered via QAD.
-2489 ///
-2490 /// When possible an iroh node will perform QAD to discover which is the address
-2491 /// from which it sends data on the public internet. This can be different from locally
-2492 /// bound addresses when the node is on a local network which performs NAT or similar.
-2493 Qad,
-2494 /// An address assigned by the router using port mapping.
+2384/// Counter to always generate unique addresses for [`NodeIdMappedAddr`].
+2385static NODE_ID_ADDR_COUNTER: AtomicU64 = AtomicU64::new(1);
+2386
+2387impl NodeIdMappedAddr {
+2388 /// The Prefix/L of our Unique Local Addresses.
+2389 const ADDR_PREFIXL: u8 = 0xfd;
+2390 /// The Global ID used in our Unique Local Addresses.
+2391 const ADDR_GLOBAL_ID: [u8; 5] = [21, 7, 10, 81, 11];
+2392 /// The Subnet ID used in our Unique Local Addresses.
+2393 const ADDR_SUBNET: [u8; 2] = [0; 2];
+2394
+2395 /// The dummy port used for all [`NodeIdMappedAddr`]s.
+2396 const NODE_ID_MAPPED_PORT: u16 = 12345;
+2397
+2398 /// Generates a globally unique fake UDP address.
+2399 ///
+2400 /// This generates and IPv6 Unique Local Address according to RFC 4193.
+2401 pub(crate) fn generate() -> Self {
+2402 let mut addr = [0u8; 16];
+2403 addr[0] = Self::ADDR_PREFIXL;
+2404 addr[1..6].copy_from_slice(&Self::ADDR_GLOBAL_ID);
+2405 addr[6..8].copy_from_slice(&Self::ADDR_SUBNET);
+2406
+2407 let counter = NODE_ID_ADDR_COUNTER.fetch_add(1, Ordering::Relaxed);
+2408 addr[8..16].copy_from_slice(&counter.to_be_bytes());
+2409
+2410 Self(Ipv6Addr::from(addr))
+2411 }
+2412
+2413 /// Returns a consistent [`SocketAddr`] for the [`NodeIdMappedAddr`].
+2414 ///
+2415 /// This socket address does not have a routable IP address.
+2416 ///
+2417 /// This uses a made-up port number, since the port does not play a role in looking up
+2418 /// the node in the [`NodeMap`]. This socket address is only to be used to pass into
+2419 /// Quinn.
+2420 pub(crate) fn private_socket_addr(&self) -> SocketAddr {
+2421 SocketAddr::new(IpAddr::from(self.0), Self::NODE_ID_MAPPED_PORT)
+2422 }
+2423}
+2424
+2425impl TryFrom<Ipv6Addr> for NodeIdMappedAddr {
+2426 type Error = NodeIdMappedAddrError;
+2427
+2428 fn try_from(value: Ipv6Addr) -> Result<Self, Self::Error> {
+2429 let octets = value.octets();
+2430 if octets[0] == Self::ADDR_PREFIXL
+2431 && octets[1..6] == Self::ADDR_GLOBAL_ID
+2432 && octets[6..8] == Self::ADDR_SUBNET
+2433 {
+2434 return Ok(Self(value));
+2435 }
+2436 Err(NodeIdMappedAddrError)
+2437 }
+2438}
+2439
+2440impl std::fmt::Display for NodeIdMappedAddr {
+2441 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
+2442 write!(f, "NodeIdMappedAddr({})", self.0)
+2443 }
+2444}
+2445
+2446fn disco_message_sent(msg: &disco::Message, metrics: &MagicsockMetrics) {
+2447 match msg {
+2448 disco::Message::Ping(_) => {
+2449 metrics.sent_disco_ping.inc();
+2450 }
+2451 disco::Message::Pong(_) => {
+2452 metrics.sent_disco_pong.inc();
+2453 }
+2454 disco::Message::CallMeMaybe(_) => {
+2455 metrics.sent_disco_call_me_maybe.inc();
+2456 }
+2457 }
+2458}
+2459
+2460/// A *direct address* on which an iroh-node might be contactable.
+2461///
+2462/// Direct addresses are UDP socket addresses on which an iroh node could potentially be
+2463/// contacted. These can come from various sources depending on the network topology of the
+2464/// iroh node, see [`DirectAddrType`] for the several kinds of sources.
+2465#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
+2466pub struct DirectAddr {
+2467 /// The address.
+2468 pub addr: SocketAddr,
+2469 /// The origin of this direct address.
+2470 pub typ: DirectAddrType,
+2471}
+2472
+2473/// The type of direct address.
+2474///
+2475/// These are the various sources or origins from which an iroh node might have found a
+2476/// possible [`DirectAddr`].
+2477#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
+2478pub enum DirectAddrType {
+2479 /// Not yet determined..
+2480 Unknown,
+2481 /// A locally bound socket address.
+2482 Local,
+2483 /// Public internet address discovered via QAD.
+2484 ///
+2485 /// When possible an iroh node will perform QAD to discover which is the address
+2486 /// from which it sends data on the public internet. This can be different from locally
+2487 /// bound addresses when the node is on a local network which performs NAT or similar.
+2488 Qad,
+2489 /// An address assigned by the router using port mapping.
+2490 ///
+2491 /// When possible an iroh node will request a port mapping from the local router to
+2492 /// get a publicly routable direct address.
+2493 Portmapped,
+2494 /// Hard NAT: QAD'ed IPv4 address + local fixed port.
2495 ///
-2496 /// When possible an iroh node will request a port mapping from the local router to
-2497 /// get a publicly routable direct address.
-2498 Portmapped,
-2499 /// Hard NAT: QAD'ed IPv4 address + local fixed port.
-2500 ///
-2501 /// It is possible to configure iroh to bound to a specific port and independently
-2502 /// configure the router to forward this port to the iroh node. This indicates a
-2503 /// situation like this, which still uses QAD to discover the public address.
-2504 Qad4LocalPort,
-2505}
-2506
-2507impl Display for DirectAddrType {
-2508 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
-2509 match self {
-2510 DirectAddrType::Unknown => write!(f, "?"),
-2511 DirectAddrType::Local => write!(f, "local"),
-2512 DirectAddrType::Qad => write!(f, "qad"),
-2513 DirectAddrType::Portmapped => write!(f, "portmap"),
-2514 DirectAddrType::Qad4LocalPort => write!(f, "qad4localport"),
-2515 }
-2516 }
-2517}
-2518
-2519#[cfg(test)]
-2520mod tests {
-2521 use std::{collections::BTreeSet, sync::Arc, time::Duration};
-2522
-2523 use data_encoding::HEXLOWER;
-2524 use iroh_base::{NodeAddr, NodeId, PublicKey};
-2525 use n0_future::{time, StreamExt};
-2526 use n0_snafu::{Result, ResultExt};
-2527 use n0_watcher::Watcher;
-2528 use quinn::ServerConfig;
-2529 use rand::{Rng, RngCore};
-2530 use tokio::task::JoinSet;
-2531 use tokio_util::task::AbortOnDropHandle;
-2532 use tracing::{error, info, info_span, instrument, Instrument};
-2533 use tracing_test::traced_test;
-2534
-2535 use super::{NodeIdMappedAddr, Options};
-2536 use crate::{
-2537 dns::DnsResolver,
-2538 endpoint::{DirectAddr, PathSelection, Source},
-2539 magicsock::{node_map, Handle, MagicSock},
-2540 tls, Endpoint, RelayMap, RelayMode, SecretKey,
-2541 };
-2542
-2543 const ALPN: &[u8] = b"n0/test/1";
-2544
-2545 impl Default for Options {
-2546 fn default() -> Self {
-2547 let secret_key = SecretKey::generate(rand::rngs::OsRng);
-2548 let server_config = make_default_server_config(&secret_key);
-2549 Options {
-2550 addr_v4: None,
-2551 addr_v6: None,
-2552 secret_key,
-2553 relay_map: RelayMap::empty(),
-2554 relay_protocol: iroh_relay::http::Protocol::default(),
-2555 node_map: None,
-2556 discovery: None,
-2557 proxy_url: None,
-2558 dns_resolver: DnsResolver::new(),
-2559 server_config,
-2560 #[cfg(any(test, feature = "test-utils"))]
-2561 insecure_skip_relay_cert_verify: false,
-2562 #[cfg(any(test, feature = "test-utils"))]
-2563 path_selection: PathSelection::default(),
-2564 discovery_user_data: None,
-2565 metrics: Default::default(),
-2566 }
-2567 }
-2568 }
-2569
-2570 /// Generate a server config with no ALPNS and a default transport configuration
-2571 fn make_default_server_config(secret_key: &SecretKey) -> ServerConfig {
-2572 let quic_server_config =
-2573 crate::tls::TlsConfig::new(secret_key.clone()).make_server_config(vec![], false);
-2574 let mut server_config = ServerConfig::with_crypto(Arc::new(quic_server_config));
-2575 server_config.transport_config(Arc::new(quinn::TransportConfig::default()));
-2576 server_config
-2577 }
-2578
-2579 impl MagicSock {
-2580 #[track_caller]
-2581 pub fn add_test_addr(&self, node_addr: NodeAddr) {
-2582 self.add_node_addr(
-2583 node_addr,
-2584 Source::NamedApp {
-2585 name: "test".into(),
-2586 },
-2587 )
-2588 .unwrap()
-2589 }
-2590 }
-2591
-2592 /// Magicsock plus wrappers for sending packets
-2593 #[derive(Clone)]
-2594 struct MagicStack {
-2595 secret_key: SecretKey,
-2596 endpoint: Endpoint,
-2597 }
-2598
-2599 impl MagicStack {
-2600 async fn new(relay_mode: RelayMode) -> Self {
-2601 let secret_key = SecretKey::generate(rand::thread_rng());
-2602
-2603 let mut transport_config = quinn::TransportConfig::default();
-2604 transport_config.max_idle_timeout(Some(Duration::from_secs(10).try_into().unwrap()));
-2605
-2606 let endpoint = Endpoint::builder()
-2607 .secret_key(secret_key.clone())
-2608 .transport_config(transport_config)
-2609 .relay_mode(relay_mode)
-2610 .alpns(vec![ALPN.to_vec()])
-2611 .bind()
-2612 .await
-2613 .unwrap();
-2614
-2615 Self {
-2616 secret_key,
-2617 endpoint,
-2618 }
-2619 }
-2620
-2621 fn tracked_endpoints(&self) -> Vec<PublicKey> {
-2622 self.endpoint
-2623 .magic_sock()
-2624 .list_remote_infos()
-2625 .into_iter()
-2626 .map(|ep| ep.node_id)
-2627 .collect()
-2628 }
+2496 /// It is possible to configure iroh to bound to a specific port and independently
+2497 /// configure the router to forward this port to the iroh node. This indicates a
+2498 /// situation like this, which still uses QAD to discover the public address.
+2499 Qad4LocalPort,
+2500}
+2501
+2502impl Display for DirectAddrType {
+2503 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+2504 match self {
+2505 DirectAddrType::Unknown => write!(f, "?"),
+2506 DirectAddrType::Local => write!(f, "local"),
+2507 DirectAddrType::Qad => write!(f, "qad"),
+2508 DirectAddrType::Portmapped => write!(f, "portmap"),
+2509 DirectAddrType::Qad4LocalPort => write!(f, "qad4localport"),
+2510 }
+2511 }
+2512}
+2513
+2514#[cfg(test)]
+2515mod tests {
+2516 use std::{collections::BTreeSet, sync::Arc, time::Duration};
+2517
+2518 use data_encoding::HEXLOWER;
+2519 use iroh_base::{NodeAddr, NodeId, PublicKey};
+2520 use n0_future::{time, StreamExt};
+2521 use n0_snafu::{Result, ResultExt};
+2522 use n0_watcher::Watcher;
+2523 use quinn::ServerConfig;
+2524 use rand::{Rng, RngCore};
+2525 use tokio::task::JoinSet;
+2526 use tokio_util::task::AbortOnDropHandle;
+2527 use tracing::{error, info, info_span, instrument, Instrument};
+2528 use tracing_test::traced_test;
+2529
+2530 use super::{NodeIdMappedAddr, Options};
+2531 use crate::{
+2532 dns::DnsResolver,
+2533 endpoint::{DirectAddr, PathSelection, Source},
+2534 magicsock::{node_map, Handle, MagicSock},
+2535 tls, Endpoint, RelayMap, RelayMode, SecretKey,
+2536 };
+2537
+2538 const ALPN: &[u8] = b"n0/test/1";
+2539
+2540 impl Default for Options {
+2541 fn default() -> Self {
+2542 let secret_key = SecretKey::generate(rand::rngs::OsRng);
+2543 let server_config = make_default_server_config(&secret_key);
+2544 Options {
+2545 addr_v4: None,
+2546 addr_v6: None,
+2547 secret_key,
+2548 relay_map: RelayMap::empty(),
+2549 relay_protocol: iroh_relay::http::Protocol::default(),
+2550 node_map: None,
+2551 discovery: None,
+2552 proxy_url: None,
+2553 dns_resolver: DnsResolver::new(),
+2554 server_config,
+2555 #[cfg(any(test, feature = "test-utils"))]
+2556 insecure_skip_relay_cert_verify: false,
+2557 #[cfg(any(test, feature = "test-utils"))]
+2558 path_selection: PathSelection::default(),
+2559 discovery_user_data: None,
+2560 metrics: Default::default(),
+2561 }
+2562 }
+2563 }
+2564
+2565 /// Generate a server config with no ALPNS and a default transport configuration
+2566 fn make_default_server_config(secret_key: &SecretKey) -> ServerConfig {
+2567 let quic_server_config =
+2568 crate::tls::TlsConfig::new(secret_key.clone()).make_server_config(vec![], false);
+2569 let mut server_config = ServerConfig::with_crypto(Arc::new(quic_server_config));
+2570 server_config.transport_config(Arc::new(quinn::TransportConfig::default()));
+2571 server_config
+2572 }
+2573
+2574 impl MagicSock {
+2575 #[track_caller]
+2576 pub fn add_test_addr(&self, node_addr: NodeAddr) {
+2577 self.add_node_addr(
+2578 node_addr,
+2579 Source::NamedApp {
+2580 name: "test".into(),
+2581 },
+2582 )
+2583 .unwrap()
+2584 }
+2585 }
+2586
+2587 /// Magicsock plus wrappers for sending packets
+2588 #[derive(Clone)]
+2589 struct MagicStack {
+2590 secret_key: SecretKey,
+2591 endpoint: Endpoint,
+2592 }
+2593
+2594 impl MagicStack {
+2595 async fn new(relay_mode: RelayMode) -> Self {
+2596 let secret_key = SecretKey::generate(rand::thread_rng());
+2597
+2598 let mut transport_config = quinn::TransportConfig::default();
+2599 transport_config.max_idle_timeout(Some(Duration::from_secs(10).try_into().unwrap()));
+2600
+2601 let endpoint = Endpoint::builder()
+2602 .secret_key(secret_key.clone())
+2603 .transport_config(transport_config)
+2604 .relay_mode(relay_mode)
+2605 .alpns(vec![ALPN.to_vec()])
+2606 .bind()
+2607 .await
+2608 .unwrap();
+2609
+2610 Self {
+2611 secret_key,
+2612 endpoint,
+2613 }
+2614 }
+2615
+2616 fn tracked_endpoints(&self) -> Vec<PublicKey> {
+2617 self.endpoint
+2618 .magic_sock()
+2619 .list_remote_infos()
+2620 .into_iter()
+2621 .map(|ep| ep.node_id)
+2622 .collect()
+2623 }
+2624
+2625 fn public(&self) -> PublicKey {
+2626 self.secret_key.public()
+2627 }
+2628 }
2629
-2630 fn public(&self) -> PublicKey {
-2631 self.secret_key.public()
-2632 }
-2633 }
-2634
-2635 /// Monitors endpoint changes and plumbs things together.
+2630 /// Monitors endpoint changes and plumbs things together.
+2631 ///
+2632 /// This is a way of connecting endpoints without a relay server. Whenever the local
+2633 /// endpoints of a magic endpoint change this address is added to the other magic
+2634 /// sockets. This function will await until the endpoints are connected the first time
+2635 /// before returning.
2636 ///
-2637 /// This is a way of connecting endpoints without a relay server. Whenever the local
-2638 /// endpoints of a magic endpoint change this address is added to the other magic
-2639 /// sockets. This function will await until the endpoints are connected the first time
-2640 /// before returning.
-2641 ///
-2642 /// When the returned drop guard is dropped, the tasks doing this updating are stopped.
-2643 #[instrument(skip_all)]
-2644 async fn mesh_stacks(stacks: Vec<MagicStack>) -> Result<JoinSet<()>> {
-2645 /// Registers endpoint addresses of a node to all other nodes.
-2646 fn update_direct_addrs(
-2647 stacks: &[MagicStack],
-2648 my_idx: usize,
-2649 new_addrs: BTreeSet<DirectAddr>,
-2650 ) {
-2651 let me = &stacks[my_idx];
-2652 for (i, m) in stacks.iter().enumerate() {
-2653 if i == my_idx {
-2654 continue;
-2655 }
-2656
-2657 let addr = NodeAddr {
-2658 node_id: me.public(),
-2659 relay_url: None,
-2660 direct_addresses: new_addrs.iter().map(|ep| ep.addr).collect(),
-2661 };
-2662 m.endpoint.magic_sock().add_test_addr(addr);
-2663 }
-2664 }
-2665
-2666 // For each node, start a task which monitors its local endpoints and registers them
-2667 // with the other nodes as local endpoints become known.
-2668 let mut tasks = JoinSet::new();
-2669 for (my_idx, m) in stacks.iter().enumerate() {
-2670 let m = m.clone();
-2671 let stacks = stacks.clone();
-2672 tasks.spawn(async move {
-2673 let me = m.endpoint.node_id().fmt_short();
-2674 let mut stream = m.endpoint.direct_addresses().stream().filter_map(|i| i);
-2675 while let Some(new_eps) = stream.next().await {
-2676 info!(%me, "conn{} endpoints update: {:?}", my_idx + 1, new_eps);
-2677 update_direct_addrs(&stacks, my_idx, new_eps);
-2678 }
-2679 });
-2680 }
-2681
-2682 // Wait for all nodes to be registered with each other.
-2683 time::timeout(Duration::from_secs(10), async move {
-2684 let all_node_ids: Vec<_> = stacks.iter().map(|ms| ms.endpoint.node_id()).collect();
-2685 loop {
-2686 let mut ready = Vec::with_capacity(stacks.len());
-2687 for ms in stacks.iter() {
-2688 let endpoints = ms.tracked_endpoints();
-2689 let my_node_id = ms.endpoint.node_id();
-2690 let all_nodes_meshed = all_node_ids
-2691 .iter()
-2692 .filter(|node_id| **node_id != my_node_id)
-2693 .all(|node_id| endpoints.contains(node_id));
-2694 ready.push(all_nodes_meshed);
-2695 }
-2696 if ready.iter().all(|meshed| *meshed) {
-2697 break;
-2698 }
-2699 time::sleep(Duration::from_millis(200)).await;
-2700 }
-2701 })
-2702 .await
-2703 .context("timeout")?;
-2704 info!("all nodes meshed");
-2705 Ok(tasks)
-2706 }
+2637 /// When the returned drop guard is dropped, the tasks doing this updating are stopped.
+2638 #[instrument(skip_all)]
+2639 async fn mesh_stacks(stacks: Vec<MagicStack>) -> Result<JoinSet<()>> {
+2640 /// Registers endpoint addresses of a node to all other nodes.
+2641 fn update_direct_addrs(
+2642 stacks: &[MagicStack],
+2643 my_idx: usize,
+2644 new_addrs: BTreeSet<DirectAddr>,
+2645 ) {
+2646 let me = &stacks[my_idx];
+2647 for (i, m) in stacks.iter().enumerate() {
+2648 if i == my_idx {
+2649 continue;
+2650 }
+2651
+2652 let addr = NodeAddr {
+2653 node_id: me.public(),
+2654 relay_url: None,
+2655 direct_addresses: new_addrs.iter().map(|ep| ep.addr).collect(),
+2656 };
+2657 m.endpoint.magic_sock().add_test_addr(addr);
+2658 }
+2659 }
+2660
+2661 // For each node, start a task which monitors its local endpoints and registers them
+2662 // with the other nodes as local endpoints become known.
+2663 let mut tasks = JoinSet::new();
+2664 for (my_idx, m) in stacks.iter().enumerate() {
+2665 let m = m.clone();
+2666 let stacks = stacks.clone();
+2667 tasks.spawn(async move {
+2668 let me = m.endpoint.node_id().fmt_short();
+2669 let mut stream = m.endpoint.direct_addresses().stream().filter_map(|i| i);
+2670 while let Some(new_eps) = stream.next().await {
+2671 info!(%me, "conn{} endpoints update: {:?}", my_idx + 1, new_eps);
+2672 update_direct_addrs(&stacks, my_idx, new_eps);
+2673 }
+2674 });
+2675 }
+2676
+2677 // Wait for all nodes to be registered with each other.
+2678 time::timeout(Duration::from_secs(10), async move {
+2679 let all_node_ids: Vec<_> = stacks.iter().map(|ms| ms.endpoint.node_id()).collect();
+2680 loop {
+2681 let mut ready = Vec::with_capacity(stacks.len());
+2682 for ms in stacks.iter() {
+2683 let endpoints = ms.tracked_endpoints();
+2684 let my_node_id = ms.endpoint.node_id();
+2685 let all_nodes_meshed = all_node_ids
+2686 .iter()
+2687 .filter(|node_id| **node_id != my_node_id)
+2688 .all(|node_id| endpoints.contains(node_id));
+2689 ready.push(all_nodes_meshed);
+2690 }
+2691 if ready.iter().all(|meshed| *meshed) {
+2692 break;
+2693 }
+2694 time::sleep(Duration::from_millis(200)).await;
+2695 }
+2696 })
+2697 .await
+2698 .context("timeout")?;
+2699 info!("all nodes meshed");
+2700 Ok(tasks)
+2701 }
+2702
+2703 #[instrument(skip_all, fields(me = %ep.endpoint.node_id().fmt_short()))]
+2704 async fn echo_receiver(ep: MagicStack, loss: ExpectedLoss) -> Result {
+2705 info!("accepting conn");
+2706 let conn = ep.endpoint.accept().await.expect("no conn");
2707
-2708 #[instrument(skip_all, fields(me = %ep.endpoint.node_id().fmt_short()))]
-2709 async fn echo_receiver(ep: MagicStack, loss: ExpectedLoss) -> Result {
-2710 info!("accepting conn");
-2711 let conn = ep.endpoint.accept().await.expect("no conn");
+2708 info!("connecting");
+2709 let conn = conn.await.context("connecting")?;
+2710 info!("accepting bi");
+2711 let (mut send_bi, mut recv_bi) = conn.accept_bi().await.context("accept bi")?;
2712
-2713 info!("connecting");
-2714 let conn = conn.await.context("connecting")?;
-2715 info!("accepting bi");
-2716 let (mut send_bi, mut recv_bi) = conn.accept_bi().await.context("accept bi")?;
-2717
-2718 info!("reading");
-2719 let val = recv_bi
-2720 .read_to_end(usize::MAX)
-2721 .await
-2722 .context("read to end")?;
+2713 info!("reading");
+2714 let val = recv_bi
+2715 .read_to_end(usize::MAX)
+2716 .await
+2717 .context("read to end")?;
+2718
+2719 info!("replying");
+2720 for chunk in val.chunks(12) {
+2721 send_bi.write_all(chunk).await.context("write all")?;
+2722 }
2723
-2724 info!("replying");
-2725 for chunk in val.chunks(12) {
-2726 send_bi.write_all(chunk).await.context("write all")?;
-2727 }
-2728
-2729 info!("finishing");
-2730 send_bi.finish().context("finish")?;
-2731 send_bi.stopped().await.context("stopped")?;
-2732
-2733 let stats = conn.stats();
-2734 info!("stats: {:#?}", stats);
-2735 // TODO: ensure panics in this function are reported ok
-2736 if matches!(loss, ExpectedLoss::AlmostNone) {
-2737 for (id, path) in &stats.paths {
-2738 assert!(
-2739 path.lost_packets < 10,
-2740 "[receiver] path {id:?} should not loose many packets",
-2741 );
-2742 }
-2743 }
+2724 info!("finishing");
+2725 send_bi.finish().context("finish")?;
+2726 send_bi.stopped().await.context("stopped")?;
+2727
+2728 let stats = conn.stats();
+2729 info!("stats: {:#?}", stats);
+2730 // TODO: ensure panics in this function are reported ok
+2731 if matches!(loss, ExpectedLoss::AlmostNone) {
+2732 for (id, path) in &stats.paths {
+2733 assert!(
+2734 path.lost_packets < 10,
+2735 "[receiver] path {id:?} should not loose many packets",
+2736 );
+2737 }
+2738 }
+2739
+2740 info!("close");
+2741 conn.close(0u32.into(), b"done");
+2742 info!("wait idle");
+2743 ep.endpoint.endpoint().wait_idle().await;
2744
-2745 info!("close");
-2746 conn.close(0u32.into(), b"done");
-2747 info!("wait idle");
-2748 ep.endpoint.endpoint().wait_idle().await;
-2749
-2750 Ok(())
-2751 }
-2752
-2753 #[instrument(skip_all, fields(me = %ep.endpoint.node_id().fmt_short()))]
-2754 async fn echo_sender(
-2755 ep: MagicStack,
-2756 dest_id: PublicKey,
-2757 msg: &[u8],
-2758 loss: ExpectedLoss,
-2759 ) -> Result {
-2760 info!("connecting to {}", dest_id.fmt_short());
-2761 let dest = NodeAddr::new(dest_id);
-2762 let conn = ep.endpoint.connect(dest, ALPN).await?;
-2763
-2764 info!("opening bi");
-2765 let (mut send_bi, mut recv_bi) = conn.open_bi().await.context("open bi")?;
-2766
-2767 info!("writing message");
-2768 send_bi.write_all(msg).await.context("write all")?;
-2769
-2770 info!("finishing");
-2771 send_bi.finish().context("finish")?;
-2772 send_bi.stopped().await.context("stopped")?;
-2773
-2774 info!("reading_to_end");
-2775 let val = recv_bi
-2776 .read_to_end(usize::MAX)
-2777 .await
-2778 .context("read to end")?;
-2779 assert_eq!(
-2780 val,
-2781 msg,
-2782 "[sender] expected {}, got {}",
-2783 HEXLOWER.encode(msg),
-2784 HEXLOWER.encode(&val)
-2785 );
-2786
-2787 let stats = conn.stats();
-2788 info!("stats: {:#?}", stats);
-2789 if matches!(loss, ExpectedLoss::AlmostNone) {
-2790 for (id, path) in &stats.paths {
-2791 assert!(
-2792 path.lost_packets < 10,
-2793 "[sender] path {id:?} should not loose many packets",
-2794 );
-2795 }
-2796 }
-2797
-2798 info!("close");
-2799 conn.close(0u32.into(), b"done");
-2800 info!("wait idle");
-2801 ep.endpoint.endpoint().wait_idle().await;
-2802 Ok(())
-2803 }
-2804
-2805 #[derive(Debug, Copy, Clone)]
-2806 enum ExpectedLoss {
-2807 AlmostNone,
-2808 YeahSure,
-2809 }
-2810
-2811 /// Runs a roundtrip between the [`echo_sender`] and [`echo_receiver`].
-2812 async fn run_roundtrip(
-2813 sender: MagicStack,
-2814 receiver: MagicStack,
-2815 payload: &[u8],
-2816 loss: ExpectedLoss,
-2817 ) {
-2818 let send_node_id = sender.endpoint.node_id();
-2819 let recv_node_id = receiver.endpoint.node_id();
-2820 info!("\nroundtrip: {send_node_id:#} -> {recv_node_id:#}");
-2821
-2822 let receiver_task = tokio::spawn(echo_receiver(receiver, loss));
-2823 let sender_res = echo_sender(sender, recv_node_id, payload, loss).await;
-2824 let sender_is_err = match sender_res {
-2825 Ok(()) => false,
-2826 Err(err) => {
-2827 eprintln!("[sender] Error:\n{err:#?}");
-2828 true
-2829 }
-2830 };
-2831 let receiver_is_err = match receiver_task.await {
-2832 Ok(Ok(())) => false,
-2833 Ok(Err(err)) => {
-2834 eprintln!("[receiver] Error:\n{err:#?}");
-2835 true
-2836 }
-2837 Err(joinerr) => {
-2838 if joinerr.is_panic() {
-2839 std::panic::resume_unwind(joinerr.into_panic());
-2840 } else {
-2841 eprintln!("[receiver] Error:\n{joinerr:#?}");
-2842 }
-2843 true
-2844 }
-2845 };
-2846 if sender_is_err || receiver_is_err {
-2847 panic!("Sender or receiver errored");
-2848 }
-2849 }
-2850
-2851 #[tokio::test(flavor = "multi_thread")]
-2852 #[traced_test]
-2853 async fn test_two_devices_roundtrip_quinn_magic() -> Result {
-2854 let m1 = MagicStack::new(RelayMode::Disabled).await;
-2855 let m2 = MagicStack::new(RelayMode::Disabled).await;
-2856
-2857 let _guard = mesh_stacks(vec![m1.clone(), m2.clone()]).await?;
-2858
-2859 for i in 0..5 {
-2860 info!("\n-- round {i}");
-2861 run_roundtrip(
-2862 m1.clone(),
-2863 m2.clone(),
-2864 b"hello m1",
-2865 ExpectedLoss::AlmostNone,
-2866 )
-2867 .await;
-2868 run_roundtrip(
-2869 m2.clone(),
-2870 m1.clone(),
-2871 b"hello m2",
-2872 ExpectedLoss::AlmostNone,
-2873 )
-2874 .await;
-2875
-2876 info!("\n-- larger data");
-2877 let mut data = vec![0u8; 10 * 1024];
-2878 rand::thread_rng().fill_bytes(&mut data);
-2879 run_roundtrip(m1.clone(), m2.clone(), &data, ExpectedLoss::AlmostNone).await;
-2880 run_roundtrip(m2.clone(), m1.clone(), &data, ExpectedLoss::AlmostNone).await;
-2881 }
-2882
-2883 Ok(())
-2884 }
-2885
-2886 #[tokio::test]
-2887 #[traced_test]
-2888 async fn test_regression_network_change_rebind_wakes_connection_driver() -> n0_snafu::Result {
-2889 let m1 = MagicStack::new(RelayMode::Disabled).await;
-2890 let m2 = MagicStack::new(RelayMode::Disabled).await;
-2891
-2892 println!("Net change");
-2893 m1.endpoint.magic_sock().force_network_change(true).await;
-2894 tokio::time::sleep(Duration::from_secs(1)).await; // wait for socket rebinding
-2895
-2896 let _guard = mesh_stacks(vec![m1.clone(), m2.clone()]).await?;
-2897
-2898 let _handle = AbortOnDropHandle::new(tokio::spawn({
-2899 let endpoint = m2.endpoint.clone();
-2900 async move {
-2901 while let Some(incoming) = endpoint.accept().await {
-2902 println!("Incoming first conn!");
-2903 let conn = incoming.await.e()?;
-2904 conn.closed().await;
-2905 }
-2906
-2907 Ok::<_, n0_snafu::Error>(())
-2908 }
-2909 }));
-2910
-2911 println!("first conn!");
-2912 let conn = m1
-2913 .endpoint
-2914 .connect(m2.endpoint.node_addr().initialized().await?, ALPN)
-2915 .await?;
-2916 println!("Closing first conn");
-2917 conn.close(0u32.into(), b"bye lolz");
-2918 conn.closed().await;
-2919 println!("Closed first conn");
-2920
-2921 Ok(())
-2922 }
-2923
-2924 #[tokio::test(flavor = "multi_thread")]
-2925 #[traced_test]
-2926 async fn test_two_devices_roundtrip_network_change() -> Result {
-2927 time::timeout(
-2928 Duration::from_secs(90),
-2929 test_two_devices_roundtrip_network_change_impl(),
-2930 )
-2931 .await
-2932 .context("timeout")?
-2933 }
-2934
-2935 /// Same structure as `test_two_devices_roundtrip_quinn_magic`, but interrupts regularly
-2936 /// with (simulated) network changes.
-2937 async fn test_two_devices_roundtrip_network_change_impl() -> Result {
-2938 let m1 = MagicStack::new(RelayMode::Disabled).await;
-2939 let m2 = MagicStack::new(RelayMode::Disabled).await;
-2940
-2941 let _guard = mesh_stacks(vec![m1.clone(), m2.clone()]).await?;
-2942
-2943 let offset = || {
-2944 let delay = rand::thread_rng().gen_range(10..=500);
-2945 Duration::from_millis(delay)
-2946 };
-2947 let rounds = 5;
-2948
-2949 // Regular network changes to m1 only.
-2950 let m1_network_change_guard = {
-2951 let m1 = m1.clone();
-2952 let task = tokio::spawn(async move {
-2953 loop {
-2954 println!("[m1] network change");
-2955 m1.endpoint.magic_sock().force_network_change(true).await;
-2956 time::sleep(offset()).await;
-2957 }
-2958 });
-2959 AbortOnDropHandle::new(task)
-2960 };
+2745 Ok(())
+2746 }
+2747
+2748 #[instrument(skip_all, fields(me = %ep.endpoint.node_id().fmt_short()))]
+2749 async fn echo_sender(
+2750 ep: MagicStack,
+2751 dest_id: PublicKey,
+2752 msg: &[u8],
+2753 loss: ExpectedLoss,
+2754 ) -> Result {
+2755 info!("connecting to {}", dest_id.fmt_short());
+2756 let dest = NodeAddr::new(dest_id);
+2757 let conn = ep.endpoint.connect(dest, ALPN).await?;
+2758
+2759 info!("opening bi");
+2760 let (mut send_bi, mut recv_bi) = conn.open_bi().await.context("open bi")?;
+2761
+2762 info!("writing message");
+2763 send_bi.write_all(msg).await.context("write all")?;
+2764
+2765 info!("finishing");
+2766 send_bi.finish().context("finish")?;
+2767 send_bi.stopped().await.context("stopped")?;
+2768
+2769 info!("reading_to_end");
+2770 let val = recv_bi
+2771 .read_to_end(usize::MAX)
+2772 .await
+2773 .context("read to end")?;
+2774 assert_eq!(
+2775 val,
+2776 msg,
+2777 "[sender] expected {}, got {}",
+2778 HEXLOWER.encode(msg),
+2779 HEXLOWER.encode(&val)
+2780 );
+2781
+2782 let stats = conn.stats();
+2783 info!("stats: {:#?}", stats);
+2784 if matches!(loss, ExpectedLoss::AlmostNone) {
+2785 for (id, path) in &stats.paths {
+2786 assert!(
+2787 path.lost_packets < 10,
+2788 "[sender] path {id:?} should not loose many packets",
+2789 );
+2790 }
+2791 }
+2792
+2793 info!("close");
+2794 conn.close(0u32.into(), b"done");
+2795 info!("wait idle");
+2796 ep.endpoint.endpoint().wait_idle().await;
+2797 Ok(())
+2798 }
+2799
+2800 #[derive(Debug, Copy, Clone)]
+2801 enum ExpectedLoss {
+2802 AlmostNone,
+2803 YeahSure,
+2804 }
+2805
+2806 /// Runs a roundtrip between the [`echo_sender`] and [`echo_receiver`].
+2807 async fn run_roundtrip(
+2808 sender: MagicStack,
+2809 receiver: MagicStack,
+2810 payload: &[u8],
+2811 loss: ExpectedLoss,
+2812 ) {
+2813 let send_node_id = sender.endpoint.node_id();
+2814 let recv_node_id = receiver.endpoint.node_id();
+2815 info!("\nroundtrip: {send_node_id:#} -> {recv_node_id:#}");
+2816
+2817 let receiver_task = tokio::spawn(echo_receiver(receiver, loss));
+2818 let sender_res = echo_sender(sender, recv_node_id, payload, loss).await;
+2819 let sender_is_err = match sender_res {
+2820 Ok(()) => false,
+2821 Err(err) => {
+2822 eprintln!("[sender] Error:\n{err:#?}");
+2823 true
+2824 }
+2825 };
+2826 let receiver_is_err = match receiver_task.await {
+2827 Ok(Ok(())) => false,
+2828 Ok(Err(err)) => {
+2829 eprintln!("[receiver] Error:\n{err:#?}");
+2830 true
+2831 }
+2832 Err(joinerr) => {
+2833 if joinerr.is_panic() {
+2834 std::panic::resume_unwind(joinerr.into_panic());
+2835 } else {
+2836 eprintln!("[receiver] Error:\n{joinerr:#?}");
+2837 }
+2838 true
+2839 }
+2840 };
+2841 if sender_is_err || receiver_is_err {
+2842 panic!("Sender or receiver errored");
+2843 }
+2844 }
+2845
+2846 #[tokio::test(flavor = "multi_thread")]
+2847 #[traced_test]
+2848 async fn test_two_devices_roundtrip_quinn_magic() -> Result {
+2849 let m1 = MagicStack::new(RelayMode::Disabled).await;
+2850 let m2 = MagicStack::new(RelayMode::Disabled).await;
+2851
+2852 let _guard = mesh_stacks(vec![m1.clone(), m2.clone()]).await?;
+2853
+2854 for i in 0..5 {
+2855 info!("\n-- round {i}");
+2856 run_roundtrip(
+2857 m1.clone(),
+2858 m2.clone(),
+2859 b"hello m1",
+2860 ExpectedLoss::AlmostNone,
+2861 )
+2862 .await;
+2863 run_roundtrip(
+2864 m2.clone(),
+2865 m1.clone(),
+2866 b"hello m2",
+2867 ExpectedLoss::AlmostNone,
+2868 )
+2869 .await;
+2870
+2871 info!("\n-- larger data");
+2872 let mut data = vec![0u8; 10 * 1024];
+2873 rand::thread_rng().fill_bytes(&mut data);
+2874 run_roundtrip(m1.clone(), m2.clone(), &data, ExpectedLoss::AlmostNone).await;
+2875 run_roundtrip(m2.clone(), m1.clone(), &data, ExpectedLoss::AlmostNone).await;
+2876 }
+2877
+2878 Ok(())
+2879 }
+2880
+2881 #[tokio::test]
+2882 #[traced_test]
+2883 async fn test_regression_network_change_rebind_wakes_connection_driver() -> n0_snafu::Result {
+2884 let m1 = MagicStack::new(RelayMode::Disabled).await;
+2885 let m2 = MagicStack::new(RelayMode::Disabled).await;
+2886
+2887 println!("Net change");
+2888 m1.endpoint.magic_sock().force_network_change(true).await;
+2889 tokio::time::sleep(Duration::from_secs(1)).await; // wait for socket rebinding
+2890
+2891 let _guard = mesh_stacks(vec![m1.clone(), m2.clone()]).await?;
+2892
+2893 let _handle = AbortOnDropHandle::new(tokio::spawn({
+2894 let endpoint = m2.endpoint.clone();
+2895 async move {
+2896 while let Some(incoming) = endpoint.accept().await {
+2897 println!("Incoming first conn!");
+2898 let conn = incoming.await.e()?;
+2899 conn.closed().await;
+2900 }
+2901
+2902 Ok::<_, n0_snafu::Error>(())
+2903 }
+2904 }));
+2905
+2906 println!("first conn!");
+2907 let conn = m1
+2908 .endpoint
+2909 .connect(m2.endpoint.node_addr().initialized().await?, ALPN)
+2910 .await?;
+2911 println!("Closing first conn");
+2912 conn.close(0u32.into(), b"bye lolz");
+2913 conn.closed().await;
+2914 println!("Closed first conn");
+2915
+2916 Ok(())
+2917 }
+2918
+2919 #[tokio::test(flavor = "multi_thread")]
+2920 #[traced_test]
+2921 async fn test_two_devices_roundtrip_network_change() -> Result {
+2922 time::timeout(
+2923 Duration::from_secs(90),
+2924 test_two_devices_roundtrip_network_change_impl(),
+2925 )
+2926 .await
+2927 .context("timeout")?
+2928 }
+2929
+2930 /// Same structure as `test_two_devices_roundtrip_quinn_magic`, but interrupts regularly
+2931 /// with (simulated) network changes.
+2932 async fn test_two_devices_roundtrip_network_change_impl() -> Result {
+2933 let m1 = MagicStack::new(RelayMode::Disabled).await;
+2934 let m2 = MagicStack::new(RelayMode::Disabled).await;
+2935
+2936 let _guard = mesh_stacks(vec![m1.clone(), m2.clone()]).await?;
+2937
+2938 let offset = || {
+2939 let delay = rand::thread_rng().gen_range(10..=500);
+2940 Duration::from_millis(delay)
+2941 };
+2942 let rounds = 5;
+2943
+2944 // Regular network changes to m1 only.
+2945 let m1_network_change_guard = {
+2946 let m1 = m1.clone();
+2947 let task = tokio::spawn(async move {
+2948 loop {
+2949 println!("[m1] network change");
+2950 m1.endpoint.magic_sock().force_network_change(true).await;
+2951 time::sleep(offset()).await;
+2952 }
+2953 });
+2954 AbortOnDropHandle::new(task)
+2955 };
+2956
+2957 for i in 0..rounds {
+2958 println!("-- [m1 changes] round {}", i + 1);
+2959 run_roundtrip(m1.clone(), m2.clone(), b"hello m1", ExpectedLoss::YeahSure).await;
+2960 run_roundtrip(m2.clone(), m1.clone(), b"hello m2", ExpectedLoss::YeahSure).await;
2961
-2962 for i in 0..rounds {
-2963 println!("-- [m1 changes] round {}", i + 1);
-2964 run_roundtrip(m1.clone(), m2.clone(), b"hello m1", ExpectedLoss::YeahSure).await;
-2965 run_roundtrip(m2.clone(), m1.clone(), b"hello m2", ExpectedLoss::YeahSure).await;
-2966
-2967 println!("-- [m1 changes] larger data");
-2968 let mut data = vec![0u8; 10 * 1024];
-2969 rand::thread_rng().fill_bytes(&mut data);
-2970 run_roundtrip(m1.clone(), m2.clone(), &data, ExpectedLoss::YeahSure).await;
-2971 run_roundtrip(m2.clone(), m1.clone(), &data, ExpectedLoss::YeahSure).await;
-2972 }
-2973
-2974 std::mem::drop(m1_network_change_guard);
-2975
-2976 // Regular network changes to m2 only.
-2977 let m2_network_change_guard = {
-2978 let m2 = m2.clone();
-2979 let task = tokio::spawn(async move {
-2980 loop {
-2981 println!("[m2] network change");
-2982 m2.endpoint.magic_sock().force_network_change(true).await;
-2983 time::sleep(offset()).await;
-2984 }
-2985 });
-2986 AbortOnDropHandle::new(task)
-2987 };
+2962 println!("-- [m1 changes] larger data");
+2963 let mut data = vec![0u8; 10 * 1024];
+2964 rand::thread_rng().fill_bytes(&mut data);
+2965 run_roundtrip(m1.clone(), m2.clone(), &data, ExpectedLoss::YeahSure).await;
+2966 run_roundtrip(m2.clone(), m1.clone(), &data, ExpectedLoss::YeahSure).await;
+2967 }
+2968
+2969 std::mem::drop(m1_network_change_guard);
+2970
+2971 // Regular network changes to m2 only.
+2972 let m2_network_change_guard = {
+2973 let m2 = m2.clone();
+2974 let task = tokio::spawn(async move {
+2975 loop {
+2976 println!("[m2] network change");
+2977 m2.endpoint.magic_sock().force_network_change(true).await;
+2978 time::sleep(offset()).await;
+2979 }
+2980 });
+2981 AbortOnDropHandle::new(task)
+2982 };
+2983
+2984 for i in 0..rounds {
+2985 println!("-- [m2 changes] round {}", i + 1);
+2986 run_roundtrip(m1.clone(), m2.clone(), b"hello m1", ExpectedLoss::YeahSure).await;
+2987 run_roundtrip(m2.clone(), m1.clone(), b"hello m2", ExpectedLoss::YeahSure).await;
2988
-2989 for i in 0..rounds {
-2990 println!("-- [m2 changes] round {}", i + 1);
-2991 run_roundtrip(m1.clone(), m2.clone(), b"hello m1", ExpectedLoss::YeahSure).await;
-2992 run_roundtrip(m2.clone(), m1.clone(), b"hello m2", ExpectedLoss::YeahSure).await;
-2993
-2994 println!("-- [m2 changes] larger data");
-2995 let mut data = vec![0u8; 10 * 1024];
-2996 rand::thread_rng().fill_bytes(&mut data);
-2997 run_roundtrip(m1.clone(), m2.clone(), &data, ExpectedLoss::YeahSure).await;
-2998 run_roundtrip(m2.clone(), m1.clone(), &data, ExpectedLoss::YeahSure).await;
-2999 }
-3000
-3001 std::mem::drop(m2_network_change_guard);
-3002
-3003 // Regular network changes to both m1 and m2 only.
-3004 let m1_m2_network_change_guard = {
-3005 let m1 = m1.clone();
-3006 let m2 = m2.clone();
-3007 let task = tokio::spawn(async move {
-3008 println!("-- [m1] network change");
-3009 m1.endpoint.magic_sock().force_network_change(true).await;
-3010 println!("-- [m2] network change");
-3011 m2.endpoint.magic_sock().force_network_change(true).await;
-3012 time::sleep(offset()).await;
-3013 });
-3014 AbortOnDropHandle::new(task)
-3015 };
+2989 println!("-- [m2 changes] larger data");
+2990 let mut data = vec![0u8; 10 * 1024];
+2991 rand::thread_rng().fill_bytes(&mut data);
+2992 run_roundtrip(m1.clone(), m2.clone(), &data, ExpectedLoss::YeahSure).await;
+2993 run_roundtrip(m2.clone(), m1.clone(), &data, ExpectedLoss::YeahSure).await;
+2994 }
+2995
+2996 std::mem::drop(m2_network_change_guard);
+2997
+2998 // Regular network changes to both m1 and m2 only.
+2999 let m1_m2_network_change_guard = {
+3000 let m1 = m1.clone();
+3001 let m2 = m2.clone();
+3002 let task = tokio::spawn(async move {
+3003 println!("-- [m1] network change");
+3004 m1.endpoint.magic_sock().force_network_change(true).await;
+3005 println!("-- [m2] network change");
+3006 m2.endpoint.magic_sock().force_network_change(true).await;
+3007 time::sleep(offset()).await;
+3008 });
+3009 AbortOnDropHandle::new(task)
+3010 };
+3011
+3012 for i in 0..rounds {
+3013 println!("-- [m1 & m2 changes] round {}", i + 1);
+3014 run_roundtrip(m1.clone(), m2.clone(), b"hello m1", ExpectedLoss::YeahSure).await;
+3015 run_roundtrip(m2.clone(), m1.clone(), b"hello m2", ExpectedLoss::YeahSure).await;
3016
-3017 for i in 0..rounds {
-3018 println!("-- [m1 & m2 changes] round {}", i + 1);
-3019 run_roundtrip(m1.clone(), m2.clone(), b"hello m1", ExpectedLoss::YeahSure).await;
-3020 run_roundtrip(m2.clone(), m1.clone(), b"hello m2", ExpectedLoss::YeahSure).await;
-3021
-3022 println!("-- [m1 & m2 changes] larger data");
-3023 let mut data = vec![0u8; 10 * 1024];
-3024 rand::thread_rng().fill_bytes(&mut data);
-3025 run_roundtrip(m1.clone(), m2.clone(), &data, ExpectedLoss::YeahSure).await;
-3026 run_roundtrip(m2.clone(), m1.clone(), &data, ExpectedLoss::YeahSure).await;
-3027 }
-3028
-3029 std::mem::drop(m1_m2_network_change_guard);
-3030 Ok(())
-3031 }
-3032
-3033 #[tokio::test(flavor = "multi_thread")]
-3034 #[traced_test]
-3035 async fn test_two_devices_setup_teardown() -> Result {
-3036 for i in 0..10 {
-3037 println!("-- round {i}");
-3038 println!("setting up magic stack");
-3039 let m1 = MagicStack::new(RelayMode::Disabled).await;
-3040 let m2 = MagicStack::new(RelayMode::Disabled).await;
-3041
-3042 let _guard = mesh_stacks(vec![m1.clone(), m2.clone()]).await?;
-3043
-3044 println!("closing endpoints");
-3045 let msock1 = m1.endpoint.magic_sock();
-3046 let msock2 = m2.endpoint.magic_sock();
-3047 m1.endpoint.close().await;
-3048 m2.endpoint.close().await;
-3049
-3050 assert!(msock1.msock.is_closed());
-3051 assert!(msock2.msock.is_closed());
-3052 }
-3053 Ok(())
-3054 }
+3017 println!("-- [m1 & m2 changes] larger data");
+3018 let mut data = vec![0u8; 10 * 1024];
+3019 rand::thread_rng().fill_bytes(&mut data);
+3020 run_roundtrip(m1.clone(), m2.clone(), &data, ExpectedLoss::YeahSure).await;
+3021 run_roundtrip(m2.clone(), m1.clone(), &data, ExpectedLoss::YeahSure).await;
+3022 }
+3023
+3024 std::mem::drop(m1_m2_network_change_guard);
+3025 Ok(())
+3026 }
+3027
+3028 #[tokio::test(flavor = "multi_thread")]
+3029 #[traced_test]
+3030 async fn test_two_devices_setup_teardown() -> Result {
+3031 for i in 0..10 {
+3032 println!("-- round {i}");
+3033 println!("setting up magic stack");
+3034 let m1 = MagicStack::new(RelayMode::Disabled).await;
+3035 let m2 = MagicStack::new(RelayMode::Disabled).await;
+3036
+3037 let _guard = mesh_stacks(vec![m1.clone(), m2.clone()]).await?;
+3038
+3039 println!("closing endpoints");
+3040 let msock1 = m1.endpoint.magic_sock();
+3041 let msock2 = m2.endpoint.magic_sock();
+3042 m1.endpoint.close().await;
+3043 m2.endpoint.close().await;
+3044
+3045 assert!(msock1.msock.is_closed());
+3046 assert!(msock2.msock.is_closed());
+3047 }
+3048 Ok(())
+3049 }
+3050
+3051 #[tokio::test]
+3052 #[traced_test]
+3053 async fn test_local_endpoints() {
+3054 let ms = Handle::new(Default::default()).await.unwrap();
3055
-3056 #[tokio::test]
-3057 #[traced_test]
-3058 async fn test_local_endpoints() {
-3059 let ms = Handle::new(Default::default()).await.unwrap();
+3056 // See if we can get endpoints.
+3057 let eps0 = ms.direct_addresses().initialized().await.unwrap();
+3058 println!("{eps0:?}");
+3059 assert!(!eps0.is_empty());
3060
-3061 // See if we can get endpoints.
-3062 let eps0 = ms.direct_addresses().initialized().await.unwrap();
-3063 println!("{eps0:?}");
-3064 assert!(!eps0.is_empty());
-3065
-3066 // Getting the endpoints again immediately should give the same results.
-3067 let eps1 = ms.direct_addresses().initialized().await.unwrap();
-3068 println!("{eps1:?}");
-3069 assert_eq!(eps0, eps1);
-3070 }
-3071
-3072 /// Creates a new [`quinn::Endpoint`] hooked up to a [`MagicSock`].
-3073 ///
-3074 /// This is without involving [`crate::endpoint::Endpoint`]. The socket will accept
-3075 /// connections using [`ALPN`].
-3076 ///
-3077 /// Use [`magicsock_connect`] to establish connections.
-3078 #[instrument(name = "ep", skip_all, fields(me = secret_key.public().fmt_short()))]
-3079 async fn magicsock_ep(secret_key: SecretKey) -> Result<Handle> {
-3080 let quic_server_config =
-3081 tls::TlsConfig::new(secret_key.clone()).make_server_config(vec![ALPN.to_vec()], true);
-3082 let mut server_config = ServerConfig::with_crypto(Arc::new(quic_server_config));
-3083 server_config.transport_config(Arc::new(quinn::TransportConfig::default()));
-3084
-3085 let dns_resolver = DnsResolver::new();
-3086 let opts = Options {
-3087 addr_v4: None,
-3088 addr_v6: None,
-3089 secret_key: secret_key.clone(),
-3090 relay_map: RelayMap::empty(),
-3091 relay_protocol: iroh_relay::http::Protocol::default(),
-3092 node_map: None,
-3093 discovery: None,
-3094 discovery_user_data: None,
-3095 dns_resolver,
-3096 proxy_url: None,
-3097 server_config,
-3098 insecure_skip_relay_cert_verify: false,
-3099 path_selection: PathSelection::default(),
-3100 metrics: Default::default(),
-3101 };
-3102 let msock = MagicSock::spawn(opts).await?;
-3103 Ok(msock)
-3104 }
-3105
-3106 /// Connects from `ep` returned by [`magicsock_ep`] to the `node_id`.
-3107 ///
-3108 /// Uses [`ALPN`], `node_id`, must match `addr`.
-3109 #[instrument(name = "connect", skip_all, fields(me = ep_secret_key.public().fmt_short()))]
-3110 async fn magicsock_connect(
-3111 ep: &quinn::Endpoint,
-3112 ep_secret_key: SecretKey,
-3113 addr: NodeIdMappedAddr,
-3114 node_id: NodeId,
-3115 ) -> Result<quinn::Connection> {
-3116 // Endpoint::connect sets this, do the same to have similar behaviour.
-3117 let mut transport_config = quinn::TransportConfig::default();
-3118 transport_config.keep_alive_interval(Some(Duration::from_secs(1)));
-3119
-3120 magicsock_connect_with_transport_config(
-3121 ep,
-3122 ep_secret_key,
-3123 addr,
-3124 node_id,
-3125 Arc::new(transport_config),
-3126 )
-3127 .await
-3128 }
-3129
-3130 /// Connects from `ep` returned by [`magicsock_ep`] to the `node_id`.
-3131 ///
-3132 /// This version allows customising the transport config.
-3133 ///
-3134 /// Uses [`ALPN`], `node_id`, must match `addr`.
-3135 #[instrument(name = "connect", skip_all, fields(me = ep_secret_key.public().fmt_short()))]
-3136 async fn magicsock_connect_with_transport_config(
-3137 ep: &quinn::Endpoint,
-3138 ep_secret_key: SecretKey,
-3139 mapped_addr: NodeIdMappedAddr,
-3140 node_id: NodeId,
-3141 transport_config: Arc<quinn::TransportConfig>,
-3142 ) -> Result<quinn::Connection> {
-3143 let alpns = vec![ALPN.to_vec()];
-3144 let quic_client_config =
-3145 tls::TlsConfig::new(ep_secret_key.clone()).make_client_config(alpns, true);
-3146 let mut client_config = quinn::ClientConfig::new(Arc::new(quic_client_config));
-3147 client_config.transport_config(transport_config);
-3148 let connect = ep
-3149 .connect_with(
-3150 client_config,
-3151 mapped_addr.private_socket_addr(),
-3152 &tls::name::encode(node_id),
-3153 )
-3154 .context("connect")?;
-3155 let connection = connect.await.e()?;
-3156 Ok(connection)
-3157 }
-3158
-3159 #[tokio::test]
-3160 #[traced_test]
-3161 async fn test_try_send_no_send_addr() {
-3162 // Regression test: if there is no send_addr we should keep being able to use the
-3163 // Endpoint.
-3164
-3165 let secret_key_1 = SecretKey::from_bytes(&[1u8; 32]);
-3166 let secret_key_2 = SecretKey::from_bytes(&[2u8; 32]);
-3167 let node_id_2 = secret_key_2.public();
-3168 let secret_key_missing_node = SecretKey::from_bytes(&[255u8; 32]);
-3169 let node_id_missing_node = secret_key_missing_node.public();
+3061 // Getting the endpoints again immediately should give the same results.
+3062 let eps1 = ms.direct_addresses().initialized().await.unwrap();
+3063 println!("{eps1:?}");
+3064 assert_eq!(eps0, eps1);
+3065 }
+3066
+3067 /// Creates a new [`quinn::Endpoint`] hooked up to a [`MagicSock`].
+3068 ///
+3069 /// This is without involving [`crate::endpoint::Endpoint`]. The socket will accept
+3070 /// connections using [`ALPN`].
+3071 ///
+3072 /// Use [`magicsock_connect`] to establish connections.
+3073 #[instrument(name = "ep", skip_all, fields(me = secret_key.public().fmt_short()))]
+3074 async fn magicsock_ep(secret_key: SecretKey) -> Result<Handle> {
+3075 let quic_server_config =
+3076 tls::TlsConfig::new(secret_key.clone()).make_server_config(vec![ALPN.to_vec()], true);
+3077 let mut server_config = ServerConfig::with_crypto(Arc::new(quic_server_config));
+3078 server_config.transport_config(Arc::new(quinn::TransportConfig::default()));
+3079
+3080 let dns_resolver = DnsResolver::new();
+3081 let opts = Options {
+3082 addr_v4: None,
+3083 addr_v6: None,
+3084 secret_key: secret_key.clone(),
+3085 relay_map: RelayMap::empty(),
+3086 relay_protocol: iroh_relay::http::Protocol::default(),
+3087 node_map: None,
+3088 discovery: None,
+3089 discovery_user_data: None,
+3090 dns_resolver,
+3091 proxy_url: None,
+3092 server_config,
+3093 insecure_skip_relay_cert_verify: false,
+3094 path_selection: PathSelection::default(),
+3095 metrics: Default::default(),
+3096 };
+3097 let msock = MagicSock::spawn(opts).await?;
+3098 Ok(msock)
+3099 }
+3100
+3101 /// Connects from `ep` returned by [`magicsock_ep`] to the `node_id`.
+3102 ///
+3103 /// Uses [`ALPN`], `node_id`, must match `addr`.
+3104 #[instrument(name = "connect", skip_all, fields(me = ep_secret_key.public().fmt_short()))]
+3105 async fn magicsock_connect(
+3106 ep: &quinn::Endpoint,
+3107 ep_secret_key: SecretKey,
+3108 addr: NodeIdMappedAddr,
+3109 node_id: NodeId,
+3110 ) -> Result<quinn::Connection> {
+3111 // Endpoint::connect sets this, do the same to have similar behaviour.
+3112 let mut transport_config = quinn::TransportConfig::default();
+3113 transport_config.keep_alive_interval(Some(Duration::from_secs(1)));
+3114
+3115 magicsock_connect_with_transport_config(
+3116 ep,
+3117 ep_secret_key,
+3118 addr,
+3119 node_id,
+3120 Arc::new(transport_config),
+3121 )
+3122 .await
+3123 }
+3124
+3125 /// Connects from `ep` returned by [`magicsock_ep`] to the `node_id`.
+3126 ///
+3127 /// This version allows customising the transport config.
+3128 ///
+3129 /// Uses [`ALPN`], `node_id`, must match `addr`.
+3130 #[instrument(name = "connect", skip_all, fields(me = ep_secret_key.public().fmt_short()))]
+3131 async fn magicsock_connect_with_transport_config(
+3132 ep: &quinn::Endpoint,
+3133 ep_secret_key: SecretKey,
+3134 mapped_addr: NodeIdMappedAddr,
+3135 node_id: NodeId,
+3136 transport_config: Arc<quinn::TransportConfig>,
+3137 ) -> Result<quinn::Connection> {
+3138 let alpns = vec![ALPN.to_vec()];
+3139 let quic_client_config =
+3140 tls::TlsConfig::new(ep_secret_key.clone()).make_client_config(alpns, true);
+3141 let mut client_config = quinn::ClientConfig::new(Arc::new(quic_client_config));
+3142 client_config.transport_config(transport_config);
+3143 let connect = ep
+3144 .connect_with(
+3145 client_config,
+3146 mapped_addr.private_socket_addr(),
+3147 &tls::name::encode(node_id),
+3148 )
+3149 .context("connect")?;
+3150 let connection = connect.await.e()?;
+3151 Ok(connection)
+3152 }
+3153
+3154 #[tokio::test]
+3155 #[traced_test]
+3156 async fn test_try_send_no_send_addr() {
+3157 // Regression test: if there is no send_addr we should keep being able to use the
+3158 // Endpoint.
+3159
+3160 let secret_key_1 = SecretKey::from_bytes(&[1u8; 32]);
+3161 let secret_key_2 = SecretKey::from_bytes(&[2u8; 32]);
+3162 let node_id_2 = secret_key_2.public();
+3163 let secret_key_missing_node = SecretKey::from_bytes(&[255u8; 32]);
+3164 let node_id_missing_node = secret_key_missing_node.public();
+3165
+3166 let msock_1 = magicsock_ep(secret_key_1.clone()).await.unwrap();
+3167
+3168 // Generate an address not present in the NodeMap.
+3169 let bad_addr = NodeIdMappedAddr::generate();
3170
-3171 let msock_1 = magicsock_ep(secret_key_1.clone()).await.unwrap();
-3172
-3173 // Generate an address not present in the NodeMap.
-3174 let bad_addr = NodeIdMappedAddr::generate();
-3175
-3176 // 500ms is rather fast here. Running this locally it should always be the correct
-3177 // timeout. If this is too slow however the test will not become flaky as we are
-3178 // expecting the timeout, we might just get the timeout for the wrong reason. But
-3179 // this speeds up the test.
-3180 let res = tokio::time::timeout(
-3181 Duration::from_millis(500),
-3182 magicsock_connect(
-3183 msock_1.endpoint(),
-3184 secret_key_1.clone(),
-3185 bad_addr,
-3186 node_id_missing_node,
-3187 ),
-3188 )
-3189 .await;
-3190 assert!(res.is_err(), "expecting timeout");
-3191
-3192 // Now check we can still create another connection with this endpoint.
-3193 let msock_2 = magicsock_ep(secret_key_2.clone()).await.unwrap();
-3194
-3195 // This needs an accept task
-3196 let accept_task = tokio::spawn({
-3197 async fn accept(ep: quinn::Endpoint) -> Result<()> {
-3198 let incoming = ep.accept().await.context("no incoming")?;
-3199 let _conn = incoming
-3200 .accept()
-3201 .context("accept")?
-3202 .await
-3203 .context("connecting")?;
-3204
-3205 // Keep this connection alive for a while
-3206 tokio::time::sleep(Duration::from_secs(10)).await;
-3207 info!("accept finished");
-3208 Ok(())
-3209 }
-3210 let ep = msock_2.endpoint().clone();
-3211 async move {
-3212 if let Err(err) = accept(ep).await {
-3213 error!("{err:#}");
-3214 }
-3215 }
-3216 .instrument(info_span!("ep2.accept, me = node_id_2.fmt_short()"))
-3217 });
-3218 let _accept_task = AbortOnDropHandle::new(accept_task);
-3219
-3220 let node_addr_2 = NodeAddr {
-3221 node_id: node_id_2,
-3222 relay_url: None,
-3223 direct_addresses: msock_2
-3224 .direct_addresses()
-3225 .initialized()
-3226 .await
-3227 .expect("no direct addrs")
-3228 .into_iter()
-3229 .map(|x| x.addr)
-3230 .collect(),
-3231 };
-3232 msock_1
-3233 .add_node_addr(
-3234 node_addr_2,
-3235 Source::NamedApp {
-3236 name: "test".into(),
-3237 },
-3238 )
-3239 .unwrap();
-3240 let addr = msock_1.get_mapping_addr(node_id_2).unwrap();
-3241 let res = tokio::time::timeout(
-3242 Duration::from_secs(10),
-3243 magicsock_connect(msock_1.endpoint(), secret_key_1.clone(), addr, node_id_2),
-3244 )
-3245 .await
-3246 .expect("timeout while connecting");
-3247
-3248 // aka assert!(res.is_ok()) but with nicer error reporting.
-3249 res.unwrap();
-3250
-3251 // TODO: Now check if we can connect to a repaired ep_3, but we can't modify that
-3252 // much internal state for now.
-3253 }
-3254
-3255 #[tokio::test]
-3256 #[traced_test]
-3257 async fn test_try_send_no_udp_addr_or_relay_url() {
-3258 // This specifically tests the `if udp_addr.is_none() && relay_url.is_none()`
-3259 // behaviour of MagicSock::try_send.
-3260
-3261 let secret_key_1 = SecretKey::from_bytes(&[1u8; 32]);
-3262 let secret_key_2 = SecretKey::from_bytes(&[2u8; 32]);
-3263 let node_id_2 = secret_key_2.public();
-3264
-3265 let msock_1 = magicsock_ep(secret_key_1.clone()).await.unwrap();
-3266 let msock_2 = magicsock_ep(secret_key_2.clone()).await.unwrap();
-3267 let ep_2 = msock_2.endpoint().clone();
-3268
-3269 // We need a task to accept the connection.
-3270 let accept_task = tokio::spawn({
-3271 async fn accept(ep: quinn::Endpoint) -> Result<()> {
-3272 let incoming = ep.accept().await.context("no incoming")?;
-3273 let conn = incoming
-3274 .accept()
-3275 .context("accept")?
-3276 .await
-3277 .context("connecting")?;
-3278 let mut stream = conn.accept_uni().await.context("accept uni")?;
-3279 stream.read_to_end(1 << 16).await.context("read to end")?;
-3280 info!("accept finished");
-3281 Ok(())
+3171 // 500ms is rather fast here. Running this locally it should always be the correct
+3172 // timeout. If this is too slow however the test will not become flaky as we are
+3173 // expecting the timeout, we might just get the timeout for the wrong reason. But
+3174 // this speeds up the test.
+3175 let res = tokio::time::timeout(
+3176 Duration::from_millis(500),
+3177 magicsock_connect(
+3178 msock_1.endpoint(),
+3179 secret_key_1.clone(),
+3180 bad_addr,
+3181 node_id_missing_node,
+3182 ),
+3183 )
+3184 .await;
+3185 assert!(res.is_err(), "expecting timeout");
+3186
+3187 // Now check we can still create another connection with this endpoint.
+3188 let msock_2 = magicsock_ep(secret_key_2.clone()).await.unwrap();
+3189
+3190 // This needs an accept task
+3191 let accept_task = tokio::spawn({
+3192 async fn accept(ep: quinn::Endpoint) -> Result<()> {
+3193 let incoming = ep.accept().await.context("no incoming")?;
+3194 let _conn = incoming
+3195 .accept()
+3196 .context("accept")?
+3197 .await
+3198 .context("connecting")?;
+3199
+3200 // Keep this connection alive for a while
+3201 tokio::time::sleep(Duration::from_secs(10)).await;
+3202 info!("accept finished");
+3203 Ok(())
+3204 }
+3205 let ep = msock_2.endpoint().clone();
+3206 async move {
+3207 if let Err(err) = accept(ep).await {
+3208 error!("{err:#}");
+3209 }
+3210 }
+3211 .instrument(info_span!("ep2.accept, me = node_id_2.fmt_short()"))
+3212 });
+3213 let _accept_task = AbortOnDropHandle::new(accept_task);
+3214
+3215 let node_addr_2 = NodeAddr {
+3216 node_id: node_id_2,
+3217 relay_url: None,
+3218 direct_addresses: msock_2
+3219 .direct_addresses()
+3220 .initialized()
+3221 .await
+3222 .expect("no direct addrs")
+3223 .into_iter()
+3224 .map(|x| x.addr)
+3225 .collect(),
+3226 };
+3227 msock_1
+3228 .add_node_addr(
+3229 node_addr_2,
+3230 Source::NamedApp {
+3231 name: "test".into(),
+3232 },
+3233 )
+3234 .unwrap();
+3235 let addr = msock_1.get_mapping_addr(node_id_2).unwrap();
+3236 let res = tokio::time::timeout(
+3237 Duration::from_secs(10),
+3238 magicsock_connect(msock_1.endpoint(), secret_key_1.clone(), addr, node_id_2),
+3239 )
+3240 .await
+3241 .expect("timeout while connecting");
+3242
+3243 // aka assert!(res.is_ok()) but with nicer error reporting.
+3244 res.unwrap();
+3245
+3246 // TODO: Now check if we can connect to a repaired ep_3, but we can't modify that
+3247 // much internal state for now.
+3248 }
+3249
+3250 #[tokio::test]
+3251 #[traced_test]
+3252 async fn test_try_send_no_udp_addr_or_relay_url() {
+3253 // This specifically tests the `if udp_addr.is_none() && relay_url.is_none()`
+3254 // behaviour of MagicSock::try_send.
+3255
+3256 let secret_key_1 = SecretKey::from_bytes(&[1u8; 32]);
+3257 let secret_key_2 = SecretKey::from_bytes(&[2u8; 32]);
+3258 let node_id_2 = secret_key_2.public();
+3259
+3260 let msock_1 = magicsock_ep(secret_key_1.clone()).await.unwrap();
+3261 let msock_2 = magicsock_ep(secret_key_2.clone()).await.unwrap();
+3262 let ep_2 = msock_2.endpoint().clone();
+3263
+3264 // We need a task to accept the connection.
+3265 let accept_task = tokio::spawn({
+3266 async fn accept(ep: quinn::Endpoint) -> Result<()> {
+3267 let incoming = ep.accept().await.context("no incoming")?;
+3268 let conn = incoming
+3269 .accept()
+3270 .context("accept")?
+3271 .await
+3272 .context("connecting")?;
+3273 let mut stream = conn.accept_uni().await.context("accept uni")?;
+3274 stream.read_to_end(1 << 16).await.context("read to end")?;
+3275 info!("accept finished");
+3276 Ok(())
+3277 }
+3278 async move {
+3279 if let Err(err) = accept(ep_2).await {
+3280 error!("{err:#}");
+3281 }
3282 }
-3283 async move {
-3284 if let Err(err) = accept(ep_2).await {
-3285 error!("{err:#}");
-3286 }
-3287 }
-3288 .instrument(info_span!("ep2.accept", me = node_id_2.fmt_short()))
-3289 });
-3290 let _accept_task = AbortOnDropHandle::new(accept_task);
-3291
-3292 // Add an empty entry in the NodeMap of ep_1
-3293 msock_1.node_map.add_node_addr(
-3294 NodeAddr {
-3295 node_id: node_id_2,
-3296 relay_url: None,
-3297 direct_addresses: Default::default(),
-3298 },
-3299 Source::NamedApp {
-3300 name: "test".into(),
-3301 },
-3302 &msock_1.metrics.magicsock,
-3303 );
-3304 let addr_2 = msock_1.get_mapping_addr(node_id_2).unwrap();
-3305
-3306 // Set a low max_idle_timeout so quinn gives up on this quickly and our test does
-3307 // not take forever. You need to check the log output to verify this is really
-3308 // triggering the correct error.
-3309 // In test_try_send_no_send_addr() above you may have noticed we used
-3310 // tokio::time::timeout() on the connection attempt instead. Here however we want
-3311 // Quinn itself to have fully given up on the connection attempt because we will
-3312 // later connect to **the same** node. If Quinn did not give up on the connection
-3313 // we'd close it on drop, and the retransmits of the close packets would interfere
-3314 // with the next handshake, closing it during the handshake. This makes the test a
-3315 // little slower though.
-3316 let mut transport_config = quinn::TransportConfig::default();
-3317 transport_config.max_idle_timeout(Some(Duration::from_millis(200).try_into().unwrap()));
-3318 let res = magicsock_connect_with_transport_config(
-3319 msock_1.endpoint(),
-3320 secret_key_1.clone(),
-3321 addr_2,
-3322 node_id_2,
-3323 Arc::new(transport_config),
-3324 )
-3325 .await;
-3326 assert!(res.is_err(), "expected timeout");
-3327 info!("first connect timed out as expected");
-3328
-3329 // Provide correct addressing information
-3330 msock_1.node_map.add_node_addr(
-3331 NodeAddr {
-3332 node_id: node_id_2,
-3333 relay_url: None,
-3334 direct_addresses: msock_2
-3335 .direct_addresses()
-3336 .initialized()
-3337 .await
-3338 .expect("no direct addrs")
-3339 .into_iter()
-3340 .map(|x| x.addr)
-3341 .collect(),
-3342 },
-3343 Source::NamedApp {
-3344 name: "test".into(),
-3345 },
-3346 &msock_1.metrics.magicsock,
-3347 );
-3348
-3349 // We can now connect
-3350 tokio::time::timeout(Duration::from_secs(10), async move {
-3351 info!("establishing new connection");
-3352 let conn =
-3353 magicsock_connect(msock_1.endpoint(), secret_key_1.clone(), addr_2, node_id_2)
-3354 .await
-3355 .unwrap();
-3356 info!("have connection");
-3357 let mut stream = conn.open_uni().await.unwrap();
-3358 stream.write_all(b"hello").await.unwrap();
-3359 stream.finish().unwrap();
-3360 stream.stopped().await.unwrap();
-3361 info!("finished stream");
-3362 })
-3363 .await
-3364 .expect("connection timed out");
-3365
-3366 // TODO: could remove the addresses again, send, add it back and see it recover.
-3367 // But we don't have that much private access to the NodeMap. This will do for now.
-3368 }
+3283 .instrument(info_span!("ep2.accept", me = node_id_2.fmt_short()))
+3284 });
+3285 let _accept_task = AbortOnDropHandle::new(accept_task);
+3286
+3287 // Add an empty entry in the NodeMap of ep_1
+3288 msock_1.node_map.add_node_addr(
+3289 NodeAddr {
+3290 node_id: node_id_2,
+3291 relay_url: None,
+3292 direct_addresses: Default::default(),
+3293 },
+3294 Source::NamedApp {
+3295 name: "test".into(),
+3296 },
+3297 &msock_1.metrics.magicsock,
+3298 );
+3299 let addr_2 = msock_1.get_mapping_addr(node_id_2).unwrap();
+3300
+3301 // Set a low max_idle_timeout so quinn gives up on this quickly and our test does
+3302 // not take forever. You need to check the log output to verify this is really
+3303 // triggering the correct error.
+3304 // In test_try_send_no_send_addr() above you may have noticed we used
+3305 // tokio::time::timeout() on the connection attempt instead. Here however we want
+3306 // Quinn itself to have fully given up on the connection attempt because we will
+3307 // later connect to **the same** node. If Quinn did not give up on the connection
+3308 // we'd close it on drop, and the retransmits of the close packets would interfere
+3309 // with the next handshake, closing it during the handshake. This makes the test a
+3310 // little slower though.
+3311 let mut transport_config = quinn::TransportConfig::default();
+3312 transport_config.max_idle_timeout(Some(Duration::from_millis(200).try_into().unwrap()));
+3313 let res = magicsock_connect_with_transport_config(
+3314 msock_1.endpoint(),
+3315 secret_key_1.clone(),
+3316 addr_2,
+3317 node_id_2,
+3318 Arc::new(transport_config),
+3319 )
+3320 .await;
+3321 assert!(res.is_err(), "expected timeout");
+3322 info!("first connect timed out as expected");
+3323
+3324 // Provide correct addressing information
+3325 msock_1.node_map.add_node_addr(
+3326 NodeAddr {
+3327 node_id: node_id_2,
+3328 relay_url: None,
+3329 direct_addresses: msock_2
+3330 .direct_addresses()
+3331 .initialized()
+3332 .await
+3333 .expect("no direct addrs")
+3334 .into_iter()
+3335 .map(|x| x.addr)
+3336 .collect(),
+3337 },
+3338 Source::NamedApp {
+3339 name: "test".into(),
+3340 },
+3341 &msock_1.metrics.magicsock,
+3342 );
+3343
+3344 // We can now connect
+3345 tokio::time::timeout(Duration::from_secs(10), async move {
+3346 info!("establishing new connection");
+3347 let conn =
+3348 magicsock_connect(msock_1.endpoint(), secret_key_1.clone(), addr_2, node_id_2)
+3349 .await
+3350 .unwrap();
+3351 info!("have connection");
+3352 let mut stream = conn.open_uni().await.unwrap();
+3353 stream.write_all(b"hello").await.unwrap();
+3354 stream.finish().unwrap();
+3355 stream.stopped().await.unwrap();
+3356 info!("finished stream");
+3357 })
+3358 .await
+3359 .expect("connection timed out");
+3360
+3361 // TODO: could remove the addresses again, send, add it back and see it recover.
+3362 // But we don't have that much private access to the NodeMap. This will do for now.
+3363 }
+3364
+3365 #[tokio::test]
+3366 async fn test_add_node_addr() -> Result {
+3367 let stack = MagicStack::new(RelayMode::Default).await;
+3368 let mut rng = rand::thread_rng();
3369
-3370 #[tokio::test]
-3371 async fn test_add_node_addr() -> Result {
-3372 let stack = MagicStack::new(RelayMode::Default).await;
-3373 let mut rng = rand::thread_rng();
-3374
-3375 assert_eq!(stack.endpoint.magic_sock().node_map.node_count(), 0);
-3376
-3377 // Empty
-3378 let empty_addr = NodeAddr {
-3379 node_id: SecretKey::generate(&mut rng).public(),
-3380 relay_url: None,
-3381 direct_addresses: Default::default(),
-3382 };
-3383 let err = stack
-3384 .endpoint
-3385 .magic_sock()
-3386 .add_node_addr(empty_addr, node_map::Source::App)
-3387 .unwrap_err();
-3388 assert!(err
-3389 .to_string()
-3390 .to_lowercase()
-3391 .contains("empty addressing info"));
-3392
-3393 // relay url only
-3394 let addr = NodeAddr {
-3395 node_id: SecretKey::generate(&mut rng).public(),
-3396 relay_url: Some("http://my-relay.com".parse().unwrap()),
-3397 direct_addresses: Default::default(),
-3398 };
-3399 stack
-3400 .endpoint
-3401 .magic_sock()
-3402 .add_node_addr(addr, node_map::Source::App)?;
-3403 assert_eq!(stack.endpoint.magic_sock().node_map.node_count(), 1);
-3404
-3405 // addrs only
-3406 let addr = NodeAddr {
-3407 node_id: SecretKey::generate(&mut rng).public(),
-3408 relay_url: None,
-3409 direct_addresses: ["127.0.0.1:1234".parse().unwrap()].into_iter().collect(),
-3410 };
-3411 stack
-3412 .endpoint
-3413 .magic_sock()
-3414 .add_node_addr(addr, node_map::Source::App)?;
-3415 assert_eq!(stack.endpoint.magic_sock().node_map.node_count(), 2);
-3416
-3417 // both
-3418 let addr = NodeAddr {
-3419 node_id: SecretKey::generate(&mut rng).public(),
-3420 relay_url: Some("http://my-relay.com".parse().unwrap()),
-3421 direct_addresses: ["127.0.0.1:1234".parse().unwrap()].into_iter().collect(),
-3422 };
-3423 stack
-3424 .endpoint
-3425 .magic_sock()
-3426 .add_node_addr(addr, node_map::Source::App)?;
-3427 assert_eq!(stack.endpoint.magic_sock().node_map.node_count(), 3);
-3428
-3429 Ok(())
-3430 }
-3431}
\ No newline at end of file
+3370 assert_eq!(stack.endpoint.magic_sock().node_map.node_count(), 0);
+3371
+3372 // Empty
+3373 let empty_addr = NodeAddr {
+3374 node_id: SecretKey::generate(&mut rng).public(),
+3375 relay_url: None,
+3376 direct_addresses: Default::default(),
+3377 };
+3378 let err = stack
+3379 .endpoint
+3380 .magic_sock()
+3381 .add_node_addr(empty_addr, node_map::Source::App)
+3382 .unwrap_err();
+3383 assert!(err
+3384 .to_string()
+3385 .to_lowercase()
+3386 .contains("empty addressing info"));
+3387
+3388 // relay url only
+3389 let addr = NodeAddr {
+3390 node_id: SecretKey::generate(&mut rng).public(),
+3391 relay_url: Some("http://my-relay.com".parse().unwrap()),
+3392 direct_addresses: Default::default(),
+3393 };
+3394 stack
+3395 .endpoint
+3396 .magic_sock()
+3397 .add_node_addr(addr, node_map::Source::App)?;
+3398 assert_eq!(stack.endpoint.magic_sock().node_map.node_count(), 1);
+3399
+3400 // addrs only
+3401 let addr = NodeAddr {
+3402 node_id: SecretKey::generate(&mut rng).public(),
+3403 relay_url: None,
+3404 direct_addresses: ["127.0.0.1:1234".parse().unwrap()].into_iter().collect(),
+3405 };
+3406 stack
+3407 .endpoint
+3408 .magic_sock()
+3409 .add_node_addr(addr, node_map::Source::App)?;
+3410 assert_eq!(stack.endpoint.magic_sock().node_map.node_count(), 2);
+3411
+3412 // both
+3413 let addr = NodeAddr {
+3414 node_id: SecretKey::generate(&mut rng).public(),
+3415 relay_url: Some("http://my-relay.com".parse().unwrap()),
+3416 direct_addresses: ["127.0.0.1:1234".parse().unwrap()].into_iter().collect(),
+3417 };
+3418 stack
+3419 .endpoint
+3420 .magic_sock()
+3421 .add_node_addr(addr, node_map::Source::App)?;
+3422 assert_eq!(stack.endpoint.magic_sock().node_map.node_count(), 3);
+3423
+3424 Ok(())
+3425 }
+3426}
\ No newline at end of file
diff --git a/pr/3381/docs/trait.impl/core/convert/trait.From.js b/pr/3381/docs/trait.impl/core/convert/trait.From.js
index 301235bb2d..2ae75d6be2 100644
--- a/pr/3381/docs/trait.impl/core/convert/trait.From.js
+++ b/pr/3381/docs/trait.impl/core/convert/trait.From.js
@@ -1,9 +1,9 @@
(function() {
- var implementors = Object.fromEntries([["iroh",[["impl From<IntoDiscoveryError> for BindError"],["impl From<PkarrError> for DiscoveryError"],["impl From<AddNodeAddrError> for ConnectWithOptsError"],["impl From<ConnectWithOptsError> for ConnectError"],["impl From<ConnectionError> for AlpnError"],["impl From<ConnectionError> for ConnectError"],["impl From<ConnectionError> for AcceptError"],["impl From<Box<dyn Error + Send + Sync>> for AcceptError"],["impl From<Error> for AcceptError"],["impl From<DiscoveryItem> for NodeInfo"],["impl From<ClosedStream> for AcceptError"],["impl From<RemoteInfo> for NodeAddr"],["impl From<RemoteNodeIdError> for AcceptError"],["impl<T> From<T> for ConcurrentDiscovery"],["impl<T: ProtocolHandler> From<T> for Box<dyn DynProtocolHandler>"]]],["iroh_base",[["impl From<(PublicKey, Option<RelayUrl>, &[SocketAddr])> for NodeAddr"],["impl From<Url> for RelayUrl"],["impl From<NodeAddr> for NodeTicket"],["impl From<PublicKey> for NodeAddr"],["impl From<RelayUrl> for Url"],["impl From<NodeTicket> for NodeAddr"],["impl From<DecodeError> for KeyParsingError"],["impl From<DecodeError> for ParseError"],["impl From<Error> for KeyParsingError"],["impl From<Error> for ParseError"],["impl From<SigningKey> for SecretKey"],["impl From<VerifyingKey> for PublicKey"],["impl From<[u8; 32]> for SecretKey"]]],["iroh_relay",[["impl From<DialError> for ConnectError"],["impl From<SendError> for SendError"],["impl From<DnsError> for DialError"],["impl From<DecodingError> for ParseError"],["impl From<FrameType> for u8"],["impl From<RecvError> for RecvError"],["impl From<SendError> for ConnectError"],["impl From<SendError> for RecvError"],["impl From<u8> for FrameType"],["impl From<Error> for DialError"],["impl From<Error> for RecvError"],["impl From<Error> for SendError"],["impl From<Error> for RecvError"],["impl From<Error> for SendError"],["impl From<NodeAddr> for NodeData"],["impl From<NodeAddr> for NodeInfo"],["impl From<RelayUrl> for RelayMap"],["impl From<RelayUrl> for RelayNode"],["impl From<NodeInfo> for NodeAddr"],["impl From<RelayNode> for RelayMap"],["impl From<ConnectError> for Error"],["impl From<ConnectionError> for Error"],["impl From<Elapsed> for DialError"],["impl From<Elapsed> for DnsError"],["impl From<Elapsed> for RecvError"],["impl From<Elapsed> for SendError"],["impl From<Error> for ConnectError"],["impl From<Error> for RecvError"],["impl From<Error> for SendError"],["impl From<Error> for RecvError"],["impl From<Error> for RecvError"],["impl From<Error> for SendError"],["impl From<JoinError> for SupervisorError"],["impl From<RecvError> for Error"],["impl From<ResolveError> for DnsError"],["impl From<Resolver<GenericConnector<TokioRuntimeProvider>>> for DnsResolver"],["impl From<SignedPacketBuildError> for EncodingError"],["impl From<TxtLookup> for TxtLookup"]]]]);
+ var implementors = Object.fromEntries([["iroh",[["impl From<IntoDiscoveryError> for BindError"],["impl From<PkarrError> for DiscoveryError"],["impl From<AddNodeAddrError> for ConnectWithOptsError"],["impl From<ConnectWithOptsError> for ConnectError"],["impl From<ConnectionError> for AlpnError"],["impl From<ConnectionError> for ConnectError"],["impl From<ConnectionError> for AcceptError"],["impl From<Box<dyn Error + Send + Sync>> for AcceptError"],["impl From<Error> for AcceptError"],["impl From<DiscoveryItem> for NodeInfo"],["impl From<ClosedStream> for AcceptError"],["impl From<RemoteInfo> for NodeAddr"],["impl From<RemoteNodeIdError> for AcceptError"],["impl<T> From<T> for ConcurrentDiscovery"],["impl<T: ProtocolHandler> From<T> for Box<dyn DynProtocolHandler>"]]],["iroh_base",[["impl From<(PublicKey, Option<RelayUrl>, &[SocketAddr])> for NodeAddr"],["impl From<Url> for RelayUrl"],["impl From<NodeAddr> for NodeTicket"],["impl From<PublicKey> for NodeAddr"],["impl From<RelayUrl> for Url"],["impl From<NodeTicket> for NodeAddr"],["impl From<DecodeError> for KeyParsingError"],["impl From<DecodeError> for ParseError"],["impl From<Error> for KeyParsingError"],["impl From<Error> for ParseError"],["impl From<SigningKey> for SecretKey"],["impl From<VerifyingKey> for PublicKey"],["impl From<[u8; 32]> for SecretKey"]]],["iroh_relay",[["impl From<DialError> for ConnectError"],["impl From<SendError> for SendError"],["impl From<DnsError> for DialError"],["impl From<DecodingError> for ParseError"],["impl From<FrameType> for u8"],["impl From<RecvError> for RecvError"],["impl From<SendError> for ConnectError"],["impl From<SendError> for RecvError"],["impl From<u8> for FrameType"],["impl From<Error> for DialError"],["impl From<Error> for RecvError"],["impl From<Error> for SendError"],["impl From<Error> for RecvError"],["impl From<Error> for SendError"],["impl From<NodeInfo> for NodeAddr"],["impl From<RelayNode> for RelayMap"],["impl From<ConnectError> for Error"],["impl From<ConnectionError> for Error"],["impl From<Elapsed> for DialError"],["impl From<Elapsed> for DnsError"],["impl From<Elapsed> for RecvError"],["impl From<Elapsed> for SendError"],["impl From<Error> for ConnectError"],["impl From<Error> for RecvError"],["impl From<Error> for SendError"],["impl From<Error> for RecvError"],["impl From<Error> for RecvError"],["impl From<Error> for SendError"],["impl From<JoinError> for SupervisorError"],["impl From<NodeAddr> for NodeData"],["impl From<NodeAddr> for NodeInfo"],["impl From<RecvError> for Error"],["impl From<RelayUrl> for RelayMap"],["impl From<RelayUrl> for RelayNode"],["impl From<ResolveError> for DnsError"],["impl From<Resolver<GenericConnector<TokioRuntimeProvider>>> for DnsResolver"],["impl From<SignedPacketBuildError> for EncodingError"],["impl From<TxtLookup> for TxtLookup"]]]]);
if (window.register_implementors) {
window.register_implementors(implementors);
} else {
window.pending_implementors = implementors;
}
})()
-//{"start":57,"fragment_lengths":[7257,4938,13608]}
\ No newline at end of file
+//{"start":57,"fragment_lengths":[7257,4938,12998]}
\ No newline at end of file
diff --git a/pr/3381/docs/trait.impl/core/iter/traits/collect/trait.FromIterator.js b/pr/3381/docs/trait.impl/core/iter/traits/collect/trait.FromIterator.js
index 8cd585bc9e..d104c409e3 100644
--- a/pr/3381/docs/trait.impl/core/iter/traits/collect/trait.FromIterator.js
+++ b/pr/3381/docs/trait.impl/core/iter/traits/collect/trait.FromIterator.js
@@ -1,9 +1,9 @@
(function() {
- var implementors = Object.fromEntries([["iroh_relay",[["impl FromIterator<RelayUrl> for RelayMap"],["impl FromIterator<RelayNode> for RelayMap"]]]]);
+ var implementors = Object.fromEntries([["iroh_relay",[["impl FromIterator<RelayNode> for RelayMap"],["impl FromIterator<RelayUrl> for RelayMap"]]]]);
if (window.register_implementors) {
window.register_implementors(implementors);
} else {
window.pending_implementors = implementors;
}
})()
-//{"start":57,"fragment_lengths":[898]}
\ No newline at end of file
+//{"start":57,"fragment_lengths":[776]}
\ No newline at end of file