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