iroh/
socket.rs

1//! Implements a socket that can change its communication path while in use, actively searching for the best way to communicate.
2//!
3//!
4//! ### `RelayOnly` path selection:
5//! When set this will force all packets to be sent over
6//! the relay connection, regardless of whether or
7//! not we have a direct UDP address for the given endpoint.
8//!
9//! The intended use is for testing the relay protocol inside the Socket
10//! to ensure that we can rely on the relay to send packets when two endpoints
11//! are unable to find direct UDP connections to each other.
12//!
13//! This also prevent this endpoint from attempting to hole punch and prevents it
14//! from responding to any hole punching attempts. This endpoint will still,
15//! however, read any packets that come off the UDP sockets.
16
17use std::{
18    collections::{BTreeMap, BTreeSet},
19    fmt::Display,
20    io,
21    net::{IpAddr, SocketAddr},
22    sync::{
23        Arc, Mutex, RwLock,
24        atomic::{AtomicBool, Ordering},
25    },
26};
27
28use iroh_base::{EndpointAddr, EndpointId, RelayUrl, SecretKey, TransportAddr};
29use iroh_relay::{RelayConfig, RelayMap};
30use mapped_addrs::MultipathMappedAddr;
31use n0_error::{AnyError, anyerr, bail, e, stack_error};
32use n0_future::{
33    MaybeFuture,
34    task::{self, AbortOnDropHandle},
35    time::{self, Duration, Instant},
36};
37use n0_watcher::{self, Watchable, Watcher};
38use netwatch::netmon;
39#[cfg(not(wasm_browser))]
40use netwatch::{
41    interfaces::{IpNet, Ipv6AddrFlags},
42    ip::LocalAddresses,
43};
44use noq::{
45    NetworkChangeHint, TokenStore,
46    crypto::rustls::{QuicClientConfig, QuicServerConfig},
47};
48use rand::RngExt;
49use rustc_hash::FxHashSet;
50use tokio::sync::{
51    Mutex as AsyncMutex,
52    mpsc::{self},
53    oneshot,
54};
55use tokio_util::sync::{CancellationToken, WaitForCancellationFutureOwned};
56use tracing::{Instrument, Level, Span, debug, error, event, info_span, instrument, trace, warn};
57use transports::{LocalAddrsWatch, Transport, TransportConfig};
58use url::Url;
59
60use self::{
61    remote_map::{RemoteMap, RemoteStateMessage},
62    transports::{RelayActorConfig, Transports},
63};
64#[cfg(not(wasm_browser))]
65use crate::dns::DnsResolver;
66#[cfg(not(wasm_browser))]
67use crate::net_report::QuicConfig;
68use crate::{
69    address_lookup::{self, AddressLookupFailed, EndpointData, UserData},
70    defaults::timeouts::NET_REPORT_TIMEOUT,
71    endpoint::{
72        LocalTransportAddr, RelayStatus, hooks::EndpointHooksList, quic::QuicTransportConfig,
73    },
74    metrics::EndpointMetrics,
75    net_report::{self, IfStateDetails, Report},
76    portmapper,
77    runtime::Runtime,
78    socket::{
79        concurrent_read_map::ReadOnlyMap,
80        remote_map::{MappedAddrs, PathSelector, PathStateReceiver, RemoteInfo},
81        transports::{HomeRelayWatch, HomeRelayWatcher},
82    },
83    tls::{
84        self,
85        misc::{Blake3HmacKey, RustlsTokenKey},
86    },
87};
88
89mod metrics;
90
91pub(crate) mod biased_rtt_path_selector;
92pub(crate) mod concurrent_read_map;
93pub(crate) mod mapped_addrs;
94pub(crate) mod remote_map;
95pub(crate) mod transports;
96
97use self::mapped_addrs::{EndpointIdMappedAddr, MappedAddr};
98pub use self::metrics::Metrics;
99
100// TODO: Use this
101// /// How long we consider a QAD-derived endpoint valid for. UDP NAT mappings typically
102// /// expire at 30 seconds, so this is a few seconds shy of that.
103// const ENDPOINTS_FRESH_ENOUGH_DURATION: Duration = Duration::from_secs(27);
104
105/// The duration in which we send keep-alives.
106///
107/// If a path is idle for this long, a PING frame will be sent to keep the connection
108/// alive.
109pub(crate) const HEARTBEAT_INTERVAL: Duration = Duration::from_secs(5);
110
111/// The maximum time a path can stay idle before being closed.
112///
113/// 15s gives 3x [`HEARTBEAT_INTERVAL`] (5s) for multiple retry chances, and enough
114/// margin for real-world outages (WiFi reconnect 2-5s, cellular handoff 2-10s).
115/// iroh 0.35 used 10s at the QUIC level; tailscale uses 45s at the WireGuard session
116/// level with 3s heartbeats.
117pub(crate) const PATH_MAX_IDLE_TIMEOUT: Duration = Duration::from_secs(15);
118
119/// The maximum time a relay path can stay idle before being closed.
120///
121/// Relay paths need a longer idle timeout than direct paths because the relay actor
122/// manages the WebSocket connection and transparently reconnects after network changes
123/// or relay server restarts. During network outages the interface may be down for
124/// 5-15s, during which no relay traffic flows. Once the interface recovers, the relay
125/// actor reconnects (DNS + TCP + TLS + WebSocket upgrade), which adds another 1-2s.
126///
127/// Set to match the connection-level idle timeout (30s) so the relay path survives
128/// as long as the connection itself.
129pub(crate) const RELAY_PATH_MAX_IDLE_TIMEOUT: Duration = Duration::from_secs(30);
130
131/// Maximum number of concurrent QUIC multipath paths per connection.
132///
133/// We expect 1 relay path, and then leave space for ~3 IP and custom transport paths.
134/// On top of that, when we expect a network change, we might be closing these paths
135/// (except for the relay path) and open new ones, and give us 3 more paths to spare.
136/// And finally we round that up to 8 for good measure.
137pub(crate) const MAX_MULTIPATH_PATHS: u32 = 8;
138
139/// Maximum number of n0 QUIC NAT Traversal addresses that the QUIC stack should allow.
140///
141/// This needs to be big enough to accommodate for machines which have lots of network
142/// interfaces enabled. We've seen MacOS machines with >25 interfaces in the wild
143/// (mostly due to VPN TUN and docket interfaces), so this seems like a reasonable
144/// value.
145pub(crate) const MAX_QNT_ADDRESSES: u8 = 32;
146
147/// Error returned when the endpoint state actor stopped while waiting for a reply.
148#[stack_error(add_meta, derive)]
149#[error("endpoint state actor stopped")]
150#[derive(Clone)]
151pub(crate) struct RemoteStateActorStoppedError;
152
153impl From<mpsc::error::SendError<RemoteStateMessage>> for RemoteStateActorStoppedError {
154    #[track_caller]
155    fn from(_value: mpsc::error::SendError<RemoteStateMessage>) -> Self {
156        Self::new()
157    }
158}
159
160/// Contains options for `Socket::listen`.
161#[derive(derive_more::Debug)]
162pub(crate) struct Options {
163    /// The configuration for the different transports.
164    pub(crate) transports: Vec<TransportConfig>,
165
166    /// Secret key for this endpoint.
167    pub(crate) secret_key: SecretKey,
168
169    /// Optional user-defined Address Lookup data.
170    pub(crate) address_lookup_user_data: Option<UserData>,
171
172    /// A DNS resolver to use for resolving relay URLs.
173    ///
174    /// You can use [`crate::dns::DnsResolver::new`] for a resolver
175    /// that uses the system's DNS configuration.
176    #[cfg(not(wasm_browser))]
177    pub(crate) dns_resolver: DnsResolver,
178
179    /// Proxy configuration.
180    pub(crate) proxy_url: Option<Url>,
181
182    /// TLS configuration for HTTPS and non-iroh-QUIC connections.
183    pub(crate) tls_config: rustls::ClientConfig,
184
185    /// ServerConfig for the internal QUIC endpoint
186    pub(crate) server_config: noq_proto::ServerConfig,
187
188    pub(crate) metrics: EndpointMetrics,
189    pub(crate) hooks: EndpointHooksList,
190    pub(crate) path_selector: Arc<dyn PathSelector>,
191    pub(crate) portmapper_config: portmapper::PortmapperConfig,
192    pub(crate) net_report_config: crate::net_report::NetReportConfig,
193
194    /// Static configuration for the endpoint.
195    pub(crate) static_config: StaticConfig,
196
197    /// Explicitly configured external addresses to advertise.
198    pub(crate) configured_addrs: BTreeSet<SocketAddr>,
199}
200
201/// Inner state for an iroh [`crate::Endpoint`].
202///
203/// Dereferences to [`Socket`], and handles closing.
204#[derive(Debug, derive_more::Deref)]
205pub(crate) struct EndpointInner {
206    #[deref(forward)]
207    sock: Arc<Socket>,
208    // empty when shutdown
209    actor_task: Mutex<Option<AbortOnDropHandle<()>>>,
210    /// Channel to send to the internal actor.
211    actor_sender: mpsc::Sender<ActorMessage>,
212    // noq endpoint
213    endpoint: noq::Endpoint,
214    // Runtime used by noq
215    runtime: Arc<Runtime>,
216    /// Static configuration for the endpoint.
217    pub(crate) static_config: StaticConfig,
218}
219
220impl Drop for EndpointInner {
221    fn drop(&mut self) {
222        if self.sock.is_closed() {
223            return;
224        }
225        tracing::error!(
226            "Endpoint dropped without calling `Endpoint::close`. Aborting ungracefully."
227        );
228        self.abort();
229    }
230}
231
232/// Configuration for a [`noq::Endpoint`] that cannot be changed at runtime.
233#[derive(derive_more::Debug)]
234pub(crate) struct StaticConfig {
235    pub(crate) tls_config: tls::TlsConfig,
236    #[debug("QuicServerConifg")]
237    pub(crate) server_config: QuicServerConfig,
238    #[debug("QuicClientConfig")]
239    pub(crate) client_config: QuicClientConfig,
240    #[debug("Arc<RustlsTokenKey>")]
241    pub(crate) token_key: Arc<RustlsTokenKey>,
242    #[debug("Arc<dyn TokenStore>")]
243    pub(crate) token_store: Arc<dyn TokenStore>,
244    pub(crate) transport_config: QuicTransportConfig,
245}
246
247impl StaticConfig {
248    /// Create a [`noq_proto::ServerConfig`] with the specified ALPN protocols.
249    pub(crate) fn create_server_config(
250        &self,
251        alpn_protocols: Vec<Vec<u8>>,
252    ) -> noq_proto::ServerConfig {
253        let mut quic_server_config = self.server_config.clone();
254        quic_server_config.set_alpn_protocols(alpn_protocols);
255        let mut inner =
256            noq::ServerConfig::new(Arc::new(quic_server_config), self.token_key.clone());
257        inner.transport_config(self.transport_config.to_inner_arc());
258        inner
259    }
260
261    /// Create a [`noq_proto::ClientConfig`] with the specified ALPN protocols.
262    pub(crate) fn create_client_config(
263        &self,
264        alpn_protocols: Vec<Vec<u8>>,
265        transport_config: Arc<noq::TransportConfig>,
266    ) -> noq_proto::ClientConfig {
267        let mut quic_client_config = self.client_config.clone();
268        quic_client_config.set_alpn_protocols(alpn_protocols);
269        let mut inner = noq::ClientConfig::new(Arc::new(quic_client_config));
270        inner.transport_config(transport_config);
271        inner.token_store(self.token_store.clone());
272        inner
273    }
274}
275
276/// This coordinates the shutdown of the [`Socket`] and all its tasks.
277///
278/// It also tightly binds to the [`EndpointInner`] and [`Actor`] closing as that is where
279/// most of the logic lives.
280#[derive(Debug)]
281struct ShutdownState {
282    /// Token that is cancelled at the moment [`crate::Endpoint::close`] is called.
283    ///
284    /// Currently cancelled from [`EndpointInner::close`].
285    at_close_start: CancellationToken,
286    /// Token that is cancelled once the [`noq::Endpoint`] is drained.
287    ///
288    /// Only 100ms after this is cancelled will the [`Actor`] task be cancelled, it should
289    /// have exited already by then as it is considered an error if it was still running.
290    at_endpoint_closed: CancellationToken,
291    /// Set if the endpoint is closed and all tasks are stopped.
292    ///
293    /// This is only set once both [`Self::at_close_start`] and [`Self::at_endpoint_closed`]
294    /// are cancelled **and** the [`Actor`] task is no longer running.
295    closed: AtomicBool,
296}
297
298impl Default for ShutdownState {
299    fn default() -> Self {
300        Self {
301            at_close_start: CancellationToken::new(),
302            at_endpoint_closed: CancellationToken::new(),
303            closed: AtomicBool::new(false),
304        }
305    }
306}
307
308impl ShutdownState {
309    /// Whether the endpoint has started closing, or is already closed.
310    ///
311    /// This is true once [`crate::Endpoint::close`] is called, and remains true forever
312    /// after. Tasks might still be shutting down.
313    fn is_closing(&self) -> bool {
314        self.at_close_start.is_cancelled()
315    }
316
317    /// Whether the endpoint is fully closed and all tasks stopped.
318    ///
319    /// The endpoint will be drained, all transports and sockets will be closed.
320    fn is_closed(&self) -> bool {
321        self.closed.load(Ordering::Relaxed)
322    }
323}
324
325/// Iroh connectivity layer.
326///
327/// This is responsible for routing packets to endpoints based on endpoint IDs, it will initially
328/// route packets via a relay and transparently try and establish an endpoint-to-endpoint
329/// connection and upgrade to it.  It will also keep looking for better connections as the
330/// network details of both endpoints change.
331///
332/// It is usually only necessary to use a single [`Socket`] instance in an application, it
333/// means any QUIC endpoints on top will be sharing as much information about endpoints as
334/// possible.
335#[derive(Debug)]
336pub(crate) struct Socket {
337    /// Read-only view of the per-remote `RemoteStateActor` inboxes.
338    ///
339    /// Lets callers send to an existing `RemoteStateActor` without going through
340    /// the socket actor.
341    ///
342    /// A missing entry means no actor is running for that remote. Spawning new
343    /// `RemoteStateActor`s must go through the socket actor channel.
344    remote_actors: ReadOnlyMap<EndpointId, mpsc::Sender<RemoteStateMessage>>,
345
346    // - Shutdown Management
347    shutdown: ShutdownState,
348
349    // - Networking Info
350    /// Our discovered direct addresses.
351    direct_addrs: DiscoveredDirectAddrs,
352    /// Our latest net-report
353    net_report: Watchable<(Option<Report>, UpdateReason)>,
354    /// If the last net_report report, reports IPv6 to be available.
355    ipv6_reported: Arc<AtomicBool>,
356    /// Maps for resolving mapped addrs to/from IP and relay addresses.
357    mapped_addrs: MappedAddrs,
358
359    /// Local addresses
360    local_addrs_watch: LocalAddrsWatch,
361    home_relay_watch: HomeRelayWatcher,
362    /// Currently bound IP addresses of all sockets
363    #[cfg(not(wasm_browser))]
364    ip_bind_addrs: Vec<SocketAddr>,
365    /// The DNS resolver to be used in this socket.
366    #[cfg(not(wasm_browser))]
367    dns_resolver: DnsResolver,
368    relay_map: RelayMap,
369
370    /// Optional Address Lookup
371    address_lookup: address_lookup::AddressLookupServices,
372    /// Optional user-defined discover data.
373    address_lookup_user_data: RwLock<Option<UserData>>,
374    /// Explicitly configured external addresses to advertise.
375    configured_addrs: RwLock<BTreeSet<SocketAddr>>,
376
377    pub(crate) tls_config: rustls::ClientConfig,
378    /// The proxy for HTTP(S) traffic, if any.
379    pub(crate) proxy_url: Option<Url>,
380
381    /// Metrics
382    pub(crate) metrics: EndpointMetrics,
383    pub(crate) hooks: EndpointHooksList,
384    /// Tracing span for this endpoint.
385    pub(crate) span: Span,
386}
387
388impl Socket {
389    /// Returns the relay endpoint we are connected to, that has the best latency.
390    ///
391    /// If `None`, then we are not connected to any relay endpoints.
392    pub(crate) fn my_relay(&self) -> Option<RelayUrl> {
393        self.local_addr().into_iter().find_map(|a| {
394            if let transports::Addr::Relay(url, _) = a {
395                Some(url)
396            } else {
397                None
398            }
399        })
400    }
401
402    /// Whether the iroh endpoint is closed and all its actors stopped.
403    pub(crate) fn is_closed(&self) -> bool {
404        self.shutdown.is_closed()
405    }
406
407    /// Whether [`crate::Endpoint::close`] has been called.
408    fn is_closing(&self) -> bool {
409        self.shutdown.is_closing()
410    }
411
412    /// Returns a future that resolves once endpoint shutdown has started.
413    pub(crate) fn closed(&self) -> WaitForCancellationFutureOwned {
414        self.shutdown.at_close_start.clone().cancelled_owned()
415    }
416
417    /// Get the cached version of addresses.
418    pub(crate) fn local_addr(&self) -> Vec<transports::Addr> {
419        self.local_addrs_watch.clone().get()
420    }
421
422    #[cfg(not(wasm_browser))]
423    fn ip_bind_addrs(&self) -> &[SocketAddr] {
424        &self.ip_bind_addrs
425    }
426
427    fn ip_local_addrs(&self) -> impl Iterator<Item = SocketAddr> + use<> {
428        self.local_addr()
429            .into_iter()
430            .filter_map(|addr| addr.into_socket_addr())
431    }
432
433    /// Tries to send a [`RemoteStateMessage`] to the `RemoteStateActor` for given [`EndpointId`].
434    ///
435    /// Returns an error if there currently is no remote state actor running for this, or when it
436    /// is currently shutting down.
437    pub(crate) fn try_send_remote_state_msg(
438        &self,
439        endpoint_id: EndpointId,
440        message: RemoteStateMessage,
441    ) -> Result<(), RemoteStateMessage> {
442        let Some(sender) = self.remote_actors.get(&endpoint_id) else {
443            return Err(message);
444        };
445        sender.try_send(message).map_err(|err| err.into_inner())
446    }
447
448    /// Returns a [`Watcher`] for this socket's direct addresses.
449    ///
450    /// The [`Socket`] continuously monitors the direct addresses, the network addresses
451    /// it might be able to be contacted on, for changes.  Whenever changes are detected
452    /// this [`Watcher`] will yield a new list of addresses.
453    ///
454    /// Upon the first creation on the [`Socket`] it may not yet have completed a first
455    /// net report to discover IP addresses, in this case the current item in this [`Watcher`] will be
456    /// [`None`].  Once the first set of ip addresses are discovered the [`Watcher`] will
457    /// store [`Some`] set of addresses.
458    ///
459    /// To get the current direct addresses, use [`Watcher::initialized`].
460    ///
461    /// [`Watcher`]: n0_watcher::Watcher
462    /// [`Watcher::initialized`]: n0_watcher::Watcher::initialized
463    pub(crate) fn ip_addrs(&self) -> n0_watcher::Direct<BTreeSet<DirectAddr>> {
464        self.direct_addrs.addrs.watch()
465    }
466
467    /// Returns a [`Watcher`] for this socket's net-report.
468    ///
469    /// The [`Socket`] continuously monitors the network conditions for changes.
470    /// Whenever changes are detected this [`Watcher`] will yield a new report.
471    ///
472    /// Upon the first creation on the [`Socket`] it may not yet have completed
473    /// a first net-report. In this case, the current item in this [`Watcher`] will
474    /// be [`None`].  Once the first report has been run, the [`Watcher`] will
475    /// store [`Some`] report.
476    ///
477    /// To get the current `net-report`, use [`Watcher::initialized`].
478    ///
479    /// [`Watcher`]: n0_watcher::Watcher
480    /// [`Watcher::initialized`]: n0_watcher::Watcher::initialized
481    #[cfg(feature = "unstable-net-report")]
482    pub(crate) fn net_report(&self) -> impl Watcher<Value = Option<Report>> + use<> {
483        self.net_report.watch().map(|(r, _)| r)
484    }
485
486    /// Watch for changes to the home relay.
487    ///
488    /// Note that this can be used to wait for the initial home relay to be known using
489    /// [`Watcher::initialized`].
490    pub(crate) fn home_relay(&self) -> impl Watcher<Value = Vec<RelayUrl>> + use<> {
491        self.local_addrs_watch.clone().map(|addrs| {
492            addrs
493                .into_iter()
494                .filter_map(|addr| {
495                    if let transports::Addr::Relay(url, _) = addr {
496                        Some(url)
497                    } else {
498                        None
499                    }
500                })
501                .collect()
502        })
503    }
504
505    pub(crate) fn home_relay_status(&self) -> impl Watcher<Value = Vec<RelayStatus>> + use<> {
506        self.home_relay_watch.clone()
507    }
508
509    /// Stores a new set of direct addresses.
510    ///
511    /// If the direct addresses have changed from the previous set, they are published to
512    /// the address lookup system.
513    fn store_direct_addresses(&self, addrs: BTreeSet<DirectAddr>) {
514        let updated = self.direct_addrs.update(addrs);
515        if updated {
516            self.publish_my_addr();
517        }
518    }
519
520    /// Get a reference to the DNS resolver used in this [`Socket`].
521    #[cfg(not(wasm_browser))]
522    pub(crate) fn dns_resolver(&self) -> &DnsResolver {
523        &self.dns_resolver
524    }
525
526    /// Translates a possible IP-mapped [`SocketAddr`] into a [`transports::Addr`].
527    ///
528    /// For regular IP addresses this returns `Addr::Ip`. For mapped addresses this performs
529    /// a reverse lookup.
530    pub(crate) fn to_transport_addr(&self, addr: SocketAddr) -> Option<transports::Addr> {
531        self.mapped_addrs.to_transport_addr(addr)
532    }
533
534    pub(crate) fn to_local_transport_addr(
535        &self,
536        local_ip: Option<IpAddr>,
537        remote_addr: SocketAddr,
538    ) -> LocalTransportAddr {
539        let remote_addr = self.to_transport_addr(remote_addr).unwrap_or_else(|| {
540            error!(
541                mapped_addr = ?remote_addr,
542                "Socket::to_local_transport_addr: invalid mapped address",
543            );
544            transports::Addr::Ip(remote_addr)
545        });
546        LocalTransportAddr::from_noq_local_ip(
547            local_ip,
548            &remote_addr,
549            &self.mapped_addrs.custom_addrs,
550        )
551    }
552
553    /// Reference to the internal Address Lookup
554    pub(crate) fn address_lookup(&self) -> &address_lookup::AddressLookupServices {
555        &self.address_lookup
556    }
557
558    /// Updates the user-defined Address Lookup data for this endpoint.
559    pub(crate) fn set_user_data_for_address_lookup(&self, user_data: Option<UserData>) {
560        let mut guard = self
561            .address_lookup_user_data
562            .write()
563            .expect("lock poisened");
564        if *guard != user_data {
565            *guard = user_data;
566            drop(guard);
567            self.publish_my_addr();
568        }
569    }
570
571    /// Process datagrams received from all the transports.
572    ///
573    /// All the `bufs` and `metas` should have initialized packets in them.
574    ///
575    /// This fixes up the datagrams to use the correct [`MultipathMappedAddr`] and extracts
576    /// DISCO packets, processing them inside the socket.
577    ///
578    /// [`MultipathMappedAddr`]: mapped_addrs::MultipathMappedAddr
579    fn process_datagrams(
580        &self,
581        bufs: &mut [io::IoSliceMut<'_>],
582        metas: &mut [noq_udp::RecvMeta],
583        recv_infos: &[transports::RecvInfo],
584    ) {
585        assert_eq!(bufs.len(), metas.len(), "non matching bufs & metas");
586        assert_eq!(
587            bufs.len(),
588            recv_infos.len(),
589            "non matching bufs & recv_infos"
590        );
591
592        // zip is slow :(
593        for i in 0..metas.len() {
594            let noq_meta = &mut metas[i];
595            let recv_info = &recv_infos[i];
596            let remote_addr = recv_info.remote();
597            let datagram_count = if noq_meta.stride == 0 {
598                if noq_meta.len > 0 {
599                    warn!(
600                        src = ?remote_addr,
601                        len = noq_meta.len,
602                        "received datagram with stride=0 but len>0",
603                    );
604                    // fix the weird len
605                    noq_meta.len = 0;
606                }
607                // one empty datagram
608                1
609            } else {
610                noq_meta.len.div_ceil(noq_meta.stride)
611            };
612            self.metrics
613                .socket
614                .recv_datagrams
615                .inc_by(datagram_count as _);
616            if noq_meta.len > noq_meta.stride {
617                trace!(
618                    src = ?remote_addr,
619                    len = noq_meta.len,
620                    stride = %noq_meta.stride,
621                    datagram_count,
622                    "GRO datagram received",
623                );
624                self.metrics.socket.recv_gro_datagrams.inc();
625            } else {
626                trace!(src = ?remote_addr, len = noq_meta.len, "datagram received");
627            }
628            match remote_addr {
629                transports::Addr::Ip(SocketAddr::V4(..)) => {
630                    self.metrics.socket.recv_data_ipv4.inc_by(noq_meta.len as _);
631                }
632                transports::Addr::Ip(SocketAddr::V6(..)) => {
633                    self.metrics.socket.recv_data_ipv6.inc_by(noq_meta.len as _);
634                }
635                transports::Addr::Relay(src_url, src_node) => {
636                    self.metrics
637                        .socket
638                        .recv_data_relay
639                        .inc_by(noq_meta.len as _);
640
641                    // Fill in the correct mapped address
642                    let mapped_addr = self
643                        .mapped_addrs
644                        .relay_addrs
645                        .get(&(src_url.clone(), *src_node));
646                    noq_meta.addr = mapped_addr.private_socket_addr();
647                }
648                transports::Addr::Custom(remote) => {
649                    self.metrics
650                        .socket
651                        .recv_data_custom
652                        .inc_by(noq_meta.len as _);
653                    // Fill in the correct mapped address
654                    let mapped_addr = self.mapped_addrs.custom_addrs.get(remote);
655                    noq_meta.addr = mapped_addr.private_socket_addr();
656                    if let Some(local) = recv_info.local() {
657                        let local_mapped = self.mapped_addrs.custom_addrs.get(local);
658                        noq_meta.dst_ip = Some(local_mapped.private_socket_addr().ip());
659                    }
660                }
661            }
662        }
663    }
664
665    /// Publishes our address to an address lookup service, if configured.
666    ///
667    /// Called whenever our addresses or home relay endpoint changes.
668    fn publish_my_addr(&self) {
669        let relay_url = self.my_relay();
670        let mut addrs: Vec<_> = self
671            .direct_addrs
672            .sockaddrs()
673            .map(TransportAddr::Ip)
674            .collect();
675
676        let user_data = self
677            .address_lookup_user_data
678            .read()
679            .expect("lock poisened")
680            .clone();
681        if relay_url.is_none() && addrs.is_empty() && user_data.is_none() {
682            // do not bother publishing if we don't have any information
683            return;
684        }
685        if let Some(url) = relay_url {
686            addrs.push(TransportAddr::Relay(url));
687        }
688
689        let mut data = EndpointData::new(addrs);
690        data.set_user_data(user_data);
691        self.address_lookup.publish(&data);
692    }
693}
694
695/// Manages currently running net reports to learn this endpoint's IP addresses.
696///
697/// Invariants:
698/// - only one direct addr update must be running at a time
699/// - if an update is scheduled while another one is running, remember that
700///   and start a new one when the current one has finished
701#[derive(Debug)]
702struct DirectAddrUpdateState {
703    /// If set, start a new update as soon as the current one is finished.
704    want_update: Option<UpdateReason>,
705    sock: Arc<Socket>,
706    port_mapper: portmapper::Client,
707    /// The prober that discovers local network conditions, including the closest relay relay and NAT mappings.
708    net_reporter: Arc<AsyncMutex<net_report::Client>>,
709    relay_map: RelayMap,
710    run_done: mpsc::Sender<()>,
711    shutdown_token: CancellationToken,
712}
713
714#[derive(Default, Debug, PartialEq, Eq, Clone, Copy)]
715enum UpdateReason {
716    /// Initial state
717    #[default]
718    None,
719    Periodic,
720    PortmapUpdated,
721    LinkChangeMajor,
722    LinkChangeMinor,
723    RelayMapChange,
724}
725
726impl UpdateReason {
727    fn is_major(self) -> bool {
728        matches!(self, Self::LinkChangeMajor | Self::RelayMapChange)
729    }
730}
731
732impl DirectAddrUpdateState {
733    fn new(
734        sock: Arc<Socket>,
735        port_mapper: portmapper::Client,
736        net_reporter: Arc<AsyncMutex<net_report::Client>>,
737        relay_map: RelayMap,
738        run_done: mpsc::Sender<()>,
739        shutdown_token: CancellationToken,
740    ) -> Self {
741        DirectAddrUpdateState {
742            want_update: Default::default(),
743            port_mapper,
744            net_reporter,
745            sock,
746            relay_map,
747            run_done,
748            shutdown_token,
749        }
750    }
751
752    /// Schedules a new run, either starting it immediately if none is running or
753    /// scheduling it for later.
754    fn schedule_run(&mut self, why: UpdateReason, if_state: IfStateDetails) {
755        match self.net_reporter.clone().try_lock_owned() {
756            Ok(net_reporter) => {
757                self.run(why, if_state, net_reporter);
758            }
759            Err(_) => {
760                let _ = self.want_update.insert(why);
761            }
762        }
763    }
764
765    /// If another run is needed, triggers this run, otherwise does nothing.
766    fn try_run(&mut self, if_state: IfStateDetails) {
767        match self.net_reporter.clone().try_lock_owned() {
768            Ok(net_reporter) => {
769                if let Some(why) = self.want_update.take() {
770                    self.run(why, if_state, net_reporter);
771                }
772            }
773            Err(_) => {
774                // do nothing
775            }
776        }
777    }
778
779    /// Trigger a new run.
780    fn run(
781        &mut self,
782        why: UpdateReason,
783        if_state: IfStateDetails,
784        mut net_reporter: tokio::sync::OwnedMutexGuard<net_report::Client>,
785    ) {
786        debug!("starting direct addr update ({:?})", why);
787        // Don't start a net report probe if we know
788        // we are shutting down
789        if self.shutdown_token.is_cancelled() {
790            debug!("skipping net_report, socket is shutting down");
791            // deactivate portmapper
792            self.port_mapper.deactivate();
793            return;
794        }
795        if self.relay_map.is_empty() {
796            debug!("skipping net_report, empty RelayMap");
797            self.sock.net_report.set((None, why)).ok();
798            return;
799        }
800
801        self.sock.metrics.net_report.portmap_attempts.inc();
802        self.port_mapper.procure_mapping();
803
804        trace!("requesting net_report report");
805        let sock = self.sock.clone();
806
807        let run_done = self.run_done.clone();
808
809        // Ensure that reports are cancelled when we shutdown
810        let token = self.shutdown_token.child_token();
811        let inner_token = token.child_token();
812        task::spawn(
813            async move {
814                let fut = token.run_until_cancelled(time::timeout(
815                    NET_REPORT_TIMEOUT,
816                    net_reporter.get_report(if_state, why.is_major(), inner_token),
817                ));
818
819                match fut.await {
820                    Some(Ok(report)) => {
821                        sock.net_report.set((Some(report), why)).ok();
822                    }
823                    Some(Err(time::Elapsed { .. })) => {
824                        warn!("net_report report timed out");
825                    }
826                    None => {
827                        trace!("net_report cancelled");
828                    }
829                }
830
831                // mark run as finished
832                debug!("direct addr update done ({:?})", why);
833                run_done.send(()).await.ok();
834            }
835            .instrument(tracing::Span::current()),
836        );
837    }
838}
839
840#[allow(missing_docs)]
841#[stack_error(derive, add_meta)]
842#[non_exhaustive]
843pub enum BindError {
844    #[error("Failed to bind sockets")]
845    Sockets { source: io::Error },
846    #[error("Failed to create internal QUIC endpoint")]
847    CreateQuicEndpoint { source: io::Error },
848    #[error("Failed to create netmon monitor")]
849    CreateNetmonMonitor { source: AnyError },
850    #[error("Invalid transport configuration")]
851    InvalidTransportConfig,
852    #[error("Invalid CA root configuration")]
853    InvalidCaRootConfig { source: io::Error },
854    #[error("Failed to create an address lookup service")]
855    AddressLookup {
856        #[error(from)]
857        source: crate::address_lookup::AddressLookupBuilderError,
858    },
859    #[error("Missing or incompatible rustls crypto provider configured")]
860    InvalidCryptoProvider,
861    #[error("Error constructing TLS configuration")]
862    TlsConfigError {
863        #[error(from)]
864        source: tls::TlsConfigError,
865    },
866}
867
868impl EndpointInner {
869    /// Creates a [`EndpointInner`].
870    pub(crate) async fn bind(opts: Options) -> Result<Self, BindError> {
871        // Use the current span as the main span for all tasks spawned in this endpoint.
872        // `EndpointInner::bind` is not public and only called from `crate::endpoint::Builder::bind`,
873        // which instruments the call with a span created for this purpose.
874        let span = tracing::Span::current();
875
876        let Options {
877            secret_key,
878            transports: transport_configs,
879            address_lookup_user_data,
880            #[cfg(not(wasm_browser))]
881            dns_resolver,
882            proxy_url,
883            server_config,
884            tls_config,
885            metrics,
886            hooks,
887            path_selector,
888            portmapper_config,
889            net_report_config,
890            static_config,
891            configured_addrs,
892        } = opts;
893
894        let address_lookup =
895            address_lookup::AddressLookupServices::with_metrics(metrics.address_lookup.clone());
896        let port_mapper = portmapper::create_client(&portmapper_config);
897
898        let relay_transport_configs: Vec<_> = transport_configs
899            .iter()
900            .filter(|t| matches!(t, TransportConfig::Relay { .. }))
901            .collect();
902
903        // Currently we only support a single relay transport
904        if relay_transport_configs.len() > 1 {
905            bail!(BindError::InvalidTransportConfig);
906        }
907        let relay_map = relay_transport_configs
908            .iter()
909            .filter_map(|t| {
910                #[allow(irrefutable_let_patterns)]
911                if let TransportConfig::Relay { relay_map, .. } = t {
912                    Some(relay_map.clone())
913                } else {
914                    None
915                }
916            })
917            .next()
918            .unwrap_or_else(RelayMap::empty);
919
920        let ipv6_reported = Arc::new(AtomicBool::new(false));
921
922        let relay_actor_config = RelayActorConfig {
923            my_relay: HomeRelayWatch::default(),
924            secret_key: secret_key.clone(),
925            #[cfg(not(wasm_browser))]
926            dns_resolver: dns_resolver.clone(),
927            proxy_url: proxy_url.clone(),
928            ipv6_reported: ipv6_reported.clone(),
929            tls_config: tls_config.clone(),
930            metrics: metrics.socket.clone(),
931            relay_map: relay_map.clone(),
932        };
933
934        let shutdown_state = ShutdownState::default();
935        let shutdown_token = shutdown_state.at_endpoint_closed.child_token();
936
937        let transports = Transports::bind(
938            &transport_configs,
939            relay_actor_config,
940            &metrics,
941            shutdown_token.child_token(),
942        )
943        .map_err(|err| e!(BindError::Sockets, err))?;
944
945        if let Some(v4_port) = transports.local_addrs().into_iter().find_map(|t| {
946            if let transports::Addr::Ip(SocketAddr::V4(addr)) = t {
947                Some(addr.port())
948            } else {
949                None
950            }
951        }) {
952            // NOTE: we can end up with a zero port if `netwatch::UdpSocket::socket_addr` fails
953            match v4_port.try_into() {
954                Ok(non_zero_port) => {
955                    port_mapper.update_local_port(non_zero_port);
956                }
957                Err(_zero_port) => debug!("Skipping port mapping with zero local port"),
958            }
959        }
960
961        let (actor_sender, actor_receiver) = mpsc::channel(256);
962
963        #[cfg(not(wasm_browser))]
964        let has_ipv6_transport = transports
965            .ip_bind_addrs()
966            .into_iter()
967            .any(|addr| addr.is_ipv6());
968
969        #[cfg(not(wasm_browser))]
970        let has_ip_transports = !transports.ip_bind_addrs().is_empty();
971
972        let direct_addrs = DiscoveredDirectAddrs::default();
973
974        let remote_map = {
975            RemoteMap::new(
976                metrics.socket.clone(),
977                direct_addrs.addrs.watch(),
978                address_lookup.clone(),
979                shutdown_token.child_token(),
980                path_selector,
981                span.clone(),
982            )
983        };
984
985        let home_relay_watch = transports.home_relay_watch();
986
987        let sock = Arc::new(Socket {
988            remote_actors: remote_map.senders(),
989            shutdown: shutdown_state,
990            ipv6_reported,
991            mapped_addrs: remote_map.mapped_addrs.clone(),
992            address_lookup,
993            relay_map: relay_map.clone(),
994            address_lookup_user_data: RwLock::new(address_lookup_user_data),
995            configured_addrs: RwLock::new(configured_addrs),
996            direct_addrs,
997            net_report: Watchable::new((None, UpdateReason::None)),
998            #[cfg(not(wasm_browser))]
999            dns_resolver: dns_resolver.clone(),
1000            metrics: metrics.clone(),
1001            local_addrs_watch: transports.local_addrs_watch(),
1002            home_relay_watch,
1003            #[cfg(not(wasm_browser))]
1004            ip_bind_addrs: transports.ip_bind_addrs(),
1005            tls_config: tls_config.clone(),
1006            proxy_url: proxy_url.clone(),
1007            hooks,
1008            span: span.clone(),
1009        });
1010
1011        let mut endpoint_config =
1012            noq::EndpointConfig::new(Arc::new(Blake3HmacKey::new(&mut rand::rng())));
1013        // Setting this to false means that noq will ignore packets that have the QUIC fixed bit
1014        // set to 0. The fixed bit is the 3rd bit of the first byte of a packet.
1015        // For performance reasons and to not rewrite buffers we pass non-QUIC UDP packets straight
1016        // through to noq. We set the first byte of the packet to zero, which makes noq ignore
1017        // the packet if grease_quic_bit is set to false.
1018        endpoint_config.grease_quic_bit(false);
1019
1020        let local_addrs_watch = transports.local_addrs_watch();
1021        let transports_network_change = transports.create_network_change_sender();
1022
1023        let runtime = Arc::new(Runtime::new(secret_key.public()));
1024
1025        let endpoint = noq::Endpoint::new_with_abstract_socket(
1026            endpoint_config,
1027            Some(server_config),
1028            Box::new(Transport::new(sock.clone(), transports)),
1029            runtime.clone(),
1030        )
1031        .map_err(|err| e!(BindError::CreateQuicEndpoint, err))?;
1032
1033        let network_monitor = netmon::Monitor::new()
1034            .await
1035            .map_err(|err| e!(BindError::CreateNetmonMonitor, anyerr!(err)))?;
1036
1037        #[cfg(not(wasm_browser))]
1038        let net_report_config = {
1039            // Set a `QuicConfig` for address discovery (QAD), but only if we have IP transports.
1040            //
1041            // If there are no IP transports configured, then we don't set a QuicConfig.
1042            // If we would, the `noq::Endpoint` passed along will not have IP connectivity,
1043            // and the QAD probes that connect to the relay's QUIC endpoints would time out
1044            // because all outgoing packets to IP destinations would be dropped.
1045            let qad_config = has_ip_transports.then(|| QuicConfig {
1046                ep: endpoint.clone(),
1047                client_config: tls_config.clone(),
1048                ipv4: true,
1049                ipv6: has_ipv6_transport,
1050            });
1051            net_report::Options::new(tls_config.clone())
1052                .quic_config(qad_config)
1053                .proxy_url(proxy_url.clone())
1054                .net_report_config(net_report_config)
1055        };
1056
1057        #[cfg(wasm_browser)]
1058        let net_report_config = net_report::Options::default().net_report_config(net_report_config);
1059
1060        let net_reporter = net_report::Client::new(
1061            #[cfg(not(wasm_browser))]
1062            dns_resolver,
1063            relay_map.clone(),
1064            net_report_config,
1065            metrics.net_report.clone(),
1066        );
1067
1068        let (direct_addr_done_tx, direct_addr_done_rx) = mpsc::channel(8);
1069        let direct_addr_update_state = DirectAddrUpdateState::new(
1070            sock.clone(),
1071            port_mapper,
1072            Arc::new(AsyncMutex::new(net_reporter)),
1073            relay_map,
1074            direct_addr_done_tx,
1075            sock.shutdown.at_close_start.child_token(),
1076        );
1077
1078        let local_interfaces_watcher = network_monitor.interface_state();
1079
1080        #[cfg_attr(not(wasm_browser), allow(unused_mut))]
1081        let mut actor = Actor {
1082            endpoint: endpoint.clone(),
1083            sock: sock.clone(),
1084            remote_map,
1085            periodic_re_stun_timer: new_re_stun_timer(false),
1086            network_monitor,
1087            local_interfaces_watcher,
1088            direct_addr_update_state,
1089            transports_network_change,
1090            direct_addr_done_rx,
1091            call_notify_quic_network_change: None,
1092        };
1093        // Initialize addresses
1094        #[cfg(not(wasm_browser))]
1095        actor.update_direct_addresses(None);
1096
1097        let actor_task = task::spawn(
1098            actor
1099                .run(
1100                    actor_receiver,
1101                    shutdown_token.child_token(),
1102                    local_addrs_watch,
1103                )
1104                .instrument(info_span!(parent: span, "actor")),
1105        );
1106
1107        let actor_task = Mutex::new(Some(AbortOnDropHandle::new(actor_task)));
1108
1109        Ok(EndpointInner {
1110            sock,
1111            actor_sender,
1112            actor_task,
1113            endpoint,
1114            runtime,
1115            static_config,
1116        })
1117    }
1118
1119    /// Returns a reference to the underlying [`noq::Endpoint`].
1120    pub(crate) fn noq_endpoint(&self) -> &noq::Endpoint {
1121        &self.endpoint
1122    }
1123
1124    /// Closes the iroh endpoint.
1125    ///
1126    /// Only the first close does anything. Any later closes return nil.  Polling the socket
1127    /// ([`noq::AsyncUdpSocket::poll_recv`]) will return [`Poll::Pending`] indefinitely
1128    /// after this call.
1129    ///
1130    /// [`Poll::Pending`]: std::task::Poll::Pending
1131    #[instrument(skip_all, parent = self.sock.span.clone())]
1132    pub(crate) async fn close(&self) {
1133        if self.sock.is_closed() || self.sock.is_closing() {
1134            return;
1135        }
1136        trace!("socket closing...");
1137
1138        // Cancel at_close_start token, which cancels running netreports.
1139        self.sock.shutdown.at_close_start.cancel();
1140
1141        // Remove address lookup services
1142        self.sock.address_lookup().clear();
1143
1144        // Initiate closing all connections, and refuse future connections.
1145        self.noq_endpoint().close(0u16.into(), b"");
1146
1147        // In the history of this code, this call had been
1148        // - removed: https://github.com/n0-computer/iroh/pull/1753
1149        // - then added back in: https://github.com/n0-computer/iroh/pull/2227/files#diff-ba27e40e2986a3919b20f6b412ad4fe63154af648610ea5d9ed0b5d5b0e2d780R573
1150        // - then removed again: https://github.com/n0-computer/iroh/pull/3165
1151        // and finally added back in together with this comment.
1152        // So before removing this call, please consider carefully.
1153        // Among other things, this call tries its best to make sure that any queued close frames
1154        // (e.g. via the call to `endpoint.close(...)` above), are flushed out to the sockets
1155        // *and acknowledged* (or time out with the "probe timeout" of usually 3 seconds).
1156        // This allows the other endpoints for these connections to be notified to release
1157        // their resources, or - depending on the protocol - that all data was received.
1158        // With the current noq API, this is the only way to ensure protocol code can use
1159        // connection close codes, and close the endpoint properly.
1160        // If this call is skipped, then connections that protocols close just shortly before the
1161        // call to `Endpoint::close` will in most cases cause connection time-outs on remote ends.
1162        trace!("wait_all_draining start");
1163        self.noq_endpoint().wait_all_draining().await;
1164        trace!("wait_all_draining done");
1165
1166        // Start cancellation of all actors.
1167        self.sock.shutdown.at_endpoint_closed.cancel();
1168
1169        // MutexGuard is not held across await points
1170        let task = self.actor_task.lock().expect("poisoned").take();
1171        if let Some(task) = task {
1172            // give the tasks a moment to shutdown cleanly
1173            let shutdown_done = time::timeout(Duration::from_millis(100), async move {
1174                if let Err(err) = task.await {
1175                    warn!("unexpected error in task shutdown: {:?}", err);
1176                }
1177            })
1178            .await;
1179            match shutdown_done {
1180                Ok(_) => trace!("tasks finished in time, shutdown complete"),
1181                Err(time::Elapsed { .. }) => {
1182                    // Dropping the task will abort it
1183                    warn!("tasks didn't finish in time, aborting");
1184                }
1185            }
1186        }
1187
1188        // Waits for the EndpointDriver and all ConnectionDrivers to shut down
1189        // Expects that the `noq::Endpoint` has been closed before this call,
1190        // otherwise, the runtime will never shutdown.
1191        self.runtime.shutdown().await;
1192
1193        self.sock.shutdown.closed.store(true, Ordering::SeqCst);
1194
1195        trace!("socket closed");
1196    }
1197
1198    /// Aborts the endpoint ungracefully:
1199    ///
1200    /// - Calls cancellation token that stops running net reports
1201    /// - Removes all address lookup services
1202    /// - Calls cancellation token that stops all the Socket actors
1203    /// - Aborts the runtime
1204    /// - Drops the actor task
1205    /// - Sets the `Socket::is_closed` state to true
1206    ///
1207    /// This does not wait for any current connections or tasks to close gracefully.
1208    ///
1209    /// This should only be called in the `iroh::Endpoint` `Drop` impl when the
1210    /// `iroh::Endpoint` is dropped without first calling `Endpoint::close`.
1211    #[instrument(skip_all, parent = self.sock.span.clone())]
1212    pub(crate) fn abort(&self) {
1213        if self.sock.is_closed() || self.sock.is_closing() {
1214            return;
1215        }
1216        trace!("socket aborting...");
1217
1218        // Cancel at_close_start token, which cancels running netreports.
1219        self.sock.shutdown.at_close_start.cancel();
1220
1221        self.sock.address_lookup().clear();
1222
1223        // Cancel all actors.
1224        self.sock.shutdown.at_endpoint_closed.cancel();
1225
1226        // Aborts all tasks, not waiting for any to close gracefully.
1227        self.runtime.abort();
1228
1229        self.actor_task.lock().expect("poisoned").take();
1230
1231        self.sock.shutdown.closed.store(true, Ordering::SeqCst);
1232        trace!("socket closed");
1233    }
1234
1235    pub(crate) async fn insert_relay(
1236        &self,
1237        relay: RelayUrl,
1238        endpoint: Arc<RelayConfig>,
1239    ) -> Option<Arc<RelayConfig>> {
1240        let res = self.relay_map.insert(relay, endpoint);
1241        self.actor_sender
1242            .send(ActorMessage::RelayMapChange)
1243            .await
1244            .ok();
1245        res
1246    }
1247
1248    pub(crate) async fn remove_relay(&self, relay: &RelayUrl) -> Option<Arc<RelayConfig>> {
1249        let res = self.relay_map.remove(relay);
1250        self.actor_sender
1251            .send(ActorMessage::RelayMapChange)
1252            .await
1253            .ok();
1254        res
1255    }
1256
1257    /// Adds an external address to advertise to peers.
1258    pub(crate) async fn add_external_addr(&self, addr: SocketAddr) {
1259        self.sock
1260            .configured_addrs
1261            .write()
1262            .expect("poisoned")
1263            .insert(addr);
1264        self.actor_sender
1265            .send(ActorMessage::DirectAddrRefresh)
1266            .await
1267            .ok();
1268    }
1269
1270    /// Removes a configured external address. Returns `true` if it was present.
1271    pub(crate) async fn remove_external_addr(&self, addr: &SocketAddr) -> bool {
1272        let removed = self
1273            .sock
1274            .configured_addrs
1275            .write()
1276            .expect("poisoned")
1277            .remove(addr);
1278        if removed {
1279            self.actor_sender
1280                .send(ActorMessage::DirectAddrRefresh)
1281                .await
1282                .ok();
1283        }
1284        removed
1285    }
1286
1287    /// Call to notify the system of potential network changes.
1288    pub(crate) async fn network_change(&self) {
1289        self.actor_sender
1290            .send(ActorMessage::NetworkChange)
1291            .await
1292            .ok();
1293    }
1294
1295    #[cfg(all(test, with_crypto_provider))]
1296    async fn force_network_change(&self, is_major: bool) {
1297        self.actor_sender
1298            .send(ActorMessage::ForceNetworkChange(is_major))
1299            .await
1300            .ok();
1301    }
1302
1303    /// Resolves an [`EndpointAddr`] to an [`EndpointIdMappedAddr`] to connect to via [`EndpointInner::endpoint`].
1304    ///
1305    /// This starts a `RemoteStateActor` for the remote if not running already, and then checks
1306    /// if the actor has any known paths to the remote. If not, it starts address lookup and waits for
1307    /// at least one result to arrive.
1308    ///
1309    /// Returns `Ok(Ok(EndpointIdMappedAddr))` if there is a known path or Address Lookup produced
1310    /// at least one result. This does not mean there is a working path, only that we have at least
1311    /// one transport address we can try to connect to.
1312    ///
1313    /// Returns `Ok(Err(address_lookup_error))` if there are no known paths to the remote and Address Lookup
1314    /// failed or produced no results. This means that we don't have any transport address for
1315    /// the remote, thus there is no point in trying to connect over the noq endpoint.
1316    ///
1317    /// Returns `Err(RemoteStateActorStoppedError)` if the `RemoteStateActor` for the remote has stopped,
1318    /// which may never happen and thus is a bug if it does.
1319    pub(crate) async fn resolve_remote(
1320        &self,
1321        addr: EndpointAddr,
1322    ) -> Result<Result<EndpointIdMappedAddr, AddressLookupFailed>, RemoteStateActorStoppedError>
1323    {
1324        let (tx, rx) = oneshot::channel();
1325        let remote_id = addr.id;
1326        self.actor_sender
1327            .send(ActorMessage::ResolveRemote(addr, tx))
1328            .await
1329            .ok();
1330        let reply = rx.await.map_err(|_| RemoteStateActorStoppedError::new())?;
1331        match reply {
1332            Ok(()) => Ok(Ok(self.mapped_addrs.endpoint_addrs.get(&remote_id))),
1333            Err(err) => Ok(Err(err)),
1334        }
1335    }
1336
1337    /// Fetches the [`RemoteInfo`] about a remote from the `RemoteStateActor`.
1338    ///
1339    /// Returns `None` if no actor is running for the remote.
1340    pub(crate) async fn remote_info(&self, id: EndpointId) -> Option<RemoteInfo> {
1341        let (tx, rx) = oneshot::channel();
1342        self.remote_actors
1343            .get(&id)?
1344            .send(RemoteStateMessage::RemoteInfo(tx))
1345            .await
1346            .ok()?;
1347        rx.await.ok()
1348    }
1349
1350    /// Registers the connection in the `RemoteStateActor`.
1351    ///
1352    /// The actor is responsible for holepunching and opening additional paths to this
1353    /// connection.
1354    ///
1355    /// Returns a future that resolves to a [`PathStateReceiver`] for the new connection.
1356    ///
1357    /// The returned future is `'static`, so it can be stored without being lifetime-bound to `&self`.
1358    pub(crate) fn register_connection(
1359        &self,
1360        remote: EndpointId,
1361        conn: noq::Connection,
1362    ) -> impl Future<Output = Result<PathStateReceiver, RemoteStateActorStoppedError>> + Send + 'static
1363    {
1364        let (tx, rx) = oneshot::channel();
1365        let sender = self.actor_sender.clone();
1366        async move {
1367            sender
1368                .send(ActorMessage::AddConnection(remote, conn, tx))
1369                .await
1370                .map_err(|_| RemoteStateActorStoppedError::new())?;
1371            rx.await.map_err(|_| RemoteStateActorStoppedError::new())
1372        }
1373    }
1374}
1375
1376#[derive(derive_more::Debug)]
1377#[allow(clippy::enum_variant_names)]
1378enum ActorMessage {
1379    NetworkChange,
1380    RelayMapChange,
1381    #[debug("ResolveRemote(..)")]
1382    ResolveRemote(
1383        EndpointAddr,
1384        oneshot::Sender<Result<(), AddressLookupFailed>>,
1385    ),
1386    #[debug("AddConnection(..)")]
1387    AddConnection(
1388        EndpointId,
1389        noq::Connection,
1390        oneshot::Sender<PathStateReceiver>,
1391    ),
1392    /// Re-evaluate direct addresses, e.g. after configured external addresses changed.
1393    DirectAddrRefresh,
1394    #[cfg(all(test, with_crypto_provider))]
1395    ForceNetworkChange(bool),
1396}
1397
1398/// State for polling until a default route is available after a network change.
1399///
1400/// When a network change is detected but no default route exists yet (e.g.,
1401/// interface just came up but gateway not assigned), we poll with exponential
1402/// backoff until the gateway appears. This avoids the fixed 2s delay that was
1403/// too slow for interface recovery scenarios.
1404struct PendingNetworkChangeNotify {
1405    /// Next time to check for default route.
1406    next_check: Instant,
1407    /// Current backoff interval.
1408    interval: Duration,
1409    /// Whether this was a major change.
1410    is_major: bool,
1411    /// When we started polling (to enforce a max wait).
1412    started: Instant,
1413}
1414
1415impl PendingNetworkChangeNotify {
1416    const INITIAL_INTERVAL: Duration = Duration::from_millis(100);
1417    const MAX_INTERVAL: Duration = Duration::from_secs(1);
1418    const MAX_WAIT: Duration = Duration::from_secs(5);
1419
1420    fn new(is_major: bool) -> Self {
1421        Self {
1422            next_check: Instant::now() + Self::INITIAL_INTERVAL,
1423            interval: Self::INITIAL_INTERVAL,
1424            is_major,
1425            started: Instant::now(),
1426        }
1427    }
1428
1429    /// Advance to the next check interval (exponential backoff, capped).
1430    fn advance(&mut self) {
1431        self.interval = (self.interval * 2).min(Self::MAX_INTERVAL);
1432        self.next_check = Instant::now() + self.interval;
1433    }
1434
1435    /// Whether we've exceeded the maximum wait time.
1436    fn expired(&self) -> bool {
1437        self.started.elapsed() >= Self::MAX_WAIT
1438    }
1439}
1440
1441struct Actor {
1442    /// A clone of the quinn Endpoint.
1443    ///
1444    /// The task of this actor is currently owned by the [`crate::Endpoint`] and wrapped in
1445    /// an [`AbortOnDropHandle`]. When [`crate::Endpoint::close`] is called various
1446    /// subsystems are being stopped. Then, when [`ShutdownState::at_endpoint_closed`] is
1447    /// called by [`crate::Endpoint::close`], this actor itself is stopped via it's
1448    /// [`CancellationToken`] and we will drop this clone of the endpoint. The endpoint is
1449    /// then finally dropped when the [`crate::Endpoint`] itself is dropped.
1450    ///
1451    /// All of this to say: keeping the quinn endpoint alive here does not impact the
1452    /// lifetime of it since it's lifetime is shorter than that one that's stored in the
1453    /// [`crate::Endpoint`].
1454    endpoint: noq::Endpoint,
1455    /// Shared state between an awful lot of iroh subsystems.
1456    ///
1457    /// In particular both the [`EndpointInner`] as well as this actor itself have a
1458    /// copy. But also other subsystems that consequently have access to way to much state.
1459    sock: Arc<Socket>,
1460    /// Tracks the networkmap endpoint entity for each endpoint discovery key.
1461    remote_map: RemoteMap,
1462    /// When set, is an AfterFunc timer that will call Socket::do_periodic_stun.
1463    periodic_re_stun_timer: time::Interval,
1464    /// An actor watching the local network interfaces.
1465    ///
1466    /// The monitored changes are emitted via [`Self::local_interfaces_watcher`].
1467    network_monitor: netmon::Monitor,
1468    /// Watcher for changes to the local network interfaces, IP addresses and routes.
1469    local_interfaces_watcher: n0_watcher::Direct<netmon::State>,
1470    transports_network_change: transports::NetworkChangeSender,
1471    /// Indicates the direct addr update state.
1472    direct_addr_update_state: DirectAddrUpdateState,
1473    direct_addr_done_rx: mpsc::Receiver<()>,
1474    /// Polling state for [`Actor::notify_quic_network_change`].
1475    ///
1476    /// When a network change is detected but no default route is available yet,
1477    /// we poll with exponential backoff (100ms, 200ms, 400ms, 800ms, 1s, 1s, ...)
1478    /// until the gateway appears. Once it does, we notify immediately.
1479    /// After 5s total we notify anyway even without a gateway.
1480    call_notify_quic_network_change: Option<PendingNetworkChangeNotify>,
1481}
1482
1483impl Actor {
1484    async fn run(
1485        mut self,
1486        mut msg_receiver: mpsc::Receiver<ActorMessage>,
1487        shutdown_token: CancellationToken,
1488        mut local_addrs_watcher: impl Watcher<Value = Vec<transports::Addr>> + Send + Sync,
1489    ) {
1490        // Setup network monitoring
1491        let mut current_netmon_state = self.local_interfaces_watcher.get();
1492
1493        let mut portmap_watcher = self
1494            .direct_addr_update_state
1495            .port_mapper
1496            .watch_external_address();
1497
1498        let mut receiver_closed = false;
1499        let mut portmap_watcher_closed = false;
1500
1501        let mut net_report_watcher = self.sock.net_report.watch();
1502
1503        // ensure we are doing an initial publish of our addresses
1504        self.sock.publish_my_addr();
1505
1506        while !shutdown_token.is_cancelled() {
1507            self.sock.metrics.socket.actor_tick_main.inc();
1508            let portmap_watcher_changed = portmap_watcher.changed();
1509
1510            let notify_quic_network_change = match &self.call_notify_quic_network_change {
1511                Some(pending) => {
1512                    MaybeFuture::Some(n0_future::time::sleep_until(pending.next_check))
1513                }
1514                None => MaybeFuture::None,
1515            };
1516            n0_future::pin!(notify_quic_network_change);
1517
1518            tokio::select! {
1519                _ = shutdown_token.cancelled() => {
1520                    debug!("tick: shutting down");
1521                    return;
1522                }
1523                msg = msg_receiver.recv(), if !receiver_closed => {
1524                    let Some(msg) = msg else {
1525                        trace!("tick: socket receiver closed");
1526                        self.sock.metrics.socket.actor_tick_other.inc();
1527                        receiver_closed = true;
1528                        continue;
1529                    };
1530
1531                    trace!(?msg, "tick: msg");
1532                    self.sock.metrics.socket.actor_tick_msg.inc();
1533                    self.handle_actor_message(msg).await;
1534                }
1535                tick = self.periodic_re_stun_timer.tick() => {
1536                    trace!("tick: re_stun {:?}", tick);
1537                    self.sock.metrics.socket.actor_tick_re_stun.inc();
1538                    self.re_stun(UpdateReason::Periodic);
1539                }
1540                new_addr = local_addrs_watcher.updated() => {
1541                    match new_addr {
1542                        Ok(addrs) => {
1543                            if !addrs.is_empty() {
1544                                trace!(?addrs, "local addrs");
1545                                self.sock.publish_my_addr();
1546                            }
1547                        }
1548                        Err(_) => {
1549                            warn!("local addr watcher stopped");
1550                        }
1551                    }
1552                }
1553                report = net_report_watcher.updated() => {
1554                    match report {
1555                        Ok((report, _)) => {
1556                            self.handle_net_report_report(report);
1557                            #[cfg(not(wasm_browser))]
1558                            {
1559                                self.periodic_re_stun_timer = new_re_stun_timer(true);
1560                            }
1561                        }
1562                        Err(_) => {
1563                            warn!("net report watcher stopped");
1564                        }
1565                    }
1566                }
1567                reason = self.direct_addr_done_rx.recv() => {
1568                    match reason {
1569                        Some(()) => {
1570                            // check if a new run needs to be scheduled
1571                            let state = self.local_interfaces_watcher.get();
1572                            self.direct_addr_update_state.try_run(state.into());
1573                        }
1574                        None => {
1575                            warn!("direct addr watcher died");
1576                        }
1577                    }
1578                }
1579                change = portmap_watcher_changed, if !portmap_watcher_closed => {
1580                    if change.is_err() {
1581                        trace!("tick: portmap watcher closed");
1582                        self.sock.metrics.socket.actor_tick_other.inc();
1583
1584                        portmap_watcher_closed = true;
1585                        continue;
1586                    }
1587
1588                    trace!("tick: portmap changed");
1589                    self.sock.metrics.socket.actor_tick_portmap_changed.inc();
1590                    let new_external_address = *portmap_watcher.borrow();
1591                    if new_external_address.is_some() {
1592                        self.sock.metrics.net_report.portmap_external_address_updated.inc();
1593                    }
1594                    debug!("external address updated: {new_external_address:?}");
1595                    self.re_stun(UpdateReason::PortmapUpdated);
1596                },
1597                state = self.local_interfaces_watcher.updated() => {
1598                    let Ok(state) = state else {
1599                        trace!("tick: link change receiver closed");
1600                        self.sock.metrics.socket.actor_tick_other.inc();
1601                        continue;
1602                    };
1603                    let is_major = state.is_major_change(&current_netmon_state);
1604                    event!(
1605                        target: "iroh::_events::link_change",
1606                        Level::DEBUG,
1607                        ?state,
1608                        is_major
1609                    );
1610                    current_netmon_state = state;
1611                    self.sock.metrics.socket.actor_link_change.inc();
1612                    self.handle_network_change(is_major);
1613                }
1614                _remote_id = self.remote_map.cleanup() => {},
1615                _ = &mut notify_quic_network_change => {
1616                    let has_network = self.has_usable_network();
1617                    let Some(pending) = self.call_notify_quic_network_change.as_mut() else {
1618                        continue;
1619                    };
1620                    if has_network || pending.expired() {
1621                        // Gateway appeared or we've waited long enough, notify now.
1622                        let is_major = pending.is_major;
1623                        self.call_notify_quic_network_change = None;
1624                        self.notify_quic_network_change(is_major);
1625                    } else {
1626                        // No gateway yet, back off and try again.
1627                        trace!(
1628                            interval = ?pending.interval,
1629                            elapsed = ?pending.started.elapsed(),
1630                            "no default route yet, retrying"
1631                        );
1632                        pending.advance();
1633                    }
1634                }
1635                else => {
1636                    trace!("tick: else");
1637                }
1638            }
1639        }
1640    }
1641
1642    /// Whether the local network has a default route and at least one IP address.
1643    fn has_usable_network(&mut self) -> bool {
1644        #[cfg(target_family = "wasm")]
1645        {
1646            true
1647        }
1648        #[cfg(not(target_family = "wasm"))]
1649        {
1650            let interfaces = self.local_interfaces_watcher.get();
1651            interfaces.default_route_interface.is_some()
1652                && (interfaces.have_v4 || interfaces.have_v6)
1653        }
1654    }
1655
1656    /// Handles a change detected in the local network conditions.
1657    ///
1658    /// This is triggered when the netmon actor detects a change in the local network
1659    /// interfaces, assigned IP addresses and routes.
1660    fn handle_network_change(&mut self, is_major: bool) {
1661        debug!(is_major, "link change detected");
1662
1663        if is_major {
1664            if let Err(err) = self.transports_network_change.rebind() {
1665                warn!("failed to rebind transports: {err:?}");
1666            }
1667            self.transports_network_change.check_relay_connection();
1668
1669            #[cfg(not(wasm_browser))]
1670            self.sock.dns_resolver.reset();
1671            self.re_stun(UpdateReason::LinkChangeMajor);
1672        } else {
1673            self.re_stun(UpdateReason::LinkChangeMinor);
1674        }
1675
1676        if self.has_usable_network() {
1677            // This is considered a usable network change, propagate it to the QUIC stack
1678            // right away.
1679            self.call_notify_quic_network_change = None;
1680            self.notify_quic_network_change(is_major);
1681        } else {
1682            // No default route yet (e.g., interface just came up but gateway not
1683            // assigned). Poll with exponential backoff until the gateway appears.
1684            match &mut self.call_notify_quic_network_change {
1685                Some(pending) => {
1686                    // Update is_major if this change is more severe.
1687                    pending.is_major |= is_major;
1688                }
1689                None => {
1690                    self.call_notify_quic_network_change =
1691                        Some(PendingNetworkChangeNotify::new(is_major));
1692                }
1693            }
1694        }
1695    }
1696
1697    /// Notifies the QUIC stack of the network change we observed.
1698    ///
1699    /// This is decoupled from receiving the network change, because we try to debounce
1700    /// network changes as they often arrive in groups.
1701    fn notify_quic_network_change(&mut self, is_major: bool) {
1702        #[derive(Debug)]
1703        struct Hint {
1704            local_addrs: FxHashSet<IpAddr>,
1705        }
1706
1707        impl NetworkChangeHint for Hint {
1708            fn is_path_recoverable(
1709                &self,
1710                _path_id: noq::PathId,
1711                network_path: noq_proto::FourTuple,
1712            ) -> bool {
1713                match MultipathMappedAddr::from(network_path.remote()) {
1714                    MultipathMappedAddr::Mixed(_) => {
1715                        // This address is only ever used to send an Initial packet to, it
1716                        // should never appear as an established path.
1717                        error!("A mixed address can not be used for network changes");
1718                        false
1719                    }
1720                    MultipathMappedAddr::Relay(_) => {
1721                        // We pretend the relay path is never affected by link changes. The
1722                        // relay actor transparently reconnects and the addresses never
1723                        // change.
1724                        true
1725                    }
1726                    MultipathMappedAddr::Ip(_) => {
1727                        // If we no longer have a valid interface to send from for a local
1728                        // IP then it can not be recovered.
1729                        match network_path.local_ip() {
1730                            Some(local_ip) => self.local_addrs.contains(&local_ip),
1731                            None => true,
1732                        }
1733                    }
1734                    MultipathMappedAddr::Custom(_) => {
1735                        // Assume it is unrecoverable for now
1736                        false
1737                    }
1738                }
1739            }
1740        }
1741
1742        let hint = Hint {
1743            #[cfg(not(wasm_browser))]
1744            local_addrs: {
1745                let interfaces = self.local_interfaces_watcher.get();
1746                interfaces
1747                    .local_addresses
1748                    .regular
1749                    .iter()
1750                    .chain(interfaces.local_addresses.loopback.iter())
1751                    .copied()
1752                    .collect()
1753            },
1754            #[cfg(wasm_browser)]
1755            local_addrs: Default::default(),
1756        };
1757
1758        self.endpoint.handle_network_change(Some(Arc::new(hint)));
1759        self.remote_map.on_network_change(is_major);
1760    }
1761
1762    fn handle_relay_map_change(&mut self) {
1763        self.re_stun(UpdateReason::RelayMapChange);
1764    }
1765
1766    fn re_stun(&mut self, why: UpdateReason) {
1767        let state = self.local_interfaces_watcher.get();
1768
1769        if self.sock.relay_map.is_empty() {
1770            // Reports don't run if rleays aren't available, so inject a default one.
1771            self.transports_network_change
1772                .on_network_change(&net_report::Report::default());
1773        }
1774
1775        // This block is a band-aid for https://github.com/n0-computer/iroh/issues/4588
1776        // See patchbay test `lan_switch_advertises_new_addr_without_relay`
1777        #[cfg(not(wasm_browser))]
1778        {
1779            if self.sock.relay_map.is_empty() {
1780                // When there are no relays, update direct addresses immediately from local interfaces
1781                // without waiting for net_report. Also reset the periodic timer.
1782                self.update_direct_addresses(None);
1783                self.periodic_re_stun_timer = new_re_stun_timer(true);
1784                return; // Skip schedule_run since we handled it directly
1785            }
1786        }
1787
1788        self.direct_addr_update_state
1789            .schedule_run(why, state.into());
1790    }
1791
1792    /// Processes an incoming actor message.
1793    ///
1794    /// Returns `true` if it was a shutdown.
1795    async fn handle_actor_message(&mut self, msg: ActorMessage) {
1796        match msg {
1797            ActorMessage::NetworkChange => {
1798                self.network_monitor.network_change().await.ok();
1799            }
1800            ActorMessage::RelayMapChange => {
1801                self.handle_relay_map_change();
1802            }
1803            ActorMessage::ResolveRemote(addr, tx) => {
1804                self.remote_map.resolve_remote(addr, tx).await;
1805            }
1806            ActorMessage::AddConnection(remote, conn, tx) => {
1807                self.remote_map.add_connection(remote, conn, tx).await;
1808            }
1809            ActorMessage::DirectAddrRefresh => {
1810                #[cfg(not(wasm_browser))]
1811                {
1812                    let (report, _reason) = self.sock.net_report.get();
1813                    self.update_direct_addresses(report.as_ref());
1814                }
1815            }
1816            #[cfg(all(test, with_crypto_provider))]
1817            ActorMessage::ForceNetworkChange(is_major) => {
1818                self.handle_network_change(is_major);
1819            }
1820        }
1821    }
1822
1823    /// Updates the direct addresses of this socket.
1824    ///
1825    /// Updates the [`DiscoveredDirectAddrs`] of this [`Socket`] with the current set of
1826    /// direct addresses from:
1827    ///
1828    /// - The portmapper.
1829    /// - A net_report report.
1830    /// - The local interfaces IP addresses.
1831    /// - User configured addresses.
1832    #[cfg(not(wasm_browser))]
1833    fn update_direct_addresses(&mut self, net_report_report: Option<&net_report::Report>) {
1834        // We only want to have one DirectAddr for each SocketAddr we have.  So we store
1835        // this as a map of SocketAddr -> DirectAddrType.  At the end we will construct a
1836        // DirectAddr from each entry.
1837        let mut addrs: BTreeMap<SocketAddr, (DirectAddrType, Option<Ipv6AddrFlags>)> =
1838            BTreeMap::new();
1839
1840        // First add PortMapper provided addresses.
1841        let portmap_watcher = self
1842            .direct_addr_update_state
1843            .port_mapper
1844            .watch_external_address();
1845        let maybe_port_mapped = *portmap_watcher.borrow();
1846        if let Some(portmap_ext) = maybe_port_mapped.map(SocketAddr::V4) {
1847            addrs
1848                .entry(portmap_ext)
1849                .or_insert((DirectAddrType::Portmapped, None));
1850        }
1851
1852        // Next add STUN addresses from the net_report report.
1853        if let Some(net_report_report) = net_report_report {
1854            if let Some(global_v4) = net_report_report.global_v4 {
1855                addrs
1856                    .entry(global_v4.into())
1857                    .or_insert((DirectAddrType::Qad, None));
1858
1859                // If they're behind a hard NAT and are using a fixed
1860                // port locally, assume they might've added a static
1861                // port mapping on their router to the same explicit
1862                // port that we are running with. Worst case it's an invalid candidate mapping.
1863                let port = self.sock.ip_bind_addrs().iter().find_map(|addr| {
1864                    if addr.port() != 0 {
1865                        Some(addr.port())
1866                    } else {
1867                        None
1868                    }
1869                });
1870
1871                if let Some(port) = port
1872                    && net_report_report
1873                        .mapping_varies_by_dest()
1874                        .unwrap_or_default()
1875                {
1876                    let mut addr = global_v4;
1877                    addr.set_port(port);
1878                    addrs
1879                        .entry(addr.into())
1880                        .or_insert((DirectAddrType::Qad4LocalPort, None));
1881                }
1882            }
1883            if let Some(global_v6) = net_report_report.global_v6 {
1884                addrs
1885                    .entry(global_v6.into())
1886                    .or_insert((DirectAddrType::Qad, None));
1887            }
1888        }
1889
1890        self.collect_local_addresses(&mut addrs);
1891
1892        // Add configured external addresses.
1893        for addr in self.sock.configured_addrs.read().expect("poisoned").iter() {
1894            addrs.entry(*addr).or_insert((DirectAddrType::Config, None));
1895        }
1896
1897        // Finally create and store store all these direct addresses
1898        let stored_addrs = addrs
1899            .into_iter()
1900            .filter_map(|(addr, (typ, flags))| {
1901                // Filter out deprecated IPs
1902                let is_deprecated = flags.map(|f| f.deprecated).unwrap_or(false);
1903                if is_deprecated {
1904                    return None;
1905                }
1906                Some(DirectAddr { addr, typ })
1907            })
1908            .collect();
1909        self.sock.store_direct_addresses(stored_addrs);
1910    }
1911
1912    #[cfg(not(wasm_browser))]
1913    fn collect_local_addresses(
1914        &mut self,
1915        addrs: &mut BTreeMap<SocketAddr, (DirectAddrType, Option<Ipv6AddrFlags>)>,
1916    ) {
1917        let netmon_state = self.local_interfaces_watcher.get();
1918
1919        // Matches the addresses that have been bound vs the requested ones.
1920        let local_addrs: Vec<(SocketAddr, SocketAddr)> = self
1921            .sock
1922            .ip_bind_addrs()
1923            .iter()
1924            .copied()
1925            .zip(self.sock.ip_local_addrs())
1926            .collect();
1927
1928        // Do we listen on any IPv4 unspecified address?
1929        let has_ipv4_unspecified = local_addrs.iter().find_map(|(_, a)| {
1930            if a.is_ipv4() && a.ip().is_unspecified() {
1931                Some(a.port())
1932            } else {
1933                None
1934            }
1935        });
1936        // Do we listen on any IPv6 unspecified address?
1937        let has_ipv6_unspecified = local_addrs.iter().find_map(|(_, a)| {
1938            if a.is_ipv6() && a.ip().is_unspecified() {
1939                Some(a.port())
1940            } else {
1941                None
1942            }
1943        });
1944
1945        // If a socket is bound to the unspecified address, create SocketAddrs for
1946        // each local IP address by pairing it with the port the socket is bound on.
1947        if local_addrs
1948            .iter()
1949            .any(|(_, local)| local.ip().is_unspecified())
1950        {
1951            let LocalAddresses {
1952                regular: mut ips,
1953                loopback,
1954            } = self.local_interfaces_watcher.get().local_addresses;
1955            if ips.is_empty() && addrs.is_empty() {
1956                // Include loopback addresses only if there are no other interfaces
1957                // or public addresses, this allows testing offline.
1958                ips = loopback;
1959            }
1960
1961            for ip in ips {
1962                let port_if_unspecified = match ip {
1963                    IpAddr::V4(_) => has_ipv4_unspecified,
1964                    IpAddr::V6(_) => has_ipv6_unspecified,
1965                };
1966                if let Some(port) = port_if_unspecified {
1967                    let addr = SocketAddr::new(ip, port);
1968                    let flags = find_flags(&netmon_state, ip);
1969                    addrs.entry(addr).or_insert((DirectAddrType::Local, flags));
1970                }
1971            }
1972        }
1973
1974        // If a socket is bound to a specific address, add it.
1975        for (bound, local) in local_addrs {
1976            if !bound.ip().is_unspecified() {
1977                let flags = find_flags(&netmon_state, local.ip());
1978                addrs.entry(local).or_insert((DirectAddrType::Local, flags));
1979            }
1980        }
1981    }
1982
1983    fn handle_net_report_report(&mut self, mut report: Option<net_report::Report>) {
1984        if let Some(ref mut r) = report {
1985            self.sock.ipv6_reported.store(r.udp_v6, Ordering::Relaxed);
1986            let relay_map = &self.sock.relay_map;
1987            // A report that started before a relay was removed can still prefer that relay.
1988            r.preferred_relay.take_if(|url| !relay_map.contains(url));
1989            if r.preferred_relay.is_none()
1990                && let Some(my_relay) = self.sock.my_relay()
1991                && relay_map.contains(&my_relay)
1992            {
1993                r.preferred_relay.replace(my_relay);
1994            }
1995
1996            // Notify all transports
1997            self.transports_network_change.on_network_change(r);
1998        }
1999
2000        #[cfg(not(wasm_browser))]
2001        self.update_direct_addresses(report.as_ref());
2002    }
2003}
2004
2005#[cfg(not(wasm_browser))]
2006fn find_flags(state: &netmon::State, ip: IpAddr) -> Option<Ipv6AddrFlags> {
2007    if ip.is_ipv6() {
2008        state
2009            .interfaces
2010            .values()
2011            .flat_map(|i| i.addrs())
2012            .find_map(|addr| match addr {
2013                IpNet::V4(_) => None,
2014                IpNet::V6 { net, flags, .. } => {
2015                    if net.addr() == ip {
2016                        Some(flags)
2017                    } else {
2018                        None
2019                    }
2020                }
2021            })
2022    } else {
2023        None
2024    }
2025}
2026
2027fn new_re_stun_timer(initial_delay: bool) -> time::Interval {
2028    // Pick a random duration between 20 and 26 seconds (just under 30s,
2029    // a common UDP NAT timeout on Linux,etc)
2030    let mut rng = rand::rng();
2031    let d: Duration = rng.random_range(Duration::from_secs(20)..=Duration::from_secs(26));
2032    if initial_delay {
2033        debug!("scheduling periodic_stun to run in {}s", d.as_secs());
2034        time::interval_at(time::Instant::now() + d, d)
2035    } else {
2036        debug!(
2037            "scheduling periodic_stun to run immediately and in {}s",
2038            d.as_secs()
2039        );
2040        time::interval(d)
2041    }
2042}
2043
2044/// The discovered direct addresses of this [`Socket`].
2045///
2046/// These are all the [`DirectAddr`]s that this [`Socket`] is aware of for itself.
2047/// They include all locally bound ones as well as those discovered by other mechanisms like
2048/// QAD.
2049#[derive(derive_more::Debug, Clone, Default)]
2050struct DiscoveredDirectAddrs {
2051    /// The last set of discovered direct addresses.
2052    addrs: Watchable<BTreeSet<DirectAddr>>,
2053
2054    /// The last time the direct addresses were updated, even if there was no change.
2055    ///
2056    /// This is only ever None at startup.
2057    updated_at: Arc<RwLock<Option<Instant>>>,
2058}
2059
2060impl DiscoveredDirectAddrs {
2061    /// Updates the direct addresses, returns `true` if they changed, `false` if not.
2062    fn update(&self, addrs: BTreeSet<DirectAddr>) -> bool {
2063        *self.updated_at.write().expect("poisoned") = Some(Instant::now());
2064        let updated = self.addrs.set(addrs).is_ok();
2065        if updated {
2066            event!(
2067                target: "iroh::_events::direct_addrs",
2068                Level::DEBUG,
2069                addrs = ?self.addrs.get(),
2070            );
2071        }
2072        updated
2073    }
2074
2075    fn sockaddrs(&self) -> impl Iterator<Item = SocketAddr> {
2076        self.addrs.get().into_iter().map(|da| da.addr)
2077    }
2078}
2079
2080/// A *direct address* on which an iroh-endpoint might be contactable.
2081///
2082/// Direct addresses are UDP socket addresses on which an iroh endpoint could potentially be
2083/// contacted.  These can come from various sources depending on the network topology of the
2084/// iroh endpoint, see [`DirectAddrType`] for the several kinds of sources.
2085///
2086/// This is essentially a combination of our local addresses combined with any reflexive
2087/// transport addresses we discovered using QAD.
2088#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
2089pub struct DirectAddr {
2090    /// The address.
2091    pub addr: SocketAddr,
2092    /// The origin of this direct address.
2093    pub typ: DirectAddrType,
2094}
2095
2096/// The type of direct address.
2097///
2098/// These are the various sources or origins from which an iroh endpoint might have found a
2099/// possible [`DirectAddr`].
2100#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
2101#[non_exhaustive]
2102pub enum DirectAddrType {
2103    /// Not yet determined..
2104    Unknown,
2105    /// A locally bound socket address.
2106    Local,
2107    /// Public internet address discovered via QAD.
2108    ///
2109    /// When possible an iroh endpoint will perform QAD to discover which is the address
2110    /// from which it sends data on the public internet.  This can be different from locally
2111    /// bound addresses when the endpoint is on a local network which performs NAT or similar.
2112    Qad,
2113    /// An address assigned by the router using port mapping.
2114    ///
2115    /// When possible an iroh endpoint will request a port mapping from the local router to
2116    /// get a publicly routable direct address.
2117    Portmapped,
2118    /// Hard NAT: QAD'ed IPv4 address + local fixed port.
2119    ///
2120    /// It is possible to configure iroh to bound to a specific port and independently
2121    /// configure the router to forward this port to the iroh endpoint.  This indicates a
2122    /// situation like this, which still uses QAD to discover the public address.
2123    Qad4LocalPort,
2124    /// An address explicitly provided by the user via configuration.
2125    Config,
2126}
2127
2128impl Display for DirectAddrType {
2129    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2130        match self {
2131            DirectAddrType::Unknown => write!(f, "?"),
2132            DirectAddrType::Local => write!(f, "local"),
2133            DirectAddrType::Qad => write!(f, "qad"),
2134            DirectAddrType::Portmapped => write!(f, "portmap"),
2135            DirectAddrType::Qad4LocalPort => write!(f, "qad4localport"),
2136            DirectAddrType::Config => write!(f, "config"),
2137        }
2138    }
2139}
2140
2141#[cfg(all(test, with_crypto_provider))]
2142mod tests {
2143    use std::{net::SocketAddrV4, sync::Arc, time::Duration};
2144
2145    use data_encoding::HEXLOWER;
2146    use iroh_base::{EndpointAddr, EndpointId, TransportAddr};
2147    use iroh_relay::tls::{CaTlsConfig, default_provider};
2148    use n0_error::{Result, StackResultExt, StdResultExt};
2149    use n0_future::{MergeBounded, StreamExt, time};
2150    use n0_tracing_test::traced_test;
2151    use n0_watcher::Watcher;
2152    use rand::{CryptoRng, Rng, RngExt, SeedableRng};
2153    use tokio_util::task::AbortOnDropHandle;
2154    use tracing::{Instrument, error, info, info_span, instrument};
2155
2156    use super::Options;
2157    use crate::{
2158        Endpoint, SecretKey,
2159        address_lookup::memory::MemoryLookup,
2160        dns::DnsResolver,
2161        endpoint::{QuicTransportConfig, presets},
2162        socket::{
2163            EndpointInner, StaticConfig, TransportConfig,
2164            biased_rtt_path_selector::BiasedRttPathSelector,
2165            mapped_addrs::{EndpointIdMappedAddr, MappedAddr},
2166        },
2167        tls::{self, DEFAULT_MAX_TLS_TICKETS, misc::RustlsTokenKey},
2168    };
2169
2170    const ALPN: &[u8] = b"n0/test/1";
2171
2172    fn default_options(rng: &mut impl CryptoRng) -> Options {
2173        let crypto_provider = default_provider();
2174        let secret_key = SecretKey::from_bytes(&rng.random());
2175        let tls_config = tls::TlsConfig::new(
2176            secret_key.clone(),
2177            DEFAULT_MAX_TLS_TICKETS,
2178            crypto_provider.clone(),
2179        );
2180        let static_config = StaticConfig {
2181            server_config: tls_config.make_server_config(false).unwrap(),
2182            client_config: tls_config.make_client_config(false).unwrap(),
2183            tls_config,
2184            token_key: Arc::new(RustlsTokenKey::new(rng, &crypto_provider).unwrap()),
2185            token_store: Arc::new(noq::TokenMemoryCache::default()),
2186            transport_config: QuicTransportConfig::default(),
2187        };
2188        let server_config = static_config.create_server_config(vec![]);
2189        Options {
2190            transports: vec![
2191                TransportConfig::default_ipv4(),
2192                TransportConfig::default_ipv6(),
2193            ],
2194            secret_key,
2195            proxy_url: None,
2196            dns_resolver: DnsResolver::new(),
2197            server_config,
2198            tls_config: CaTlsConfig::default()
2199                .client_config(crypto_provider.clone())
2200                .unwrap(),
2201            #[cfg(any(test, feature = "test-utils"))]
2202            address_lookup_user_data: None,
2203            metrics: Default::default(),
2204            hooks: Default::default(),
2205            path_selector: Arc::new(BiasedRttPathSelector::default()),
2206            portmapper_config: Default::default(),
2207            net_report_config: Default::default(),
2208            static_config,
2209            configured_addrs: Default::default(),
2210        }
2211    }
2212
2213    #[instrument(skip_all, fields(me = %ep.id().fmt_short()))]
2214    async fn echo_receiver(ep: Endpoint, loss: ExpectedLoss) -> Result {
2215        info!("accepting conn");
2216        let conn = ep.accept().await.expect("no conn");
2217
2218        info!("accepting");
2219        let conn = conn.await.context("accepting")?;
2220        info!("accepting bi");
2221        let (mut send_bi, mut recv_bi) = conn.accept_bi().await.std_context("accept bi")?;
2222
2223        info!("reading");
2224        let val = recv_bi
2225            .read_to_end(usize::MAX)
2226            .await
2227            .std_context("read to end")?;
2228
2229        info!("replying");
2230        for chunk in val.chunks(12) {
2231            send_bi.write_all(chunk).await.std_context("write all")?;
2232        }
2233
2234        info!("finishing");
2235        send_bi.finish().std_context("finish")?;
2236
2237        let stats = conn.stats();
2238        info!("stats: {:#?}", stats);
2239        if matches!(loss, ExpectedLoss::AlmostNone) {
2240            for info in conn.paths().iter() {
2241                assert!(
2242                    info.stats().lost_packets < 10,
2243                    "[receiver] path {:?} should not loose many packets",
2244                    info.remote_addr()
2245                );
2246            }
2247        }
2248
2249        conn.closed().await;
2250        info!("closed");
2251        ep.inner()?.noq_endpoint().wait_idle().await;
2252        info!("idle");
2253
2254        Ok(())
2255    }
2256
2257    #[instrument(skip_all, fields(me = %ep.id().fmt_short()))]
2258    async fn echo_sender(
2259        ep: Endpoint,
2260        dest_id: EndpointId,
2261        msg: &[u8],
2262        loss: ExpectedLoss,
2263    ) -> Result {
2264        info!("connecting to {}", dest_id.fmt_short());
2265        let dest = EndpointAddr::new(dest_id);
2266        let conn = ep.connect(dest, ALPN).await?;
2267
2268        info!("opening bi");
2269        let (mut send_bi, mut recv_bi) = conn.open_bi().await.std_context("open bi")?;
2270
2271        info!("writing message");
2272        send_bi.write_all(msg).await.std_context("write all")?;
2273
2274        info!("finishing");
2275        send_bi.finish().std_context("finish")?;
2276
2277        info!("reading_to_end");
2278        let val = recv_bi
2279            .read_to_end(usize::MAX)
2280            .await
2281            .std_context("read to end")?;
2282        assert_eq!(
2283            val,
2284            msg,
2285            "[sender] expected {}, got {}",
2286            HEXLOWER.encode(msg),
2287            HEXLOWER.encode(&val)
2288        );
2289
2290        let stats = conn.stats();
2291        info!("stats: {:#?}", stats);
2292        if matches!(loss, ExpectedLoss::AlmostNone) {
2293            for info in conn.paths().iter() {
2294                assert!(
2295                    info.stats().lost_packets < 10,
2296                    "[sender] path {:?} should not loose many packets",
2297                    info.remote_addr()
2298                );
2299            }
2300        }
2301
2302        conn.close(0u32.into(), b"done");
2303        info!("closed");
2304        ep.inner()?.noq_endpoint().wait_idle().await;
2305        info!("idle");
2306        Ok(())
2307    }
2308
2309    #[derive(Debug, Copy, Clone)]
2310    enum ExpectedLoss {
2311        AlmostNone,
2312        YeahSure,
2313    }
2314
2315    /// Runs a roundtrip between the [`echo_sender`] and [`echo_receiver`].
2316    async fn run_roundtrip(
2317        sender: Endpoint,
2318        receiver: Endpoint,
2319        payload: &[u8],
2320        loss: ExpectedLoss,
2321    ) -> Result<()> {
2322        tokio::time::timeout(Duration::from_secs(20), async move {
2323            let send_endpoint_id = sender.id();
2324            let recv_endpoint_id = receiver.id();
2325            info!("\nroundtrip: {send_endpoint_id:#} -> {recv_endpoint_id:#}");
2326
2327            let receiver_task = AbortOnDropHandle::new(tokio::spawn(echo_receiver(receiver, loss)));
2328            let sender_res = echo_sender(sender, recv_endpoint_id, payload, loss).await;
2329            let sender_is_err = match sender_res {
2330                Ok(()) => false,
2331                Err(err) => {
2332                    error!("[sender] Error:\n{err:#?}");
2333                    true
2334                }
2335            };
2336            let receiver_is_err = match receiver_task.await {
2337                Ok(Ok(())) => false,
2338                Ok(Err(err)) => {
2339                    error!("[receiver] Error:\n{err:#?}");
2340                    true
2341                }
2342                Err(joinerr) => {
2343                    if joinerr.is_panic() {
2344                        std::panic::resume_unwind(joinerr.into_panic());
2345                    } else {
2346                        error!("[receiver] Error:\n{joinerr:#?}");
2347                    }
2348                    true
2349                }
2350            };
2351            if sender_is_err || receiver_is_err {
2352                panic!("Sender or receiver errored");
2353            }
2354        })
2355        .await
2356        .std_context("timeout")?;
2357        Ok(())
2358    }
2359
2360    /// Returns a pair of endpoints with a shared [`MemoryLookup`].
2361    ///
2362    /// The endpoints do not use a relay server but can connect to each other via local
2363    /// addresses.  Dialing by [`EndpointId`] is possible, and the addresses get updated even if
2364    /// the endpoints rebind.
2365    async fn endpoint_pair() -> (AbortOnDropHandle<()>, Endpoint, Endpoint) {
2366        let address_lookup = MemoryLookup::new();
2367        let ep1 = Endpoint::builder(presets::Minimal)
2368            .alpns(vec![ALPN.to_vec()])
2369            .address_lookup(address_lookup.clone())
2370            .bind()
2371            .await
2372            .unwrap();
2373        let ep2 = Endpoint::builder(presets::Minimal)
2374            .alpns(vec![ALPN.to_vec()])
2375            .address_lookup(address_lookup.clone())
2376            .bind()
2377            .await
2378            .unwrap();
2379        address_lookup.add_endpoint_info(ep1.addr());
2380        address_lookup.add_endpoint_info(ep2.addr());
2381
2382        let ep1_addr_stream = ep1.watch_addr().stream();
2383        let ep2_addr_stream = ep2.watch_addr().stream();
2384        let mut addr_stream = MergeBounded::from_iter([ep1_addr_stream, ep2_addr_stream]);
2385        let task = tokio::spawn(async move {
2386            while let Some(addr) = addr_stream.next().await {
2387                address_lookup.add_endpoint_info(addr);
2388            }
2389        });
2390
2391        (AbortOnDropHandle::new(task), ep1, ep2)
2392    }
2393
2394    #[tokio::test(flavor = "multi_thread")]
2395    #[traced_test]
2396    async fn test_two_devices_roundtrip_noq_small() -> Result {
2397        let (_guard, m1, m2) = endpoint_pair().await;
2398
2399        run_roundtrip(
2400            m1.clone(),
2401            m2.clone(),
2402            b"hello m1",
2403            ExpectedLoss::AlmostNone,
2404        )
2405        .await?;
2406        run_roundtrip(
2407            m2.clone(),
2408            m1.clone(),
2409            b"hello m2",
2410            ExpectedLoss::AlmostNone,
2411        )
2412        .await?;
2413        Ok(())
2414    }
2415
2416    #[tokio::test(flavor = "multi_thread")]
2417    #[traced_test]
2418    async fn test_two_devices_roundtrip_noq_large() -> Result {
2419        let (_guard, m1, m2) = endpoint_pair().await;
2420        let mut data = vec![0u8; 10 * 1024];
2421        let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(0u64);
2422        rng.fill_bytes(&mut data);
2423        run_roundtrip(m1.clone(), m2.clone(), &data, ExpectedLoss::AlmostNone).await?;
2424        run_roundtrip(m2.clone(), m1.clone(), &data, ExpectedLoss::AlmostNone).await?;
2425
2426        Ok(())
2427    }
2428
2429    // EADDRINUSE on the GitHub Android emulator persists past
2430    // `force_network_change()`, so the rebind fails and connect() never
2431    // wakes the connection driver. Passes locally.
2432    #[cfg_attr(
2433        target_os = "android",
2434        ignore = "rebind flakes against the GitHub Android emulator"
2435    )]
2436    #[tokio::test]
2437    #[traced_test]
2438    async fn test_regression_network_change_rebind_wakes_connection_driver() -> Result {
2439        let (_guard, m1, m2) = endpoint_pair().await;
2440
2441        println!("Net change");
2442        m1.inner()?.force_network_change(true).await;
2443        tokio::time::sleep(Duration::from_secs(1)).await; // wait for socket rebinding
2444
2445        let _handle = AbortOnDropHandle::new(tokio::spawn({
2446            let endpoint = m2.clone();
2447            async move {
2448                while let Some(incoming) = endpoint.accept().await {
2449                    println!("Incoming first conn!");
2450                    let conn = incoming.await.anyerr()?;
2451                    conn.closed().await;
2452                }
2453
2454                n0_error::Ok(())
2455            }
2456        }));
2457
2458        println!("first conn!");
2459        let conn = m1.connect(m2.addr(), ALPN).await?;
2460        println!("Closing first conn");
2461        conn.close(0u32.into(), b"bye lolz");
2462        conn.closed().await;
2463        println!("Closed first conn");
2464
2465        Ok(())
2466    }
2467
2468    fn offset(rng: &mut rand_chacha::ChaCha8Rng) -> Duration {
2469        let delay = rng.random_range(1..=5);
2470        Duration::from_millis(delay * 50)
2471    }
2472
2473    /// Same structure as `test_two_devices_roundtrip_noq`, but interrupts regularly
2474    /// with (simulated) network changes.
2475    /// Regular network changes to m1 only.
2476    #[tokio::test(flavor = "multi_thread")]
2477    #[traced_test]
2478    async fn test_two_devices_roundtrip_network_change_only_a() -> Result {
2479        let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(0u64);
2480        let (_guard, m1, m2) = endpoint_pair().await;
2481
2482        let _network_change_guard = {
2483            let m1 = m1.clone();
2484            let mut rng = rng.clone();
2485            let task = tokio::spawn(async move {
2486                loop {
2487                    info!("[m1] network change");
2488                    m1.inner()
2489                        .expect("haven't closed the endpoint yet")
2490                        .force_network_change(true)
2491                        .await;
2492                    time::sleep(offset(&mut rng)).await;
2493                }
2494            });
2495            AbortOnDropHandle::new(task)
2496        };
2497
2498        let mut data = vec![0u8; 10 * 1024];
2499        rng.fill_bytes(&mut data);
2500        run_roundtrip(m1.clone(), m2.clone(), &data, ExpectedLoss::YeahSure).await?;
2501        run_roundtrip(m2.clone(), m1.clone(), &data, ExpectedLoss::YeahSure).await?;
2502
2503        Ok(())
2504    }
2505
2506    /// Regular network changes to both m1 and m2.
2507    #[tokio::test(flavor = "multi_thread")]
2508    #[traced_test]
2509    async fn test_two_devices_roundtrip_network_change_a_and_b() -> Result {
2510        let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(0u64);
2511        let (_guard, m1, m2) = endpoint_pair().await;
2512
2513        let _network_change_guard = {
2514            let m1 = m1.clone();
2515            let m2 = m2.clone();
2516            let mut rng = rng.clone();
2517            let task = tokio::spawn(async move {
2518                info!("-- [m1] network change");
2519                m1.inner()
2520                    .expect("haven't closed the endpoint yet")
2521                    .force_network_change(true)
2522                    .await;
2523                info!("-- [m2] network change");
2524                m2.inner()
2525                    .expect("haven't closed the endpoint yet")
2526                    .force_network_change(true)
2527                    .await;
2528                time::sleep(offset(&mut rng)).await;
2529            });
2530            AbortOnDropHandle::new(task)
2531        };
2532
2533        let mut data = vec![0u8; 10 * 1024];
2534        rng.fill_bytes(&mut data);
2535        run_roundtrip(m1.clone(), m2.clone(), &data, ExpectedLoss::YeahSure).await?;
2536        run_roundtrip(m2.clone(), m1.clone(), &data, ExpectedLoss::YeahSure).await?;
2537
2538        Ok(())
2539    }
2540
2541    #[tokio::test(flavor = "multi_thread")]
2542    #[traced_test]
2543    async fn test_two_devices_setup_teardown() -> Result {
2544        for i in 0..10 {
2545            info!("-- round {i}");
2546            info!("setting up stack");
2547            let (_guard, m1, m2) = endpoint_pair().await;
2548
2549            info!("closing endpoints");
2550            let sock1 = m1.inner()?;
2551            let sock2 = m2.inner()?;
2552            m1.close().await;
2553            m2.close().await;
2554
2555            assert!(sock1.is_closed());
2556            assert!(sock2.is_closed());
2557        }
2558        Ok(())
2559    }
2560
2561    #[tokio::test]
2562    #[traced_test]
2563    async fn test_direct_addresses() {
2564        let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(0u64);
2565        let sock = EndpointInner::bind(default_options(&mut rng))
2566            .await
2567            .unwrap();
2568
2569        // See if we can get endpoints.
2570        let eps0 = sock.ip_addrs().get();
2571        info!("{eps0:?}");
2572        assert!(!eps0.is_empty());
2573
2574        // Getting the endpoints again immediately should give the same results.
2575        let eps1 = sock.ip_addrs().get();
2576        info!("{eps1:?}");
2577        assert_eq!(eps0, eps1);
2578    }
2579
2580    /// Creates a new [`noq::Endpoint`] hooked up to a [`Socket`].
2581    ///
2582    /// This is without involving [`crate::endpoint::Endpoint`].  The socket will accept
2583    /// connections using [`ALPN`].
2584    ///
2585    /// Use [`socket_connect`] to establish connections.
2586    #[instrument(name = "ep", skip_all, fields(me = %secret_key.public().fmt_short()))]
2587    async fn socket_ep(secret_key: SecretKey) -> Result<EndpointInner> {
2588        let crypto_provider = default_provider();
2589        let tls_config = tls::TlsConfig::new(
2590            secret_key.clone(),
2591            DEFAULT_MAX_TLS_TICKETS,
2592            crypto_provider.clone(),
2593        );
2594        let keylog = true;
2595        let static_config = StaticConfig {
2596            server_config: tls_config.make_server_config(keylog).unwrap(),
2597            client_config: tls_config.make_client_config(keylog).unwrap(),
2598            tls_config,
2599            token_key: Arc::new(RustlsTokenKey::new(&mut rand::rng(), &crypto_provider).unwrap()),
2600            token_store: Arc::new(noq::TokenMemoryCache::default()),
2601            transport_config: QuicTransportConfig::default(),
2602        };
2603        let server_config = static_config.create_server_config(vec![ALPN.to_vec()]);
2604
2605        let dns_resolver = DnsResolver::new();
2606        let opts = Options {
2607            transports: vec![
2608                TransportConfig::default_ipv4(),
2609                TransportConfig::default_ipv6(),
2610            ],
2611            secret_key: secret_key.clone(),
2612            address_lookup_user_data: None,
2613            dns_resolver,
2614            proxy_url: None,
2615            server_config,
2616            tls_config: CaTlsConfig::default()
2617                .client_config(crypto_provider.clone())
2618                .unwrap(),
2619            metrics: Default::default(),
2620            hooks: Default::default(),
2621            path_selector: Arc::new(BiasedRttPathSelector::default()),
2622            portmapper_config: Default::default(),
2623            net_report_config: Default::default(),
2624            static_config,
2625            configured_addrs: Default::default(),
2626        };
2627        let sock = EndpointInner::bind(opts).await?;
2628        Ok(sock)
2629    }
2630
2631    /// Connects from `ep` returned by [`socket_ep`] to the `endpoint_id`.
2632    ///
2633    /// Uses [`ALPN`], `endpoint_id`, must match `addr`.
2634    #[instrument(name = "connect", skip_all, fields(me = %ep_secret_key.public().fmt_short()))]
2635    async fn socket_connect(
2636        ep: noq::Endpoint,
2637        ep_secret_key: SecretKey,
2638        addr: EndpointIdMappedAddr,
2639        endpoint_id: EndpointId,
2640    ) -> Result<noq::Connection> {
2641        // Endpoint::connect sets this, do the same to have similar behaviour.
2642        let mut transport_config = noq::TransportConfig::default();
2643        transport_config.server_handshake_migration(true);
2644        transport_config.keep_alive_interval(Some(Duration::from_secs(1)));
2645
2646        socket_connect_with_transport_config(
2647            ep,
2648            ep_secret_key,
2649            addr,
2650            endpoint_id,
2651            Arc::new(transport_config),
2652        )
2653        .await
2654    }
2655
2656    /// Connects from `ep` returned by [`socket_ep`] to the `endpoint_id`.
2657    ///
2658    /// This version allows customising the transport config.
2659    ///
2660    /// Uses [`ALPN`], `endpoint_id`, must match `addr`.
2661    #[instrument(name = "connect", skip_all, fields(me = %ep_secret_key.public().fmt_short()))]
2662    async fn socket_connect_with_transport_config(
2663        ep: noq::Endpoint,
2664        ep_secret_key: SecretKey,
2665        mapped_addr: EndpointIdMappedAddr,
2666        endpoint_id: EndpointId,
2667        transport_config: Arc<noq::TransportConfig>,
2668    ) -> Result<noq::Connection> {
2669        let mut quic_client_config = tls::TlsConfig::new(
2670            ep_secret_key.clone(),
2671            DEFAULT_MAX_TLS_TICKETS,
2672            default_provider(),
2673        )
2674        .make_client_config(true)?;
2675        quic_client_config.set_alpn_protocols(vec![ALPN.to_vec()]);
2676        let mut client_config = noq::ClientConfig::new(Arc::new(quic_client_config));
2677        client_config.transport_config(transport_config);
2678        let connect = ep
2679            .connect_with(
2680                client_config,
2681                mapped_addr.private_socket_addr(),
2682                &tls::name::encode(endpoint_id),
2683            )
2684            .std_context("connect")?;
2685        let connection = connect.await.anyerr()?;
2686        Ok(connection)
2687    }
2688
2689    #[tokio::test]
2690    #[traced_test]
2691    async fn test_try_send_no_send_addr() {
2692        // Regression test: if there is no send_addr we should keep being able to use the
2693        // Endpoint.
2694
2695        let secret_key_1 = SecretKey::from_bytes(&[1u8; 32]);
2696        let secret_key_2 = SecretKey::from_bytes(&[2u8; 32]);
2697        let endpoint_id_2 = secret_key_2.public();
2698        let secret_key_missing_endpoint = SecretKey::from_bytes(&[255u8; 32]);
2699        let endpoint_id_missing_endpoint = secret_key_missing_endpoint.public();
2700
2701        let sock_1 = socket_ep(secret_key_1.clone()).await.unwrap();
2702
2703        // Generate an address not present in the RemoteMap.
2704        let bad_addr = EndpointIdMappedAddr::generate();
2705
2706        // 500ms is rather fast here.  Running this locally it should always be the correct
2707        // timeout.  If this is too slow however the test will not become flaky as we are
2708        // expecting the timeout, we might just get the timeout for the wrong reason.  But
2709        // this speeds up the test.
2710        let res = tokio::time::timeout(
2711            Duration::from_millis(500),
2712            socket_connect(
2713                sock_1.noq_endpoint().clone(),
2714                secret_key_1.clone(),
2715                bad_addr,
2716                endpoint_id_missing_endpoint,
2717            ),
2718        )
2719        .await;
2720        assert!(res.is_err(), "expecting timeout");
2721
2722        // Now check we can still create another connection with this endpoint.
2723        let sock_2 = socket_ep(secret_key_2.clone()).await.unwrap();
2724
2725        // This needs an accept task
2726        let accept_task = tokio::spawn({
2727            async fn accept(ep: noq::Endpoint) -> Result<()> {
2728                let incoming = ep.accept().await.std_context("no incoming")?;
2729                let _conn = incoming
2730                    .accept()
2731                    .std_context("accept")?
2732                    .await
2733                    .std_context("accepting")?;
2734
2735                // Keep this connection alive for a while
2736                tokio::time::sleep(Duration::from_secs(10)).await;
2737                info!("accept finished");
2738                Ok(())
2739            }
2740            let ep = sock_2.noq_endpoint().clone();
2741            async move {
2742                if let Err(err) = accept(ep).await {
2743                    error!("{err:#}");
2744                }
2745            }
2746            .instrument(info_span!("ep2.accept, me = endpoint_id_2.fmt_short()"))
2747        });
2748        let _accept_task = AbortOnDropHandle::new(accept_task);
2749
2750        let addrs = sock_2
2751            .ip_addrs()
2752            .get()
2753            .into_iter()
2754            .map(|x| TransportAddr::Ip(x.addr));
2755        let endpoint_addr_2 = EndpointAddr::from_parts(endpoint_id_2, addrs);
2756        let addr = sock_1
2757            .resolve_remote(endpoint_addr_2)
2758            .await
2759            .unwrap()
2760            .unwrap();
2761        let res = tokio::time::timeout(
2762            Duration::from_secs(10),
2763            socket_connect(
2764                sock_1.noq_endpoint().clone(),
2765                secret_key_1.clone(),
2766                addr,
2767                endpoint_id_2,
2768            ),
2769        )
2770        .await
2771        .expect("timeout while connecting");
2772
2773        // aka assert!(res.is_ok()) but with nicer error reporting.
2774        res.unwrap();
2775
2776        // TODO: Now check if we can connect to a repaired ep_3, but we can't modify that
2777        // much internal state for now.
2778    }
2779
2780    #[tokio::test]
2781    #[traced_test]
2782    async fn test_try_send_no_udp_addr_or_relay_url() {
2783        // This specifically tests the `if udp_addr.is_none() && relay_url.is_none()`
2784        // behaviour of Socket::try_send.
2785
2786        let secret_key_1 = SecretKey::from_bytes(&[1u8; 32]);
2787        let secret_key_2 = SecretKey::from_bytes(&[2u8; 32]);
2788        let endpoint_id_2 = secret_key_2.public();
2789
2790        let sock_1 = socket_ep(secret_key_1.clone()).await.unwrap();
2791        let sock_2 = socket_ep(secret_key_2.clone()).await.unwrap();
2792        let ep_2 = sock_2.noq_endpoint().clone();
2793
2794        // We need a task to accept the connection.
2795        let accept_task = tokio::spawn({
2796            async fn accept(ep: noq::Endpoint) -> Result<()> {
2797                let incoming = ep.accept().await.std_context("no incoming")?;
2798                let conn = incoming
2799                    .accept()
2800                    .std_context("accept")?
2801                    .await
2802                    .std_context("connecting")?;
2803                let mut stream = conn.accept_uni().await.std_context("accept uni")?;
2804                stream
2805                    .read_to_end(1 << 16)
2806                    .await
2807                    .std_context("read to end")?;
2808                info!("accept finished");
2809                Ok(())
2810            }
2811            async move {
2812                if let Err(err) = accept(ep_2).await {
2813                    error!("{err:#}");
2814                }
2815            }
2816            .instrument(info_span!("ep2.accept", me = %endpoint_id_2.fmt_short()))
2817        });
2818        let _accept_task = AbortOnDropHandle::new(accept_task);
2819
2820        // Add an entry in the RemoteMap of ep_1 with an invalid socket address
2821        let empty_addr_2 = EndpointAddr::from_parts(
2822            endpoint_id_2,
2823            [TransportAddr::Ip(
2824                // Reserved IP range for documentation (unreachable)
2825                SocketAddrV4::new([192, 0, 2, 1].into(), 12345).into(),
2826            )],
2827        );
2828        let addr_2 = sock_1.resolve_remote(empty_addr_2).await.unwrap().unwrap();
2829
2830        // Set a low max_idle_timeout so noq gives up on this quickly and our test does
2831        // not take forever.  You need to check the log output to verify this is really
2832        // triggering the correct error.
2833        // In test_try_send_no_send_addr() above you may have noticed we used
2834        // tokio::time::timeout() on the connection attempt instead.  Here however we want
2835        // Noq itself to have fully given up on the connection attempt because we will
2836        // later connect to **the same** endpoint.  If Noq did not give up on the connection
2837        // we'd close it on drop, and the retransmits of the close packets would interfere
2838        // with the next handshake, closing it during the handshake.  This makes the test a
2839        // little slower though.
2840        let mut transport_config = noq::TransportConfig::default();
2841        transport_config.server_handshake_migration(true);
2842        transport_config.max_idle_timeout(Some(Duration::from_millis(200).try_into().unwrap()));
2843        let res = socket_connect_with_transport_config(
2844            sock_1.noq_endpoint().clone(),
2845            secret_key_1.clone(),
2846            addr_2,
2847            endpoint_id_2,
2848            Arc::new(transport_config),
2849        )
2850        .await;
2851        assert!(res.is_err(), "expected timeout");
2852        info!("first connect timed out as expected");
2853
2854        // Provide correct addressing information
2855        let correct_addr_2 = EndpointAddr::from_parts(
2856            endpoint_id_2,
2857            sock_2
2858                .ip_addrs()
2859                .get()
2860                .into_iter()
2861                .map(|x| TransportAddr::Ip(x.addr)),
2862        );
2863        let addr_2a = sock_1
2864            .resolve_remote(correct_addr_2)
2865            .await
2866            .unwrap()
2867            .unwrap();
2868        assert_eq!(addr_2, addr_2a);
2869
2870        // We can now connect
2871        tokio::time::timeout(Duration::from_secs(10), async move {
2872            info!("establishing new connection");
2873            let conn = socket_connect(
2874                sock_1.noq_endpoint().clone(),
2875                secret_key_1.clone(),
2876                addr_2,
2877                endpoint_id_2,
2878            )
2879            .await
2880            .unwrap();
2881            info!("have connection");
2882            let mut stream = conn.open_uni().await.unwrap();
2883            stream.write_all(b"hello").await.unwrap();
2884            stream.finish().unwrap();
2885            stream.stopped().await.unwrap();
2886            info!("finished stream");
2887        })
2888        .await
2889        .expect("connection timed out");
2890
2891        // TODO: could remove the addresses again, send, add it back and see it recover.
2892        // But we don't have that much private access to the RemoteMap.  This will do for now.
2893    }
2894}