iroh/
endpoint.rs

1//! The [`Endpoint`] allows establishing connections to other iroh endpoints.
2//!
3//! The [`Endpoint`] is the main API interface to manage a local iroh endpoint.  It allows
4//! connecting to and accepting connections from other endpoints.  See the [module docs] for
5//! more details on how iroh connections work.
6//!
7//! The main items in this module are:
8//!
9//! - [`Endpoint`] to establish iroh connections with other endpoints.
10//! - [`Builder`] to create an [`Endpoint`].
11//!
12//! [module docs]: crate
13
14use std::{collections::BTreeSet, net::SocketAddr, pin::Pin, sync::Arc};
15
16#[cfg(not(wasm_browser))]
17use ipnet::{Ipv4Net, Ipv6Net};
18use iroh_base::{EndpointAddr, EndpointId, RelayUrl, SecretKey, TransportAddr};
19use iroh_relay::{RelayConfig, RelayMap, tls::CaTlsConfig};
20#[cfg(not(wasm_browser))]
21use n0_error::bail;
22use n0_error::{AnyError, e, ensure, stack_error};
23use n0_watcher::Watcher;
24use pin_project::pin_project;
25use tokio_util::sync::WaitForCancellationFutureOwned;
26use tracing::{Instrument, Span, debug, event, instrument, warn};
27use url::Url;
28
29#[cfg(feature = "unstable-custom-transports")]
30pub mod transports {
31    //! Types for defining custom transports and path selectors.
32    //!
33    //! <div class="warning">
34    //!
35    //! These items are unstable and gated behind the `unstable-custom-transport` feature.
36    //! They are not covered by semantic versioning guarantees and may change in any release
37    //! without a major version bump.
38    //!
39    //! </div>
40
41    pub use super::socket::{
42        remote_map::{PathSelection, PathSelectionContext, PathSelectionData, PathSelector},
43        transports::{
44            Addr, AddrKind, FourTuple, RecvInfo, Transmit,
45            custom::{CustomEndpoint, CustomSender, CustomTransport},
46        },
47    };
48}
49
50use self::hooks::EndpointHooksList;
51pub use super::socket::{
52    BindError, DirectAddr, DirectAddrType,
53    remote_map::{
54        Path, PathEvent, PathEventStream, PathList, PathListIter, PathListStream, RemoteInfo,
55        TransportAddrInfo, TransportAddrUsage,
56    },
57    transports::LocalTransportAddr,
58};
59#[cfg(wasm_browser)]
60use crate::address_lookup::PkarrResolver;
61#[cfg(not(wasm_browser))]
62use crate::dns::DnsResolver;
63#[cfg(feature = "unstable-custom-transports")]
64use crate::endpoint::transports::CustomTransport;
65#[cfg(feature = "unstable-net-report")]
66use crate::net_report::Report as NetReport;
67pub use crate::tls::TlsConfigError;
68use crate::{
69    address_lookup::{
70        AddrFilter, AddressLookupBuilder, AddressLookupFailed, AddressLookupServices,
71        DynAddressLookupBuilder, UserData,
72    },
73    endpoint::presets::Preset,
74    metrics::EndpointMetrics,
75    socket::{
76        self, EndpointInner, RemoteStateActorStoppedError, StaticConfig,
77        biased_rtt_path_selector::BiasedRttPathSelector,
78        mapped_addrs::MappedAddr,
79        remote_map::PathSelector,
80        transports::{RelayConnectionFailure, RelayConnectionState},
81    },
82    tls::{self, DEFAULT_MAX_TLS_TICKETS, misc::RustlsTokenKey},
83};
84
85#[cfg(not(wasm_browser))]
86mod bind;
87mod connection;
88pub(crate) mod hooks;
89pub mod presets;
90pub(crate) mod quic;
91
92#[cfg(not(wasm_browser))]
93pub use bind::{BindOpts, InvalidSocketAddr, ToSocketAddr};
94pub use hooks::{AfterHandshakeOutcome, BeforeConnectOutcome, EndpointHooks};
95
96#[cfg(feature = "qlog")]
97pub use self::quic::{QlogConfig, QlogFactory, QlogFileFactory};
98pub use self::{
99    connection::{
100        Accept, Accepting, AlpnError, AuthenticationError, Connecting, ConnectingError, Connection,
101        ConnectionState, HandshakeCompleted, Incoming, IncomingAddr, IncomingZeroRtt,
102        IncomingZeroRttConnection, OutgoingZeroRtt, OutgoingZeroRttConnection,
103        RemoteEndpointIdError, RetryError, WeakConnectionHandle, ZeroRttStatus,
104    },
105    quic::{
106        AcceptBi, AcceptUni, AckFrequencyConfig, ApplicationClose, Chunk, Closed, ClosedStream,
107        ConnectionClose, ConnectionError, ConnectionStats, Controller, ControllerFactory,
108        ControllerMetrics, CryptoError, DecryptedInitial, Dir, ExportKeyingMaterialError,
109        FrameStats, FrameType, HandshakeTokenKey, HeaderKey, IdleTimeout, IncomingAlpns, Keys,
110        MtuDiscoveryConfig, OpenBi, OpenUni, PacketKey, PathId, PathStats, QuicConnectError,
111        QuicTransportConfig, QuicTransportConfigBuilder, ReadDatagram, ReadError, ReadExactError,
112        ReadManyDatagrams, ReadToEndError, RecvStream, ResetError, RttEstimator, SendDatagram,
113        SendDatagramError, SendStream, ServerConfig, ServerConfigBuilder, Side, StoppedError,
114        StreamId, TimeSource, TokenLog, TokenReuseError, TransportError, TransportErrorCode,
115        TransportParameters, UdpStats, UnorderedRecvStream, UnsupportedVersion,
116        ValidationTokenConfig, VarInt, VarIntBoundsExceeded, WriteError,
117    },
118};
119#[cfg(not(wasm_browser))]
120use crate::socket::transports::IpConfig;
121use crate::socket::transports::TransportConfig;
122pub use crate::{net_report::NetReportConfig, portmapper::PortmapperConfig};
123
124/// Builder for [`Endpoint`].
125///
126/// By default the endpoint will generate a new random [`SecretKey`], which will result in a
127/// new [`EndpointId`].
128///
129/// To create the [`Endpoint`] call [`Builder::bind`].
130#[derive(Debug)]
131pub struct Builder {
132    secret_key: Option<SecretKey>,
133    alpn_protocols: Vec<Vec<u8>>,
134    transport_config: QuicTransportConfig,
135    keylog: bool,
136    address_lookup: Vec<Box<dyn DynAddressLookupBuilder>>,
137    address_lookup_user_data: Option<UserData>,
138    /// Default address filter applied to all address lookup services added via
139    /// [`Builder::address_lookup`].
140    addr_filter: Option<AddrFilter>,
141    proxy_url: Option<Url>,
142    ca_tls_config: Option<CaTlsConfig>,
143    #[cfg(not(wasm_browser))]
144    dns_resolver: Option<DnsResolver>,
145    transports: Vec<TransportConfig>,
146    max_tls_tickets: usize,
147    hooks: EndpointHooksList,
148    path_selector: Arc<dyn PathSelector>,
149    portmapper_config: PortmapperConfig,
150    net_report_config: NetReportConfig,
151    crypto_provider: Option<Arc<rustls::crypto::CryptoProvider>>,
152    configured_addrs: BTreeSet<SocketAddr>,
153}
154
155impl From<RelayMode> for Option<TransportConfig> {
156    fn from(mode: RelayMode) -> Self {
157        match mode {
158            RelayMode::Disabled => None,
159            RelayMode::Default => Some(TransportConfig::Relay {
160                relay_map: mode.relay_map(),
161                is_user_defined: true,
162            }),
163            RelayMode::Staging => Some(TransportConfig::Relay {
164                relay_map: mode.relay_map(),
165                is_user_defined: true,
166            }),
167            RelayMode::Custom(relay_map) => Some(TransportConfig::Relay {
168                relay_map,
169                is_user_defined: true,
170            }),
171        }
172    }
173}
174
175impl Builder {
176    // The ordering of public methods is reflected directly in the documentation.  This is
177    // roughly ordered by what is most commonly needed by users.
178
179    /// Creates a new [`Builder`] using the given [`Preset`].
180    ///
181    /// See [`presets`] for more.
182    pub fn new(preset: impl Preset) -> Self {
183        Self::empty().preset(preset)
184    }
185
186    /// Applies the given [`Preset`].
187    pub fn preset(mut self, preset: impl Preset) -> Self {
188        self = preset.apply(self);
189        self
190    }
191
192    /// Creates an empty builder with no address lookup services, and [`RelayMode::Disabled`].
193    pub fn empty() -> Self {
194        let transports = vec![
195            #[cfg(not(wasm_browser))]
196            TransportConfig::default_ipv4(),
197            #[cfg(not(wasm_browser))]
198            TransportConfig::default_ipv6(),
199        ];
200
201        Self {
202            secret_key: Default::default(),
203            alpn_protocols: Default::default(),
204            transport_config: QuicTransportConfig::default(),
205            keylog: Default::default(),
206            address_lookup: Default::default(),
207            address_lookup_user_data: Default::default(),
208            addr_filter: None,
209            proxy_url: None,
210            ca_tls_config: None,
211            #[cfg(not(wasm_browser))]
212            dns_resolver: None,
213            max_tls_tickets: DEFAULT_MAX_TLS_TICKETS,
214            transports,
215            hooks: Default::default(),
216            path_selector: Arc::new(BiasedRttPathSelector::default()),
217            portmapper_config: Default::default(),
218            net_report_config: Default::default(),
219            crypto_provider: None,
220            configured_addrs: Default::default(),
221        }
222    }
223
224    // # The final constructor that everyone needs.
225
226    /// Binds the endpoint.
227    #[instrument(name = "endpoint", skip_all, fields(id))]
228    pub async fn bind(self) -> Result<Endpoint, BindError> {
229        let secret_key = self.secret_key.unwrap_or_else(SecretKey::generate);
230        tracing::Span::current().record(
231            "id",
232            tracing::field::display(secret_key.public().fmt_short()),
233        );
234
235        let crypto_provider = self
236            .crypto_provider
237            .ok_or_else(|| e!(BindError::InvalidCryptoProvider))?;
238        let token_key = Arc::new(
239            RustlsTokenKey::new(&mut rand::rng(), &crypto_provider)
240                .ok_or_else(|| e!(BindError::InvalidCryptoProvider))?,
241        );
242        let tls_config = tls::TlsConfig::new(
243            secret_key.clone(),
244            self.max_tls_tickets,
245            crypto_provider.clone(),
246        );
247        let static_config = StaticConfig {
248            server_config: tls_config.make_server_config(self.keylog)?,
249            client_config: tls_config.make_client_config(self.keylog)?,
250            tls_config,
251            transport_config: self.transport_config.clone(),
252            token_key,
253            token_store: Arc::new(noq::TokenMemoryCache::default()),
254        };
255        let server_config = static_config.create_server_config(self.alpn_protocols);
256        let metrics = EndpointMetrics::default();
257        let tls_config = self
258            .ca_tls_config
259            .unwrap_or_default()
260            .client_config(crypto_provider)
261            .map_err(|err| e!(BindError::InvalidCaRootConfig, err))?;
262
263        #[cfg(not(wasm_browser))]
264        let dns_resolver = self.dns_resolver.unwrap_or_else(|| {
265            DnsResolver::builder()
266                .with_system_defaults()
267                .tls_client_config(tls_config.clone())
268                .build()
269        });
270
271        let sock_opts = socket::Options {
272            transports: self.transports,
273            secret_key,
274            address_lookup_user_data: self.address_lookup_user_data,
275            proxy_url: self.proxy_url,
276            #[cfg(not(wasm_browser))]
277            dns_resolver,
278            server_config,
279            tls_config,
280            metrics,
281            hooks: self.hooks,
282            path_selector: self.path_selector,
283            portmapper_config: self.portmapper_config,
284            net_report_config: self.net_report_config,
285            static_config,
286            configured_addrs: self.configured_addrs,
287        };
288
289        let inner = socket::EndpointInner::bind(sock_opts)
290            .instrument(Span::current())
291            .await?;
292        debug!(
293            id = %inner.static_config.tls_config.secret_key.public(),
294            iroh_version = %env!("CARGO_PKG_VERSION"),
295            "iroh endpoint bound"
296        );
297
298        let ep = Endpoint {
299            inner: Arc::new(inner),
300        };
301
302        // Add Address Lookup mechanisms
303        let address_lookup = ep.address_lookup().expect("just created the endpoint");
304        if let Some(filter) = self.addr_filter {
305            address_lookup.set_addr_filter(filter);
306        }
307        for create_service in self.address_lookup {
308            let service = create_service.into_address_lookup(&ep)?;
309            address_lookup.add_boxed(service);
310        }
311
312        Ok(ep)
313    }
314
315    // # The very common methods everyone basically needs.
316
317    /// Binds an IP socket at the provided socket address.
318    ///
319    /// This is an advanced API to tightly control the sockets used by the endpoint. Most
320    /// uses do not need to explicitly bind sockets.
321    ///
322    /// # Warning
323    ///
324    /// - The builder always comes pre-configured with an IPv4 socket to be bound on the
325    ///   *unspecified* address: `0.0.0.0`. This is the equivalent of using `INADDR_ANY`
326    ///   special bind address and results in a socket listening on *all* interfaces
327    ///   available.
328    ///
329    /// - Likewise the builder always comes pre-configured with an IPv6 socket to be bound
330    ///   on the *unspecified* address: `[::]`. This bind is allowed to fail however.
331    ///
332    /// - Adding a bind address removes the pre-configured unspecified bind address for this
333    ///   address family. Use [`Self::bind_addr_with_opts`] to bind additional addresses without
334    ///   replacing the default bind address.
335    ///
336    /// - This should be called at most once for each address family: once for IPv4 and/or
337    ///   once for IPv6. Calling it multiple times for the same address family will result
338    ///   in undefined routing behaviour. To bind multiple sockets of the same address
339    ///   family, use [`Self::bind_addr_with_opts`].
340    ///
341    /// # Description
342    ///
343    /// Requests a socket to be bound on a specific address, with an implied netmask of
344    /// `/0`. This allows restricting binding to only one network interface for a given
345    /// address family.
346    ///
347    /// If the port specified is already in use, binding the endpoint will fail. Using
348    /// port `0` in the socket address assigns a random free port.
349    ///
350    /// # Example
351    ///
352    /// ```no_run
353    /// # #[cfg(with_crypto_provider)]
354    /// # {
355    /// # #[tokio::main]
356    /// # async fn main() -> n0_error::Result<()> {
357    /// # use iroh::{Endpoint, endpoint::presets};
358    /// let endpoint = Endpoint::builder(presets::N0)
359    ///     .clear_ip_transports()
360    ///     .bind_addr("127.0.0.1:0")?
361    ///     .bind_addr("[::1]:0")?
362    ///     .bind()
363    ///     .await?;
364    /// # Ok(()) }
365    /// # }
366    /// ```
367    #[cfg(not(wasm_browser))]
368    pub fn bind_addr<A>(self, addr: A) -> Result<Self, InvalidSocketAddr>
369    where
370        A: ToSocketAddr,
371        <A as ToSocketAddr>::Err: Into<InvalidSocketAddr>,
372    {
373        self.bind_addr_with_opts(addr, BindOpts::default())
374    }
375
376    /// Binds an IP socket at the provided socket address.
377    ///
378    /// This is an advanced API to tightly control the sockets used by the endpoint. Most
379    /// uses do not need to explicitly bind sockets.
380    ///
381    /// # Warning
382    ///
383    /// - The builder always comes pre-configured with an IPv4 socket to be bound on the
384    ///   *unspecified* address: `0.0.0.0`. This is the equivalent of using `INADDR_ANY`
385    ///   special bind address and results in a socket listening on *all* interfaces
386    ///   available.
387    ///
388    /// - Likewise the builder always comes pre-configured with an IPv6 socket to be bound
389    ///   on the *unspecified* address: `[::]`. This bind is allowed to fail however.
390    ///
391    /// # Description
392    ///
393    /// Requests a socket to be bound on a specific address. This allows restricting binding
394    /// to only one network interface for a given address family.
395    ///
396    /// [`BindOpts::set_prefix_len`] **should** be used to configure the netmask of the
397    /// network interface. This allows outgoing datagrams that start a new network flow to
398    /// be sent over the socket which is attached to the subnet of the destination
399    /// address. If multiple sockets are bound the standard routing-table semantics are
400    /// used: the socket attached to the subnet with the longest prefix matching the
401    /// destination is used. Practically this means the smallest subnets are at the top of
402    /// the routing table, and the first subnet containing the destination address is
403    /// chosen.
404    ///
405    /// If no socket is bound to a subnet that contains the destination address, the notion
406    /// of "default route" is used. At most one socket per address family may be marked as
407    /// the default route using [`BindOpts::set_is_default_route`], and this will be used
408    /// for destinations not contained by the subnets of the bound sockets. This network is
409    /// expected to have a default gateway configured. A socket with a prefix length of `/0`
410    /// will be set as a "default route" implicitly, unless [`BindOpts::set_is_default_route`]
411    /// is set to `false` explicitly.
412    ///
413    /// Be aware that using a subnet with a prefix length of `/0` will always contain all
414    /// destination addresses. It is valid to configure this, but no more than one such
415    /// socket should be bound or the routing will be non-deterministic.
416    ///
417    /// To use a subnet with a non-zero prefix length as the default route in addition to
418    /// being routed when its prefix matches, use [`BindOpts::set_is_default_route`].
419    /// Subnets with a prefix length of zero are always marked as default routes.
420    ///
421    /// Finally note that most outgoing datagrams are part of an existing network flow. That
422    /// is, they are in response to an incoming datagram. In this case the outgoing datagram
423    /// will be sent over the same socket as the incoming datagram was received on, and the
424    /// routing with the prefix length and default route as described above does not apply.
425    ///
426    /// Using port `0` in the socket address assigns a random free port.
427    ///
428    /// If the port specified is already in use, binding the endpoint will fail, unless
429    /// [`BindOpts::set_is_required`] is set to `false`
430    ///
431    /// # Example
432    /// ```no_run
433    /// # #[cfg(with_crypto_provider)]
434    /// # {
435    /// # #[tokio::main]
436    /// # async fn main() -> n0_error::Result<()> {
437    /// # use iroh::{Endpoint, endpoint::{BindOpts, presets}};
438    /// let endpoint = Endpoint::builder(presets::N0)
439    ///     .clear_ip_transports()
440    ///     .bind_addr_with_opts("127.0.0.1:0", BindOpts::default().set_prefix_len(24))?
441    ///     .bind_addr_with_opts("[::1]:0", BindOpts::default().set_prefix_len(48))?
442    ///     .bind()
443    ///     .await?;
444    /// # Ok(()) }
445    /// # }
446    /// ```
447    #[cfg(not(wasm_browser))]
448    pub fn bind_addr_with_opts<A>(
449        mut self,
450        addr: A,
451        opts: BindOpts,
452    ) -> Result<Self, InvalidSocketAddr>
453    where
454        A: ToSocketAddr,
455        <A as ToSocketAddr>::Err: Into<InvalidSocketAddr>,
456    {
457        let addr = addr.to_socket_addr().map_err(Into::into)?;
458        match addr {
459            SocketAddr::V4(addr) => {
460                if self
461                    .transports
462                    .iter()
463                    .any(|t| t.is_ipv4_default() && t.is_user_defined())
464                {
465                    bail!(InvalidSocketAddr::DuplicateDefaultAddr);
466                }
467
468                let ip_net = Ipv4Net::new(*addr.ip(), opts.prefix_len())
469                    .map_err(|_| e!(InvalidSocketAddr::InvalidPrefixLength))?;
470                self.transports.push(TransportConfig::Ip {
471                    config: IpConfig::V4 {
472                        ip_net,
473                        port: addr.port(),
474                        is_required: opts.is_required(),
475                        is_default: opts.is_default_route(),
476                    },
477                    is_user_defined: true,
478                });
479            }
480            SocketAddr::V6(addr) => {
481                if self
482                    .transports
483                    .iter()
484                    .any(|t| t.is_ipv6_default() && t.is_user_defined())
485                {
486                    bail!(InvalidSocketAddr::DuplicateDefaultAddr);
487                }
488
489                let ip_net = Ipv6Net::new(*addr.ip(), opts.prefix_len())
490                    .map_err(|_| e!(InvalidSocketAddr::InvalidPrefixLength))?;
491                self.transports.push(TransportConfig::Ip {
492                    config: IpConfig::V6 {
493                        ip_net,
494                        scope_id: addr.scope_id(),
495                        port: addr.port(),
496                        is_required: opts.is_required(),
497                        is_default: opts.is_default_route(),
498                    },
499                    is_user_defined: true,
500                });
501            }
502        }
503        Ok(self)
504    }
505
506    /// Removes all IP based transports.
507    #[cfg(not(wasm_browser))]
508    pub fn clear_ip_transports(mut self) -> Self {
509        self.transports
510            .retain(|t| !matches!(t, TransportConfig::Ip { .. }));
511        self
512    }
513
514    /// Removes all relay based transports.
515    pub fn clear_relay_transports(mut self) -> Self {
516        self.transports
517            .retain(|t| !matches!(t, TransportConfig::Relay { .. }));
518        self
519    }
520
521    /// Sets a secret key to authenticate with other peers.
522    ///
523    /// This secret key's public key will be the [`PublicKey`] of this endpoint and thus
524    /// also its [`EndpointId`]
525    ///
526    /// If not set, a new secret key will be generated.
527    ///
528    /// [`PublicKey`]: iroh_base::PublicKey
529    pub fn secret_key(mut self, secret_key: SecretKey) -> Self {
530        self.secret_key = Some(secret_key);
531        self
532    }
533
534    /// Sets the [ALPN] protocols that this endpoint will accept on incoming connections.
535    ///
536    /// Not setting this will still allow creating connections, but to accept incoming
537    /// connections at least one [ALPN] must be set.
538    ///
539    /// Ordering matters for protocol negotiation. When an incoming connection offers multiple ALPNs,
540    /// the first matching ALPN will be chosen. This means that `alpns` should be ordered such
541    /// that the preferred protocols come first.
542    ///
543    /// [ALPN]: https://en.wikipedia.org/wiki/Application-Layer_Protocol_Negotiation
544    pub fn alpns(mut self, alpn_protocols: Vec<Vec<u8>>) -> Self {
545        self.alpn_protocols = alpn_protocols;
546        self
547    }
548
549    // # Methods for common customisation items.
550
551    /// Sets the relay servers to assist in establishing connectivity.
552    ///
553    /// Relay servers are used to establish initial connection with another iroh endpoint.
554    /// They also perform various functions related to hole punching, see the [crate docs]
555    /// for more details.
556    ///
557    /// By default the [number 0] relay servers are used, see [`RelayMode::Default`].
558    ///
559    /// When using [RelayMode::Custom], the provided `relay_map` must contain at least one
560    /// configured relay endpoint.  If an invalid RelayMap is provided [`bind`]
561    /// will result in an error.
562    ///
563    /// [`bind`]: Builder::bind
564    /// [crate docs]: crate
565    /// [number 0]: https://n0.computer
566    pub fn relay_mode(mut self, relay_mode: RelayMode) -> Self {
567        let transport: Option<_> = relay_mode.into();
568        match transport {
569            Some(transport) => {
570                if let Some(og) = self
571                    .transports
572                    .iter_mut()
573                    .find(|t| matches!(t, TransportConfig::Relay { .. }))
574                {
575                    *og = transport;
576                } else {
577                    self.transports.push(transport);
578                }
579            }
580            None => {
581                self.transports
582                    .retain(|t| !matches!(t, TransportConfig::Relay { .. }));
583            }
584        }
585        self
586    }
587
588    /// Removes all Address Lookup services from the builder.
589    ///
590    /// If no Address Lookup is set, connecting to an endpoint without providing its
591    /// direct addresses or relay URLs will fail.
592    ///
593    /// See the documentation of the [`crate::address_lookup::AddressLookup`] trait for details.
594    pub fn clear_address_lookup(mut self) -> Self {
595        self.address_lookup.clear();
596        self
597    }
598
599    /// Adds an additional Address Lookup for this endpoint.
600    ///
601    /// Once the endpoint is created the provided [`AddressLookupBuilder::into_address_lookup`] will be
602    /// called. This allows Address Lookup's to finalize their configuration by e.g. using
603    /// the secret key from the endpoint which can be needed to sign published information.
604    ///
605    /// This method can be called multiple times and all the Address Lookup's passed in
606    /// will be combined using an internal instance of the
607    /// [`crate::address_lookup::AddressLookupServices`]. To clear all Address Lookup's, use
608    /// [`Self::clear_address_lookup`].
609    ///
610    /// If no Address Lookup is set, connecting to an endpoint without providing its
611    /// direct addresses or relay URLs will fail.
612    ///
613    /// See the documentation of the [`crate::address_lookup::AddressLookup`] trait for details.
614    pub fn address_lookup(mut self, address_lookup: impl AddressLookupBuilder) -> Self {
615        self.address_lookup.push(Box::new(address_lookup));
616        self
617    }
618
619    /// Sets the address filter applied to all address data before publishing.
620    ///
621    /// This filter is applied once, at the [`AddressLookupServices`] level, before
622    /// distributing data to any individual address lookup service. This ensures
623    /// consistent filtering regardless of how the services are configured.
624    ///
625    /// [`AddressLookupServices`]: crate::address_lookup::AddressLookupServices
626    pub fn addr_filter(mut self, filter: AddrFilter) -> Self {
627        self.addr_filter = Some(filter);
628        self
629    }
630
631    /// Clears the address filter, allowing all addresses to be published.
632    ///
633    /// This removes any filter previously set via [`Self::addr_filter`], including
634    /// filters set by presets.
635    pub fn clear_addr_filter(mut self) -> Self {
636        self.addr_filter = None;
637        self
638    }
639
640    /// Sets the initial user-defined data to be published in Address Lookup's for this node.
641    ///
642    /// When using Address Lookup's, this string of [`UserData`] will be published together
643    /// with the endpoint's addresses and relay URL. When other endpoints discover this endpoint,
644    /// they retrieve the [`UserData`] in addition to the addressing info.
645    ///
646    /// Iroh itself does not interpret the user-defined data in any way, it is purely left
647    /// for applications to parse and use.
648    pub fn user_data_for_address_lookup(mut self, user_data: UserData) -> Self {
649        self.address_lookup_user_data = Some(user_data);
650        self
651    }
652
653    /// Adds an external address on which this endpoint is directly reachable.
654    ///
655    /// This address will be advertised to peers together with any discovered external addresses
656    /// and will be used in NAT traversal and to establish direct connections.
657    ///
658    /// Can be called multiple times. See also [`Endpoint::add_external_addr`] for
659    /// adding addresses at runtime.
660    pub fn external_addr(mut self, addr: SocketAddr) -> Self {
661        self.configured_addrs.insert(addr);
662        self
663    }
664
665    // # Methods for more specialist customisation.
666
667    /// Sets a custom [`QuicTransportConfig`] for this endpoint.
668    ///
669    /// The transport config contains parameters governing the QUIC state machine.
670    ///
671    /// If unset, the default config is used. Default values should be suitable for most
672    /// internet applications. Applications protocols which forbid remotely-initiated
673    /// streams should set `max_concurrent_bidi_streams` and `max_concurrent_uni_streams` to
674    /// zero.
675    ///
676    /// Please be aware that changing some settings may have adverse effects on establishing
677    /// and maintaining direct connections.
678    pub fn transport_config(mut self, transport_config: QuicTransportConfig) -> Self {
679        self.transport_config = transport_config;
680        self
681    }
682
683    /// Optionally sets a custom DNS resolver to use for this endpoint.
684    ///
685    /// The DNS resolver is used to resolve relay hostnames, and endpoint addresses if
686    /// [`crate::address_lookup::DnsAddressLookup`] is configured.
687    ///
688    /// By default, a new DNS resolver is created which is configured to use the
689    /// host system's DNS configuration. You can pass a custom instance of [`DnsResolver`]
690    /// here to use a differently configured DNS resolver for this endpoint, or to share
691    /// a [`DnsResolver`] between multiple endpoints.
692    #[cfg(not(wasm_browser))]
693    pub fn dns_resolver(mut self, dns_resolver: DnsResolver) -> Self {
694        self.dns_resolver = Some(dns_resolver);
695        self
696    }
697
698    /// Sets an explicit proxy url to proxy all HTTP(S) traffic through.
699    pub fn proxy_url(mut self, url: Url) -> Self {
700        self.proxy_url.replace(url);
701        self
702    }
703
704    /// Sets the proxy url from the environment, in this order:
705    ///
706    /// - `HTTP_PROXY`
707    /// - `http_proxy`
708    /// - `HTTPS_PROXY`
709    /// - `https_proxy`
710    pub fn proxy_from_env(mut self) -> Self {
711        self.proxy_url = proxy_url_from_env();
712        self
713    }
714
715    /// Sets the trusted CA root certificates for non-iroh TLS connections.
716    ///
717    /// These Certificate Authority roots are used as trust anchors for verifying
718    /// the validity of TLS certificates presented by external services, such as
719    /// iroh relays, pkarr servers, or DNS-over-HTTPS resolvers.
720    /// They don't need to be trusted for the integrity or authenticity of native
721    /// iroh connections, which rely on iroh's own cryptographic authentication mechanisms.
722    pub fn ca_tls_config(mut self, ca_tls_config: CaTlsConfig) -> Self {
723        self.ca_tls_config = Some(ca_tls_config);
724        self
725    }
726
727    /// Renamed to [`Builder::ca_tls_config`].
728    #[deprecated(since = "1.0.0", note = "Renamed to `ca_tls_config`")]
729    pub fn ca_roots_config(self, ca_roots_config: CaTlsConfig) -> Self {
730        self.ca_tls_config(ca_roots_config)
731    }
732
733    /// Enables saving the TLS pre-master key for connections.
734    ///
735    /// This key should normally remain secret but can be useful to debug networking issues
736    /// by decrypting captured traffic.
737    ///
738    /// If *keylog* is `true` then setting the `SSLKEYLOGFILE` environment variable to a
739    /// filename will result in this file being used to log the TLS pre-master keys.
740    pub fn keylog(mut self, keylog: bool) -> Self {
741        self.keylog = keylog;
742        self
743    }
744
745    /// Set the maximum number of TLS tickets to cache.
746    ///
747    /// Set this to a larger value if you want to do 0rtt connections to a large
748    /// number of clients.
749    ///
750    /// The default is 256, taking about 150 KiB in memory.
751    pub fn max_tls_tickets(mut self, n: usize) -> Self {
752        self.max_tls_tickets = n;
753        self
754    }
755
756    /// Specify the rustls cryptography to use for all TLS operations.
757    ///
758    /// This includes
759    /// - TLS for encryption and authentication of iroh connections themselves, but also
760    /// - HTTPS connections to relays
761    /// - Pkarr relay publishing HTTPS connections
762    /// - and any other Address Lookup services that decide to use [`Endpoint::tls_config`].
763    ///
764    /// The two most common crypto providers in use today are `ring` as well as `aws-lc-rs`.
765    ///
766    /// If either the `tls-ring` or `tls-aws-lc-rs` feature is set in iroh, this function doesn't
767    /// need to be called.
768    ///
769    /// If none of these features are set, then calling this function in the builder is mandatory.
770    pub fn crypto_provider(mut self, crypto_provider: Arc<rustls::crypto::CryptoProvider>) -> Self {
771        self.crypto_provider = Some(crypto_provider);
772        self
773    }
774
775    /// Install hooks onto the endpoint.
776    ///
777    /// Endpoint hooks intercept the connection establishment process of an [`Endpoint`].
778    ///
779    /// You can install multiple [`EndpointHooks`] by calling this function multiple times.
780    /// Order matters: hooks are invoked in the order they were installed onto the endpoint
781    /// builder. Once a hook returns reject, further processing
782    /// is aborted and other hooks won't be invoked.
783    ///
784    /// See [`EndpointHooks`] for details on the possible interception points in the connection lifecycle.
785    pub fn hooks(mut self, hooks: impl EndpointHooks + 'static) -> Self {
786        self.hooks.push(hooks);
787        self
788    }
789
790    /// Configures the portmapper service (UPnP, PCP, NAT-PMP).
791    ///
792    /// Defaults to [`PortmapperConfig::Enabled`]. Pass
793    /// [`PortmapperConfig::Disabled`] to avoid gateway probing (e.g. if it
794    /// triggers firewall prompts).
795    pub fn portmapper_config(mut self, config: PortmapperConfig) -> Self {
796        self.portmapper_config = config;
797        self
798    }
799
800    /// Configures the net report.
801    ///
802    /// The net report component is responsible for figuring out if and how the endpoint is connected to the internet.
803    /// It does this by doing various probes to the configured relay servers to get public addresses, NAT behaviour, and
804    /// relay latencies. In addition it tries to detect captive portals.
805    ///
806    /// Some non-essential features of the net report component can be disabled via this configuration.
807    pub fn net_report_config(mut self, config: NetReportConfig) -> Self {
808        self.net_report_config = config;
809        self
810    }
811
812    /// Adds a custom transport to the endpoint.
813    ///
814    /// <div class="warning">
815    ///
816    /// This API is unstable and gated behind the `unstable-custom-transport` feature.
817    /// It is not covered by semantic versioning guarantees and may change in any release
818    /// without a major version bump.
819    ///
820    /// </div>
821    #[cfg(feature = "unstable-custom-transports")]
822    pub fn add_custom_transport(mut self, factory: Arc<dyn CustomTransport>) -> Self {
823        self.transports.push(TransportConfig::Custom(factory));
824        self
825    }
826
827    /// Sets a custom [`PathSelector`] for this endpoint.
828    ///
829    /// The path selector decides which path to use among the candidate paths to a
830    /// remote endpoint.  By default iroh uses a built-in selector that sorts paths by
831    /// biased RTT (with IPv6 preferred over IPv4 and relay treated as backup) and is
832    /// sticky to avoid flapping.  Pass a custom [`PathSelector`] here to override that
833    /// policy — for example, to make a custom transport always win over IP.
834    ///
835    /// Takes an `Arc<dyn PathSelector>` so the same selector instance can be shared
836    /// across multiple endpoints if desired.  See `examples/custom-transport.rs` for
837    /// an example implementation.
838    ///
839    /// <div class="warning">
840    ///
841    /// This API is unstable and gated behind the `unstable-custom-transport` feature.
842    /// It is not covered by semantic versioning guarantees and may change in any release
843    /// without a major version bump.
844    ///
845    /// </div>
846    ///
847    /// [`PathSelector`]: socket::remote_map::PathSelector
848    #[cfg(feature = "unstable-custom-transports")]
849    pub fn path_selector(mut self, selector: Arc<dyn PathSelector>) -> Self {
850        self.path_selector = selector;
851        self
852    }
853}
854
855#[allow(missing_docs)]
856#[stack_error(derive, add_meta)]
857#[non_exhaustive]
858pub enum EndpointError {
859    #[error("Endpoint is closed")]
860    Closed,
861}
862
863/// Controls an iroh endpoint, establishing connections with other endpoints.
864///
865/// This is the main API interface to create connections to, and accept connections from
866/// other iroh endpoints.  The connections are peer-to-peer and encrypted, a Relay server is
867/// used to make the connections reliable.  See the [crate docs] for a more detailed
868/// overview of iroh.
869///
870/// It is recommended to only create a single instance per application.  This ensures all
871/// the connections made share the same peer-to-peer connections to other iroh endpoints,
872/// while still remaining independent connections.  This will result in more optimal network
873/// behaviour.
874///
875/// The endpoint is created using the [`Builder`], which can be created using
876/// [`Endpoint::builder`].
877///
878/// Once an endpoint exists, new connections are typically created using the
879/// [`Endpoint::connect`] and [`Endpoint::accept`] methods.  Once established, the
880/// [`Connection`] gives access to most [QUIC] features.  Individual streams to send data to
881/// the peer are created using the [`Connection::open_bi`], [`Connection::accept_bi`],
882/// [`Connection::open_uni`] and [`Connection::accept_uni`] functions.
883///
884/// Note that due to the light-weight properties of streams a stream will only be accepted
885/// once the initiating peer has sent some data on it.
886///
887/// # Usage on Android
888///
889/// The endpoint's default [`DnsResolver`] reads the system DNS configuration
890/// through JNI, which needs a JVM context published to [`ndk_context`]. Apps
891/// should initialize that context before constructing the endpoint. See
892/// [`iroh_dns::install_android_jni_context`] for details (the function is also
893/// exported as `iroh::dns::install_android_jni_context`).
894///
895/// If no JNI context is installed, iroh relies on panic unwinding to detect
896/// the error, and will then use the fallback nameservers instead, subject to the
897/// resolver's [`FallbackMode`]. Note that if your compilation profile sets
898/// `panic = "abort"`, this can't work, and thus your app will panic if using a
899/// default `DnsResolver` without first initializing the JNI context.
900///
901/// [QUIC]: https://quicwg.org
902/// [`DnsResolver`]: crate::dns::DnsResolver
903/// [`FallbackMode`]: crate::dns::FallbackMode
904/// [`ndk_context`]: https://docs.rs/ndk-context
905/// [`iroh_dns::install_android_jni_context`]: https://docs.rs/iroh-dns/latest/iroh_dns/fn.install_android_jni_context.html
906// The last link can't be a normal doclink, because #[cfg(doc)] can't cross crate boundaries unfortunately.
907#[derive(Clone, Debug)]
908pub struct Endpoint {
909    inner: Arc<EndpointInner>,
910}
911
912#[allow(missing_docs)]
913#[stack_error(derive, add_meta, from_sources)]
914#[non_exhaustive]
915#[allow(private_interfaces)]
916pub enum ConnectWithOptsError {
917    #[error("Connecting to ourself is not supported")]
918    SelfConnect,
919    #[error("No addressing information available")]
920    NoAddress { source: AddressLookupFailed },
921    #[error("Unable to connect to remote")]
922    Noq {
923        #[error(std_err)]
924        source: QuicConnectError,
925    },
926    #[error("Internal consistency error")]
927    InternalConsistencyError {
928        /// Private source type, cannot be created publicly.
929        source: RemoteStateActorStoppedError,
930    },
931    #[error("Connection was rejected locally")]
932    LocallyRejected,
933    #[error("Endpoint is closed")]
934    EndpointClosed,
935    #[error("Invalid ALPN")]
936    InvalidAlpn,
937}
938
939#[allow(missing_docs)]
940#[stack_error(derive, add_meta, from_sources)]
941#[non_exhaustive]
942pub enum ConnectError {
943    #[error(transparent)]
944    Connect { source: ConnectWithOptsError },
945    #[error(transparent)]
946    Connecting { source: ConnectingError },
947    #[error(transparent)]
948    Connection {
949        #[error(std_err)]
950        source: ConnectionError,
951    },
952}
953
954impl Endpoint {
955    // The ordering of public methods is reflected directly in the documentation.  This is
956    // roughly ordered by what is most commonly needed by users, but grouped in similar
957    // items.
958
959    // # Methods relating to construction.
960
961    /// Returns the builder for an [`Endpoint`], with the given [`Preset`] configuration.
962    pub fn builder(preset: impl Preset) -> Builder {
963        Builder::new(preset)
964    }
965
966    /// Constructs a default [`Endpoint`] using the provided [`Preset`] and binds it immediately.
967    pub async fn bind(preset: impl Preset) -> Result<Self, BindError> {
968        Self::builder(preset).bind().await
969    }
970
971    /// Sets the list of accepted ALPN protocols.
972    ///
973    /// Ordering matters for protocol negotiation. When an incoming connection offers multiple ALPNs,
974    /// the first matching ALPN will be chosen. This means that `alpns` should be ordered such
975    /// that the preferred protocols come first.
976    ///
977    /// This will only affect new incoming connections.
978    /// Note that this *overrides* the current list of ALPNs.
979    ///
980    /// If the endpoint is closed, this method will log a warning and ignore
981    /// the request to set new ALPNs.
982    pub fn set_alpns(&self, alpns: Vec<Vec<u8>>) {
983        if self.is_closed() {
984            warn!("Attempting to set ALPNs for a closed endpoint. Ignoring.");
985            return;
986        }
987        let server_config = self.inner.static_config.create_server_config(alpns);
988        self.inner
989            .noq_endpoint()
990            .set_server_config(Some(server_config));
991    }
992
993    /// Adds the provided configuration to the [`RelayMap`].
994    ///
995    /// Replacing and returning any existing configuration for [`RelayUrl`].
996    ///
997    /// Will also return `None` if the endpoint is closed.
998    pub async fn insert_relay(
999        &self,
1000        relay: RelayUrl,
1001        config: Arc<RelayConfig>,
1002    ) -> Option<Arc<RelayConfig>> {
1003        if self.is_closed() {
1004            return None;
1005        }
1006        self.inner.insert_relay(relay, config).await
1007    }
1008
1009    /// Removes the configuration from the [`RelayMap`] for the provided [`RelayUrl`].
1010    ///
1011    /// Returns any existing configuration if it exists. Will also return `None` if the endpoint is closed.
1012    pub async fn remove_relay(&self, relay: &RelayUrl) -> Option<Arc<RelayConfig>> {
1013        if self.is_closed() {
1014            return None;
1015        }
1016        self.inner.remove_relay(relay).await
1017    }
1018
1019    /// Adds an external address on which this endpoint is directly reachable.
1020    ///
1021    /// This address will be advertised to peers together with any discovered external addresses
1022    /// and will be used in NAT traversal and to establish direct connections.
1023    ///
1024    /// See also [`Builder::external_addr`] for setting addresses at build time.
1025    pub async fn add_external_addr(&self, addr: SocketAddr) {
1026        if self.is_closed() {
1027            warn!("Attempting to add external addr for a closed endpoint. Ignoring.");
1028            return;
1029        }
1030        self.inner.add_external_addr(addr).await;
1031    }
1032
1033    /// Removes a configured external address. Returns `true` if it was present.
1034    pub async fn remove_external_addr(&self, addr: &SocketAddr) -> bool {
1035        if self.is_closed() {
1036            return false;
1037        }
1038        self.inner.remove_external_addr(addr).await
1039    }
1040
1041    // # Methods for establishing connectivity.
1042
1043    /// Connects to a remote [`Endpoint`].
1044    ///
1045    /// A value that can be converted into an [`EndpointAddr`] is required. This can be either an
1046    /// [`EndpointAddr`] or an [`EndpointId`].
1047    ///
1048    /// The [`EndpointAddr`] must contain the [`EndpointId`] to dial and may also contain a [`RelayUrl`]
1049    /// and direct addresses. If direct addresses are provided, they will be used to try and
1050    /// establish a direct connection without involving a relay server.
1051    ///
1052    /// If neither a [`RelayUrl`] or direct addresses are configured in the [`EndpointAddr`] it
1053    /// may still be possible a connection can be established.  This depends on which, if any,
1054    /// [`crate::address_lookup::AddressLookup`]s were configured using [`Builder::address_lookup`].  The Address Lookup
1055    /// service will also be used if the remote endpoint is not reachable on the provided direct
1056    /// addresses and there is no [`RelayUrl`].
1057    ///
1058    /// If addresses or relay servers are neither provided nor can be discovered, the
1059    /// connection attempt will fail with an error.
1060    ///
1061    /// The `alpn`, or application-level protocol identifier, is also required. The remote
1062    /// endpoint must support this `alpn`, otherwise the connection attempt will fail with
1063    /// an error.
1064    ///
1065    /// [`RelayUrl`]: crate::RelayUrl
1066    pub async fn connect(
1067        &self,
1068        endpoint_addr: impl Into<EndpointAddr>,
1069        alpn: &[u8],
1070    ) -> Result<Connection, ConnectError> {
1071        let endpoint_addr = endpoint_addr.into();
1072        let remote = endpoint_addr.id;
1073        let connecting = self
1074            .connect_with_opts(endpoint_addr, alpn, Default::default())
1075            .await?;
1076        let conn = connecting.await?;
1077
1078        debug!(
1079            me = %self.id().fmt_short(),
1080            remote = %remote.fmt_short(),
1081            alpn = %String::from_utf8_lossy(alpn),
1082            "Connection established."
1083        );
1084        Ok(conn)
1085    }
1086
1087    /// Starts a connection attempt with a remote [`Endpoint`].
1088    ///
1089    /// Like [`Endpoint::connect`] (see also its docs for general details), but allows for a more
1090    /// advanced connection setup with more customization in two aspects:
1091    /// 1. The returned future resolves to a [`Connecting`], which can be further processed into
1092    ///    a [`Connection`] by awaiting, or alternatively allows connecting with 0-RTT via
1093    ///    [`Connecting::into_0rtt`].
1094    ///    **Note:** Please read the documentation for `into_0rtt` carefully to assess
1095    ///    security concerns.
1096    /// 2. The [`QuicTransportConfig`] for the connection can be modified via the provided
1097    ///    [`ConnectOptions`].
1098    ///    **Note:** Please be aware that changing transport config settings may have adverse effects on
1099    ///    establishing and maintaining direct connections.  Carefully test settings you use and
1100    ///    consider this currently as still rather experimental.
1101    #[instrument(name = "connect", skip_all, fields(
1102        me = %self.id().fmt_short(),
1103        remote = tracing::field::Empty,
1104        alpn = %String::from_utf8_lossy(alpn).to_string(),
1105    ))]
1106    pub async fn connect_with_opts(
1107        &self,
1108        endpoint_addr: impl Into<EndpointAddr>,
1109        alpn: &[u8],
1110        options: ConnectOptions,
1111    ) -> Result<Connecting, ConnectWithOptsError> {
1112        if self.is_closed() {
1113            return Err(e!(ConnectWithOptsError::EndpointClosed));
1114        }
1115
1116        let endpoint_addr: EndpointAddr = endpoint_addr.into();
1117        let endpoint_id = endpoint_addr.id;
1118
1119        Span::current().record("remote", tracing::field::display(endpoint_id.fmt_short()));
1120
1121        if let BeforeConnectOutcome::Reject =
1122            self.inner.hooks.before_connect(&endpoint_addr, alpn).await
1123        {
1124            return Err(e!(ConnectWithOptsError::LocallyRejected));
1125        }
1126
1127        // Connecting to ourselves is not supported.
1128        ensure!(endpoint_id != self.id(), ConnectWithOptsError::SelfConnect);
1129        ensure!(!alpn.is_empty(), ConnectWithOptsError::InvalidAlpn);
1130
1131        event!(
1132            target: "iroh::_events::conn::connecting",
1133            tracing::Level::DEBUG,
1134            remote_id = %endpoint_id.fmt_short(),
1135            alpn = %String::from_utf8_lossy(alpn),
1136        );
1137
1138        debug!(
1139            relay_url = ?endpoint_addr.relay_urls().next().cloned(),
1140            ip_addresses = ?endpoint_addr.ip_addrs().cloned().collect::<Vec<_>>(),
1141            "connecting",
1142        );
1143
1144        let mapped_addr = self.inner.resolve_remote(endpoint_addr).await??;
1145
1146        let transport_config = options
1147            .transport_config
1148            .map(|cfg| cfg.to_inner_arc())
1149            .unwrap_or(self.inner.static_config.transport_config.to_inner_arc());
1150
1151        // Start connecting via noq. This will time out after 10 seconds if no reachable
1152        // address is available.
1153
1154        let mut alpn_protocols = vec![alpn.to_vec()];
1155        alpn_protocols.extend(options.additional_alpns);
1156        let client_config = self
1157            .inner
1158            .static_config
1159            .create_client_config(alpn_protocols, transport_config.clone());
1160
1161        let dest_addr = mapped_addr.private_socket_addr();
1162        let server_name = &tls::name::encode(endpoint_id);
1163        let connect =
1164            self.inner
1165                .noq_endpoint()
1166                .connect_with(client_config, dest_addr, server_name)?;
1167
1168        Ok(Connecting::new(connect, self.clone(), endpoint_id))
1169    }
1170
1171    /// Accepts an incoming connection on the endpoint.
1172    ///
1173    /// Only connections with the ALPNs configured in [`Builder::alpns`] will be accepted.
1174    /// If multiple ALPNs have been configured the ALPN can be inspected before accepting
1175    /// the connection using [`Connecting::alpn`].
1176    ///
1177    /// The returned future will yield `None` if the endpoint is closed by calling
1178    /// [`Endpoint::close`].
1179    pub fn accept(&self) -> Accept<'_> {
1180        Accept {
1181            inner: self.inner.noq_endpoint().accept(),
1182            ep: self.clone(),
1183        }
1184    }
1185
1186    // # Getter methods for properties of this Endpoint itself.
1187
1188    /// Returns the secret_key of this endpoint.
1189    pub fn secret_key(&self) -> &SecretKey {
1190        &self.inner.static_config.tls_config.secret_key
1191    }
1192
1193    /// Returns the endpoint id of this endpoint.
1194    ///
1195    /// This ID is the unique addressing information of this endpoint and other peers must know
1196    /// it to be able to connect to this endpoint.
1197    pub fn id(&self) -> EndpointId {
1198        self.inner.static_config.tls_config.secret_key.public()
1199    }
1200
1201    /// Returns the current [`EndpointAddr`].
1202    /// As long as the endpoint was able to bind to a network interface, some
1203    /// local addresses will be available.
1204    ///
1205    /// The state of other fields depends on the state of networking and connectivity.
1206    /// Use the [`Endpoint::online`] method to ensure that the endpoint is considered
1207    /// "online" (has contacted a relay server) before calling this method, if you want
1208    /// to ensure that the `EndpointAddr` will contain enough information to allow this endpoint
1209    /// to be dialable by a remote endpoint over the internet.
1210    ///
1211    /// You can use the [`Endpoint::watch_addr`] method to get updates when the `EndpointAddr`
1212    /// changes.
1213    pub fn addr(&self) -> EndpointAddr {
1214        self.watch_addr().get()
1215    }
1216
1217    /// Returns a [`Watcher`] for the current [`EndpointAddr`] for this endpoint.
1218    ///
1219    /// The observed [`EndpointAddr`] will have the current [`RelayUrl`] and direct addresses.
1220    ///
1221    /// ```no_run
1222    /// # #[cfg(with_crypto_provider)]
1223    /// # {
1224    /// # async fn wrapper() -> n0_error::Result<()> {
1225    /// use iroh::{Endpoint, Watcher, endpoint::presets};
1226    ///
1227    /// let endpoint = Endpoint::builder(presets::N0)
1228    ///     .alpns(vec![b"my-alpn".to_vec()])
1229    ///     .bind()
1230    ///     .await?;
1231    /// let endpoint_addr = endpoint.watch_addr().get();
1232    /// # let _ = endpoint_addr;
1233    /// # Ok(())
1234    /// # }
1235    /// # }
1236    /// ```
1237    ///
1238    /// The [`Endpoint::online`] method can be used as a convenience method to
1239    /// understand if the endpoint has ever been considered "online". But after
1240    /// that initial call to [`Endpoint::online`], to understand if your
1241    /// endpoint is no longer able to be connected to by endpoints outside
1242    /// of the private or local network, watch for changes in its [`EndpointAddr`].
1243    /// If there are no `addrs` in the [`EndpointAddr`], you may not be dialable by other endpoints
1244    /// on the internet.
1245    ///
1246    /// The `EndpointAddr` will change as:
1247    /// - network conditions change
1248    /// - the endpoint connects to a relay server
1249    /// - the endpoint changes its preferred relay server
1250    /// - more addresses are discovered for this endpoint
1251    ///
1252    /// ## Closing behavior
1253    ///
1254    /// The returned watcher only becomes disconnected once the last clone of the [`Endpoint`]
1255    /// is dropped. Closing the endpoint does not disconnect the watcher. Thus, a stream created
1256    /// via [`Watcher::stream`] only terminates once the endpoint is fully dropped. To stop a task
1257    /// that loops over a watcher stream once the endpoint stops, combine with [`Self::closed`]:
1258    ///
1259    /// ```no_run
1260    /// # #[cfg(with_crypto_provider)]
1261    /// # {
1262    /// # use iroh::{Watcher, Endpoint, endpoint::presets};
1263    /// # use n0_future::StreamExt;
1264    /// # use tracing::info;
1265    /// # async fn wrapper() -> n0_error::Result<()> {
1266    /// let endpoint = Endpoint::bind(presets::N0).await?;
1267    /// // We want to watch address changes in a different task, and stop our task
1268    /// // once the endpoint stops.
1269    /// let mut addr_stream = endpoint.watch_addr().stream();
1270    /// let endpoint_closed = endpoint.closed();
1271    /// tokio::spawn(endpoint_closed.run_until(async move {
1272    ///     while let Some(addr) = addr_stream.next().await {
1273    ///         info!("our address changed: {addr:?}");
1274    ///     }
1275    ///     info!("endpoint closed");
1276    /// }));
1277    /// // Do fancy things, then close the endpoint.
1278    /// // Our task above will stop even if there are still clones of `Endpoint` alive somewhere.
1279    /// endpoint.close().await;
1280    /// # Ok(())
1281    /// # }
1282    /// # }
1283    /// ```
1284    ///
1285    /// [`RelayUrl`]: crate::RelayUrl
1286    #[cfg(not(wasm_browser))]
1287    pub fn watch_addr(&self) -> impl n0_watcher::Watcher<Value = EndpointAddr> + use<> {
1288        let watch_addrs = self.inner.ip_addrs();
1289        let watch_relay = self.inner.home_relay();
1290        let endpoint_id = self.id();
1291
1292        watch_addrs.or(watch_relay).map(move |(addrs, relays)| {
1293            EndpointAddr::from_parts(
1294                endpoint_id,
1295                relays
1296                    .into_iter()
1297                    .map(TransportAddr::Relay)
1298                    .chain(addrs.into_iter().map(|x| TransportAddr::Ip(x.addr))),
1299            )
1300        })
1301    }
1302
1303    /// Returns a [`Watcher`] for the current [`EndpointAddr`] for this endpoint.
1304    ///
1305    /// When compiled to Wasm, this function returns a watcher that initializes
1306    /// with an [`EndpointAddr`] that only contains a relay URL, but no direct addresses,
1307    /// as there are no APIs for directly using sockets in browsers.
1308    ///
1309    /// The returned watcher only becomes disconnected once the last clone of the [`Endpoint`]
1310    /// is dropped. Closing the endpoint does not disconnect the watcher. Thus, a stream created
1311    /// via [`Watcher::stream`] only terminates once the endpoint stops. If you want to stop a
1312    /// task once the endpoint stops combine with [`Self::closed`].
1313    #[cfg(wasm_browser)]
1314    pub fn watch_addr(&self) -> impl n0_watcher::Watcher<Value = EndpointAddr> + use<> {
1315        // In browsers, there will never be any direct addresses, so we wait
1316        // for the home relay instead. This makes the `EndpointAddr` have *some* way
1317        // of connecting to us.
1318        let watch_relay = self.inner.home_relay();
1319        let endpoint_id = self.id();
1320        watch_relay.map(move |mut relays| {
1321            EndpointAddr::from_parts(endpoint_id, relays.into_iter().map(TransportAddr::Relay))
1322        })
1323    }
1324
1325    /// A convenience method that waits for the endpoint to be considered "online".
1326    ///
1327    /// This currently means at least one relay server has completed its
1328    /// connection handshake (i.e. the endpoint is registered and reachable
1329    /// via that relay). Merely selecting a relay URL is not sufficient.
1330    ///
1331    /// If no relays are configured, this will pend forever.
1332    ///
1333    /// This has no timeout, so if that is needed, you need to wrap it in a
1334    /// timeout. We recommend using a timeout close to
1335    /// [`crate::NET_REPORT_TIMEOUT`]s, so you can be sure that at least one
1336    /// net report has been attempted.
1337    ///
1338    /// To understand if the endpoint has gone back "offline",
1339    /// you must use the [`Endpoint::watch_addr`] method, to
1340    /// get information on the current relay and direct address information.
1341    ///
1342    /// In the common case where the endpoint's configured relay servers are
1343    /// only accessible via a wide area network (WAN) connection, this method
1344    /// will await indefinitely when the endpoint has no WAN connection. If you're
1345    /// writing an app that's designed to work without a WAN connection, defer
1346    /// any calls to `online` as long as possible, or avoid calling `online`
1347    /// entirely.
1348    ///
1349    /// The online method does not interact with [`crate::address_lookup::AddressLookup`]
1350    /// services, which means that any Address Lookup that relies on a WAN
1351    /// connection is independent of the endpoint's online status.
1352    ///
1353    /// # Examples
1354    ///
1355    /// ```no_run
1356    /// # #[cfg(with_crypto_provider)]
1357    /// # {
1358    /// # #[tokio::main]
1359    /// # async fn main() -> n0_error::Result<()> {
1360    /// # use iroh::{Endpoint, endpoint::presets};
1361    /// // After this await returns, the endpoint is bound to a local socket.
1362    /// // It can be dialed, but almost certainly hasn't finished picking a
1363    /// // relay.
1364    /// let endpoint = Endpoint::bind(presets::N0).await?;
1365    ///
1366    /// // After this await returns we have a connection to at least one relay
1367    /// // and holepunching should work as expected.
1368    /// endpoint.online().await;
1369    /// # Ok(()) }
1370    /// # }
1371    /// ```
1372    pub async fn online(&self) {
1373        let mut watcher = self.inner.home_relay_status();
1374        let mut value = watcher.get();
1375        loop {
1376            if value.into_iter().any(|status| status.is_connected()) {
1377                return;
1378            }
1379            value = match watcher.updated().await {
1380                Ok(value) => value,
1381                Err(_disconnected) => {
1382                    std::future::pending::<()>().await;
1383                    break;
1384                }
1385            }
1386        }
1387    }
1388
1389    /// Returns a [`Watcher`] over the connection status of the endpoint's home relays.
1390    ///
1391    /// The watched value has one entry per home relay whose URL is known,
1392    /// and is empty when no relays are configured or before the endpoint has
1393    /// selected a home relay from the list of configured relays.
1394    /// The watcher updates whenever any home relay's connection status changes.
1395    /// See [`RelayStatus`] for the information available on each entry.
1396    ///
1397    /// This may be used to observe connection failures to the home relay:
1398    /// [`RelayStatus::last_error`] reports the most recent error, and
1399    /// [`RelayStatus::auth_denied_reason`] singles out the case of the relay
1400    /// server denying the endpoint's authentication.
1401    ///
1402    /// The returned watcher only becomes disconnected once the last clone of
1403    /// the [`Endpoint`] is dropped. Closing the endpoint does not disconnect
1404    /// the watcher. To stop a task once the endpoint stops, combine with
1405    /// [`Self::closed`].
1406    pub fn home_relay_status(&self) -> impl Watcher<Value = Vec<RelayStatus>> + use<> {
1407        self.inner.home_relay_status()
1408    }
1409
1410    /// Returns a [`Watcher`] for any net report runs from this [`Endpoint`].
1411    ///
1412    /// <div class="warning">
1413    ///
1414    /// This API is unstable and gated behind the `unstable-net-report` feature.
1415    /// It is not covered by semantic versioning guarantees and may change in any release
1416    /// without a major version bump.
1417    ///
1418    /// </div>
1419    ///
1420    /// A net report checks the network conditions of the [`Endpoint`], such as
1421    /// whether it is connected to the internet via IPv4 and/or IPv6, its NAT
1422    /// status, its latency to the relay servers, and its public addresses.
1423    ///
1424    /// The [`Endpoint`] continuously runs net reports to monitor if network
1425    /// conditions have changed. This [`Watcher`] will return the latest
1426    /// net report.
1427    ///
1428    /// When issuing the first call to this method the first report might
1429    /// still be underway, in this case the [`Watcher`] might not be initialized
1430    /// with [`Some`] value yet.  Once the net report has been successfully
1431    /// run, the [`Watcher`] will always return [`Some`] immediately, which
1432    /// is the most recently run net report.
1433    ///
1434    /// The returned watcher only becomes disconnected once the last clone of the [`Endpoint`]
1435    /// is dropped. Closing the endpoint does not disconnect the watcher. Thus, a stream created
1436    /// via [`Watcher::stream`] only terminates once the endpoint stops. If you want to stop a
1437    /// task once the endpoint stops combine with [`Self::closed`].
1438    ///
1439    /// # Examples
1440    ///
1441    /// To get the first report use [`Watcher::initialized`]:
1442    /// ```no_run
1443    /// # #[cfg(with_crypto_provider)]
1444    /// # {
1445    /// use iroh::{Endpoint, Watcher as _, endpoint::presets};
1446    ///
1447    /// # let rt = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
1448    /// # rt.block_on(async move {
1449    /// let ep = Endpoint::bind(presets::N0).await.unwrap();
1450    /// let _report = ep.net_report().initialized().await;
1451    /// # });
1452    /// # }
1453    /// ```
1454    #[cfg(feature = "unstable-net-report")]
1455    pub fn net_report(&self) -> impl Watcher<Value = Option<NetReport>> + use<> {
1456        self.inner.net_report()
1457    }
1458
1459    /// Returns the local socket addresses on which the underlying sockets are bound.
1460    ///
1461    /// The [`Endpoint`] always binds on an IPv4 address and also tries to bind on an IPv6
1462    /// address if available.
1463    #[cfg(not(wasm_browser))]
1464    pub fn bound_sockets(&self) -> Vec<SocketAddr> {
1465        self.inner
1466            .local_addr()
1467            .into_iter()
1468            .filter_map(|addr| addr.into_socket_addr())
1469            .collect()
1470    }
1471
1472    // # Methods for less common getters.
1473    //
1474    // Partially they return things passed into the builder.
1475
1476    /// Returns the DNS resolver used in this [`Endpoint`].
1477    ///
1478    /// # Errors
1479    ///
1480    /// Returns an `EndpointError::Closed` error if the endpoint is closed.
1481    ///
1482    /// See [`Builder::dns_resolver`].
1483    #[cfg(not(wasm_browser))]
1484    pub fn dns_resolver(&self) -> Result<&DnsResolver, EndpointError> {
1485        if self.is_closed() {
1486            return Err(e!(EndpointError::Closed));
1487        }
1488        Ok(self.inner.dns_resolver())
1489    }
1490
1491    /// Returns the [`rustls::ClientConfig`] used by the endpoint for connecting to external services.
1492    ///
1493    /// This might be useful for address lookup services or other functions
1494    /// that want to use the same trust anchors as iroh does for verifying the
1495    /// validity of TLS certificates presented by external services.
1496    ///
1497    /// Note that this TLS config is unrelated to how iroh validates the authenticity
1498    /// of iroh connections itself.
1499    ///
1500    /// The config is based on the trust anchors set via [`Builder::ca_tls_config`].
1501    pub fn tls_config(&self) -> &rustls::ClientConfig {
1502        &self.inner.tls_config
1503    }
1504
1505    /// Returns the proxy that HTTP(S) traffic is sent through, if any.
1506    ///
1507    /// The pkarr publisher and resolver send their HTTP requests through it.
1508    #[cfg(not(wasm_browser))]
1509    pub(crate) fn proxy_url(&self) -> Option<&Url> {
1510        self.inner.proxy_url.as_ref()
1511    }
1512
1513    /// Returns the Address Lookup service, if configured.
1514    ///
1515    /// # Errors
1516    ///
1517    /// Returns a `EndpointError::Closed` error if the endpoint is closed.
1518    ///
1519    /// See [`Builder::address_lookup`].
1520    pub fn address_lookup(&self) -> Result<&AddressLookupServices, EndpointError> {
1521        if self.is_closed() {
1522            return Err(e!(EndpointError::Closed));
1523        }
1524        Ok(self.inner.address_lookup())
1525    }
1526
1527    /// Returns metrics collected for this endpoint.
1528    ///
1529    /// The endpoint internally collects various metrics about its operation.
1530    /// The returned [`EndpointMetrics`] struct contains all of these metrics.
1531    ///
1532    /// You can access individual metrics directly by using the public fields:
1533    /// ```rust
1534    /// # use std::collections::BTreeMap;
1535    /// # use iroh::endpoint::{Endpoint, presets};
1536    /// # async fn wrapper() -> n0_error::Result<()> {
1537    /// let endpoint = Endpoint::bind(presets::N0).await?;
1538    /// assert_eq!(endpoint.metrics().socket.recv_datagrams.get(), 0);
1539    /// # Ok(())
1540    /// # }
1541    /// ```
1542    ///
1543    /// [`EndpointMetrics`] implements [`MetricsGroupSet`], and each field
1544    /// implements [`MetricsGroup`]. These traits provide methods to iterate over
1545    /// the groups in the set, and over the individual metrics in each group, without having
1546    /// to access each field manually. With these methods, it is straightforward to collect
1547    /// all metrics into a map or push their values to a metrics collector.
1548    ///
1549    /// For example, the following snippet collects all metrics into a map:
1550    /// ```rust
1551    /// # use std::collections::BTreeMap;
1552    /// # use iroh_metrics::{Metric, MetricsGroup, MetricValue, MetricsGroupSet};
1553    /// # use iroh::endpoint::{Endpoint, presets};
1554    /// # async fn wrapper() -> n0_error::Result<()> {
1555    /// let endpoint = Endpoint::bind(presets::N0).await?;
1556    /// let metrics: BTreeMap<String, MetricValue> = endpoint
1557    ///     .metrics()
1558    ///     .iter()
1559    ///     .map(|(group, metric)| {
1560    ///         let name = [group, metric.name()].join(":");
1561    ///         (name, metric.value())
1562    ///     })
1563    ///     .collect();
1564    ///
1565    /// assert_eq!(metrics["socket:recv_datagrams"], MetricValue::Counter(0));
1566    /// # Ok(())
1567    /// # }
1568    /// ```
1569    ///
1570    /// The metrics can also be encoded into the OpenMetrics text format, as used by Prometheus.
1571    /// To do so, use the [`iroh_metrics::Registry`], add the endpoint metrics to the
1572    /// registry with [`Registry::register_all`], and encode the metrics to a string with
1573    /// [`encode_openmetrics_to_string`]:
1574    /// ```rust
1575    /// # use iroh_metrics::{Registry, MetricsSource};
1576    /// # use iroh::endpoint::{Endpoint, presets};
1577    /// # async fn wrapper() -> n0_error::Result<()> {
1578    /// let endpoint = Endpoint::bind(presets::N0).await?;
1579    /// let mut registry = Registry::default();
1580    /// registry.register_all(endpoint.metrics());
1581    /// let s = registry.encode_openmetrics_to_string()?;
1582    /// assert!(s.contains(r#"TYPE socket_recv_datagrams counter"#));
1583    /// assert!(s.contains(r#"socket_recv_datagrams_total 0"#));
1584    /// # Ok(())
1585    /// # }
1586    /// ```
1587    ///
1588    /// Through a registry, you can also add labels or prefixes to metrics with
1589    /// [`Registry::sub_registry_with_label`] or [`Registry::sub_registry_with_prefix`].
1590    /// Furthermore, [`iroh_metrics::service`] provides functions to easily start services
1591    /// to serve the metrics with a HTTP server, dump them to a file, or push them
1592    /// to a Prometheus gateway.
1593    ///
1594    /// For example, the following snippet launches an HTTP server that serves the metrics in the
1595    /// OpenMetrics text format:
1596    /// ```no_run
1597    /// # use std::sync::{Arc, RwLock};
1598    /// # use iroh_metrics::{Registry, MetricsSource};
1599    /// # use iroh::endpoint::{Endpoint, presets};
1600    /// # use n0_error::{StackResultExt, StdResultExt};
1601    /// # async fn wrapper() -> n0_error::Result<()> {
1602    /// // Create a registry, wrapped in a read-write lock so that we can register and serve
1603    /// // the metrics independently.
1604    /// let registry = Arc::new(RwLock::new(Registry::default()));
1605    /// // Spawn an OpenMetrics HTTP server backed by the registry.
1606    /// let addr = "0.0.0.0:9100".parse().unwrap();
1607    /// let metrics_server = iroh_metrics::service::MetricsServer::spawn(addr, registry.clone())
1608    ///     .await
1609    ///     .std_context("spawn metrics server")?;
1610    ///
1611    /// // Spawn an endpoint and add the metrics to the registry.
1612    /// let endpoint = Endpoint::bind(presets::N0).await?;
1613    /// registry.write().unwrap().register_all(endpoint.metrics());
1614    ///
1615    /// // Fetch the metrics via HTTP.
1616    /// let res = reqwest::get("http://localhost:9100/metrics")
1617    ///     .await
1618    ///     .std_context("get")?
1619    ///     .text()
1620    ///     .await
1621    ///     .std_context("text")?;
1622    ///
1623    /// assert!(res.contains(r#"TYPE socket_recv_datagrams counter"#));
1624    /// assert!(res.contains(r#"socket_recv_datagrams_total 0"#));
1625    /// # metrics_server.shutdown().await;
1626    /// # Ok(())
1627    /// # }
1628    /// ```
1629    ///
1630    /// [`Registry`]: iroh_metrics::Registry
1631    /// [`Registry::register_all`]: iroh_metrics::Registry::register_all
1632    /// [`Registry::sub_registry_with_label`]: iroh_metrics::Registry::sub_registry_with_label
1633    /// [`Registry::sub_registry_with_prefix`]: iroh_metrics::Registry::sub_registry_with_prefix
1634    /// [`encode_openmetrics_to_string`]: iroh_metrics::MetricsSource::encode_openmetrics_to_string
1635    /// [`MetricsGroup`]: iroh_metrics::MetricsGroup
1636    /// [`MetricsGroupSet`]: iroh_metrics::MetricsGroupSet
1637    #[cfg(feature = "metrics")]
1638    pub fn metrics(&self) -> &EndpointMetrics {
1639        &self.inner.metrics
1640    }
1641
1642    /// Returns addressing information about a recently used remote endpoint.
1643    ///
1644    /// The returned [`RemoteInfo`] contains a list of all transport addresses for the remote
1645    /// that we know about. This is a snapshot in time and not a watcher.
1646    ///
1647    /// Returns `None` if the endpoint doesn't have information about the remote or if the endpoint is closed.
1648    /// When remote endpoints are no longer used, our endpoint will keep information around
1649    /// for a little while, and then drop it. Afterwards, this will return `None`.
1650    pub async fn remote_info(&self, endpoint_id: EndpointId) -> Option<RemoteInfo> {
1651        if self.is_closed() {
1652            return None;
1653        }
1654        self.inner.remote_info(endpoint_id).await
1655    }
1656
1657    // # Methods for less common state updates.
1658
1659    /// Notifies the system of potential network changes.
1660    ///
1661    /// On many systems iroh is able to detect network changes by itself, however
1662    /// some systems like android do not expose this functionality to native code.
1663    /// Android does however provide this functionality to Java code.  This
1664    /// function allows for notifying iroh of any potential network changes like
1665    /// this.
1666    ///
1667    /// Even when the network did not change, or iroh was already able to detect
1668    /// the network change itself, there is no harm in calling this function.
1669    ///
1670    /// If the endpoint is closed, this method will log a warning and ignore the request.
1671    pub async fn network_change(&self) {
1672        if self.is_closed() {
1673            debug!("Attempting to notify a closed endpoint about a network change. Ignoring.");
1674            return;
1675        }
1676        self.inner.network_change().await;
1677    }
1678
1679    // # Methods to update internal state.
1680
1681    /// Sets the initial user-defined data to be published in Address Lookups for this endpoint.
1682    ///
1683    /// If the user-defined data passed to this function is different to the previous one,
1684    /// the endpoint will republish its endpoint info to the configured Address Lookups.
1685    ///
1686    /// See also [`Builder::user_data_for_address_lookup`] for setting an initial value when
1687    /// building the endpoint.
1688    ///
1689    /// If the endpoint is closed, this method will log a warning and ignore the
1690    /// request.
1691    pub fn set_user_data_for_address_lookup(&self, user_data: Option<UserData>) {
1692        if self.is_closed() {
1693            warn!("Attempting to set user data for a closed endpoint. Ignoring.");
1694            return;
1695        }
1696        self.inner.set_user_data_for_address_lookup(user_data);
1697    }
1698
1699    // # Methods for terminating the endpoint.
1700
1701    /// Closes the QUIC endpoint and the socket.
1702    ///
1703    /// This will close any remaining open [`Connection`]s with an error code
1704    /// of `0` and an empty reason.  Though it is best practice to close those
1705    /// explicitly before with a custom error code and reason.
1706    ///
1707    /// It will then make a best effort to wait for all close notifications to be
1708    /// acknowledged by the peers, re-transmitting them if needed. This ensures the
1709    /// peers are aware of the closed connections instead of having to wait for a timeout
1710    /// on the connection. Once all connections are closed or timed out, the future
1711    /// finishes.
1712    ///
1713    /// The maximum time-out that this future will wait for depends on QUIC transport
1714    /// configurations of non-drained connections at the time of calling, and their current
1715    /// estimates of round trip time. With default parameters and a conservative estimate
1716    /// of round trip time, this call's future should take 3 seconds to resolve in cases of
1717    /// bad connectivity or failed connections. In the usual case, this call's future should
1718    /// return much more quickly.
1719    ///
1720    /// It is highly recommended you *do* wait for this close call to finish, if possible.
1721    /// Not doing so will make connections that were still open while closing the endpoint
1722    /// time out on the remote end. Thus remote ends will assume connections to have failed
1723    /// even if all application data was transmitted successfully.
1724    ///
1725    /// Note: Someone used to closing TCP sockets might wonder why it is necessary to wait
1726    /// for timeouts when closing QUIC endpoints, while they don't have to do this for TCP
1727    /// sockets. This is due to QUIC and its acknowledgments being implemented in user-land,
1728    /// while TCP sockets usually get closed and drained by the operating system in the
1729    /// kernel during the "Time-Wait" period of the TCP socket.
1730    ///
1731    /// Be aware however that the underlying UDP sockets are only closed once all clones of
1732    /// the respective [`Endpoint`] are dropped.
1733    pub async fn close(&self) {
1734        self.inner.close().await;
1735    }
1736
1737    /// Check if this endpoint is still alive, or already closed.
1738    pub fn is_closed(&self) -> bool {
1739        self.inner.is_closed()
1740    }
1741
1742    /// Returns a future that resolves once the endpoint closes.
1743    ///
1744    /// The returned future does not contain a clone or reference to the [`Endpoint`],
1745    /// so keeping the returned future alive does not prevent the endpoint from being dropped.
1746    ///
1747    /// To run a task and stop it once the endpoint closes, you can use
1748    /// [`EndpointClosed::run_until`]:
1749    /// ```no_run
1750    /// # #[cfg(with_crypto_provider)]
1751    /// # {
1752    /// # use iroh::endpoint::{Endpoint, presets};
1753    /// # async fn wrapper() -> n0_error::Result<()> {
1754    /// let endpoint = Endpoint::bind(presets::N0).await?;
1755    /// tokio::spawn(endpoint.closed().run_until(async move {
1756    ///     // the future will be aborted once the endpoint closes.
1757    /// }));
1758    /// # Ok(())
1759    /// # }
1760    /// # }
1761    /// ```
1762    pub fn closed(&self) -> EndpointClosed {
1763        EndpointClosed {
1764            inner: self.inner.closed(),
1765        }
1766    }
1767
1768    /// Create a [`ServerConfigBuilder`] for this endpoint that includes the given alpns.
1769    ///
1770    /// Use the [`ServerConfigBuilder`] to customize the [`ServerConfig`] connection configuration
1771    /// for a connection accepted using the [`Incoming::accept_with`] method.
1772    pub fn create_server_config_builder(&self, alpns: Vec<Vec<u8>>) -> ServerConfigBuilder {
1773        let inner = self.inner.static_config.create_server_config(alpns);
1774        ServerConfigBuilder::new(inner, self.inner.static_config.transport_config.clone())
1775    }
1776
1777    // # Remaining private methods
1778
1779    /// Translates a possible IP-mapped [`SocketAddr`] into a transport address.
1780    pub(crate) fn to_transport_addr(
1781        &self,
1782        addr: SocketAddr,
1783    ) -> Option<crate::socket::transports::Addr> {
1784        self.inner.to_transport_addr(addr)
1785    }
1786
1787    #[cfg(all(test, with_crypto_provider))]
1788    pub(crate) fn inner(&self) -> Result<Arc<EndpointInner>, EndpointError> {
1789        if self.is_closed() {
1790            return Err(e!(EndpointError::Closed));
1791        }
1792        Ok(self.inner.clone())
1793    }
1794}
1795
1796/// Options for the [`Endpoint::connect_with_opts`] function.
1797#[derive(Default, Debug, Clone)]
1798pub struct ConnectOptions {
1799    transport_config: Option<QuicTransportConfig>,
1800    additional_alpns: Vec<Vec<u8>>,
1801}
1802
1803impl ConnectOptions {
1804    /// Initializes new connection options.
1805    ///
1806    /// By default, the connection will use the same options
1807    /// as [`Endpoint::connect`], e.g. a default [`QuicTransportConfig`].
1808    pub fn new() -> Self {
1809        Self::default()
1810    }
1811
1812    /// Sets the QUIC transport config options for this connection.
1813    pub fn with_transport_config(mut self, transport_config: QuicTransportConfig) -> Self {
1814        self.transport_config = Some(transport_config);
1815        self
1816    }
1817
1818    /// Sets [ALPN] identifiers that should be signaled as supported on connection, *in
1819    /// addition* to the main [ALPN] identifier used in [`Endpoint::connect_with_opts`].
1820    ///
1821    /// This allows connecting to servers that may only support older versions of your
1822    /// protocol. In this case, you would add the older [ALPN] identifiers with this
1823    /// function.
1824    ///
1825    /// You'll know the final negotiated [ALPN] identifier once your connection was
1826    /// established using [`Connection::alpn`], or even slightly earlier in the
1827    /// handshake by using [`Connecting::alpn`].
1828    /// The negotiated [ALPN] identifier may be any of the [ALPN] identifiers in this
1829    /// list or the main [ALPN] used in [`Endpoint::connect_with_opts`].
1830    ///
1831    /// The [ALPN] identifier order on the connect side doesn't matter, since it's the
1832    /// accept side that determines the protocol.
1833    ///
1834    /// For setting the supported [ALPN] identifiers on the accept side, see the endpoint
1835    /// builder's [`Builder::alpns`] function.
1836    ///
1837    /// [ALPN]: https://en.wikipedia.org/wiki/Application-Layer_Protocol_Negotiation
1838    pub fn with_additional_alpns(mut self, alpns: Vec<Vec<u8>>) -> Self {
1839        self.additional_alpns = alpns;
1840        self
1841    }
1842}
1843
1844/// Future returned from [`Endpoint::closed`].
1845#[derive(derive_more::Debug)]
1846#[pin_project]
1847#[debug("EndpointClosed")]
1848pub struct EndpointClosed {
1849    #[pin]
1850    inner: WaitForCancellationFutureOwned,
1851}
1852
1853impl Future for EndpointClosed {
1854    type Output = ();
1855
1856    fn poll(
1857        self: Pin<&mut Self>,
1858        cx: &mut std::task::Context<'_>,
1859    ) -> std::task::Poll<Self::Output> {
1860        let this = self.project();
1861        this.inner.poll(cx)
1862    }
1863}
1864
1865impl EndpointClosed {
1866    /// Runs a future to completion, or until the [`Endpoint`] is closed.
1867    ///
1868    /// Returns the output of `fut` if it completes before the endpoint closes,
1869    /// or `None` otherwise.
1870    pub async fn run_until<F: Future>(self, fut: F) -> Option<F::Output> {
1871        n0_future::future::or(async { Some(fut.await) }, async {
1872            self.await;
1873            None
1874        })
1875        .await
1876    }
1877}
1878
1879/// Read a proxy url from the environment, in this order
1880///
1881/// - `HTTP_PROXY`
1882/// - `http_proxy`
1883/// - `HTTPS_PROXY`
1884/// - `https_proxy`
1885fn proxy_url_from_env() -> Option<Url> {
1886    if let Some(url) = std::env::var("HTTP_PROXY")
1887        .ok()
1888        .and_then(|s| s.parse::<Url>().ok())
1889    {
1890        if is_cgi() {
1891            warn!("HTTP_PROXY environment variable ignored in CGI");
1892        } else {
1893            return Some(url);
1894        }
1895    }
1896    if let Some(url) = std::env::var("http_proxy")
1897        .ok()
1898        .and_then(|s| s.parse::<Url>().ok())
1899    {
1900        return Some(url);
1901    }
1902    if let Some(url) = std::env::var("HTTPS_PROXY")
1903        .ok()
1904        .and_then(|s| s.parse::<Url>().ok())
1905    {
1906        return Some(url);
1907    }
1908    if let Some(url) = std::env::var("https_proxy")
1909        .ok()
1910        .and_then(|s| s.parse::<Url>().ok())
1911    {
1912        return Some(url);
1913    }
1914
1915    None
1916}
1917
1918/// Connection status of a single home relay.
1919///
1920/// Observed via [`Endpoint::home_relay_status`].
1921#[derive(Debug, Clone, PartialEq, Eq)]
1922pub struct RelayStatus {
1923    url: RelayUrl,
1924    state: RelayConnectionState,
1925}
1926
1927impl RelayStatus {
1928    pub(crate) fn new(url: RelayUrl, state: RelayConnectionState) -> Self {
1929        Self { url, state }
1930    }
1931
1932    /// Returns the URL of the home relay.
1933    pub fn url(&self) -> &RelayUrl {
1934        &self.url
1935    }
1936
1937    /// Returns `true` if the endpoint is connected to the relay.
1938    pub fn is_connected(&self) -> bool {
1939        self.state.is_connected()
1940    }
1941
1942    /// Returns the most recent connection error.
1943    ///
1944    /// Returns `None` when the relay is connected, or when the endpoint has
1945    /// not yet observed a failed connection attempt.
1946    ///
1947    /// The error is meant to be logged or displayed, not matched on: it is an
1948    /// [`AnyError`] wrapping a chain of private error types, none of which are
1949    /// covered by semver guarantees. Use [`Self::auth_denied_reason`] to
1950    /// distinguish the one failure that usually calls for a different reaction
1951    /// than retrying.
1952    pub fn last_error(&self) -> Option<&AnyError> {
1953        self.state.last_failure().map(RelayConnectionFailure::error)
1954    }
1955
1956    /// Returns the reason if the relay server denied our authentication.
1957    ///
1958    /// Unlike most connection failures, this one will not usually resolve
1959    /// itself. The endpoint keeps retrying with a backoff, but it presents the
1960    /// same credentials every time, so unless the relay's access policy
1961    /// changes it will keep being denied and [`Endpoint::online`] will never
1962    /// resolve. An application that configures a relay auth token should
1963    /// surface this to the user rather than wait to come online.
1964    ///
1965    /// The returned string is the reason reported by the relay server. It is
1966    /// meant to be human-readable, don't attempt to match on it.
1967    ///
1968    /// Returns `None` when the relay is connected, when no connection attempt
1969    /// has failed yet, or when the last failure had another cause.
1970    ///
1971    /// ```no_run
1972    /// # async fn wrapper() -> n0_error::Result<()> {
1973    /// # #[cfg(with_crypto_provider)]
1974    /// # {
1975    /// use iroh::{Endpoint, Watcher, endpoint::presets};
1976    /// use n0_future::StreamExt;
1977    ///
1978    /// let endpoint = Endpoint::builder(presets::Minimal).bind().await?;
1979    /// let mut status = endpoint.home_relay_status().stream();
1980    /// while let Some(relays) = status.next().await {
1981    ///     for relay in relays {
1982    ///         if let Some(reason) = relay.auth_denied_reason() {
1983    ///             println!("{}: authentication denied ({reason})", relay.url());
1984    ///         }
1985    ///     }
1986    /// }
1987    /// # }
1988    /// # Ok(()) }
1989    /// ```
1990    pub fn auth_denied_reason(&self) -> Option<&str> {
1991        self.state
1992            .last_failure()
1993            .and_then(RelayConnectionFailure::auth_denied_reason)
1994    }
1995}
1996
1997/// Configuration of the relay servers for an [`Endpoint`].
1998#[derive(Debug, Clone, PartialEq, Eq)]
1999pub enum RelayMode {
2000    /// Disable relay servers completely.
2001    /// This means that neither listening nor dialing relays will be available.
2002    Disabled,
2003    /// Use the default relay map, with production relay servers from n0.
2004    ///
2005    /// See [`crate::defaults::prod`] for the severs used.
2006    Default,
2007    /// Use the staging relay servers from n0.
2008    Staging,
2009    /// Use a custom relay map.
2010    Custom(RelayMap),
2011}
2012
2013impl RelayMode {
2014    /// Returns the relay map for this mode.
2015    pub fn relay_map(&self) -> RelayMap {
2016        match self {
2017            RelayMode::Disabled => RelayMap::empty(),
2018            RelayMode::Default => crate::defaults::prod::default_relay_map(),
2019            RelayMode::Staging => crate::defaults::staging::default_relay_map(),
2020            RelayMode::Custom(relay_map) => relay_map.clone(),
2021        }
2022    }
2023
2024    /// Create a custom relay mode from a list of [`RelayUrl`]s.
2025    ///
2026    /// # Example
2027    ///
2028    /// ```
2029    /// # fn main() -> n0_error::Result<()> {
2030    /// # use iroh::RelayMode;
2031    /// RelayMode::custom([
2032    ///     "https://use1-1.relay.n0.iroh.link.".parse()?,
2033    ///     "https://euw-1.relay.n0.iroh.link.".parse()?,
2034    /// ]);
2035    /// # Ok(()) }
2036    /// ```
2037    pub fn custom(map: impl IntoIterator<Item = RelayUrl>) -> Self {
2038        let m = RelayMap::from_iter(map);
2039        Self::Custom(m)
2040    }
2041}
2042
2043/// Environment variable to force the use of staging relays.
2044pub const ENV_FORCE_STAGING_RELAYS: &str = "IROH_FORCE_STAGING_RELAYS";
2045
2046/// Returns `true` if the use of staging relays is forced.
2047pub fn force_staging_infra() -> bool {
2048    matches!(std::env::var(ENV_FORCE_STAGING_RELAYS), Ok(value) if !value.is_empty())
2049}
2050
2051/// Returns the default relay mode.
2052///
2053/// If the `IROH_FORCE_STAGING_RELAYS` environment variable is non empty, it will return `RelayMode::Staging`.
2054/// Otherwise, it will return `RelayMode::Default`.
2055pub fn default_relay_mode() -> RelayMode {
2056    // Use staging in testing
2057    match force_staging_infra() {
2058        true => RelayMode::Staging,
2059        false => RelayMode::Default,
2060    }
2061}
2062
2063/// Check if we are being executed in a CGI context.
2064///
2065/// If so, a malicious client can send the `Proxy:` header, and it will
2066/// be in the `HTTP_PROXY` env var. So we don't use it :)
2067fn is_cgi() -> bool {
2068    std::env::var_os("REQUEST_METHOD").is_some()
2069}
2070
2071#[cfg(all(test, with_crypto_provider))]
2072mod tests {
2073    use std::{
2074        collections::BTreeMap,
2075        io,
2076        net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4},
2077        str::FromStr,
2078        sync::Arc,
2079        time::{Duration, Instant},
2080    };
2081
2082    use assert_matches::assert_matches;
2083    use iroh_base::{EndpointAddr, EndpointId, RelayUrl, SecretKey, TransportAddr};
2084    use iroh_dns::endpoint_info::UserData;
2085    use iroh_relay::{RelayConfig, RelayQuicConfig, server::Access, tls::CaTlsConfig};
2086    use n0_error::{AnyError as Error, Result, StackResultExt, StdResultExt};
2087    use n0_future::{BufferedStreamExt, StreamExt, future::now_or_never, stream, time};
2088    use n0_tracing_test::traced_test;
2089    use n0_watcher::Watcher;
2090    use noq::PathStats;
2091    use rand::{RngExt, SeedableRng};
2092    use rand_chacha::ChaCha8Rng;
2093    use tokio::sync::oneshot;
2094    use tracing::{Instrument, debug_span, error_span, info, info_span, instrument};
2095
2096    use super::Endpoint;
2097    use crate::{
2098        RelayMap, RelayMode,
2099        address_lookup::memory::MemoryLookup,
2100        endpoint::{
2101            ApplicationClose, BindError, BindOpts, ConnectError, ConnectOptions,
2102            ConnectWithOptsError, Connection, ConnectionError, PathEvent, PathEventStream, presets,
2103        },
2104        protocol::{AcceptError, ProtocolHandler, Router},
2105        test_utils::{
2106            QlogFileGroup, run_relay_server, run_relay_server_with, run_relay_server_with_access,
2107        },
2108    };
2109
2110    const TEST_ALPN: &[u8] = b"n0/iroh/test";
2111
2112    #[tokio::test]
2113    #[traced_test]
2114    async fn test_connect_self() -> Result {
2115        let ep = Endpoint::builder(presets::Minimal)
2116            .alpns(vec![TEST_ALPN.to_vec()])
2117            .bind()
2118            .await
2119            .unwrap();
2120        let my_addr = ep.addr();
2121        let res = ep.connect(my_addr.clone(), TEST_ALPN).await;
2122        assert!(res.is_err());
2123        let err = res.err().unwrap();
2124        assert!(err.to_string().starts_with("Connecting to ourself"));
2125
2126        Ok(())
2127    }
2128
2129    #[tokio::test]
2130    #[traced_test]
2131    async fn test_connect_empty_alpn() -> Result {
2132        let server = Endpoint::builder(presets::Minimal)
2133            .alpns(vec![TEST_ALPN.to_vec()])
2134            .bind()
2135            .await
2136            .unwrap();
2137        let server_addr = server.addr();
2138
2139        let client = Endpoint::builder(presets::Minimal).bind().await.unwrap();
2140        let res = client.connect(server_addr, b"").await;
2141        assert!(res.is_err());
2142        let err = res.err().unwrap();
2143        assert_matches!(
2144            err,
2145            ConnectError::Connect {
2146                source: ConnectWithOptsError::InvalidAlpn { .. },
2147                ..
2148            }
2149        );
2150
2151        Ok(())
2152    }
2153
2154    #[tokio::test]
2155    #[traced_test]
2156    async fn endpoint_connect_close() -> Result {
2157        let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(0u64);
2158        let (relay_map, relay_url, _guard) = run_relay_server().await?;
2159        let server_secret_key = SecretKey::from_bytes(&rng.random());
2160        let server_peer_id = server_secret_key.public();
2161
2162        let qlog = QlogFileGroup::from_env("endpoint_connect_close");
2163
2164        // Wait for the endpoint to be started to make sure it's up before clients try to connect
2165        let ep = Endpoint::builder(presets::Minimal)
2166            .relay_mode(RelayMode::Custom(relay_map.clone()))
2167            .secret_key(server_secret_key)
2168            .transport_config(qlog.create("server")?)
2169            .alpns(vec![TEST_ALPN.to_vec()])
2170            .ca_tls_config(CaTlsConfig::insecure_skip_verify())
2171            .bind()
2172            .await?;
2173        // Wait for the endpoint to be reachable via relay
2174        ep.online().await;
2175
2176        let server = tokio::spawn(
2177            async move {
2178                info!("accepting connection");
2179                let incoming = ep.accept().await.anyerr()?;
2180                let conn = incoming.await.anyerr()?;
2181                let mut stream = conn.accept_uni().await.anyerr()?;
2182                let mut buf = [0u8; 5];
2183                stream.read_exact(&mut buf).await.anyerr()?;
2184                info!("Accepted 1 stream, received {buf:?}.  Closing now.");
2185                // close the connection
2186                conn.close(7u8.into(), b"bye");
2187
2188                let res = conn.accept_uni().await;
2189                assert_eq!(res.unwrap_err(), ConnectionError::LocallyClosed);
2190
2191                let res = stream.read_to_end(10).await;
2192                assert_eq!(
2193                    res.unwrap_err(),
2194                    noq::ReadToEndError::Read(noq::ReadError::ConnectionLost(
2195                        ConnectionError::LocallyClosed
2196                    ))
2197                );
2198                info!("Closing the endpoint");
2199                ep.close().await;
2200                info!("server test completed");
2201                Ok::<_, Error>(())
2202            }
2203            .instrument(info_span!("test-server")),
2204        );
2205
2206        let client = tokio::spawn(
2207            async move {
2208                let ep = Endpoint::builder(presets::Minimal)
2209                    .relay_mode(RelayMode::Custom(relay_map))
2210                    .alpns(vec![TEST_ALPN.to_vec()])
2211                    .ca_tls_config(CaTlsConfig::insecure_skip_verify())
2212                    .transport_config(qlog.create("client")?)
2213                    .bind()
2214                    .await?;
2215                info!("client connecting");
2216                let endpoint_addr = EndpointAddr::new(server_peer_id).with_relay_url(relay_url);
2217                let conn = ep.connect(endpoint_addr, TEST_ALPN).await?;
2218                let mut stream = conn.open_uni().await.anyerr()?;
2219
2220                // First write is accepted by server.  We need this bit of synchronisation
2221                // because if the server closes after simply accepting the connection we can
2222                // not be sure our .open_uni() call would succeed as it may already receive
2223                // the error.
2224                stream.write_all(b"hello").await.anyerr()?;
2225
2226                info!("waiting for closed");
2227                // Remote now closes the connection, we should see an error sometime soon.
2228                let err = conn.closed().await;
2229                let expected_err = ConnectionError::ApplicationClosed(ApplicationClose {
2230                    error_code: 7u8.into(),
2231                    reason: b"bye".to_vec().into(),
2232                });
2233                assert_eq!(err, expected_err);
2234
2235                info!("opening new - expect it to fail");
2236                let res = conn.open_uni().await;
2237                assert_eq!(res.unwrap_err(), expected_err);
2238                info!("Closing the client");
2239                ep.close().await;
2240                info!("client test completed");
2241                Ok::<_, Error>(())
2242            }
2243            .instrument(info_span!("test-client")),
2244        );
2245
2246        let (server, client) = tokio::time::timeout(
2247            Duration::from_secs(30),
2248            n0_future::future::zip(server, client),
2249        )
2250        .await
2251        .anyerr()?;
2252        server.anyerr()??;
2253        client.anyerr()??;
2254        Ok(())
2255    }
2256
2257    #[tokio::test]
2258    #[traced_test]
2259    async fn endpoint_relay_connect_loop() -> Result {
2260        let test_start = Instant::now();
2261        let n_clients = 5;
2262        let n_chunks_per_client = 2;
2263        let chunk_size = 100;
2264        let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(42);
2265        let (relay_map, relay_url, _relay_guard) = run_relay_server().await.unwrap();
2266        let server_secret_key = SecretKey::from_bytes(&rng.random());
2267        let server_endpoint_id = server_secret_key.public();
2268
2269        // Make sure the server is bound before having clients connect to it:
2270        let ep = Endpoint::builder(presets::Minimal)
2271            .relay_mode(RelayMode::Custom(relay_map.clone()))
2272            .ca_tls_config(CaTlsConfig::insecure_skip_verify())
2273            .secret_key(server_secret_key)
2274            .alpns(vec![TEST_ALPN.to_vec()])
2275            .bind()
2276            .await?;
2277        // Also make sure the server has a working relay connection
2278        ep.online().await;
2279
2280        info!(time = ?test_start.elapsed(), "test setup done");
2281
2282        // The server accepts the connections of the clients sequentially.
2283        let server = tokio::spawn(
2284            async move {
2285                let eps = ep.bound_sockets();
2286
2287                info!(me = %ep.id().fmt_short(), eps = ?eps, "server listening on");
2288                for i in 0..n_clients {
2289                    let res = tokio::time::timeout(Duration::from_secs(5), async {
2290                        let round_start = Instant::now();
2291                        info!("[server] round {i}");
2292                        let incoming = ep.accept().await.anyerr()?;
2293                        let conn = incoming.await.anyerr()?;
2294                        let endpoint_id = conn.remote_id();
2295                        info!(%i, peer = %endpoint_id.fmt_short(), "accepted connection");
2296                        let (mut send, mut recv) = conn.accept_bi().await.anyerr()?;
2297                        let mut buf = vec![0u8; chunk_size];
2298                        for _i in 0..n_chunks_per_client {
2299                            recv.read_exact(&mut buf).await.anyerr()?;
2300                            send.write_all(&buf).await.anyerr()?;
2301                        }
2302                        info!(%i, peer = %endpoint_id.fmt_short(), "finishing");
2303                        send.finish().anyerr()?;
2304                        conn.closed().await; // we're the last to send data, so we wait for the other side to close
2305                        info!(%i, peer = %endpoint_id.fmt_short(), "finished");
2306                        info!("[server] round {i} done in {:?}", round_start.elapsed());
2307                        Ok::<_, Error>(())
2308                    })
2309                    .await
2310                    .std_context("timeout");
2311                    match res {
2312                        Err(err) | Ok(Err(err)) => {
2313                            // ensure we close the endpoint before returning early
2314                            // on error
2315                            ep.close().await;
2316                            return Err(err);
2317                        }
2318                        _ => {
2319                            // if this round went `Ok` don't close the endpoint yet
2320                        }
2321                    }
2322                }
2323                // close the endpoint before dropping the server task
2324                ep.close().await;
2325                Ok::<_, Error>(())
2326            }
2327            .instrument(debug_span!("server")),
2328        );
2329
2330        let client = tokio::spawn(async move {
2331            for i in 0..n_clients {
2332                let round_start = Instant::now();
2333                info!("[client] round {i}");
2334                let client_secret_key = SecretKey::from_bytes(&rng.random());
2335                let ep = Endpoint::builder(presets::Minimal)
2336                    .relay_mode(RelayMode::Custom(relay_map.clone()))
2337                    .alpns(vec![TEST_ALPN.to_vec()])
2338                    .ca_tls_config(CaTlsConfig::insecure_skip_verify())
2339                    .secret_key(client_secret_key)
2340                    .bind()
2341                    .await?;
2342                let ep_1 = ep.clone();
2343                let res = tokio::time::timeout(
2344                    Duration::from_secs(5),
2345                    async {
2346                        info!("client binding");
2347                        let eps = ep.bound_sockets();
2348
2349                        info!(me = %ep.id().fmt_short(), eps=?eps, "client bound");
2350                        let endpoint_addr =
2351                            EndpointAddr::new(server_endpoint_id).with_relay_url(relay_url.clone());
2352                        info!(to = ?endpoint_addr, "client connecting");
2353                        let conn = ep.connect(endpoint_addr, TEST_ALPN).await.anyerr()?;
2354                        info!("client connected");
2355                        let (mut send, mut recv) = conn.open_bi().await.anyerr()?;
2356
2357                        for i in 0..n_chunks_per_client {
2358                            let mut buf = vec![i; chunk_size];
2359                            send.write_all(&buf).await.anyerr()?;
2360                            recv.read_exact(&mut buf).await.anyerr()?;
2361                            assert_eq!(buf, vec![i; chunk_size]);
2362                        }
2363                        // we're the last to receive data, so we close
2364                        conn.close(0u32.into(), b"bye!");
2365                        info!("client finished");
2366                        Ok::<_, Error>(())
2367                    }
2368                    .instrument(debug_span!("client", %i)),
2369                )
2370                .await
2371                .std_context("timeout");
2372                ep_1.close().await;
2373                info!("client endpoint closed");
2374                res??;
2375                info!("[client] round {i} done in {:?}", round_start.elapsed());
2376            }
2377            Ok::<_, Error>(())
2378        });
2379
2380        server.await.anyerr()??;
2381        client.await.anyerr()??;
2382        Ok(())
2383    }
2384
2385    #[tokio::test]
2386    #[traced_test]
2387    async fn endpoint_send_relay() -> Result {
2388        let (relay_map, _relay_url, _guard) = run_relay_server().await?;
2389        let client = Endpoint::builder(presets::Minimal)
2390            .relay_mode(RelayMode::Custom(relay_map.clone()))
2391            .ca_tls_config(CaTlsConfig::insecure_skip_verify())
2392            .bind()
2393            .await?;
2394        let server = Endpoint::builder(presets::Minimal)
2395            .relay_mode(RelayMode::Custom(relay_map))
2396            .ca_tls_config(CaTlsConfig::insecure_skip_verify())
2397            .alpns(vec![TEST_ALPN.to_vec()])
2398            .bind()
2399            .await?;
2400
2401        let task = tokio::spawn({
2402            let server = server.clone();
2403            async move {
2404                let Some(conn) = server.accept().await else {
2405                    n0_error::bail_any!("Expected an incoming connection");
2406                };
2407                let conn = conn.await.anyerr()?;
2408                let (mut send, mut recv) = conn.accept_bi().await.anyerr()?;
2409                let data = recv.read_to_end(1000).await.anyerr()?;
2410                send.write_all(&data).await.anyerr()?;
2411                send.finish().anyerr()?;
2412                conn.closed().await;
2413
2414                Ok::<_, Error>(())
2415            }
2416        });
2417
2418        let addr = server.addr();
2419        let conn = client.connect(addr, TEST_ALPN).await?;
2420        let (mut send, mut recv) = conn.open_bi().await.anyerr()?;
2421        send.write_all(b"Hello, world!").await.anyerr()?;
2422        send.finish().anyerr()?;
2423        let data = recv.read_to_end(1000).await.anyerr()?;
2424        conn.close(0u32.into(), b"bye!");
2425
2426        task.await.anyerr()??;
2427
2428        client.close().await;
2429        server.close().await;
2430
2431        assert_eq!(&data, b"Hello, world!");
2432
2433        Ok(())
2434    }
2435
2436    #[tokio::test]
2437    #[traced_test]
2438    async fn endpoint_two_direct_only() -> Result {
2439        // Connect two endpoints on the same network, without a relay server, without
2440        // Address Lookup.
2441        let ep1 = {
2442            let span = info_span!("server");
2443            let _guard = span.enter();
2444            Endpoint::builder(presets::N0)
2445                .alpns(vec![TEST_ALPN.to_vec()])
2446                .relay_mode(RelayMode::Disabled)
2447                .bind()
2448                .await?
2449        };
2450        let ep2 = {
2451            let span = info_span!("client");
2452            let _guard = span.enter();
2453            Endpoint::builder(presets::N0)
2454                .alpns(vec![TEST_ALPN.to_vec()])
2455                .relay_mode(RelayMode::Disabled)
2456                .bind()
2457                .await?
2458        };
2459        let ep1_nodeaddr = ep1.addr();
2460
2461        #[instrument(name = "client", skip_all)]
2462        async fn connect(ep: Endpoint, dst: EndpointAddr) -> Result<ConnectionError> {
2463            info!(me = %ep.id().fmt_short(), "client starting");
2464            let conn = ep.connect(dst, TEST_ALPN).await?;
2465            let mut send = conn.open_uni().await.anyerr()?;
2466            send.write_all(b"hello").await.anyerr()?;
2467            send.finish().anyerr()?;
2468            Ok(conn.closed().await)
2469        }
2470
2471        #[instrument(name = "server", skip_all)]
2472        async fn accept(ep: Endpoint, src: EndpointId) -> Result {
2473            info!(me = %ep.id().fmt_short(), "server starting");
2474            let conn = ep.accept().await.anyerr()?.await.anyerr()?;
2475            let node_id = conn.remote_id();
2476            assert_eq!(node_id, src);
2477            let mut recv = conn.accept_uni().await.anyerr()?;
2478            let msg = recv.read_to_end(100).await.anyerr()?;
2479            assert_eq!(msg, b"hello");
2480            // Dropping the connection closes it just fine.
2481            Ok(())
2482        }
2483
2484        let ep1_accept = tokio::spawn(accept(ep1.clone(), ep2.id()));
2485        let ep2_connect = tokio::spawn(connect(ep2.clone(), ep1_nodeaddr));
2486
2487        ep1_accept.await.anyerr()??;
2488        let conn_closed = dbg!(ep2_connect.await.anyerr()??);
2489        assert!(matches!(
2490            conn_closed,
2491            ConnectionError::ApplicationClosed(ApplicationClose { .. })
2492        ));
2493
2494        Ok(())
2495    }
2496
2497    #[tokio::test]
2498    #[traced_test]
2499    async fn endpoint_two_relay_only_becomes_direct() -> Result {
2500        // Connect two endpoints on the same network, via a relay server, without
2501        // Address Lookup.  Wait until there is a direct connection.
2502        let (relay_map, _relay_url, _relay_server_guard) = run_relay_server().await?;
2503        let (node_addr_tx, node_addr_rx) = oneshot::channel();
2504        let qlog = Arc::new(QlogFileGroup::from_env("two_relay_only_becomes_direct"));
2505
2506        #[instrument(name = "client", skip_all)]
2507        async fn connect(
2508            relay_map: RelayMap,
2509            node_addr_rx: oneshot::Receiver<EndpointAddr>,
2510            qlog: Arc<QlogFileGroup>,
2511        ) -> Result<ConnectionError> {
2512            let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(0u64);
2513            let secret = SecretKey::from_bytes(&rng.random());
2514            let ep = Endpoint::builder(presets::N0)
2515                .secret_key(secret)
2516                .alpns(vec![TEST_ALPN.to_vec()])
2517                .ca_tls_config(CaTlsConfig::insecure_skip_verify())
2518                .relay_mode(RelayMode::Custom(relay_map))
2519                .transport_config(qlog.create("client")?)
2520                .bind()
2521                .await?;
2522            info!(me = %ep.id().fmt_short(), "client starting");
2523            let dst = node_addr_rx.await.anyerr()?;
2524
2525            info!(me = %ep.id().fmt_short(), "client connecting");
2526            let conn = ep.connect(dst, TEST_ALPN).await?;
2527            let mut send = conn.open_uni().await.anyerr()?;
2528            send.write_all(b"hello").await.anyerr()?;
2529            let mut paths = conn.paths_stream();
2530            info!("Waiting for direct connection");
2531            paths
2532                .wait_any(|path| path.is_ip())
2533                .await
2534                .context("path stream ended")?;
2535            info!("Have direct connection");
2536            #[cfg(feature = "metrics")]
2537            {
2538                // Validate holepunch metrics.
2539                assert_eq!(ep.metrics().socket.num_conns_opened.get(), 1);
2540                assert_eq!(ep.metrics().socket.num_conns_direct.get(), 1);
2541            }
2542
2543            send.write_all(b"close please").await.anyerr()?;
2544            send.finish().anyerr()?;
2545
2546            let res = conn.closed().await;
2547            ep.close().await;
2548            Ok(res)
2549        }
2550
2551        #[instrument(name = "server", skip_all)]
2552        async fn accept(
2553            relay_map: RelayMap,
2554            node_addr_tx: oneshot::Sender<EndpointAddr>,
2555            qlog: Arc<QlogFileGroup>,
2556        ) -> Result {
2557            let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(1u64);
2558            let secret = SecretKey::from_bytes(&rng.random());
2559            let ep = Endpoint::builder(presets::N0)
2560                .secret_key(secret)
2561                .alpns(vec![TEST_ALPN.to_vec()])
2562                .ca_tls_config(CaTlsConfig::insecure_skip_verify())
2563                .transport_config(qlog.create("server")?)
2564                .relay_mode(RelayMode::Custom(relay_map))
2565                .bind()
2566                .await?;
2567            ep.online().await;
2568            let mut node_addr = ep.addr();
2569            node_addr.addrs.retain(|addr| addr.is_relay());
2570            node_addr_tx.send(node_addr).unwrap();
2571
2572            info!(me = %ep.id().fmt_short(), "server starting");
2573            let conn = ep.accept().await.anyerr()?.await.anyerr()?;
2574            // let node_id = conn.remote_node_id()?;
2575            // assert_eq!(node_id, src);
2576            let mut recv = conn.accept_uni().await.anyerr()?;
2577            let mut msg = [0u8; 5];
2578            recv.read_exact(&mut msg).await.anyerr()?;
2579            assert_eq!(&msg, b"hello");
2580            info!("received hello");
2581            let msg = recv.read_to_end(100).await.anyerr()?;
2582            assert_eq!(msg, b"close please");
2583            info!("received 'close please'");
2584            // Closing the endpoint closes all connections.
2585            ep.close().await;
2586            Ok(())
2587        }
2588
2589        let server_task = tokio::spawn(accept(relay_map.clone(), node_addr_tx, qlog.clone()));
2590        let client_task = tokio::spawn(connect(relay_map, node_addr_rx, qlog));
2591
2592        server_task.await.anyerr()??;
2593        let conn_closed = dbg!(client_task.await.anyerr()??);
2594        assert!(matches!(
2595            conn_closed,
2596            ConnectionError::ApplicationClosed(ApplicationClose { .. })
2597        ));
2598
2599        Ok(())
2600    }
2601
2602    #[tokio::test]
2603    #[traced_test]
2604    async fn endpoint_two_relay_only_no_ip() -> Result {
2605        // Connect two endpoints on the same network, via a relay server, without
2606        // Address Lookup.
2607        let (relay_map, _relay_url, _relay_server_guard) = run_relay_server().await?;
2608        let (node_addr_tx, node_addr_rx) = oneshot::channel();
2609
2610        #[instrument(name = "client", skip_all)]
2611        async fn connect(
2612            relay_map: RelayMap,
2613            node_addr_rx: oneshot::Receiver<EndpointAddr>,
2614        ) -> Result<ConnectionError> {
2615            let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(0u64);
2616            let secret = SecretKey::from_bytes(&rng.random());
2617            let ep = Endpoint::builder(presets::N0)
2618                .secret_key(secret)
2619                .alpns(vec![TEST_ALPN.to_vec()])
2620                .ca_tls_config(CaTlsConfig::insecure_skip_verify())
2621                .relay_mode(RelayMode::Custom(relay_map))
2622                .clear_ip_transports() // disable direct
2623                .bind()
2624                .await?;
2625            info!(me = %ep.id().fmt_short(), "client starting");
2626            let dst = node_addr_rx.await.anyerr()?;
2627
2628            info!(me = %ep.id().fmt_short(), "client connecting");
2629            let conn = ep.connect(dst, TEST_ALPN).await?;
2630            let mut send = conn.open_uni().await.anyerr()?;
2631            send.write_all(b"hello").await.anyerr()?;
2632            let mut paths = conn.paths_stream();
2633            info!("Waiting for connection");
2634            paths
2635                .wait_any(|path| {
2636                    assert!(!path.is_ip(), "unexpected IP path: {path:?}");
2637                    path.is_relay()
2638                })
2639                .await
2640                .context("path stream ended")?;
2641            info!("Have relay connection");
2642
2643            send.write_all(b"close please").await.anyerr()?;
2644            send.finish().anyerr()?;
2645            let res = conn.closed().await;
2646            ep.close().await;
2647            Ok(res)
2648        }
2649
2650        #[instrument(name = "server", skip_all)]
2651        async fn accept(
2652            relay_map: RelayMap,
2653            node_addr_tx: oneshot::Sender<EndpointAddr>,
2654        ) -> Result {
2655            let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(1u64);
2656            let secret = SecretKey::from_bytes(&rng.random());
2657            let ep = Endpoint::builder(presets::N0)
2658                .secret_key(secret)
2659                .alpns(vec![TEST_ALPN.to_vec()])
2660                .ca_tls_config(CaTlsConfig::insecure_skip_verify())
2661                .relay_mode(RelayMode::Custom(relay_map))
2662                .clear_ip_transports()
2663                .bind()
2664                .await?;
2665            ep.online().await;
2666            let node_addr = ep.addr();
2667            node_addr_tx.send(node_addr).unwrap();
2668
2669            info!(me = %ep.id().fmt_short(), "server starting");
2670            let conn = ep.accept().await.anyerr()?.await.anyerr()?;
2671            // let node_id = conn.remote_node_id()?;
2672            // assert_eq!(node_id, src);
2673            let mut recv = conn.accept_uni().await.anyerr()?;
2674            let mut msg = [0u8; 5];
2675            recv.read_exact(&mut msg).await.anyerr()?;
2676            assert_eq!(&msg, b"hello");
2677            info!("received hello");
2678            let msg = recv.read_to_end(100).await.anyerr()?;
2679            assert_eq!(msg, b"close please");
2680            info!("received 'close please'");
2681            // Closing the endpoint closes all connections.
2682            ep.close().await;
2683            Ok(())
2684        }
2685
2686        let server_task = tokio::spawn(accept(relay_map.clone(), node_addr_tx));
2687        let client_task = tokio::spawn(connect(relay_map, node_addr_rx));
2688
2689        server_task.await.anyerr()??;
2690        let conn_closed = dbg!(client_task.await.anyerr()??);
2691        assert!(matches!(
2692            conn_closed,
2693            ConnectionError::ApplicationClosed(ApplicationClose { .. })
2694        ));
2695
2696        Ok(())
2697    }
2698
2699    #[tokio::test]
2700    #[traced_test]
2701    async fn endpoint_two_direct_add_relay() -> Result {
2702        // Connect two endpoints on the same network, without relay server and without
2703        // Address Lookup.  Add a relay connection later.
2704        let (relay_map, _relay_url, _relay_server_guard) = run_relay_server().await?;
2705        let (node_addr_tx, node_addr_rx) = oneshot::channel();
2706
2707        #[instrument(name = "client", skip_all)]
2708        async fn connect(
2709            relay_map: RelayMap,
2710            node_addr_rx: oneshot::Receiver<EndpointAddr>,
2711        ) -> Result<()> {
2712            let secret = SecretKey::from([0u8; 32]);
2713            let ep = Endpoint::builder(presets::N0)
2714                .secret_key(secret)
2715                .alpns(vec![TEST_ALPN.to_vec()])
2716                .ca_tls_config(CaTlsConfig::insecure_skip_verify())
2717                .relay_mode(RelayMode::Custom(relay_map))
2718                .bind()
2719                .await?;
2720            info!(me = %ep.id().fmt_short(), "client starting");
2721            let dst = node_addr_rx.await.anyerr()?;
2722
2723            info!(me = %ep.id().fmt_short(), "client connecting");
2724            let conn = ep.connect(dst, TEST_ALPN).await?;
2725            info!(me = %ep.id().fmt_short(), "client connected");
2726
2727            // We should be connected via IP, because it is faster than the relay server.
2728            // TODO: Maybe not panic if this is not true?
2729
2730            let path_info = conn.paths();
2731            assert_eq!(path_info.len(), 1);
2732            assert!(path_info.iter().next().unwrap().is_ip());
2733
2734            let mut paths = conn.paths_stream();
2735            time::timeout(
2736                Duration::from_secs(5),
2737                paths.wait_any(|path| path.is_relay()),
2738            )
2739            .await
2740            .anyerr()?
2741            .context("path stream ended")?;
2742            info!("client has a relay path");
2743
2744            // wait for the server to signal it has the relay connection
2745            let mut stream = conn.accept_uni().await.anyerr()?;
2746            stream.read_to_end(100).await.anyerr()?;
2747
2748            info!("client closing");
2749            conn.close(0u8.into(), b"");
2750            ep.close().await;
2751            Ok(())
2752        }
2753
2754        #[instrument(name = "server", skip_all)]
2755        async fn accept(
2756            relay_map: RelayMap,
2757            node_addr_tx: oneshot::Sender<EndpointAddr>,
2758        ) -> Result<ConnectionError> {
2759            let secret = SecretKey::from([1u8; 32]);
2760            let ep = Endpoint::builder(presets::N0)
2761                .secret_key(secret)
2762                .alpns(vec![TEST_ALPN.to_vec()])
2763                .ca_tls_config(CaTlsConfig::insecure_skip_verify())
2764                .relay_mode(RelayMode::Custom(relay_map))
2765                .bind()
2766                .await?;
2767            ep.online().await;
2768            let node_addr = ep.addr();
2769            node_addr_tx.send(node_addr).unwrap();
2770
2771            info!(me = %ep.id().fmt_short(), "server starting");
2772            let conn = ep.accept().await.anyerr()?.await.anyerr()?;
2773            info!(me = %ep.id().fmt_short(), "server accepted connection");
2774
2775            // Wait for a relay connection to be added.  Client does all the asserting here,
2776            // we just want to wait so we get to see all the mechanics of the connection
2777            // being added on this side too.
2778            let mut paths = conn.paths_stream();
2779            time::timeout(
2780                Duration::from_secs(5),
2781                paths.wait_any(|path| path.is_relay()),
2782            )
2783            .await
2784            .anyerr()?
2785            .context("path stream ended")?;
2786            info!("server has a relay path");
2787
2788            let mut stream = conn.open_uni().await.anyerr()?;
2789            stream.write_all(b"have relay").await.anyerr()?;
2790            stream.finish().anyerr()?;
2791            info!("waiting conn.closed()");
2792
2793            Ok(conn.closed().await)
2794        }
2795
2796        let server_task = tokio::spawn(accept(relay_map.clone(), node_addr_tx));
2797        let client_task = tokio::spawn(connect(relay_map, node_addr_rx));
2798
2799        client_task.await.anyerr()??;
2800        let conn_closed = dbg!(server_task.await.anyerr()??);
2801        assert!(matches!(
2802            conn_closed,
2803            ConnectionError::ApplicationClosed(ApplicationClose { .. })
2804        ));
2805
2806        Ok(())
2807    }
2808
2809    #[tokio::test]
2810    #[traced_test]
2811    async fn endpoint_relay_map_change() -> Result {
2812        let (relay_map, relay_url, _guard1) = run_relay_server().await?;
2813        let client = Endpoint::builder(presets::Minimal)
2814            .relay_mode(RelayMode::Custom(relay_map.clone()))
2815            .ca_tls_config(CaTlsConfig::insecure_skip_verify())
2816            .bind()
2817            .await?;
2818        let server = Endpoint::builder(presets::Minimal)
2819            .relay_mode(RelayMode::Custom(relay_map))
2820            .ca_tls_config(CaTlsConfig::insecure_skip_verify())
2821            .alpns(vec![TEST_ALPN.to_vec()])
2822            .bind()
2823            .await?;
2824
2825        let task = tokio::spawn({
2826            let server = server.clone();
2827            async move {
2828                for i in 0..2 {
2829                    println!("accept: round {i}");
2830                    let Some(conn) = server.accept().await else {
2831                        n0_error::bail_any!("Expected an incoming connection");
2832                    };
2833                    let conn = conn.await.anyerr()?;
2834                    let (mut send, mut recv) = conn.accept_bi().await.anyerr()?;
2835                    let data = recv.read_to_end(1000).await.anyerr()?;
2836                    send.write_all(&data).await.anyerr()?;
2837                    send.finish().anyerr()?;
2838                    conn.closed().await;
2839                }
2840                Ok::<_, Error>(())
2841            }
2842        });
2843
2844        server.online().await;
2845
2846        let mut addr = server.addr();
2847        println!("round1: {:?}", addr);
2848
2849        // remove direct addrs to force relay usage
2850        addr.addrs
2851            .retain(|addr| !matches!(addr, TransportAddr::Ip(_)));
2852
2853        let conn = client.connect(addr, TEST_ALPN).await?;
2854        let (mut send, mut recv) = conn.open_bi().await.anyerr()?;
2855        send.write_all(b"Hello, world!").await.anyerr()?;
2856        send.finish().anyerr()?;
2857        let data = recv.read_to_end(1000).await.anyerr()?;
2858        conn.close(0u32.into(), b"bye!");
2859
2860        assert_eq!(&data, b"Hello, world!");
2861
2862        // setup a second relay server
2863        let (new_relay_map, new_relay_url, _guard2) = run_relay_server().await?;
2864        let new_endpoint = new_relay_map
2865            .get(&new_relay_url)
2866            .expect("missing endpoint")
2867            .clone();
2868        dbg!(&new_relay_map);
2869
2870        let addr_watcher = server.watch_addr();
2871
2872        // add new new relay
2873        assert!(
2874            server
2875                .insert_relay(new_relay_url.clone(), new_endpoint.clone())
2876                .await
2877                .is_none()
2878        );
2879        // remove the old relay
2880        assert!(server.remove_relay(&relay_url).await.is_some());
2881
2882        println!("------- changed ----- ");
2883
2884        let mut addr = tokio::time::timeout(Duration::from_secs(10), async move {
2885            let mut stream = addr_watcher.stream();
2886            while let Some(addr) = stream.next().await {
2887                if addr.relay_urls().next() != Some(&relay_url) {
2888                    return addr;
2889                }
2890            }
2891            panic!("failed to change relay");
2892        })
2893        .await
2894        .anyerr()?;
2895
2896        println!("round2: {:?}", addr);
2897        assert_eq!(addr.relay_urls().next(), Some(&new_relay_url));
2898
2899        // remove direct addrs to force relay usage
2900        addr.addrs
2901            .retain(|addr| !matches!(addr, TransportAddr::Ip(_)));
2902
2903        let conn = client.connect(addr, TEST_ALPN).await?;
2904        let (mut send, mut recv) = conn.open_bi().await.anyerr()?;
2905        send.write_all(b"Hello, world!").await.anyerr()?;
2906        send.finish().anyerr()?;
2907        let data = recv.read_to_end(1000).await.anyerr()?;
2908        conn.close(0u32.into(), b"bye!");
2909
2910        task.await.anyerr()??;
2911
2912        client.close().await;
2913        server.close().await;
2914
2915        assert_eq!(&data, b"Hello, world!");
2916
2917        Ok(())
2918    }
2919
2920    #[tokio::test]
2921    #[traced_test]
2922    async fn endpoint_bidi_send_recv() -> Result {
2923        let disco = MemoryLookup::new();
2924        let ep1 = Endpoint::builder(presets::Minimal)
2925            .address_lookup(disco.clone())
2926            .alpns(vec![TEST_ALPN.to_vec()])
2927            .bind()
2928            .await?;
2929
2930        let ep2 = Endpoint::builder(presets::Minimal)
2931            .address_lookup(disco.clone())
2932            .alpns(vec![TEST_ALPN.to_vec()])
2933            .bind()
2934            .await?;
2935
2936        disco.add_endpoint_info(ep1.addr());
2937        disco.add_endpoint_info(ep2.addr());
2938
2939        let ep1_endpointid = ep1.id();
2940        let ep2_endpointid = ep2.id();
2941        eprintln!("endpoint id 1 {ep1_endpointid}");
2942        eprintln!("endpoint id 2 {ep2_endpointid}");
2943
2944        async fn connect_hello(ep: Endpoint, dst: EndpointId) -> Result {
2945            let conn = ep.connect(dst, TEST_ALPN).await?;
2946            let (mut send, mut recv) = conn.open_bi().await.anyerr()?;
2947            info!("sending hello");
2948            send.write_all(b"hello").await.anyerr()?;
2949            send.finish().anyerr()?;
2950            info!("receiving world");
2951            let m = recv.read_to_end(100).await.anyerr()?;
2952            assert_eq!(m, b"world");
2953            conn.close(1u8.into(), b"done");
2954            Ok(())
2955        }
2956
2957        async fn accept_world(ep: Endpoint, src: EndpointId) -> Result {
2958            let incoming = ep.accept().await.anyerr()?;
2959            let mut iconn = incoming.accept().anyerr()?;
2960            let alpn = iconn.alpn().await?;
2961            let conn = iconn.await.anyerr()?;
2962            let endpoint_id = conn.remote_id();
2963            assert_eq!(endpoint_id, src);
2964            assert_eq!(alpn, TEST_ALPN);
2965            let (mut send, mut recv) = conn.accept_bi().await.anyerr()?;
2966            info!("receiving hello");
2967            let m = recv.read_to_end(100).await.anyerr()?;
2968            assert_eq!(m, b"hello");
2969            info!("sending hello");
2970            send.write_all(b"world").await.anyerr()?;
2971            send.finish().anyerr()?;
2972            match conn.closed().await {
2973                ConnectionError::ApplicationClosed(closed) => {
2974                    assert_eq!(closed.error_code, 1u8.into());
2975                    Ok(())
2976                }
2977                _ => panic!("wrong close error"),
2978            }
2979        }
2980
2981        let p1_accept = tokio::spawn(accept_world(ep1.clone(), ep2_endpointid).instrument(
2982            info_span!(
2983                "p1_accept",
2984                ep1 = %ep1.id().fmt_short(),
2985                dst = %ep2_endpointid.fmt_short(),
2986            ),
2987        ));
2988        let p2_accept = tokio::spawn(accept_world(ep2.clone(), ep1_endpointid).instrument(
2989            info_span!(
2990                "p2_accept",
2991                ep2 = %ep2.id().fmt_short(),
2992                dst = %ep1_endpointid.fmt_short(),
2993            ),
2994        ));
2995        let p1_connect = tokio::spawn(connect_hello(ep1.clone(), ep2_endpointid).instrument(
2996            info_span!(
2997                "p1_connect",
2998                ep1 = %ep1.id().fmt_short(),
2999                dst = %ep2_endpointid.fmt_short(),
3000            ),
3001        ));
3002        let p2_connect = tokio::spawn(connect_hello(ep2.clone(), ep1_endpointid).instrument(
3003            info_span!(
3004                "p2_connect",
3005                ep2 = %ep2.id().fmt_short(),
3006                dst = %ep1_endpointid.fmt_short(),
3007            ),
3008        ));
3009
3010        p1_accept.await.anyerr()??;
3011        p2_accept.await.anyerr()??;
3012        p1_connect.await.anyerr()??;
3013        p2_connect.await.anyerr()??;
3014
3015        Ok(())
3016    }
3017
3018    /// Regression test: Don't fail connections with dead relays on Windows.
3019    ///
3020    /// A single client connecting to a single server over a usable direct path
3021    /// must succeed even when both are configured with an unreachable home relay
3022    /// (`https://127.0.0.1:1`, nothing listening). The dead relay should be irrelevant:
3023    /// the direct path works and the connection comes up in milliseconds.
3024    ///
3025    /// This was broken on Windows because QaD sends over the same socket to the dead
3026    /// relay, and the socket would return recv errors on the next recv to report ICMP
3027    /// errors for the previous send. We now skip over these errors, implemented in
3028    /// https://github.com/n0-computer/net-tools/pull/166, so this no longer fails.
3029    #[tokio::test]
3030    async fn endpoint_unreachable_relay_direct_connect_succeeds() -> Result {
3031        // The relay url and its QADv4 probe must both hit closed ports, so the relay is
3032        // unreachable and the probe draws the ICMP port-unreachable the Windows socket
3033        // reports on its next recv. Claim an ephemeral port, then close it: it's now free,
3034        // so nothing answers. There's nothing stopping the kernel from reusing a port
3035        // right away, but on most machines that's unlikely. The url is dialed over TCP
3036        // (HTTPS), the probe over UDP, so claim each with the matching socket type.
3037        let closed_tcp_port = {
3038            let sock = std::net::TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).expect("bind");
3039            sock.local_addr().expect("local addr").port()
3040        };
3041        let closed_udp_port = {
3042            let sock = std::net::UdpSocket::bind((Ipv4Addr::LOCALHOST, 0)).expect("bind");
3043            sock.local_addr().expect("local addr").port()
3044        };
3045        let dead_relay: RelayUrl = format!("https://127.0.0.1:{closed_tcp_port}")
3046            .parse()
3047            .expect("valid relay url");
3048        let dead_relay_config = RelayConfig::new(
3049            dead_relay.clone(),
3050            Some(RelayQuicConfig::new(closed_udp_port)),
3051        );
3052
3053        let bind_endpoint = async || {
3054            Endpoint::builder(presets::Minimal)
3055                // Use the broken relay to trigger the ICMP errors from the QaD sends.
3056                .relay_mode(RelayMode::Custom(RelayMap::from_iter([
3057                    dead_relay_config.clone()
3058                ])))
3059                .ca_tls_config(CaTlsConfig::insecure_skip_verify())
3060                .alpns(vec![TEST_ALPN.to_vec()])
3061                // Bind on IPv4 only to ensure a single socket to not have spurious polls.
3062                .bind_addr((Ipv4Addr::LOCALHOST, 0))
3063                .expect("valid addr")
3064                .bind()
3065                .await
3066        };
3067
3068        let server = bind_endpoint().await?;
3069        let server_addr = server.addr().with_relay_url(dead_relay.clone());
3070        let client = bind_endpoint().await?;
3071
3072        // Server accepts the incoming connection and holds it open until the test ends.
3073        let accept = tokio::spawn(async move {
3074            let incoming = server.accept().await.anyerr()?;
3075            let conn = incoming.await.anyerr()?;
3076            conn.closed().await;
3077            server.close().await;
3078            n0_error::Ok(())
3079        });
3080
3081        // The connect must complete over the direct loopback path despite the dead relay.
3082        let _conn = tokio::time::timeout(
3083            Duration::from_secs(10),
3084            client.connect(server_addr, TEST_ALPN),
3085        )
3086        .await
3087        .expect("connection should succeed")?;
3088        client.close().await;
3089        accept.await.anyerr()??;
3090        Ok(())
3091    }
3092
3093    #[tokio::test]
3094    #[traced_test]
3095    async fn test_direct_addresses_no_qad_relay() -> Result {
3096        let (relay_map, _, _guard) = run_relay_server_with(false).await.unwrap();
3097
3098        let ep = Endpoint::builder(presets::Minimal)
3099            .relay_mode(RelayMode::Custom(relay_map))
3100            .alpns(vec![TEST_ALPN.to_vec()])
3101            .ca_tls_config(CaTlsConfig::insecure_skip_verify())
3102            .bind()
3103            .await?;
3104
3105        assert!(ep.addr().ip_addrs().count() > 0);
3106
3107        Ok(())
3108    }
3109
3110    /// Test that configured external addresses are included in the endpoint's
3111    /// direct addresses, both when set via builder and at runtime.
3112    #[tokio::test(flavor = "current_thread", start_paused = true)]
3113    #[traced_test]
3114    async fn test_external_addr() -> Result {
3115        let configured_addr = SocketAddr::from(SocketAddrV4::new(Ipv4Addr::new(1, 2, 3, 4), 12345));
3116
3117        // Test builder-configured external address
3118        let ep = Endpoint::builder(presets::Minimal)
3119            .external_addr(configured_addr)
3120            .bind()
3121            .await?;
3122
3123        let addr = ep.addr();
3124        assert!(
3125            addr.ip_addrs().any(|a| *a == configured_addr),
3126            "builder-configured external addr {configured_addr} not found in endpoint addr: {addr:?}"
3127        );
3128
3129        // Test runtime add
3130        let runtime_addr = SocketAddr::from(SocketAddrV4::new(Ipv4Addr::new(5, 6, 7, 8), 54321));
3131        ep.add_external_addr(runtime_addr).await;
3132        tokio::time::sleep(Duration::from_millis(100)).await;
3133
3134        let addr = ep.addr();
3135        assert!(
3136            addr.ip_addrs().any(|a| *a == runtime_addr),
3137            "runtime-added external addr {runtime_addr} not found in endpoint addr: {addr:?}"
3138        );
3139
3140        // Test runtime remove
3141        let removed = ep.remove_external_addr(&runtime_addr).await;
3142        assert!(removed);
3143        tokio::time::sleep(Duration::from_millis(100)).await;
3144
3145        let addr = ep.addr();
3146        assert!(
3147            !addr.ip_addrs().any(|a| *a == runtime_addr),
3148            "removed external addr {runtime_addr} still found in endpoint addr: {addr:?}"
3149        );
3150        assert!(
3151            addr.ip_addrs().any(|a| *a == configured_addr),
3152            "builder-configured external addr should still be present: {addr:?}"
3153        );
3154
3155        ep.close().await;
3156        Ok(())
3157    }
3158
3159    #[tokio::test]
3160    #[traced_test]
3161    async fn graceful_close() -> Result {
3162        let client = Endpoint::bind(presets::Minimal).await?;
3163        let server = Endpoint::builder(presets::Minimal)
3164            .alpns(vec![TEST_ALPN.to_vec()])
3165            .bind()
3166            .await?;
3167        let server_addr = server.addr();
3168        let server_task = tokio::spawn(async move {
3169            let incoming = server.accept().await.anyerr()?;
3170            let conn = incoming.await.anyerr()?;
3171            let (mut send, mut recv) = conn.accept_bi().await.anyerr()?;
3172            let msg = recv.read_to_end(1_000).await.anyerr()?;
3173            send.write_all(&msg).await.anyerr()?;
3174            send.finish().anyerr()?;
3175            let close_reason = conn.closed().await;
3176            Ok::<_, Error>(close_reason)
3177        });
3178
3179        let conn = client.connect(server_addr, TEST_ALPN).await?;
3180        let (mut send, mut recv) = conn.open_bi().await.anyerr()?;
3181        send.write_all(b"Hello, world!").await.anyerr()?;
3182        send.finish().anyerr()?;
3183        recv.read_to_end(1_000).await.anyerr()?;
3184        conn.close(42u32.into(), b"thanks, bye!");
3185        client.close().await;
3186
3187        let close_err = server_task.await.anyerr()??;
3188        let ConnectionError::ApplicationClosed(app_close) = close_err else {
3189            panic!("Unexpected close reason: {close_err:?}");
3190        };
3191
3192        assert_eq!(app_close.error_code, 42u32.into());
3193        assert_eq!(app_close.reason.as_ref(), b"thanks, bye!");
3194
3195        Ok(())
3196    }
3197
3198    #[cfg(feature = "metrics")]
3199    #[tokio::test]
3200    #[traced_test]
3201    async fn metrics_smoke() -> Result {
3202        use iroh_metrics::Registry;
3203
3204        let secret_key = SecretKey::from_bytes(&[0u8; 32]);
3205        let client = Endpoint::builder(presets::Minimal)
3206            .secret_key(secret_key)
3207            .bind()
3208            .await?;
3209        let secret_key = SecretKey::from_bytes(&[1u8; 32]);
3210        let server = Endpoint::builder(presets::Minimal)
3211            .secret_key(secret_key)
3212            .alpns(vec![TEST_ALPN.to_vec()])
3213            .bind()
3214            .await?;
3215        let server_addr = server.addr();
3216        let server_task = tokio::task::spawn(async move {
3217            let conn = server.accept().await.anyerr()?.await.anyerr()?;
3218            let mut uni = conn.accept_uni().await.anyerr()?;
3219            uni.read_to_end(10).await.anyerr()?;
3220            drop(conn);
3221            Ok::<_, Error>(server)
3222        });
3223        let conn = client.connect(server_addr, TEST_ALPN).await?;
3224        let mut uni = conn.open_uni().await.anyerr()?;
3225        uni.write_all(b"helloworld").await.anyerr()?;
3226        uni.finish().anyerr()?;
3227        conn.closed().await;
3228        drop(conn);
3229        let server = server_task.await.anyerr()??;
3230
3231        let m = client.metrics();
3232        // assert_eq!(m.socket.num_direct_conns_added.get(), 1);
3233        // assert_eq!(m.socket.connection_became_direct.get(), 1);
3234        // assert_eq!(m.socket.connection_handshake_success.get(), 1);
3235        // assert_eq!(m.socket.endpoints_contacted_directly.get(), 1);
3236        assert!(m.socket.recv_datagrams.get() > 0);
3237
3238        let m = server.metrics();
3239        // assert_eq!(m.socket.num_direct_conns_added.get(), 1);
3240        // assert_eq!(m.socket.connection_became_direct.get(), 1);
3241        // assert_eq!(m.socket.endpoints_contacted_directly.get(), 1);
3242        // assert_eq!(m.socket.connection_handshake_success.get(), 1);
3243        assert!(m.socket.recv_datagrams.get() > 0);
3244
3245        // test openmetrics encoding with labeled subregistries per endpoint
3246        fn register_endpoint(registry: &mut Registry, endpoint: &Endpoint) {
3247            let id = endpoint.id().fmt_short();
3248            let sub_registry = registry.sub_registry_with_label("id", id.to_string());
3249            sub_registry.register_all(endpoint.metrics());
3250        }
3251        let mut registry = Registry::default();
3252        register_endpoint(&mut registry, &client);
3253        register_endpoint(&mut registry, &server);
3254        // let s = registry.encode_openmetrics_to_string().anyerr()?;
3255        // assert!(s.contains(r#"socket_endpoints_contacted_directly_total{id="3b6a27bcce"} 1"#));
3256        // assert!(s.contains(r#"socket_endpoints_contacted_directly_total{id="8a88e3dd74"} 1"#));
3257        Ok(())
3258    }
3259
3260    /// Configures the accept side to take `accept_alpns` ALPNs, then connects to it with `primary_connect_alpn`
3261    /// with `secondary_connect_alpns` set, and finally returns the negotiated ALPN.
3262    async fn alpn_connection_test(
3263        accept_alpns: Vec<Vec<u8>>,
3264        primary_connect_alpn: &[u8],
3265        secondary_connect_alpns: Vec<Vec<u8>>,
3266    ) -> Result<Vec<u8>> {
3267        let client = Endpoint::bind(presets::Minimal).await?;
3268        let server = Endpoint::builder(presets::Minimal)
3269            .alpns(accept_alpns)
3270            .bind()
3271            .await?;
3272        let server_addr = server.addr();
3273        let server_task = tokio::spawn({
3274            let server = server.clone();
3275            async move {
3276                let incoming = server.accept().await.anyerr()?;
3277                let conn = incoming.await.anyerr()?;
3278                conn.close(0u32.into(), b"bye!");
3279                n0_error::Ok(conn.alpn().to_vec())
3280            }
3281        });
3282
3283        let conn = client
3284            .connect_with_opts(
3285                server_addr,
3286                primary_connect_alpn,
3287                ConnectOptions::new().with_additional_alpns(secondary_connect_alpns),
3288            )
3289            .await?;
3290        let conn = conn.await.anyerr()?;
3291        let client_alpn = conn.alpn();
3292        conn.closed().await;
3293        client.close().await;
3294        server.close().await;
3295
3296        let server_alpn = server_task.await.anyerr()??;
3297
3298        assert_eq!(client_alpn, server_alpn);
3299
3300        Ok(server_alpn.to_vec())
3301    }
3302
3303    #[tokio::test]
3304    #[traced_test]
3305    async fn connect_multiple_alpn_negotiated() -> Result {
3306        const ALPN_ONE: &[u8] = b"alpn/1";
3307        const ALPN_TWO: &[u8] = b"alpn/2";
3308
3309        assert_eq!(
3310            alpn_connection_test(
3311                // Prefer version 2 over version 1 on the accept side
3312                vec![ALPN_TWO.to_vec(), ALPN_ONE.to_vec()],
3313                ALPN_TWO,
3314                vec![ALPN_ONE.to_vec()],
3315            )
3316            .await?,
3317            ALPN_TWO.to_vec(),
3318            "accept side prefers version 2 over 1"
3319        );
3320
3321        assert_eq!(
3322            alpn_connection_test(
3323                // Only support the old version
3324                vec![ALPN_ONE.to_vec()],
3325                ALPN_TWO,
3326                vec![ALPN_ONE.to_vec()],
3327            )
3328            .await?,
3329            ALPN_ONE.to_vec(),
3330            "accept side only supports the old version"
3331        );
3332
3333        assert_eq!(
3334            alpn_connection_test(
3335                vec![ALPN_TWO.to_vec(), ALPN_ONE.to_vec()],
3336                ALPN_ONE,
3337                vec![ALPN_TWO.to_vec()],
3338            )
3339            .await?,
3340            ALPN_TWO.to_vec(),
3341            "connect side ALPN order doesn't matter"
3342        );
3343
3344        assert_eq!(
3345            alpn_connection_test(vec![ALPN_TWO.to_vec(), ALPN_ONE.to_vec()], ALPN_ONE, vec![],)
3346                .await?,
3347            ALPN_ONE.to_vec(),
3348            "connect side only supports the old version"
3349        );
3350
3351        Ok(())
3352    }
3353
3354    #[tokio::test]
3355    #[traced_test]
3356    #[cfg(feature = "unstable-net-report")]
3357    async fn watch_net_report() -> Result {
3358        let endpoint = Endpoint::builder(presets::Minimal)
3359            .relay_mode(RelayMode::Staging)
3360            .bind()
3361            .await?;
3362
3363        // can get a first report
3364        endpoint.net_report().updated().await.anyerr()?;
3365
3366        Ok(())
3367    }
3368
3369    /// Tests that initial connection establishment isn't extremely slow compared
3370    /// to subsequent connections.
3371    ///
3372    /// This is a time based test, but uses a very large ratio to reduce flakiness.
3373    /// It also does a number of connections to average out any anomalies.
3374    #[tokio::test]
3375    #[traced_test]
3376    async fn connect_multi_time() -> Result {
3377        let n = 32;
3378
3379        const NOOP_ALPN: &[u8] = b"noop";
3380
3381        #[derive(Debug, Clone)]
3382        struct Noop;
3383
3384        impl ProtocolHandler for Noop {
3385            async fn accept(&self, connection: Connection) -> Result<(), AcceptError> {
3386                connection.closed().await;
3387                Ok(())
3388            }
3389        }
3390
3391        async fn noop_server() -> Result<(Router, EndpointAddr)> {
3392            let endpoint = Endpoint::bind(presets::Minimal).await.anyerr()?;
3393            let addr = endpoint.addr();
3394            let router = Router::builder(endpoint).accept(NOOP_ALPN, Noop).spawn();
3395            Ok((router, addr))
3396        }
3397
3398        let routers = stream::iter(0..n)
3399            .map(|_| noop_server())
3400            .buffered_unordered(32)
3401            .collect::<Vec<_>>()
3402            .await
3403            .into_iter()
3404            .collect::<Result<Vec<_>, _>>()
3405            .anyerr()?;
3406
3407        let addrs = routers
3408            .iter()
3409            .map(|(_, addr)| addr.clone())
3410            .collect::<Vec<_>>();
3411        let ids = addrs.iter().map(|addr| addr.id).collect::<Vec<_>>();
3412        let address_lookup = MemoryLookup::from_endpoint_info(addrs);
3413        let endpoint = Endpoint::builder(presets::Minimal)
3414            .address_lookup(address_lookup)
3415            .bind()
3416            .await
3417            .anyerr()?;
3418        // wait for the endpoint to be initialized. This should not be needed,
3419        // but we don't want to measure endpoint init time but connection time
3420        // from a fully initialized endpoint.
3421        endpoint.addr();
3422        let t0 = Instant::now();
3423        for id in &ids {
3424            let conn = endpoint.connect(*id, NOOP_ALPN).await?;
3425            conn.close(0u32.into(), b"done");
3426        }
3427        let dt0 = t0.elapsed().as_secs_f64();
3428        let t1 = Instant::now();
3429        for id in &ids {
3430            let conn = endpoint.connect(*id, NOOP_ALPN).await?;
3431            conn.close(0u32.into(), b"done");
3432        }
3433        let dt1 = t1.elapsed().as_secs_f64();
3434
3435        assert!(dt0 / dt1 < 20.0, "First round: {dt0}s, second round {dt1}s");
3436        Ok(())
3437    }
3438
3439    #[tokio::test]
3440    async fn test_custom_relay() -> Result {
3441        let _ep = Endpoint::builder(presets::Minimal)
3442            .relay_mode(RelayMode::custom([RelayUrl::from_str(
3443                "https://use1-1.relay.n0.iroh.link.",
3444            )?]))
3445            .bind()
3446            .await?;
3447
3448        let relays = RelayMap::try_from_iter([
3449            "https://use1-1.relay.n0.iroh.link/",
3450            "https://euc1-1.relay.n0.iroh.link/",
3451        ])?;
3452        let _ep = Endpoint::builder(presets::Minimal)
3453            .relay_mode(RelayMode::Custom(relays))
3454            .bind()
3455            .await?;
3456
3457        Ok(())
3458    }
3459
3460    /// Testing bind_addr: Clear IP transports and add single IPv4 bind
3461    #[tokio::test]
3462    #[traced_test]
3463    async fn test_bind_addr_clear() -> Result {
3464        let ep = Endpoint::builder(presets::Minimal)
3465            .clear_ip_transports()
3466            .bind_addr((Ipv4Addr::LOCALHOST, 0))?
3467            .bind()
3468            .await?;
3469        let bound_sockets = ep.bound_sockets();
3470        assert_eq!(bound_sockets.len(), 1);
3471        assert_eq!(bound_sockets[0].ip(), IpAddr::V4(Ipv4Addr::LOCALHOST));
3472        ep.close().await;
3473        Ok(())
3474    }
3475
3476    /// Testing bind_addr: Do not clear IP transports and add single non-default IPv4 bind
3477    ///
3478    /// This will bind two sockets: default wildcard bind for IPv6, and our
3479    /// manually-added IPv4 bind.
3480    #[tokio::test]
3481    #[traced_test]
3482    async fn test_bind_addr_no_clear() -> Result {
3483        let ep = Endpoint::builder(presets::Minimal)
3484            .bind_addr((Ipv4Addr::LOCALHOST, 0))?
3485            .bind()
3486            .await?;
3487        let bound_sockets = ep.bound_sockets();
3488        assert_eq!(bound_sockets.len(), 2);
3489        assert_eq!(bound_sockets.iter().filter(|x| x.is_ipv4()).count(), 1);
3490        assert_eq!(bound_sockets.iter().filter(|x| x.is_ipv6()).count(), 1);
3491        // Test that our manually added socket is there
3492        assert!(
3493            bound_sockets
3494                .iter()
3495                .any(|x| x.ip() == IpAddr::V4(Ipv4Addr::LOCALHOST))
3496        );
3497        ep.close().await;
3498        Ok(())
3499    }
3500
3501    // Testing bind_addr: Do not clear IP transports and add single default IPv4 bind.
3502    //
3503    // This replaces the default IPv4 bind added by the builder,
3504    // but keeps the default wildcard IPv6 bind.
3505    #[tokio::test]
3506    #[traced_test]
3507    async fn test_bind_addr_default() -> Result {
3508        let ep = Endpoint::builder(presets::Minimal)
3509            .bind_addr_with_opts(
3510                (Ipv4Addr::LOCALHOST, 0),
3511                BindOpts::default().set_is_default_route(true),
3512            )?
3513            .bind()
3514            .await?;
3515        let bound_sockets = ep.bound_sockets();
3516        assert_eq!(bound_sockets.len(), 2);
3517        assert_eq!(bound_sockets.iter().filter(|x| x.is_ipv4()).count(), 1);
3518        assert_eq!(bound_sockets.iter().filter(|x| x.is_ipv6()).count(), 1);
3519        assert!(
3520            bound_sockets
3521                .iter()
3522                .any(|x| x.ip() == IpAddr::V4(Ipv4Addr::LOCALHOST))
3523        );
3524        ep.close().await;
3525        drop(ep);
3526
3527        Ok(())
3528    }
3529
3530    /// Testing bind_addr: Do not clear IP transports and add single IPv4 bind with a non-zero prefix len
3531    ///
3532    /// This will bind three sockets: default wildcard bind for IPv4 and IPv6, and our
3533    /// manually-added IPv4 bind.
3534    #[tokio::test]
3535    #[traced_test]
3536    async fn test_bind_addr_nonzero_prefix() -> Result {
3537        let ep = Endpoint::builder(presets::Minimal)
3538            .bind_addr_with_opts(
3539                (Ipv4Addr::LOCALHOST, 0),
3540                BindOpts::default().set_prefix_len(32),
3541            )?
3542            .bind()
3543            .await?;
3544        let bound_sockets = ep.bound_sockets();
3545        assert_eq!(bound_sockets.len(), 3);
3546        assert_eq!(bound_sockets.iter().filter(|x| x.is_ipv4()).count(), 2);
3547        assert_eq!(bound_sockets.iter().filter(|x| x.is_ipv6()).count(), 1);
3548        // Test that the default wildcard socket is there
3549        assert!(
3550            bound_sockets
3551                .iter()
3552                .any(|x| x.ip() == IpAddr::V4(Ipv4Addr::UNSPECIFIED))
3553        );
3554        // Test that our manually added socket is there
3555        assert!(
3556            bound_sockets
3557                .iter()
3558                .any(|x| x.ip() == IpAddr::V4(Ipv4Addr::LOCALHOST))
3559        );
3560        ep.close().await;
3561        Ok(())
3562    }
3563
3564    /// Bind on an unusable port with the default opts.
3565    ///
3566    /// Binding the endpoint fails with an AddrInUse error.
3567    #[tokio::test]
3568    #[traced_test]
3569    async fn test_bind_addr_badport() -> Result {
3570        let socket = std::net::UdpSocket::bind((Ipv4Addr::LOCALHOST, 0))?;
3571        let port = socket.local_addr()?.port();
3572
3573        let res = Endpoint::builder(presets::Minimal)
3574            .clear_ip_transports()
3575            .bind_addr((Ipv4Addr::LOCALHOST, port))?
3576            .bind()
3577            .await;
3578
3579        assert!(matches!(
3580            res,
3581            Err(BindError::Sockets {
3582                source: io_error,
3583                ..
3584            })
3585            if io_error.kind() == io::ErrorKind::AddrInUse
3586        ));
3587        Ok(())
3588    }
3589
3590    /// Bind a non-default route on an unusable port, but set is_required = false.
3591    ///
3592    /// Binding the endpoint succeeds.
3593    #[tokio::test]
3594    #[traced_test]
3595    async fn test_bind_addr_badport_notrequired() -> Result {
3596        let socket = std::net::UdpSocket::bind((Ipv4Addr::LOCALHOST, 0))?;
3597        let port = socket.local_addr()?.port();
3598
3599        let ep = Endpoint::builder(presets::Minimal)
3600            .bind_addr_with_opts(
3601                (Ipv4Addr::LOCALHOST, port),
3602                BindOpts::default()
3603                    .set_prefix_len(32)
3604                    .set_is_required(false),
3605            )?
3606            .bind()
3607            .await?;
3608        let bound_sockets = ep.bound_sockets();
3609        // just the default wildcard binds
3610        assert_eq!(bound_sockets.len(), 2);
3611        // our requested bind addr is not included because it failed to bind
3612        assert!(
3613            !bound_sockets
3614                .iter()
3615                .any(|x| x.ip() == IpAddr::V4(Ipv4Addr::LOCALHOST))
3616        );
3617        Ok(())
3618    }
3619
3620    /// Bind on a default route on an unusable port, but set is_required = false.
3621    ///
3622    /// Binding the endpoint succeeds.
3623    #[tokio::test]
3624    #[traced_test]
3625    async fn test_bind_addr_badport_default_notrequired() -> Result {
3626        let socket = std::net::UdpSocket::bind((Ipv4Addr::LOCALHOST, 0))?;
3627        let port = socket.local_addr()?.port();
3628
3629        let ep = Endpoint::builder(presets::Minimal)
3630            .bind_addr_with_opts(
3631                (Ipv4Addr::LOCALHOST, port),
3632                BindOpts::default().set_is_required(false),
3633            )?
3634            .bind()
3635            .await?;
3636        let bound_sockets = ep.bound_sockets();
3637        // just the IPv6 default, but no IPv4 bind at all because we replaced the default
3638        // with a bind with an unusable port and set it to not be required.
3639        assert_eq!(bound_sockets.len(), 1);
3640        assert!(bound_sockets[0].is_ipv6());
3641        Ok(())
3642    }
3643
3644    /// Bind on an unusable port, with is_required = false, and no other transports.
3645    ///
3646    /// Binding the endpoint fails with "no valid address available".
3647    #[tokio::test]
3648    #[traced_test]
3649    async fn test_bind_addr_badport_notrequired_no_other_transports() -> Result {
3650        let socket = std::net::UdpSocket::bind((Ipv4Addr::LOCALHOST, 0))?;
3651        let port = socket.local_addr()?.port();
3652
3653        let res = Endpoint::builder(presets::Minimal)
3654            .clear_ip_transports()
3655            .bind_addr_with_opts(
3656                (Ipv4Addr::LOCALHOST, port),
3657                BindOpts::default().set_is_required(false),
3658            )?
3659            .bind()
3660            .await;
3661
3662        assert!(matches!(
3663            res,
3664            Err(BindError::CreateQuicEndpoint {
3665                source: io_error,
3666                ..
3667            })
3668            if io_error.kind() == io::ErrorKind::Other && io_error.to_string() == "no valid address available"
3669        ));
3670        Ok(())
3671    }
3672
3673    /// Bind with prefix len 0 but set the route as non-default.
3674    #[tokio::test]
3675    #[traced_test]
3676    async fn test_bind_addr_prefix_len_0_not_default() -> Result {
3677        let ep = Endpoint::builder(presets::Minimal)
3678            .bind_addr_with_opts(
3679                (Ipv4Addr::LOCALHOST, 0),
3680                BindOpts::default().set_is_default_route(false),
3681            )?
3682            .bind()
3683            .await?;
3684        let bound_sockets = ep.bound_sockets();
3685        // The two default wildcard binds plus our additional route (which does not replace the default route
3686        // because we set is_default_route to false explicitly).
3687        assert_eq!(bound_sockets.len(), 3);
3688        assert!(
3689            bound_sockets
3690                .iter()
3691                .any(|x| x.ip() == IpAddr::V6(Ipv6Addr::UNSPECIFIED))
3692        );
3693        assert!(
3694            bound_sockets
3695                .iter()
3696                .any(|x| x.ip() == IpAddr::V4(Ipv4Addr::UNSPECIFIED))
3697        );
3698        assert!(
3699            bound_sockets
3700                .iter()
3701                .any(|x| x.ip() == IpAddr::V4(Ipv4Addr::LOCALHOST))
3702        );
3703        Ok(())
3704    }
3705
3706    #[ignore = "flaky"]
3707    #[tokio::test]
3708    #[traced_test]
3709    async fn connect_via_relay_becomes_direct_and_sends_direct() -> Result {
3710        let (relay_map, relay_url, _relay_server_guard) = run_relay_server().await?;
3711        let qlog = Arc::new(QlogFileGroup::from_env(
3712            "connect_via_relay_becomes_direct_and_sends_direct",
3713        ));
3714        let transfer_size = 1_000_000;
3715
3716        async fn collect_stats(mut events: PathEventStream) -> BTreeMap<TransportAddr, PathStats> {
3717            let mut stats = BTreeMap::new();
3718            while let Some(event) = events.next().await {
3719                if let PathEvent::Closed {
3720                    remote_addr,
3721                    last_stats,
3722                    ..
3723                } = event
3724                {
3725                    stats.insert(remote_addr, *last_stats);
3726                }
3727            }
3728            stats
3729        }
3730
3731        let client = Endpoint::builder(presets::Minimal)
3732            .relay_mode(RelayMode::Custom(relay_map.clone()))
3733            .ca_tls_config(CaTlsConfig::insecure_skip_verify())
3734            .transport_config(qlog.create("client")?)
3735            .bind()
3736            .await?;
3737        let server = Endpoint::builder(presets::Minimal)
3738            .relay_mode(RelayMode::Custom(relay_map))
3739            .ca_tls_config(CaTlsConfig::insecure_skip_verify())
3740            .transport_config(qlog.create("server")?)
3741            .alpns(vec![TEST_ALPN.to_vec()])
3742            .bind()
3743            .await?;
3744        let server_addr = EndpointAddr::new(server.id()).with_relay_url(relay_url);
3745        let server_task = tokio::spawn(async move {
3746            let incoming = server.accept().await.anyerr()?;
3747            let conn = incoming.await.anyerr()?;
3748            let stats_task = tokio::spawn(collect_stats(conn.path_events()));
3749            let (mut send, mut recv) = conn.accept_bi().await.anyerr()?;
3750            let msg = recv.read_to_end(transfer_size).await.anyerr()?;
3751            send.write_all(&msg).await.anyerr()?;
3752            send.finish().anyerr()?;
3753            conn.closed().await;
3754            let stats = stats_task.await.expect("stats task panicked");
3755            Ok::<_, Error>(stats)
3756        });
3757
3758        let conn = client.connect(server_addr, TEST_ALPN).await?;
3759        let client_stats_task = tokio::spawn(collect_stats(conn.path_events()));
3760        let (mut send, mut recv) = conn.open_bi().await.anyerr()?;
3761        send.write_all(&vec![42u8; transfer_size]).await.anyerr()?;
3762        send.finish().anyerr()?;
3763        recv.read_to_end(transfer_size).await.anyerr()?;
3764        conn.close(0u32.into(), b"thanks, bye!");
3765        client.close().await;
3766        let client_stats = client_stats_task.await.expect("stats task panicked");
3767        let server_stats = server_task.await.anyerr()??;
3768
3769        info!("client stats: {client_stats:#?}");
3770        info!("server stats: {server_stats:#?}");
3771
3772        let client_total_relay_tx = client_stats
3773            .iter()
3774            .filter(|(remote, _stats)| remote.is_relay())
3775            .map(|(_, stats)| stats.udp_tx.bytes)
3776            .sum::<u64>();
3777        let client_total_relay_rx = client_stats
3778            .iter()
3779            .filter(|(remote, _stats)| remote.is_relay())
3780            .map(|(_, stats)| stats.udp_rx.bytes)
3781            .sum::<u64>();
3782        let server_total_relay_tx = server_stats
3783            .iter()
3784            .filter(|(remote, _stats)| remote.is_relay())
3785            .map(|(_, stats)| stats.udp_tx.bytes)
3786            .sum::<u64>();
3787        let server_total_relay_rx = server_stats
3788            .iter()
3789            .filter(|(remote, _stats)| remote.is_relay())
3790            .map(|(_, stats)| stats.udp_rx.bytes)
3791            .sum::<u64>();
3792
3793        info!(?client_total_relay_tx, "total");
3794        info!(?client_total_relay_rx, "total");
3795        info!(?server_total_relay_tx, "total");
3796        info!(?server_total_relay_rx, "total");
3797
3798        // We should send/receive only the minorty of traffic via the relay.
3799        assert!(client_total_relay_tx < transfer_size as u64 / 2);
3800        assert!(client_total_relay_rx < transfer_size as u64 / 2);
3801        assert!(server_total_relay_tx < transfer_size as u64 / 2);
3802        assert!(server_total_relay_rx < transfer_size as u64 / 2);
3803
3804        Ok(())
3805    }
3806
3807    /// Tests that correct logs are emitted when connecting two endpoints with same secret
3808    /// keys to a relay.
3809    #[tokio::test]
3810    #[traced_test]
3811    async fn same_endpoint_id_relay() -> Result {
3812        let (relay_map, relay_url, _relay_server_guard) = run_relay_server().await?;
3813        let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(1u64);
3814        let secret_key = SecretKey::from_bytes(&rng.random());
3815
3816        let client = Endpoint::builder(presets::Minimal)
3817            .relay_mode(RelayMode::Custom(relay_map.clone()))
3818            .ca_tls_config(CaTlsConfig::insecure_skip_verify())
3819            .bind()
3820            .instrument(error_span!("ep-client"))
3821            .await?;
3822
3823        info!("client {}", client.id());
3824
3825        // bind ep1 and wait until connected to relay.
3826        let ep1 = Endpoint::builder(presets::Minimal)
3827            .relay_mode(RelayMode::Custom(relay_map.clone()))
3828            .secret_key(secret_key.clone())
3829            .ca_tls_config(CaTlsConfig::insecure_skip_verify())
3830            .alpns(vec![TEST_ALPN.to_vec()])
3831            .bind()
3832            .instrument(error_span!("ep1"))
3833            .await?;
3834        info!("ep1 bound {:?}", ep1.id());
3835        ep1.online().await;
3836        info!("ep1 online");
3837
3838        let addr = EndpointAddr::new(secret_key.public()).with_relay_url(relay_url.clone());
3839
3840        tokio::try_join!(
3841            async {
3842                let conn = client.connect(addr.clone(), TEST_ALPN).await?;
3843                let reason = conn.closed().await;
3844                assert!(is_application_closed(&reason, 1));
3845                n0_error::Ok(())
3846            },
3847            async {
3848                let conn = ep1.accept().await.unwrap().await?;
3849                conn.close(1u32.into(), b"bye");
3850                n0_error::Ok(())
3851            }
3852        )?;
3853        info!("client connected to ep1");
3854
3855        // now start second endpoint with same secret key
3856        let ep2 = Endpoint::builder(presets::Minimal)
3857            .relay_mode(RelayMode::Custom(relay_map))
3858            .secret_key(secret_key.clone())
3859            .ca_tls_config(CaTlsConfig::insecure_skip_verify())
3860            .alpns(vec![TEST_ALPN.to_vec()])
3861            .bind()
3862            .instrument(error_span!("ep2"))
3863            .await?;
3864        info!("ep2 bound {:?}", ep2.id());
3865        ep2.online().await;
3866        println!("ep2 online");
3867
3868        // `online` does not mean that the connection to the home relay was *established*,
3869        // only that the home relay was *chosen* based on the net report probes.
3870        // We need to wait for the connection to be established though, to be sure that new packets
3871        // will be routed to the new endpoint and not to the old endpoint anymore.
3872        // We don't expose being connected to the home relay on the endpoint currently,
3873        // so we resort to log assertions.
3874        // If you think this all wasn't sad enough already,
3875        // https://github.com/tokio-rs/tracing/issues/1372 means we need to look for the
3876        // repeated `id` field.
3877        // TODO(Frando): Replace once we add a proper API for this.
3878        let expected_log_line = format!(
3879            "ep2:endpoint{{id={} id={}}}:relay-actor:active-relay{{url={relay_url}}}:connected: iroh::_events::relay::connected",
3880            ep2.id().fmt_short(),
3881            ep2.id().fmt_short(),
3882        );
3883        tokio::time::timeout(Duration::from_secs(5), async {
3884            while !logs_contain(&expected_log_line) {
3885                tokio::time::sleep(Duration::from_millis(10)).await
3886            }
3887        })
3888        .await
3889        .std_context("relay connection did not establish in time")?;
3890
3891        tokio::try_join!(
3892            async {
3893                let conn = client.connect(addr.clone(), TEST_ALPN).await?;
3894                let reason = conn.closed().await;
3895                assert!(is_application_closed(&reason, 1));
3896                n0_error::Ok(())
3897            },
3898            async {
3899                let conn = ep2.accept().await.unwrap().await?;
3900                conn.close(1u32.into(), b"bye");
3901                n0_error::Ok(())
3902            }
3903        )?;
3904        println!("client connected to ep2");
3905
3906        // assert that ep1 did not receive a connection
3907        assert!(now_or_never(ep1.accept()).is_none());
3908
3909        // We assert that we get the warn log once for endpoint 1, and not at all for endpoint 2.
3910        logs_assert(|logs| {
3911            let expected_line = |line: &str| {
3912                line.contains("WARN") && line.contains("Another endpoint connected with the same endpoint id. No more messages will be received")
3913            };
3914            let count_line_ep1 = logs
3915                .iter()
3916                .filter(|line| line.contains(":ep1:") && expected_line(line))
3917                .count();
3918            let count_line_ep2 = logs
3919                .iter()
3920                .filter(|line| line.contains(":ep2:") && expected_line(line))
3921                .count();
3922            if count_line_ep1 == 1 && count_line_ep2 == 0 {
3923                Ok(())
3924            } else {
3925                Err("Logs don't match expectations".to_string())
3926            }
3927        });
3928        tokio::join!(ep1.close(), ep2.close(), client.close());
3929        Ok(())
3930    }
3931
3932    fn is_application_closed(close_reason: &ConnectionError, code: u32) -> bool {
3933        matches!(
3934            close_reason,
3935            ConnectionError::ApplicationClosed(f) if f.error_code ==code.into()
3936        )
3937    }
3938
3939    #[tokio::test]
3940    #[traced_test]
3941    async fn test_closed_endpoint_behaviour() -> Result {
3942        // create endpoint
3943        // call endpoint.close
3944        // ensure methods behave in the expected way
3945        info!("Creating endpoint");
3946        let ep = Endpoint::builder(presets::N0).bind().await?;
3947        let closed = ep.closed();
3948        info!("Closing endpoint");
3949        let now = Instant::now();
3950        ep.close().await;
3951        info!("Endpoint closed in {:?}", now.elapsed());
3952
3953        // Assert that the `closed` cancellation token is now cancelled
3954        assert_eq!(now_or_never(closed), Some(()));
3955
3956        info!("Set ALPNS fails silently");
3957        ep.set_alpns(vec![b"test".into()]);
3958
3959        info!("Insert Relay returns None");
3960        let relay_config = crate::defaults::staging::default_na_east_relay();
3961        assert!(
3962            ep.insert_relay("localhost:300".parse()?, Arc::new(relay_config))
3963                .await
3964                .is_none()
3965        );
3966
3967        info!("Remove Relay returns None");
3968        assert!(ep.remove_relay(&"localhost:300".parse()?).await.is_none());
3969
3970        info!("Connecting");
3971        let mut rng = ChaCha8Rng::seed_from_u64(41);
3972        let ep_id = SecretKey::from_bytes(&rng.random()).public();
3973
3974        // should likely be an error that states that the
3975        // endpoint is closed instead:
3976        if let ConnectError::Connect { source, .. } = ep.connect(ep_id, b"test").await.unwrap_err()
3977        {
3978            assert!(matches!(
3979                source,
3980                ConnectWithOptsError::EndpointClosed { .. }
3981            ));
3982        } else {
3983            panic!("unexpected error for connect");
3984        }
3985
3986        info!("Accepting!");
3987        assert!(ep.accept().await.is_none());
3988
3989        // this should work
3990        info!("Addr: {:?}", ep.addr());
3991
3992        // create watchers to verify they terminate after the endpoint is dropped.
3993        let mut addrs = ep.watch_addr().stream();
3994
3995        #[cfg(feature = "unstable-net-report")]
3996        let mut net_reports = {
3997            let net_reports = ep.net_report().stream();
3998
3999            // returns None
4000            let net_report = ep.net_report().get();
4001            info!("last Net report {net_report:?}");
4002            net_reports
4003        };
4004
4005        // this should work
4006        let sockets = ep.bound_sockets();
4007        info!("Sockets: {sockets:?}");
4008
4009        // these should return errors
4010        assert!(ep.dns_resolver().is_err());
4011        assert!(ep.address_lookup().is_err());
4012
4013        #[cfg(feature = "metrics")]
4014        {
4015            // this should work
4016            let metrics = ep.metrics();
4017            info!("Metrics: {metrics:?}");
4018        }
4019
4020        // this should return none
4021        assert!(ep.remote_info(ep_id).await.is_none());
4022
4023        // this should fail silently
4024        ep.network_change().await;
4025
4026        // this should fail silently
4027        ep.set_user_data_for_address_lookup(Some(
4028            UserData::try_from("TEST".to_string()).expect("valid string"),
4029        ));
4030        drop(ep);
4031        // now that the endpoint is dropped, all watchers should terminate.
4032        tokio::time::timeout(Duration::from_secs(1), async {
4033            while let Some(addr) = addrs.next().await {
4034                info!("Addrs stream: {addr:?}");
4035            }
4036
4037            #[cfg(feature = "unstable-net-report")]
4038            while let Some(net_report) = net_reports.next().await {
4039                info!("Net report stream: {net_report:?}");
4040            }
4041        })
4042        .await
4043        .expect("watchers not closed");
4044
4045        info!("Done!");
4046        Ok(())
4047    }
4048
4049    #[tokio::test]
4050    #[traced_test]
4051    async fn test_closed_endpoint_unpolled_accept_fut() -> Result {
4052        info!("Creating endpoint");
4053        let ep = Endpoint::builder(presets::N0).bind().await?;
4054
4055        info!("Get accept future");
4056        let accept_fut = ep.accept();
4057
4058        info!("Closing endpoint");
4059        let now = Instant::now();
4060        tokio::time::timeout(Duration::from_secs(5), ep.close())
4061            .await
4062            .expect("Endpoint closes in a reasonable time");
4063        info!("Endpoint closed in {:?}", now.elapsed());
4064
4065        info!("Accept future returns None after the endpoint has closed");
4066        let incoming = accept_fut.await;
4067        assert!(incoming.is_none());
4068        Ok(())
4069    }
4070
4071    #[tokio::test]
4072    #[traced_test]
4073    async fn test_closed_endpoint_polled_accept_fut() -> Result {
4074        info!("Creating endpoint");
4075        let ep = Endpoint::builder(presets::N0).bind().await?;
4076
4077        info!("Run an accept task");
4078        let ep2 = ep.clone();
4079        let accept_task = tokio::spawn(async move {
4080            info!("Waiting on Accept");
4081            let res = ep2.accept().await;
4082            info!("Accept await has returned");
4083            res
4084        });
4085
4086        // Try to ensure the accept future is polled at least once.
4087        tokio::time::sleep(Duration::from_millis(10)).await;
4088
4089        info!("Closing the endpoint");
4090        tokio::time::timeout(Duration::from_secs(5), ep.close())
4091            .await
4092            .expect("Endpoint closes in a reasonable time");
4093        info!("Endpoint closed");
4094
4095        info!("Await the accept task");
4096        let incoming = accept_task.await.expect("accept task panicked");
4097        assert!(incoming.is_none());
4098
4099        Ok(())
4100    }
4101
4102    #[tokio::test]
4103    #[traced_test]
4104    async fn test_endpoint_online_add_relay() -> Result {
4105        let ep = Endpoint::builder(presets::Minimal)
4106            .relay_mode(RelayMode::Custom(RelayMap::empty()))
4107            .ca_tls_config(CaTlsConfig::insecure_skip_verify())
4108            .bind()
4109            .await?;
4110        // should not come online without relays.
4111        let res = tokio::time::timeout(Duration::from_millis(500), ep.online()).await;
4112        assert!(res.is_err());
4113
4114        // should come online after a relay is added.
4115        let (relay_map, relay_url, _relay_server_guard) = run_relay_server().await?;
4116        ep.insert_relay(relay_url.clone(), relay_map.get(&relay_url).unwrap())
4117            .await;
4118        let res = tokio::time::timeout(Duration::from_millis(1000), ep.online()).await;
4119        assert!(res.is_ok());
4120
4121        // online should still return after endpoint close, if the endpoint was last online
4122        let ep_clone = ep.clone();
4123        let task = tokio::task::spawn(async move {
4124            tokio::time::timeout(Duration::from_millis(500), ep_clone.online()).await
4125        });
4126        ep.close().await;
4127        let res = task.await.unwrap();
4128        assert!(res.is_ok());
4129        Ok(())
4130    }
4131
4132    #[tokio::test]
4133    #[traced_test]
4134    async fn test_endpoint_online_close() -> Result {
4135        let ep = Endpoint::bind(presets::Minimal).await?;
4136        // should not come online without relays.
4137        let res = tokio::time::timeout(Duration::from_millis(500), ep.online()).await;
4138        assert!(res.is_err());
4139
4140        // online should remain pending after the endpoint is closed.
4141        let ep_clone = ep.clone();
4142        let task = tokio::task::spawn(async move {
4143            tokio::time::timeout(Duration::from_millis(500), ep_clone.online()).await
4144        });
4145        ep.close().await;
4146        let res = task.await.unwrap();
4147        assert!(res.is_err());
4148        Ok(())
4149    }
4150
4151    /// Verifies that an endpoint configured with [`RelayConfig::with_auth_token`]
4152    /// is admitted to a relay whose access control checks the token only when
4153    /// the token matches.
4154    ///
4155    /// Also verifies that [`RelayStatus::auth_denied_reason`] works correctly.
4156    #[tokio::test]
4157    #[traced_test]
4158    async fn test_endpoint_relay_auth_token() -> Result {
4159        const TOKEN: &str = "valid-token";
4160        const DENIAL_REASON: &str = "this token is no good";
4161
4162        /// Admits a connection only if it carries the expected auth token.
4163        #[derive(Debug)]
4164        struct TokenAccess(&'static str);
4165
4166        impl iroh_relay::server::AccessControl for TokenAccess {
4167            async fn on_connect(&self, request: &iroh_relay::server::ClientRequest) -> Access {
4168                if request.auth_token().as_deref() == Some(self.0) {
4169                    Access::Allow
4170                } else {
4171                    Access::Deny {
4172                        reason: Some(DENIAL_REASON.to_string()),
4173                    }
4174                }
4175            }
4176        }
4177
4178        let access = Arc::new(TokenAccess(TOKEN));
4179        let (_relay_map, relay_url, _guard) = run_relay_server_with_access(false, access).await?;
4180
4181        // Wrong token: the connection attempt fails, and the status reports the
4182        // relay-side denial both as an error and as an authentication failure.
4183        let bad_map: RelayMap = RelayConfig::new(relay_url.clone(), None)
4184            .with_auth_token("wrong-token")
4185            .into();
4186        let bad_ep = Endpoint::builder(presets::Minimal)
4187            .relay_mode(RelayMode::Custom(bad_map))
4188            .ca_tls_config(CaTlsConfig::insecure_skip_verify())
4189            .bind()
4190            .await?;
4191        let mut stream = bad_ep.home_relay_status().stream();
4192        let (auth_err, auth_denied_reason) = tokio::time::timeout(Duration::from_secs(5), async {
4193            while let Some(status) = stream.next().await {
4194                if let Some(relay) = status.iter().find(|s| s.last_error().is_some()) {
4195                    let err = relay.last_error().expect("checked above");
4196                    return (
4197                        format!("{err:#}"),
4198                        relay.auth_denied_reason().map(ToOwned::to_owned),
4199                    );
4200                }
4201            }
4202            panic!("home relay stream ended");
4203        })
4204        .await
4205        .std_context("waiting for auth error")?;
4206        assert!(
4207            auth_err.contains(DENIAL_REASON),
4208            "expected {DENIAL_REASON:?} in error, got: {auth_err}"
4209        );
4210        assert_eq!(
4211            auth_denied_reason.as_deref(),
4212            Some(DENIAL_REASON),
4213            "auth_denied_reason did not recognise a relay-side denial (error was: {auth_err})"
4214        );
4215
4216        // Correct token: the endpoint reaches the connected state.
4217        let good_map: RelayMap = RelayConfig::new(relay_url, None)
4218            .with_auth_token(TOKEN)
4219            .into();
4220        let good_ep = Endpoint::builder(presets::Minimal)
4221            .relay_mode(RelayMode::Custom(good_map))
4222            .ca_tls_config(CaTlsConfig::insecure_skip_verify())
4223            .bind()
4224            .await?;
4225        tokio::time::timeout(Duration::from_secs(5), good_ep.online())
4226            .await
4227            .std_context("waiting for endpoint to come online")?;
4228
4229        Ok(())
4230    }
4231}