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        // This block is a band-aid for https://github.com/n0-computer/iroh/issues/4588
1770        // See patchbay test `lan_switch_advertises_new_addr_without_relay`
1771        #[cfg(not(wasm_browser))]
1772        {
1773            if self.sock.relay_map.is_empty() {
1774                // When there are no relays, update direct addresses immediately from local interfaces
1775                // without waiting for net_report. Also reset the periodic timer.
1776                self.update_direct_addresses(None);
1777                self.periodic_re_stun_timer = new_re_stun_timer(true);
1778                return; // Skip schedule_run since we handled it directly
1779            }
1780        }
1781
1782        self.direct_addr_update_state
1783            .schedule_run(why, state.into());
1784    }
1785
1786    /// Processes an incoming actor message.
1787    ///
1788    /// Returns `true` if it was a shutdown.
1789    async fn handle_actor_message(&mut self, msg: ActorMessage) {
1790        match msg {
1791            ActorMessage::NetworkChange => {
1792                self.network_monitor.network_change().await.ok();
1793            }
1794            ActorMessage::RelayMapChange => {
1795                self.handle_relay_map_change();
1796            }
1797            ActorMessage::ResolveRemote(addr, tx) => {
1798                self.remote_map.resolve_remote(addr, tx).await;
1799            }
1800            ActorMessage::AddConnection(remote, conn, tx) => {
1801                self.remote_map.add_connection(remote, conn, tx).await;
1802            }
1803            ActorMessage::DirectAddrRefresh => {
1804                #[cfg(not(wasm_browser))]
1805                {
1806                    let (report, _reason) = self.sock.net_report.get();
1807                    self.update_direct_addresses(report.as_ref());
1808                }
1809            }
1810            #[cfg(all(test, with_crypto_provider))]
1811            ActorMessage::ForceNetworkChange(is_major) => {
1812                self.handle_network_change(is_major);
1813            }
1814        }
1815    }
1816
1817    /// Updates the direct addresses of this socket.
1818    ///
1819    /// Updates the [`DiscoveredDirectAddrs`] of this [`Socket`] with the current set of
1820    /// direct addresses from:
1821    ///
1822    /// - The portmapper.
1823    /// - A net_report report.
1824    /// - The local interfaces IP addresses.
1825    /// - User configured addresses.
1826    #[cfg(not(wasm_browser))]
1827    fn update_direct_addresses(&mut self, net_report_report: Option<&net_report::Report>) {
1828        // We only want to have one DirectAddr for each SocketAddr we have.  So we store
1829        // this as a map of SocketAddr -> DirectAddrType.  At the end we will construct a
1830        // DirectAddr from each entry.
1831        let mut addrs: BTreeMap<SocketAddr, (DirectAddrType, Option<Ipv6AddrFlags>)> =
1832            BTreeMap::new();
1833
1834        // First add PortMapper provided addresses.
1835        let portmap_watcher = self
1836            .direct_addr_update_state
1837            .port_mapper
1838            .watch_external_address();
1839        let maybe_port_mapped = *portmap_watcher.borrow();
1840        if let Some(portmap_ext) = maybe_port_mapped.map(SocketAddr::V4) {
1841            addrs
1842                .entry(portmap_ext)
1843                .or_insert((DirectAddrType::Portmapped, None));
1844        }
1845
1846        // Next add STUN addresses from the net_report report.
1847        if let Some(net_report_report) = net_report_report {
1848            if let Some(global_v4) = net_report_report.global_v4 {
1849                addrs
1850                    .entry(global_v4.into())
1851                    .or_insert((DirectAddrType::Qad, None));
1852
1853                // If they're behind a hard NAT and are using a fixed
1854                // port locally, assume they might've added a static
1855                // port mapping on their router to the same explicit
1856                // port that we are running with. Worst case it's an invalid candidate mapping.
1857                let port = self.sock.ip_bind_addrs().iter().find_map(|addr| {
1858                    if addr.port() != 0 {
1859                        Some(addr.port())
1860                    } else {
1861                        None
1862                    }
1863                });
1864
1865                if let Some(port) = port
1866                    && net_report_report
1867                        .mapping_varies_by_dest()
1868                        .unwrap_or_default()
1869                {
1870                    let mut addr = global_v4;
1871                    addr.set_port(port);
1872                    addrs
1873                        .entry(addr.into())
1874                        .or_insert((DirectAddrType::Qad4LocalPort, None));
1875                }
1876            }
1877            if let Some(global_v6) = net_report_report.global_v6 {
1878                addrs
1879                    .entry(global_v6.into())
1880                    .or_insert((DirectAddrType::Qad, None));
1881            }
1882        }
1883
1884        self.collect_local_addresses(&mut addrs);
1885
1886        // Add configured external addresses.
1887        for addr in self.sock.configured_addrs.read().expect("poisoned").iter() {
1888            addrs.entry(*addr).or_insert((DirectAddrType::Config, None));
1889        }
1890
1891        // Finally create and store store all these direct addresses
1892        let stored_addrs = addrs
1893            .into_iter()
1894            .filter_map(|(addr, (typ, flags))| {
1895                // Filter out deprecated IPs
1896                let is_deprecated = flags.map(|f| f.deprecated).unwrap_or(false);
1897                if is_deprecated {
1898                    return None;
1899                }
1900                Some(DirectAddr { addr, typ })
1901            })
1902            .collect();
1903        self.sock.store_direct_addresses(stored_addrs);
1904    }
1905
1906    #[cfg(not(wasm_browser))]
1907    fn collect_local_addresses(
1908        &mut self,
1909        addrs: &mut BTreeMap<SocketAddr, (DirectAddrType, Option<Ipv6AddrFlags>)>,
1910    ) {
1911        let netmon_state = self.local_interfaces_watcher.get();
1912
1913        // Matches the addresses that have been bound vs the requested ones.
1914        let local_addrs: Vec<(SocketAddr, SocketAddr)> = self
1915            .sock
1916            .ip_bind_addrs()
1917            .iter()
1918            .copied()
1919            .zip(self.sock.ip_local_addrs())
1920            .collect();
1921
1922        // Do we listen on any IPv4 unspecified address?
1923        let has_ipv4_unspecified = local_addrs.iter().find_map(|(_, a)| {
1924            if a.is_ipv4() && a.ip().is_unspecified() {
1925                Some(a.port())
1926            } else {
1927                None
1928            }
1929        });
1930        // Do we listen on any IPv6 unspecified address?
1931        let has_ipv6_unspecified = local_addrs.iter().find_map(|(_, a)| {
1932            if a.is_ipv6() && a.ip().is_unspecified() {
1933                Some(a.port())
1934            } else {
1935                None
1936            }
1937        });
1938
1939        // If a socket is bound to the unspecified address, create SocketAddrs for
1940        // each local IP address by pairing it with the port the socket is bound on.
1941        if local_addrs
1942            .iter()
1943            .any(|(_, local)| local.ip().is_unspecified())
1944        {
1945            let LocalAddresses {
1946                regular: mut ips,
1947                loopback,
1948            } = self.local_interfaces_watcher.get().local_addresses;
1949            if ips.is_empty() && addrs.is_empty() {
1950                // Include loopback addresses only if there are no other interfaces
1951                // or public addresses, this allows testing offline.
1952                ips = loopback;
1953            }
1954
1955            for ip in ips {
1956                let port_if_unspecified = match ip {
1957                    IpAddr::V4(_) => has_ipv4_unspecified,
1958                    IpAddr::V6(_) => has_ipv6_unspecified,
1959                };
1960                if let Some(port) = port_if_unspecified {
1961                    let addr = SocketAddr::new(ip, port);
1962                    let flags = find_flags(&netmon_state, ip);
1963                    addrs.entry(addr).or_insert((DirectAddrType::Local, flags));
1964                }
1965            }
1966        }
1967
1968        // If a socket is bound to a specific address, add it.
1969        for (bound, local) in local_addrs {
1970            if !bound.ip().is_unspecified() {
1971                let flags = find_flags(&netmon_state, local.ip());
1972                addrs.entry(local).or_insert((DirectAddrType::Local, flags));
1973            }
1974        }
1975    }
1976
1977    fn handle_net_report_report(&mut self, mut report: Option<net_report::Report>) {
1978        if let Some(ref mut r) = report {
1979            self.sock.ipv6_reported.store(r.udp_v6, Ordering::Relaxed);
1980            if r.preferred_relay.is_none()
1981                && let Some(my_relay) = self.sock.my_relay()
1982            {
1983                r.preferred_relay.replace(my_relay);
1984            }
1985
1986            // Notify all transports
1987            self.transports_network_change.on_network_change(r);
1988        }
1989
1990        #[cfg(not(wasm_browser))]
1991        self.update_direct_addresses(report.as_ref());
1992    }
1993}
1994
1995#[cfg(not(wasm_browser))]
1996fn find_flags(state: &netmon::State, ip: IpAddr) -> Option<Ipv6AddrFlags> {
1997    if ip.is_ipv6() {
1998        state
1999            .interfaces
2000            .values()
2001            .flat_map(|i| i.addrs())
2002            .find_map(|addr| match addr {
2003                IpNet::V4(_) => None,
2004                IpNet::V6 { net, flags, .. } => {
2005                    if net.addr() == ip {
2006                        Some(flags)
2007                    } else {
2008                        None
2009                    }
2010                }
2011            })
2012    } else {
2013        None
2014    }
2015}
2016
2017fn new_re_stun_timer(initial_delay: bool) -> time::Interval {
2018    // Pick a random duration between 20 and 26 seconds (just under 30s,
2019    // a common UDP NAT timeout on Linux,etc)
2020    let mut rng = rand::rng();
2021    let d: Duration = rng.random_range(Duration::from_secs(20)..=Duration::from_secs(26));
2022    if initial_delay {
2023        debug!("scheduling periodic_stun to run in {}s", d.as_secs());
2024        time::interval_at(time::Instant::now() + d, d)
2025    } else {
2026        debug!(
2027            "scheduling periodic_stun to run immediately and in {}s",
2028            d.as_secs()
2029        );
2030        time::interval(d)
2031    }
2032}
2033
2034/// The discovered direct addresses of this [`Socket`].
2035///
2036/// These are all the [`DirectAddr`]s that this [`Socket`] is aware of for itself.
2037/// They include all locally bound ones as well as those discovered by other mechanisms like
2038/// QAD.
2039#[derive(derive_more::Debug, Clone, Default)]
2040struct DiscoveredDirectAddrs {
2041    /// The last set of discovered direct addresses.
2042    addrs: Watchable<BTreeSet<DirectAddr>>,
2043
2044    /// The last time the direct addresses were updated, even if there was no change.
2045    ///
2046    /// This is only ever None at startup.
2047    updated_at: Arc<RwLock<Option<Instant>>>,
2048}
2049
2050impl DiscoveredDirectAddrs {
2051    /// Updates the direct addresses, returns `true` if they changed, `false` if not.
2052    fn update(&self, addrs: BTreeSet<DirectAddr>) -> bool {
2053        *self.updated_at.write().expect("poisoned") = Some(Instant::now());
2054        let updated = self.addrs.set(addrs).is_ok();
2055        if updated {
2056            event!(
2057                target: "iroh::_events::direct_addrs",
2058                Level::DEBUG,
2059                addrs = ?self.addrs.get(),
2060            );
2061        }
2062        updated
2063    }
2064
2065    fn sockaddrs(&self) -> impl Iterator<Item = SocketAddr> {
2066        self.addrs.get().into_iter().map(|da| da.addr)
2067    }
2068}
2069
2070/// A *direct address* on which an iroh-endpoint might be contactable.
2071///
2072/// Direct addresses are UDP socket addresses on which an iroh endpoint could potentially be
2073/// contacted.  These can come from various sources depending on the network topology of the
2074/// iroh endpoint, see [`DirectAddrType`] for the several kinds of sources.
2075///
2076/// This is essentially a combination of our local addresses combined with any reflexive
2077/// transport addresses we discovered using QAD.
2078#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
2079pub struct DirectAddr {
2080    /// The address.
2081    pub addr: SocketAddr,
2082    /// The origin of this direct address.
2083    pub typ: DirectAddrType,
2084}
2085
2086/// The type of direct address.
2087///
2088/// These are the various sources or origins from which an iroh endpoint might have found a
2089/// possible [`DirectAddr`].
2090#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
2091#[non_exhaustive]
2092pub enum DirectAddrType {
2093    /// Not yet determined..
2094    Unknown,
2095    /// A locally bound socket address.
2096    Local,
2097    /// Public internet address discovered via QAD.
2098    ///
2099    /// When possible an iroh endpoint will perform QAD to discover which is the address
2100    /// from which it sends data on the public internet.  This can be different from locally
2101    /// bound addresses when the endpoint is on a local network which performs NAT or similar.
2102    Qad,
2103    /// An address assigned by the router using port mapping.
2104    ///
2105    /// When possible an iroh endpoint will request a port mapping from the local router to
2106    /// get a publicly routable direct address.
2107    Portmapped,
2108    /// Hard NAT: QAD'ed IPv4 address + local fixed port.
2109    ///
2110    /// It is possible to configure iroh to bound to a specific port and independently
2111    /// configure the router to forward this port to the iroh endpoint.  This indicates a
2112    /// situation like this, which still uses QAD to discover the public address.
2113    Qad4LocalPort,
2114    /// An address explicitly provided by the user via configuration.
2115    Config,
2116}
2117
2118impl Display for DirectAddrType {
2119    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2120        match self {
2121            DirectAddrType::Unknown => write!(f, "?"),
2122            DirectAddrType::Local => write!(f, "local"),
2123            DirectAddrType::Qad => write!(f, "qad"),
2124            DirectAddrType::Portmapped => write!(f, "portmap"),
2125            DirectAddrType::Qad4LocalPort => write!(f, "qad4localport"),
2126            DirectAddrType::Config => write!(f, "config"),
2127        }
2128    }
2129}
2130
2131#[cfg(all(test, with_crypto_provider))]
2132mod tests {
2133    use std::{net::SocketAddrV4, sync::Arc, time::Duration};
2134
2135    use data_encoding::HEXLOWER;
2136    use iroh_base::{EndpointAddr, EndpointId, TransportAddr};
2137    use iroh_relay::tls::{CaTlsConfig, default_provider};
2138    use n0_error::{Result, StackResultExt, StdResultExt};
2139    use n0_future::{MergeBounded, StreamExt, time};
2140    use n0_tracing_test::traced_test;
2141    use n0_watcher::Watcher;
2142    use rand::{CryptoRng, Rng, RngExt, SeedableRng};
2143    use tokio_util::task::AbortOnDropHandle;
2144    use tracing::{Instrument, error, info, info_span, instrument};
2145
2146    use super::Options;
2147    use crate::{
2148        Endpoint, SecretKey,
2149        address_lookup::memory::MemoryLookup,
2150        dns::DnsResolver,
2151        endpoint::{QuicTransportConfig, presets},
2152        socket::{
2153            EndpointInner, StaticConfig, TransportConfig,
2154            biased_rtt_path_selector::BiasedRttPathSelector,
2155            mapped_addrs::{EndpointIdMappedAddr, MappedAddr},
2156        },
2157        tls::{self, DEFAULT_MAX_TLS_TICKETS, misc::RustlsTokenKey},
2158    };
2159
2160    const ALPN: &[u8] = b"n0/test/1";
2161
2162    fn default_options(rng: &mut impl CryptoRng) -> Options {
2163        let crypto_provider = default_provider();
2164        let secret_key = SecretKey::from_bytes(&rng.random());
2165        let tls_config = tls::TlsConfig::new(
2166            secret_key.clone(),
2167            DEFAULT_MAX_TLS_TICKETS,
2168            crypto_provider.clone(),
2169        );
2170        let static_config = StaticConfig {
2171            server_config: tls_config.make_server_config(false).unwrap(),
2172            client_config: tls_config.make_client_config(false).unwrap(),
2173            tls_config,
2174            token_key: Arc::new(RustlsTokenKey::new(rng, &crypto_provider).unwrap()),
2175            token_store: Arc::new(noq::TokenMemoryCache::default()),
2176            transport_config: QuicTransportConfig::default(),
2177        };
2178        let server_config = static_config.create_server_config(vec![]);
2179        Options {
2180            transports: vec![
2181                TransportConfig::default_ipv4(),
2182                TransportConfig::default_ipv6(),
2183            ],
2184            secret_key,
2185            proxy_url: None,
2186            dns_resolver: DnsResolver::new(),
2187            server_config,
2188            tls_config: CaTlsConfig::default()
2189                .client_config(crypto_provider.clone())
2190                .unwrap(),
2191            #[cfg(any(test, feature = "test-utils"))]
2192            address_lookup_user_data: None,
2193            metrics: Default::default(),
2194            hooks: Default::default(),
2195            path_selector: Arc::new(BiasedRttPathSelector::default()),
2196            portmapper_config: Default::default(),
2197            net_report_config: Default::default(),
2198            static_config,
2199            configured_addrs: Default::default(),
2200        }
2201    }
2202
2203    #[instrument(skip_all, fields(me = %ep.id().fmt_short()))]
2204    async fn echo_receiver(ep: Endpoint, loss: ExpectedLoss) -> Result {
2205        info!("accepting conn");
2206        let conn = ep.accept().await.expect("no conn");
2207
2208        info!("accepting");
2209        let conn = conn.await.context("accepting")?;
2210        info!("accepting bi");
2211        let (mut send_bi, mut recv_bi) = conn.accept_bi().await.std_context("accept bi")?;
2212
2213        info!("reading");
2214        let val = recv_bi
2215            .read_to_end(usize::MAX)
2216            .await
2217            .std_context("read to end")?;
2218
2219        info!("replying");
2220        for chunk in val.chunks(12) {
2221            send_bi.write_all(chunk).await.std_context("write all")?;
2222        }
2223
2224        info!("finishing");
2225        send_bi.finish().std_context("finish")?;
2226
2227        let stats = conn.stats();
2228        info!("stats: {:#?}", stats);
2229        if matches!(loss, ExpectedLoss::AlmostNone) {
2230            for info in conn.paths().iter() {
2231                assert!(
2232                    info.stats().lost_packets < 10,
2233                    "[receiver] path {:?} should not loose many packets",
2234                    info.remote_addr()
2235                );
2236            }
2237        }
2238
2239        conn.closed().await;
2240        info!("closed");
2241        ep.inner()?.noq_endpoint().wait_idle().await;
2242        info!("idle");
2243
2244        Ok(())
2245    }
2246
2247    #[instrument(skip_all, fields(me = %ep.id().fmt_short()))]
2248    async fn echo_sender(
2249        ep: Endpoint,
2250        dest_id: EndpointId,
2251        msg: &[u8],
2252        loss: ExpectedLoss,
2253    ) -> Result {
2254        info!("connecting to {}", dest_id.fmt_short());
2255        let dest = EndpointAddr::new(dest_id);
2256        let conn = ep.connect(dest, ALPN).await?;
2257
2258        info!("opening bi");
2259        let (mut send_bi, mut recv_bi) = conn.open_bi().await.std_context("open bi")?;
2260
2261        info!("writing message");
2262        send_bi.write_all(msg).await.std_context("write all")?;
2263
2264        info!("finishing");
2265        send_bi.finish().std_context("finish")?;
2266
2267        info!("reading_to_end");
2268        let val = recv_bi
2269            .read_to_end(usize::MAX)
2270            .await
2271            .std_context("read to end")?;
2272        assert_eq!(
2273            val,
2274            msg,
2275            "[sender] expected {}, got {}",
2276            HEXLOWER.encode(msg),
2277            HEXLOWER.encode(&val)
2278        );
2279
2280        let stats = conn.stats();
2281        info!("stats: {:#?}", stats);
2282        if matches!(loss, ExpectedLoss::AlmostNone) {
2283            for info in conn.paths().iter() {
2284                assert!(
2285                    info.stats().lost_packets < 10,
2286                    "[sender] path {:?} should not loose many packets",
2287                    info.remote_addr()
2288                );
2289            }
2290        }
2291
2292        conn.close(0u32.into(), b"done");
2293        info!("closed");
2294        ep.inner()?.noq_endpoint().wait_idle().await;
2295        info!("idle");
2296        Ok(())
2297    }
2298
2299    #[derive(Debug, Copy, Clone)]
2300    enum ExpectedLoss {
2301        AlmostNone,
2302        YeahSure,
2303    }
2304
2305    /// Runs a roundtrip between the [`echo_sender`] and [`echo_receiver`].
2306    async fn run_roundtrip(
2307        sender: Endpoint,
2308        receiver: Endpoint,
2309        payload: &[u8],
2310        loss: ExpectedLoss,
2311    ) -> Result<()> {
2312        tokio::time::timeout(Duration::from_secs(20), async move {
2313            let send_endpoint_id = sender.id();
2314            let recv_endpoint_id = receiver.id();
2315            info!("\nroundtrip: {send_endpoint_id:#} -> {recv_endpoint_id:#}");
2316
2317            let receiver_task = AbortOnDropHandle::new(tokio::spawn(echo_receiver(receiver, loss)));
2318            let sender_res = echo_sender(sender, recv_endpoint_id, payload, loss).await;
2319            let sender_is_err = match sender_res {
2320                Ok(()) => false,
2321                Err(err) => {
2322                    error!("[sender] Error:\n{err:#?}");
2323                    true
2324                }
2325            };
2326            let receiver_is_err = match receiver_task.await {
2327                Ok(Ok(())) => false,
2328                Ok(Err(err)) => {
2329                    error!("[receiver] Error:\n{err:#?}");
2330                    true
2331                }
2332                Err(joinerr) => {
2333                    if joinerr.is_panic() {
2334                        std::panic::resume_unwind(joinerr.into_panic());
2335                    } else {
2336                        error!("[receiver] Error:\n{joinerr:#?}");
2337                    }
2338                    true
2339                }
2340            };
2341            if sender_is_err || receiver_is_err {
2342                panic!("Sender or receiver errored");
2343            }
2344        })
2345        .await
2346        .std_context("timeout")?;
2347        Ok(())
2348    }
2349
2350    /// Returns a pair of endpoints with a shared [`MemoryLookup`].
2351    ///
2352    /// The endpoints do not use a relay server but can connect to each other via local
2353    /// addresses.  Dialing by [`EndpointId`] is possible, and the addresses get updated even if
2354    /// the endpoints rebind.
2355    async fn endpoint_pair() -> (AbortOnDropHandle<()>, Endpoint, Endpoint) {
2356        let address_lookup = MemoryLookup::new();
2357        let ep1 = Endpoint::builder(presets::Minimal)
2358            .alpns(vec![ALPN.to_vec()])
2359            .address_lookup(address_lookup.clone())
2360            .bind()
2361            .await
2362            .unwrap();
2363        let ep2 = Endpoint::builder(presets::Minimal)
2364            .alpns(vec![ALPN.to_vec()])
2365            .address_lookup(address_lookup.clone())
2366            .bind()
2367            .await
2368            .unwrap();
2369        address_lookup.add_endpoint_info(ep1.addr());
2370        address_lookup.add_endpoint_info(ep2.addr());
2371
2372        let ep1_addr_stream = ep1.watch_addr().stream();
2373        let ep2_addr_stream = ep2.watch_addr().stream();
2374        let mut addr_stream = MergeBounded::from_iter([ep1_addr_stream, ep2_addr_stream]);
2375        let task = tokio::spawn(async move {
2376            while let Some(addr) = addr_stream.next().await {
2377                address_lookup.add_endpoint_info(addr);
2378            }
2379        });
2380
2381        (AbortOnDropHandle::new(task), ep1, ep2)
2382    }
2383
2384    #[tokio::test(flavor = "multi_thread")]
2385    #[traced_test]
2386    async fn test_two_devices_roundtrip_noq_small() -> Result {
2387        let (_guard, m1, m2) = endpoint_pair().await;
2388
2389        run_roundtrip(
2390            m1.clone(),
2391            m2.clone(),
2392            b"hello m1",
2393            ExpectedLoss::AlmostNone,
2394        )
2395        .await?;
2396        run_roundtrip(
2397            m2.clone(),
2398            m1.clone(),
2399            b"hello m2",
2400            ExpectedLoss::AlmostNone,
2401        )
2402        .await?;
2403        Ok(())
2404    }
2405
2406    #[tokio::test(flavor = "multi_thread")]
2407    #[traced_test]
2408    async fn test_two_devices_roundtrip_noq_large() -> Result {
2409        let (_guard, m1, m2) = endpoint_pair().await;
2410        let mut data = vec![0u8; 10 * 1024];
2411        let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(0u64);
2412        rng.fill_bytes(&mut data);
2413        run_roundtrip(m1.clone(), m2.clone(), &data, ExpectedLoss::AlmostNone).await?;
2414        run_roundtrip(m2.clone(), m1.clone(), &data, ExpectedLoss::AlmostNone).await?;
2415
2416        Ok(())
2417    }
2418
2419    // EADDRINUSE on the GitHub Android emulator persists past
2420    // `force_network_change()`, so the rebind fails and connect() never
2421    // wakes the connection driver. Passes locally.
2422    #[cfg_attr(
2423        target_os = "android",
2424        ignore = "rebind flakes against the GitHub Android emulator"
2425    )]
2426    #[tokio::test]
2427    #[traced_test]
2428    async fn test_regression_network_change_rebind_wakes_connection_driver() -> Result {
2429        let (_guard, m1, m2) = endpoint_pair().await;
2430
2431        println!("Net change");
2432        m1.inner()?.force_network_change(true).await;
2433        tokio::time::sleep(Duration::from_secs(1)).await; // wait for socket rebinding
2434
2435        let _handle = AbortOnDropHandle::new(tokio::spawn({
2436            let endpoint = m2.clone();
2437            async move {
2438                while let Some(incoming) = endpoint.accept().await {
2439                    println!("Incoming first conn!");
2440                    let conn = incoming.await.anyerr()?;
2441                    conn.closed().await;
2442                }
2443
2444                n0_error::Ok(())
2445            }
2446        }));
2447
2448        println!("first conn!");
2449        let conn = m1.connect(m2.addr(), ALPN).await?;
2450        println!("Closing first conn");
2451        conn.close(0u32.into(), b"bye lolz");
2452        conn.closed().await;
2453        println!("Closed first conn");
2454
2455        Ok(())
2456    }
2457
2458    fn offset(rng: &mut rand_chacha::ChaCha8Rng) -> Duration {
2459        let delay = rng.random_range(1..=5);
2460        Duration::from_millis(delay * 50)
2461    }
2462
2463    /// Same structure as `test_two_devices_roundtrip_noq`, but interrupts regularly
2464    /// with (simulated) network changes.
2465    /// Regular network changes to m1 only.
2466    #[tokio::test(flavor = "multi_thread")]
2467    #[traced_test]
2468    async fn test_two_devices_roundtrip_network_change_only_a() -> Result {
2469        let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(0u64);
2470        let (_guard, m1, m2) = endpoint_pair().await;
2471
2472        let _network_change_guard = {
2473            let m1 = m1.clone();
2474            let mut rng = rng.clone();
2475            let task = tokio::spawn(async move {
2476                loop {
2477                    info!("[m1] network change");
2478                    m1.inner()
2479                        .expect("haven't closed the endpoint yet")
2480                        .force_network_change(true)
2481                        .await;
2482                    time::sleep(offset(&mut rng)).await;
2483                }
2484            });
2485            AbortOnDropHandle::new(task)
2486        };
2487
2488        let mut data = vec![0u8; 10 * 1024];
2489        rng.fill_bytes(&mut data);
2490        run_roundtrip(m1.clone(), m2.clone(), &data, ExpectedLoss::YeahSure).await?;
2491        run_roundtrip(m2.clone(), m1.clone(), &data, ExpectedLoss::YeahSure).await?;
2492
2493        Ok(())
2494    }
2495
2496    /// Regular network changes to both m1 and m2.
2497    #[tokio::test(flavor = "multi_thread")]
2498    #[traced_test]
2499    async fn test_two_devices_roundtrip_network_change_a_and_b() -> Result {
2500        let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(0u64);
2501        let (_guard, m1, m2) = endpoint_pair().await;
2502
2503        let _network_change_guard = {
2504            let m1 = m1.clone();
2505            let m2 = m2.clone();
2506            let mut rng = rng.clone();
2507            let task = tokio::spawn(async move {
2508                info!("-- [m1] network change");
2509                m1.inner()
2510                    .expect("haven't closed the endpoint yet")
2511                    .force_network_change(true)
2512                    .await;
2513                info!("-- [m2] network change");
2514                m2.inner()
2515                    .expect("haven't closed the endpoint yet")
2516                    .force_network_change(true)
2517                    .await;
2518                time::sleep(offset(&mut rng)).await;
2519            });
2520            AbortOnDropHandle::new(task)
2521        };
2522
2523        let mut data = vec![0u8; 10 * 1024];
2524        rng.fill_bytes(&mut data);
2525        run_roundtrip(m1.clone(), m2.clone(), &data, ExpectedLoss::YeahSure).await?;
2526        run_roundtrip(m2.clone(), m1.clone(), &data, ExpectedLoss::YeahSure).await?;
2527
2528        Ok(())
2529    }
2530
2531    #[tokio::test(flavor = "multi_thread")]
2532    #[traced_test]
2533    async fn test_two_devices_setup_teardown() -> Result {
2534        for i in 0..10 {
2535            info!("-- round {i}");
2536            info!("setting up stack");
2537            let (_guard, m1, m2) = endpoint_pair().await;
2538
2539            info!("closing endpoints");
2540            let sock1 = m1.inner()?;
2541            let sock2 = m2.inner()?;
2542            m1.close().await;
2543            m2.close().await;
2544
2545            assert!(sock1.is_closed());
2546            assert!(sock2.is_closed());
2547        }
2548        Ok(())
2549    }
2550
2551    #[tokio::test]
2552    #[traced_test]
2553    async fn test_direct_addresses() {
2554        let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(0u64);
2555        let sock = EndpointInner::bind(default_options(&mut rng))
2556            .await
2557            .unwrap();
2558
2559        // See if we can get endpoints.
2560        let eps0 = sock.ip_addrs().get();
2561        info!("{eps0:?}");
2562        assert!(!eps0.is_empty());
2563
2564        // Getting the endpoints again immediately should give the same results.
2565        let eps1 = sock.ip_addrs().get();
2566        info!("{eps1:?}");
2567        assert_eq!(eps0, eps1);
2568    }
2569
2570    /// Creates a new [`noq::Endpoint`] hooked up to a [`Socket`].
2571    ///
2572    /// This is without involving [`crate::endpoint::Endpoint`].  The socket will accept
2573    /// connections using [`ALPN`].
2574    ///
2575    /// Use [`socket_connect`] to establish connections.
2576    #[instrument(name = "ep", skip_all, fields(me = %secret_key.public().fmt_short()))]
2577    async fn socket_ep(secret_key: SecretKey) -> Result<EndpointInner> {
2578        let crypto_provider = default_provider();
2579        let tls_config = tls::TlsConfig::new(
2580            secret_key.clone(),
2581            DEFAULT_MAX_TLS_TICKETS,
2582            crypto_provider.clone(),
2583        );
2584        let keylog = true;
2585        let static_config = StaticConfig {
2586            server_config: tls_config.make_server_config(keylog).unwrap(),
2587            client_config: tls_config.make_client_config(keylog).unwrap(),
2588            tls_config,
2589            token_key: Arc::new(RustlsTokenKey::new(&mut rand::rng(), &crypto_provider).unwrap()),
2590            token_store: Arc::new(noq::TokenMemoryCache::default()),
2591            transport_config: QuicTransportConfig::default(),
2592        };
2593        let server_config = static_config.create_server_config(vec![ALPN.to_vec()]);
2594
2595        let dns_resolver = DnsResolver::new();
2596        let opts = Options {
2597            transports: vec![
2598                TransportConfig::default_ipv4(),
2599                TransportConfig::default_ipv6(),
2600            ],
2601            secret_key: secret_key.clone(),
2602            address_lookup_user_data: None,
2603            dns_resolver,
2604            proxy_url: None,
2605            server_config,
2606            tls_config: CaTlsConfig::default()
2607                .client_config(crypto_provider.clone())
2608                .unwrap(),
2609            metrics: Default::default(),
2610            hooks: Default::default(),
2611            path_selector: Arc::new(BiasedRttPathSelector::default()),
2612            portmapper_config: Default::default(),
2613            net_report_config: Default::default(),
2614            static_config,
2615            configured_addrs: Default::default(),
2616        };
2617        let sock = EndpointInner::bind(opts).await?;
2618        Ok(sock)
2619    }
2620
2621    /// Connects from `ep` returned by [`socket_ep`] to the `endpoint_id`.
2622    ///
2623    /// Uses [`ALPN`], `endpoint_id`, must match `addr`.
2624    #[instrument(name = "connect", skip_all, fields(me = %ep_secret_key.public().fmt_short()))]
2625    async fn socket_connect(
2626        ep: noq::Endpoint,
2627        ep_secret_key: SecretKey,
2628        addr: EndpointIdMappedAddr,
2629        endpoint_id: EndpointId,
2630    ) -> Result<noq::Connection> {
2631        // Endpoint::connect sets this, do the same to have similar behaviour.
2632        let mut transport_config = noq::TransportConfig::default();
2633        transport_config.server_handshake_migration(true);
2634        transport_config.keep_alive_interval(Some(Duration::from_secs(1)));
2635
2636        socket_connect_with_transport_config(
2637            ep,
2638            ep_secret_key,
2639            addr,
2640            endpoint_id,
2641            Arc::new(transport_config),
2642        )
2643        .await
2644    }
2645
2646    /// Connects from `ep` returned by [`socket_ep`] to the `endpoint_id`.
2647    ///
2648    /// This version allows customising the transport config.
2649    ///
2650    /// Uses [`ALPN`], `endpoint_id`, must match `addr`.
2651    #[instrument(name = "connect", skip_all, fields(me = %ep_secret_key.public().fmt_short()))]
2652    async fn socket_connect_with_transport_config(
2653        ep: noq::Endpoint,
2654        ep_secret_key: SecretKey,
2655        mapped_addr: EndpointIdMappedAddr,
2656        endpoint_id: EndpointId,
2657        transport_config: Arc<noq::TransportConfig>,
2658    ) -> Result<noq::Connection> {
2659        let mut quic_client_config = tls::TlsConfig::new(
2660            ep_secret_key.clone(),
2661            DEFAULT_MAX_TLS_TICKETS,
2662            default_provider(),
2663        )
2664        .make_client_config(true)?;
2665        quic_client_config.set_alpn_protocols(vec![ALPN.to_vec()]);
2666        let mut client_config = noq::ClientConfig::new(Arc::new(quic_client_config));
2667        client_config.transport_config(transport_config);
2668        let connect = ep
2669            .connect_with(
2670                client_config,
2671                mapped_addr.private_socket_addr(),
2672                &tls::name::encode(endpoint_id),
2673            )
2674            .std_context("connect")?;
2675        let connection = connect.await.anyerr()?;
2676        Ok(connection)
2677    }
2678
2679    #[tokio::test]
2680    #[traced_test]
2681    async fn test_try_send_no_send_addr() {
2682        // Regression test: if there is no send_addr we should keep being able to use the
2683        // Endpoint.
2684
2685        let secret_key_1 = SecretKey::from_bytes(&[1u8; 32]);
2686        let secret_key_2 = SecretKey::from_bytes(&[2u8; 32]);
2687        let endpoint_id_2 = secret_key_2.public();
2688        let secret_key_missing_endpoint = SecretKey::from_bytes(&[255u8; 32]);
2689        let endpoint_id_missing_endpoint = secret_key_missing_endpoint.public();
2690
2691        let sock_1 = socket_ep(secret_key_1.clone()).await.unwrap();
2692
2693        // Generate an address not present in the RemoteMap.
2694        let bad_addr = EndpointIdMappedAddr::generate();
2695
2696        // 500ms is rather fast here.  Running this locally it should always be the correct
2697        // timeout.  If this is too slow however the test will not become flaky as we are
2698        // expecting the timeout, we might just get the timeout for the wrong reason.  But
2699        // this speeds up the test.
2700        let res = tokio::time::timeout(
2701            Duration::from_millis(500),
2702            socket_connect(
2703                sock_1.noq_endpoint().clone(),
2704                secret_key_1.clone(),
2705                bad_addr,
2706                endpoint_id_missing_endpoint,
2707            ),
2708        )
2709        .await;
2710        assert!(res.is_err(), "expecting timeout");
2711
2712        // Now check we can still create another connection with this endpoint.
2713        let sock_2 = socket_ep(secret_key_2.clone()).await.unwrap();
2714
2715        // This needs an accept task
2716        let accept_task = tokio::spawn({
2717            async fn accept(ep: noq::Endpoint) -> Result<()> {
2718                let incoming = ep.accept().await.std_context("no incoming")?;
2719                let _conn = incoming
2720                    .accept()
2721                    .std_context("accept")?
2722                    .await
2723                    .std_context("accepting")?;
2724
2725                // Keep this connection alive for a while
2726                tokio::time::sleep(Duration::from_secs(10)).await;
2727                info!("accept finished");
2728                Ok(())
2729            }
2730            let ep = sock_2.noq_endpoint().clone();
2731            async move {
2732                if let Err(err) = accept(ep).await {
2733                    error!("{err:#}");
2734                }
2735            }
2736            .instrument(info_span!("ep2.accept, me = endpoint_id_2.fmt_short()"))
2737        });
2738        let _accept_task = AbortOnDropHandle::new(accept_task);
2739
2740        let addrs = sock_2
2741            .ip_addrs()
2742            .get()
2743            .into_iter()
2744            .map(|x| TransportAddr::Ip(x.addr));
2745        let endpoint_addr_2 = EndpointAddr::from_parts(endpoint_id_2, addrs);
2746        let addr = sock_1
2747            .resolve_remote(endpoint_addr_2)
2748            .await
2749            .unwrap()
2750            .unwrap();
2751        let res = tokio::time::timeout(
2752            Duration::from_secs(10),
2753            socket_connect(
2754                sock_1.noq_endpoint().clone(),
2755                secret_key_1.clone(),
2756                addr,
2757                endpoint_id_2,
2758            ),
2759        )
2760        .await
2761        .expect("timeout while connecting");
2762
2763        // aka assert!(res.is_ok()) but with nicer error reporting.
2764        res.unwrap();
2765
2766        // TODO: Now check if we can connect to a repaired ep_3, but we can't modify that
2767        // much internal state for now.
2768    }
2769
2770    #[tokio::test]
2771    #[traced_test]
2772    async fn test_try_send_no_udp_addr_or_relay_url() {
2773        // This specifically tests the `if udp_addr.is_none() && relay_url.is_none()`
2774        // behaviour of Socket::try_send.
2775
2776        let secret_key_1 = SecretKey::from_bytes(&[1u8; 32]);
2777        let secret_key_2 = SecretKey::from_bytes(&[2u8; 32]);
2778        let endpoint_id_2 = secret_key_2.public();
2779
2780        let sock_1 = socket_ep(secret_key_1.clone()).await.unwrap();
2781        let sock_2 = socket_ep(secret_key_2.clone()).await.unwrap();
2782        let ep_2 = sock_2.noq_endpoint().clone();
2783
2784        // We need a task to accept the connection.
2785        let accept_task = tokio::spawn({
2786            async fn accept(ep: noq::Endpoint) -> Result<()> {
2787                let incoming = ep.accept().await.std_context("no incoming")?;
2788                let conn = incoming
2789                    .accept()
2790                    .std_context("accept")?
2791                    .await
2792                    .std_context("connecting")?;
2793                let mut stream = conn.accept_uni().await.std_context("accept uni")?;
2794                stream
2795                    .read_to_end(1 << 16)
2796                    .await
2797                    .std_context("read to end")?;
2798                info!("accept finished");
2799                Ok(())
2800            }
2801            async move {
2802                if let Err(err) = accept(ep_2).await {
2803                    error!("{err:#}");
2804                }
2805            }
2806            .instrument(info_span!("ep2.accept", me = %endpoint_id_2.fmt_short()))
2807        });
2808        let _accept_task = AbortOnDropHandle::new(accept_task);
2809
2810        // Add an entry in the RemoteMap of ep_1 with an invalid socket address
2811        let empty_addr_2 = EndpointAddr::from_parts(
2812            endpoint_id_2,
2813            [TransportAddr::Ip(
2814                // Reserved IP range for documentation (unreachable)
2815                SocketAddrV4::new([192, 0, 2, 1].into(), 12345).into(),
2816            )],
2817        );
2818        let addr_2 = sock_1.resolve_remote(empty_addr_2).await.unwrap().unwrap();
2819
2820        // Set a low max_idle_timeout so noq gives up on this quickly and our test does
2821        // not take forever.  You need to check the log output to verify this is really
2822        // triggering the correct error.
2823        // In test_try_send_no_send_addr() above you may have noticed we used
2824        // tokio::time::timeout() on the connection attempt instead.  Here however we want
2825        // Noq itself to have fully given up on the connection attempt because we will
2826        // later connect to **the same** endpoint.  If Noq did not give up on the connection
2827        // we'd close it on drop, and the retransmits of the close packets would interfere
2828        // with the next handshake, closing it during the handshake.  This makes the test a
2829        // little slower though.
2830        let mut transport_config = noq::TransportConfig::default();
2831        transport_config.server_handshake_migration(true);
2832        transport_config.max_idle_timeout(Some(Duration::from_millis(200).try_into().unwrap()));
2833        let res = socket_connect_with_transport_config(
2834            sock_1.noq_endpoint().clone(),
2835            secret_key_1.clone(),
2836            addr_2,
2837            endpoint_id_2,
2838            Arc::new(transport_config),
2839        )
2840        .await;
2841        assert!(res.is_err(), "expected timeout");
2842        info!("first connect timed out as expected");
2843
2844        // Provide correct addressing information
2845        let correct_addr_2 = EndpointAddr::from_parts(
2846            endpoint_id_2,
2847            sock_2
2848                .ip_addrs()
2849                .get()
2850                .into_iter()
2851                .map(|x| TransportAddr::Ip(x.addr)),
2852        );
2853        let addr_2a = sock_1
2854            .resolve_remote(correct_addr_2)
2855            .await
2856            .unwrap()
2857            .unwrap();
2858        assert_eq!(addr_2, addr_2a);
2859
2860        // We can now connect
2861        tokio::time::timeout(Duration::from_secs(10), async move {
2862            info!("establishing new connection");
2863            let conn = socket_connect(
2864                sock_1.noq_endpoint().clone(),
2865                secret_key_1.clone(),
2866                addr_2,
2867                endpoint_id_2,
2868            )
2869            .await
2870            .unwrap();
2871            info!("have connection");
2872            let mut stream = conn.open_uni().await.unwrap();
2873            stream.write_all(b"hello").await.unwrap();
2874            stream.finish().unwrap();
2875            stream.stopped().await.unwrap();
2876            info!("finished stream");
2877        })
2878        .await
2879        .expect("connection timed out");
2880
2881        // TODO: could remove the addresses again, send, add it back and see it recover.
2882        // But we don't have that much private access to the RemoteMap.  This will do for now.
2883    }
2884}