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, 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            while let Some(infos) = paths.next().await {
2532                info!(?infos, "new PathInfos");
2533                if infos.iter().any(|info| info.is_ip()) {
2534                    break;
2535                }
2536            }
2537            info!("Have direct connection");
2538            #[cfg(feature = "metrics")]
2539            {
2540                // Validate holepunch metrics.
2541                assert_eq!(ep.metrics().socket.num_conns_opened.get(), 1);
2542                assert_eq!(ep.metrics().socket.num_conns_direct.get(), 1);
2543            }
2544
2545            send.write_all(b"close please").await.anyerr()?;
2546            send.finish().anyerr()?;
2547
2548            let res = conn.closed().await;
2549            ep.close().await;
2550            Ok(res)
2551        }
2552
2553        #[instrument(name = "server", skip_all)]
2554        async fn accept(
2555            relay_map: RelayMap,
2556            node_addr_tx: oneshot::Sender<EndpointAddr>,
2557            qlog: Arc<QlogFileGroup>,
2558        ) -> Result {
2559            let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(1u64);
2560            let secret = SecretKey::from_bytes(&rng.random());
2561            let ep = Endpoint::builder(presets::N0)
2562                .secret_key(secret)
2563                .alpns(vec![TEST_ALPN.to_vec()])
2564                .ca_tls_config(CaTlsConfig::insecure_skip_verify())
2565                .transport_config(qlog.create("server")?)
2566                .relay_mode(RelayMode::Custom(relay_map))
2567                .bind()
2568                .await?;
2569            ep.online().await;
2570            let mut node_addr = ep.addr();
2571            node_addr.addrs.retain(|addr| addr.is_relay());
2572            node_addr_tx.send(node_addr).unwrap();
2573
2574            info!(me = %ep.id().fmt_short(), "server starting");
2575            let conn = ep.accept().await.anyerr()?.await.anyerr()?;
2576            // let node_id = conn.remote_node_id()?;
2577            // assert_eq!(node_id, src);
2578            let mut recv = conn.accept_uni().await.anyerr()?;
2579            let mut msg = [0u8; 5];
2580            recv.read_exact(&mut msg).await.anyerr()?;
2581            assert_eq!(&msg, b"hello");
2582            info!("received hello");
2583            let msg = recv.read_to_end(100).await.anyerr()?;
2584            assert_eq!(msg, b"close please");
2585            info!("received 'close please'");
2586            // Closing the endpoint closes all connections.
2587            ep.close().await;
2588            Ok(())
2589        }
2590
2591        let server_task = tokio::spawn(accept(relay_map.clone(), node_addr_tx, qlog.clone()));
2592        let client_task = tokio::spawn(connect(relay_map, node_addr_rx, qlog));
2593
2594        server_task.await.anyerr()??;
2595        let conn_closed = dbg!(client_task.await.anyerr()??);
2596        assert!(matches!(
2597            conn_closed,
2598            ConnectionError::ApplicationClosed(ApplicationClose { .. })
2599        ));
2600
2601        Ok(())
2602    }
2603
2604    #[tokio::test]
2605    #[traced_test]
2606    async fn endpoint_two_relay_only_no_ip() -> Result {
2607        // Connect two endpoints on the same network, via a relay server, without
2608        // Address Lookup.
2609        let (relay_map, _relay_url, _relay_server_guard) = run_relay_server().await?;
2610        let (node_addr_tx, node_addr_rx) = oneshot::channel();
2611
2612        #[instrument(name = "client", skip_all)]
2613        async fn connect(
2614            relay_map: RelayMap,
2615            node_addr_rx: oneshot::Receiver<EndpointAddr>,
2616        ) -> Result<ConnectionError> {
2617            let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(0u64);
2618            let secret = SecretKey::from_bytes(&rng.random());
2619            let ep = Endpoint::builder(presets::N0)
2620                .secret_key(secret)
2621                .alpns(vec![TEST_ALPN.to_vec()])
2622                .ca_tls_config(CaTlsConfig::insecure_skip_verify())
2623                .relay_mode(RelayMode::Custom(relay_map))
2624                .clear_ip_transports() // disable direct
2625                .bind()
2626                .await?;
2627            info!(me = %ep.id().fmt_short(), "client starting");
2628            let dst = node_addr_rx.await.anyerr()?;
2629
2630            info!(me = %ep.id().fmt_short(), "client connecting");
2631            let conn = ep.connect(dst, TEST_ALPN).await?;
2632            let mut send = conn.open_uni().await.anyerr()?;
2633            send.write_all(b"hello").await.anyerr()?;
2634            let mut paths = conn.paths_stream();
2635            info!("Waiting for connection");
2636            'outer: while let Some(infos) = paths.next().await {
2637                info!(?infos, "new PathInfos");
2638                for info in infos.iter() {
2639                    if info.is_ip() {
2640                        panic!("should not happen: {:?}", info);
2641                    }
2642                    if info.is_relay() {
2643                        break 'outer;
2644                    }
2645                }
2646            }
2647            info!("Have relay connection");
2648
2649            send.write_all(b"close please").await.anyerr()?;
2650            send.finish().anyerr()?;
2651            let res = conn.closed().await;
2652            ep.close().await;
2653            Ok(res)
2654        }
2655
2656        #[instrument(name = "server", skip_all)]
2657        async fn accept(
2658            relay_map: RelayMap,
2659            node_addr_tx: oneshot::Sender<EndpointAddr>,
2660        ) -> Result {
2661            let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(1u64);
2662            let secret = SecretKey::from_bytes(&rng.random());
2663            let ep = Endpoint::builder(presets::N0)
2664                .secret_key(secret)
2665                .alpns(vec![TEST_ALPN.to_vec()])
2666                .ca_tls_config(CaTlsConfig::insecure_skip_verify())
2667                .relay_mode(RelayMode::Custom(relay_map))
2668                .clear_ip_transports()
2669                .bind()
2670                .await?;
2671            ep.online().await;
2672            let node_addr = ep.addr();
2673            node_addr_tx.send(node_addr).unwrap();
2674
2675            info!(me = %ep.id().fmt_short(), "server starting");
2676            let conn = ep.accept().await.anyerr()?.await.anyerr()?;
2677            // let node_id = conn.remote_node_id()?;
2678            // assert_eq!(node_id, src);
2679            let mut recv = conn.accept_uni().await.anyerr()?;
2680            let mut msg = [0u8; 5];
2681            recv.read_exact(&mut msg).await.anyerr()?;
2682            assert_eq!(&msg, b"hello");
2683            info!("received hello");
2684            let msg = recv.read_to_end(100).await.anyerr()?;
2685            assert_eq!(msg, b"close please");
2686            info!("received 'close please'");
2687            // Closing the endpoint closes all connections.
2688            ep.close().await;
2689            Ok(())
2690        }
2691
2692        let server_task = tokio::spawn(accept(relay_map.clone(), node_addr_tx));
2693        let client_task = tokio::spawn(connect(relay_map, node_addr_rx));
2694
2695        server_task.await.anyerr()??;
2696        let conn_closed = dbg!(client_task.await.anyerr()??);
2697        assert!(matches!(
2698            conn_closed,
2699            ConnectionError::ApplicationClosed(ApplicationClose { .. })
2700        ));
2701
2702        Ok(())
2703    }
2704
2705    #[tokio::test]
2706    #[traced_test]
2707    async fn endpoint_two_direct_add_relay() -> Result {
2708        // Connect two endpoints on the same network, without relay server and without
2709        // Address Lookup.  Add a relay connection later.
2710        let (relay_map, _relay_url, _relay_server_guard) = run_relay_server().await?;
2711        let (node_addr_tx, node_addr_rx) = oneshot::channel();
2712
2713        #[instrument(name = "client", skip_all)]
2714        async fn connect(
2715            relay_map: RelayMap,
2716            node_addr_rx: oneshot::Receiver<EndpointAddr>,
2717        ) -> Result<()> {
2718            let secret = SecretKey::from([0u8; 32]);
2719            let ep = Endpoint::builder(presets::N0)
2720                .secret_key(secret)
2721                .alpns(vec![TEST_ALPN.to_vec()])
2722                .ca_tls_config(CaTlsConfig::insecure_skip_verify())
2723                .relay_mode(RelayMode::Custom(relay_map))
2724                .bind()
2725                .await?;
2726            info!(me = %ep.id().fmt_short(), "client starting");
2727            let dst = node_addr_rx.await.anyerr()?;
2728
2729            info!(me = %ep.id().fmt_short(), "client connecting");
2730            let conn = ep.connect(dst, TEST_ALPN).await?;
2731            info!(me = %ep.id().fmt_short(), "client connected");
2732
2733            // We should be connected via IP, because it is faster than the relay server.
2734            // TODO: Maybe not panic if this is not true?
2735
2736            let path_info = conn.paths();
2737            assert_eq!(path_info.len(), 1);
2738            assert!(path_info.iter().next().unwrap().is_ip());
2739
2740            let mut paths = conn.paths_stream();
2741            time::timeout(Duration::from_secs(5), async move {
2742                while let Some(infos) = paths.next().await {
2743                    info!(?infos, "new PathInfos");
2744                    if infos.iter().any(|info| info.is_relay()) {
2745                        info!("client has a relay path");
2746                        break;
2747                    }
2748                }
2749            })
2750            .await
2751            .anyerr()?;
2752
2753            // wait for the server to signal it has the relay connection
2754            let mut stream = conn.accept_uni().await.anyerr()?;
2755            stream.read_to_end(100).await.anyerr()?;
2756
2757            info!("client closing");
2758            conn.close(0u8.into(), b"");
2759            ep.close().await;
2760            Ok(())
2761        }
2762
2763        #[instrument(name = "server", skip_all)]
2764        async fn accept(
2765            relay_map: RelayMap,
2766            node_addr_tx: oneshot::Sender<EndpointAddr>,
2767        ) -> Result<ConnectionError> {
2768            let secret = SecretKey::from([1u8; 32]);
2769            let ep = Endpoint::builder(presets::N0)
2770                .secret_key(secret)
2771                .alpns(vec![TEST_ALPN.to_vec()])
2772                .ca_tls_config(CaTlsConfig::insecure_skip_verify())
2773                .relay_mode(RelayMode::Custom(relay_map))
2774                .bind()
2775                .await?;
2776            ep.online().await;
2777            let node_addr = ep.addr();
2778            node_addr_tx.send(node_addr).unwrap();
2779
2780            info!(me = %ep.id().fmt_short(), "server starting");
2781            let conn = ep.accept().await.anyerr()?.await.anyerr()?;
2782            info!(me = %ep.id().fmt_short(), "server accepted connection");
2783
2784            // Wait for a relay connection to be added.  Client does all the asserting here,
2785            // we just want to wait so we get to see all the mechanics of the connection
2786            // being added on this side too.
2787            let mut paths = conn.paths_stream();
2788            time::timeout(Duration::from_secs(5), async move {
2789                while let Some(infos) = paths.next().await {
2790                    info!(?infos, "new PathInfos");
2791                    if infos.iter().any(|path| path.is_relay()) {
2792                        info!("server has a relay path");
2793                        break;
2794                    }
2795                }
2796            })
2797            .await
2798            .anyerr()?;
2799
2800            let mut stream = conn.open_uni().await.anyerr()?;
2801            stream.write_all(b"have relay").await.anyerr()?;
2802            stream.finish().anyerr()?;
2803            info!("waiting conn.closed()");
2804
2805            Ok(conn.closed().await)
2806        }
2807
2808        let server_task = tokio::spawn(accept(relay_map.clone(), node_addr_tx));
2809        let client_task = tokio::spawn(connect(relay_map, node_addr_rx));
2810
2811        client_task.await.anyerr()??;
2812        let conn_closed = dbg!(server_task.await.anyerr()??);
2813        assert!(matches!(
2814            conn_closed,
2815            ConnectionError::ApplicationClosed(ApplicationClose { .. })
2816        ));
2817
2818        Ok(())
2819    }
2820
2821    #[tokio::test]
2822    #[traced_test]
2823    async fn endpoint_relay_map_change() -> Result {
2824        let (relay_map, relay_url, _guard1) = run_relay_server().await?;
2825        let client = Endpoint::builder(presets::Minimal)
2826            .relay_mode(RelayMode::Custom(relay_map.clone()))
2827            .ca_tls_config(CaTlsConfig::insecure_skip_verify())
2828            .bind()
2829            .await?;
2830        let server = Endpoint::builder(presets::Minimal)
2831            .relay_mode(RelayMode::Custom(relay_map))
2832            .ca_tls_config(CaTlsConfig::insecure_skip_verify())
2833            .alpns(vec![TEST_ALPN.to_vec()])
2834            .bind()
2835            .await?;
2836
2837        let task = tokio::spawn({
2838            let server = server.clone();
2839            async move {
2840                for i in 0..2 {
2841                    println!("accept: round {i}");
2842                    let Some(conn) = server.accept().await else {
2843                        n0_error::bail_any!("Expected an incoming connection");
2844                    };
2845                    let conn = conn.await.anyerr()?;
2846                    let (mut send, mut recv) = conn.accept_bi().await.anyerr()?;
2847                    let data = recv.read_to_end(1000).await.anyerr()?;
2848                    send.write_all(&data).await.anyerr()?;
2849                    send.finish().anyerr()?;
2850                    conn.closed().await;
2851                }
2852                Ok::<_, Error>(())
2853            }
2854        });
2855
2856        server.online().await;
2857
2858        let mut addr = server.addr();
2859        println!("round1: {:?}", addr);
2860
2861        // remove direct addrs to force relay usage
2862        addr.addrs
2863            .retain(|addr| !matches!(addr, TransportAddr::Ip(_)));
2864
2865        let conn = client.connect(addr, TEST_ALPN).await?;
2866        let (mut send, mut recv) = conn.open_bi().await.anyerr()?;
2867        send.write_all(b"Hello, world!").await.anyerr()?;
2868        send.finish().anyerr()?;
2869        let data = recv.read_to_end(1000).await.anyerr()?;
2870        conn.close(0u32.into(), b"bye!");
2871
2872        assert_eq!(&data, b"Hello, world!");
2873
2874        // setup a second relay server
2875        let (new_relay_map, new_relay_url, _guard2) = run_relay_server().await?;
2876        let new_endpoint = new_relay_map
2877            .get(&new_relay_url)
2878            .expect("missing endpoint")
2879            .clone();
2880        dbg!(&new_relay_map);
2881
2882        let addr_watcher = server.watch_addr();
2883
2884        // add new new relay
2885        assert!(
2886            server
2887                .insert_relay(new_relay_url.clone(), new_endpoint.clone())
2888                .await
2889                .is_none()
2890        );
2891        // remove the old relay
2892        assert!(server.remove_relay(&relay_url).await.is_some());
2893
2894        println!("------- changed ----- ");
2895
2896        let mut addr = tokio::time::timeout(Duration::from_secs(10), async move {
2897            let mut stream = addr_watcher.stream();
2898            while let Some(addr) = stream.next().await {
2899                if addr.relay_urls().next() != Some(&relay_url) {
2900                    return addr;
2901                }
2902            }
2903            panic!("failed to change relay");
2904        })
2905        .await
2906        .anyerr()?;
2907
2908        println!("round2: {:?}", addr);
2909        assert_eq!(addr.relay_urls().next(), Some(&new_relay_url));
2910
2911        // remove direct addrs to force relay usage
2912        addr.addrs
2913            .retain(|addr| !matches!(addr, TransportAddr::Ip(_)));
2914
2915        let conn = client.connect(addr, TEST_ALPN).await?;
2916        let (mut send, mut recv) = conn.open_bi().await.anyerr()?;
2917        send.write_all(b"Hello, world!").await.anyerr()?;
2918        send.finish().anyerr()?;
2919        let data = recv.read_to_end(1000).await.anyerr()?;
2920        conn.close(0u32.into(), b"bye!");
2921
2922        task.await.anyerr()??;
2923
2924        client.close().await;
2925        server.close().await;
2926
2927        assert_eq!(&data, b"Hello, world!");
2928
2929        Ok(())
2930    }
2931
2932    #[tokio::test]
2933    #[traced_test]
2934    async fn endpoint_bidi_send_recv() -> Result {
2935        let disco = MemoryLookup::new();
2936        let ep1 = Endpoint::builder(presets::Minimal)
2937            .address_lookup(disco.clone())
2938            .alpns(vec![TEST_ALPN.to_vec()])
2939            .bind()
2940            .await?;
2941
2942        let ep2 = Endpoint::builder(presets::Minimal)
2943            .address_lookup(disco.clone())
2944            .alpns(vec![TEST_ALPN.to_vec()])
2945            .bind()
2946            .await?;
2947
2948        disco.add_endpoint_info(ep1.addr());
2949        disco.add_endpoint_info(ep2.addr());
2950
2951        let ep1_endpointid = ep1.id();
2952        let ep2_endpointid = ep2.id();
2953        eprintln!("endpoint id 1 {ep1_endpointid}");
2954        eprintln!("endpoint id 2 {ep2_endpointid}");
2955
2956        async fn connect_hello(ep: Endpoint, dst: EndpointId) -> Result {
2957            let conn = ep.connect(dst, TEST_ALPN).await?;
2958            let (mut send, mut recv) = conn.open_bi().await.anyerr()?;
2959            info!("sending hello");
2960            send.write_all(b"hello").await.anyerr()?;
2961            send.finish().anyerr()?;
2962            info!("receiving world");
2963            let m = recv.read_to_end(100).await.anyerr()?;
2964            assert_eq!(m, b"world");
2965            conn.close(1u8.into(), b"done");
2966            Ok(())
2967        }
2968
2969        async fn accept_world(ep: Endpoint, src: EndpointId) -> Result {
2970            let incoming = ep.accept().await.anyerr()?;
2971            let mut iconn = incoming.accept().anyerr()?;
2972            let alpn = iconn.alpn().await?;
2973            let conn = iconn.await.anyerr()?;
2974            let endpoint_id = conn.remote_id();
2975            assert_eq!(endpoint_id, src);
2976            assert_eq!(alpn, TEST_ALPN);
2977            let (mut send, mut recv) = conn.accept_bi().await.anyerr()?;
2978            info!("receiving hello");
2979            let m = recv.read_to_end(100).await.anyerr()?;
2980            assert_eq!(m, b"hello");
2981            info!("sending hello");
2982            send.write_all(b"world").await.anyerr()?;
2983            send.finish().anyerr()?;
2984            match conn.closed().await {
2985                ConnectionError::ApplicationClosed(closed) => {
2986                    assert_eq!(closed.error_code, 1u8.into());
2987                    Ok(())
2988                }
2989                _ => panic!("wrong close error"),
2990            }
2991        }
2992
2993        let p1_accept = tokio::spawn(accept_world(ep1.clone(), ep2_endpointid).instrument(
2994            info_span!(
2995                "p1_accept",
2996                ep1 = %ep1.id().fmt_short(),
2997                dst = %ep2_endpointid.fmt_short(),
2998            ),
2999        ));
3000        let p2_accept = tokio::spawn(accept_world(ep2.clone(), ep1_endpointid).instrument(
3001            info_span!(
3002                "p2_accept",
3003                ep2 = %ep2.id().fmt_short(),
3004                dst = %ep1_endpointid.fmt_short(),
3005            ),
3006        ));
3007        let p1_connect = tokio::spawn(connect_hello(ep1.clone(), ep2_endpointid).instrument(
3008            info_span!(
3009                "p1_connect",
3010                ep1 = %ep1.id().fmt_short(),
3011                dst = %ep2_endpointid.fmt_short(),
3012            ),
3013        ));
3014        let p2_connect = tokio::spawn(connect_hello(ep2.clone(), ep1_endpointid).instrument(
3015            info_span!(
3016                "p2_connect",
3017                ep2 = %ep2.id().fmt_short(),
3018                dst = %ep1_endpointid.fmt_short(),
3019            ),
3020        ));
3021
3022        p1_accept.await.anyerr()??;
3023        p2_accept.await.anyerr()??;
3024        p1_connect.await.anyerr()??;
3025        p2_connect.await.anyerr()??;
3026
3027        Ok(())
3028    }
3029
3030    /// Regression test: Don't fail connections with dead relays on Windows.
3031    ///
3032    /// A single client connecting to a single server over a usable direct path
3033    /// must succeed even when both are configured with an unreachable home relay
3034    /// (`https://127.0.0.1:1`, nothing listening). The dead relay should be irrelevant:
3035    /// the direct path works and the connection comes up in milliseconds.
3036    ///
3037    /// This was broken on Windows because QaD sends over the same socket to the dead
3038    /// relay, and the socket would return recv errors on the next recv to report ICMP
3039    /// errors for the previous send. We now skip over these errors, implemented in
3040    /// https://github.com/n0-computer/net-tools/pull/166, so this no longer fails.
3041    #[tokio::test]
3042    async fn endpoint_unreachable_relay_direct_connect_succeeds() -> Result {
3043        // The relay url and its QADv4 probe must both hit closed ports, so the relay is
3044        // unreachable and the probe draws the ICMP port-unreachable the Windows socket
3045        // reports on its next recv. Claim an ephemeral port, then close it: it's now free,
3046        // so nothing answers. There's nothing stopping the kernel from reusing a port
3047        // right away, but on most machines that's unlikely. The url is dialed over TCP
3048        // (HTTPS), the probe over UDP, so claim each with the matching socket type.
3049        let closed_tcp_port = {
3050            let sock = std::net::TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).expect("bind");
3051            sock.local_addr().expect("local addr").port()
3052        };
3053        let closed_udp_port = {
3054            let sock = std::net::UdpSocket::bind((Ipv4Addr::LOCALHOST, 0)).expect("bind");
3055            sock.local_addr().expect("local addr").port()
3056        };
3057        let dead_relay: RelayUrl = format!("https://127.0.0.1:{closed_tcp_port}")
3058            .parse()
3059            .expect("valid relay url");
3060        let dead_relay_config = RelayConfig::new(
3061            dead_relay.clone(),
3062            Some(RelayQuicConfig::new(closed_udp_port)),
3063        );
3064
3065        let bind_endpoint = async || {
3066            Endpoint::builder(presets::Minimal)
3067                // Use the broken relay to trigger the ICMP errors from the QaD sends.
3068                .relay_mode(RelayMode::Custom(RelayMap::from_iter([
3069                    dead_relay_config.clone()
3070                ])))
3071                .ca_tls_config(CaTlsConfig::insecure_skip_verify())
3072                .alpns(vec![TEST_ALPN.to_vec()])
3073                // Bind on IPv4 only to ensure a single socket to not have spurious polls.
3074                .bind_addr((Ipv4Addr::LOCALHOST, 0))
3075                .expect("valid addr")
3076                .bind()
3077                .await
3078        };
3079
3080        let server = bind_endpoint().await?;
3081        let server_addr = server.addr().with_relay_url(dead_relay.clone());
3082        let client = bind_endpoint().await?;
3083
3084        // Server accepts the incoming connection and holds it open until the test ends.
3085        let accept = tokio::spawn(async move {
3086            let incoming = server.accept().await.anyerr()?;
3087            let conn = incoming.await.anyerr()?;
3088            conn.closed().await;
3089            server.close().await;
3090            n0_error::Ok(())
3091        });
3092
3093        // The connect must complete over the direct loopback path despite the dead relay.
3094        let _conn = tokio::time::timeout(
3095            Duration::from_secs(10),
3096            client.connect(server_addr, TEST_ALPN),
3097        )
3098        .await
3099        .expect("connection should succeed")?;
3100        client.close().await;
3101        accept.await.anyerr()??;
3102        Ok(())
3103    }
3104
3105    #[tokio::test]
3106    #[traced_test]
3107    async fn test_direct_addresses_no_qad_relay() -> Result {
3108        let (relay_map, _, _guard) = run_relay_server_with(false).await.unwrap();
3109
3110        let ep = Endpoint::builder(presets::Minimal)
3111            .relay_mode(RelayMode::Custom(relay_map))
3112            .alpns(vec![TEST_ALPN.to_vec()])
3113            .ca_tls_config(CaTlsConfig::insecure_skip_verify())
3114            .bind()
3115            .await?;
3116
3117        assert!(ep.addr().ip_addrs().count() > 0);
3118
3119        Ok(())
3120    }
3121
3122    /// Test that configured external addresses are included in the endpoint's
3123    /// direct addresses, both when set via builder and at runtime.
3124    #[tokio::test(flavor = "current_thread", start_paused = true)]
3125    #[traced_test]
3126    async fn test_external_addr() -> Result {
3127        let configured_addr = SocketAddr::from(SocketAddrV4::new(Ipv4Addr::new(1, 2, 3, 4), 12345));
3128
3129        // Test builder-configured external address
3130        let ep = Endpoint::builder(presets::Minimal)
3131            .external_addr(configured_addr)
3132            .bind()
3133            .await?;
3134
3135        let addr = ep.addr();
3136        assert!(
3137            addr.ip_addrs().any(|a| *a == configured_addr),
3138            "builder-configured external addr {configured_addr} not found in endpoint addr: {addr:?}"
3139        );
3140
3141        // Test runtime add
3142        let runtime_addr = SocketAddr::from(SocketAddrV4::new(Ipv4Addr::new(5, 6, 7, 8), 54321));
3143        ep.add_external_addr(runtime_addr).await;
3144        tokio::time::sleep(Duration::from_millis(100)).await;
3145
3146        let addr = ep.addr();
3147        assert!(
3148            addr.ip_addrs().any(|a| *a == runtime_addr),
3149            "runtime-added external addr {runtime_addr} not found in endpoint addr: {addr:?}"
3150        );
3151
3152        // Test runtime remove
3153        let removed = ep.remove_external_addr(&runtime_addr).await;
3154        assert!(removed);
3155        tokio::time::sleep(Duration::from_millis(100)).await;
3156
3157        let addr = ep.addr();
3158        assert!(
3159            !addr.ip_addrs().any(|a| *a == runtime_addr),
3160            "removed external addr {runtime_addr} still found in endpoint addr: {addr:?}"
3161        );
3162        assert!(
3163            addr.ip_addrs().any(|a| *a == configured_addr),
3164            "builder-configured external addr should still be present: {addr:?}"
3165        );
3166
3167        ep.close().await;
3168        Ok(())
3169    }
3170
3171    #[tokio::test]
3172    #[traced_test]
3173    async fn graceful_close() -> Result {
3174        let client = Endpoint::bind(presets::Minimal).await?;
3175        let server = Endpoint::builder(presets::Minimal)
3176            .alpns(vec![TEST_ALPN.to_vec()])
3177            .bind()
3178            .await?;
3179        let server_addr = server.addr();
3180        let server_task = tokio::spawn(async move {
3181            let incoming = server.accept().await.anyerr()?;
3182            let conn = incoming.await.anyerr()?;
3183            let (mut send, mut recv) = conn.accept_bi().await.anyerr()?;
3184            let msg = recv.read_to_end(1_000).await.anyerr()?;
3185            send.write_all(&msg).await.anyerr()?;
3186            send.finish().anyerr()?;
3187            let close_reason = conn.closed().await;
3188            Ok::<_, Error>(close_reason)
3189        });
3190
3191        let conn = client.connect(server_addr, TEST_ALPN).await?;
3192        let (mut send, mut recv) = conn.open_bi().await.anyerr()?;
3193        send.write_all(b"Hello, world!").await.anyerr()?;
3194        send.finish().anyerr()?;
3195        recv.read_to_end(1_000).await.anyerr()?;
3196        conn.close(42u32.into(), b"thanks, bye!");
3197        client.close().await;
3198
3199        let close_err = server_task.await.anyerr()??;
3200        let ConnectionError::ApplicationClosed(app_close) = close_err else {
3201            panic!("Unexpected close reason: {close_err:?}");
3202        };
3203
3204        assert_eq!(app_close.error_code, 42u32.into());
3205        assert_eq!(app_close.reason.as_ref(), b"thanks, bye!");
3206
3207        Ok(())
3208    }
3209
3210    #[cfg(feature = "metrics")]
3211    #[tokio::test]
3212    #[traced_test]
3213    async fn metrics_smoke() -> Result {
3214        use iroh_metrics::Registry;
3215
3216        let secret_key = SecretKey::from_bytes(&[0u8; 32]);
3217        let client = Endpoint::builder(presets::Minimal)
3218            .secret_key(secret_key)
3219            .bind()
3220            .await?;
3221        let secret_key = SecretKey::from_bytes(&[1u8; 32]);
3222        let server = Endpoint::builder(presets::Minimal)
3223            .secret_key(secret_key)
3224            .alpns(vec![TEST_ALPN.to_vec()])
3225            .bind()
3226            .await?;
3227        let server_addr = server.addr();
3228        let server_task = tokio::task::spawn(async move {
3229            let conn = server.accept().await.anyerr()?.await.anyerr()?;
3230            let mut uni = conn.accept_uni().await.anyerr()?;
3231            uni.read_to_end(10).await.anyerr()?;
3232            drop(conn);
3233            Ok::<_, Error>(server)
3234        });
3235        let conn = client.connect(server_addr, TEST_ALPN).await?;
3236        let mut uni = conn.open_uni().await.anyerr()?;
3237        uni.write_all(b"helloworld").await.anyerr()?;
3238        uni.finish().anyerr()?;
3239        conn.closed().await;
3240        drop(conn);
3241        let server = server_task.await.anyerr()??;
3242
3243        let m = client.metrics();
3244        // assert_eq!(m.socket.num_direct_conns_added.get(), 1);
3245        // assert_eq!(m.socket.connection_became_direct.get(), 1);
3246        // assert_eq!(m.socket.connection_handshake_success.get(), 1);
3247        // assert_eq!(m.socket.endpoints_contacted_directly.get(), 1);
3248        assert!(m.socket.recv_datagrams.get() > 0);
3249
3250        let m = server.metrics();
3251        // assert_eq!(m.socket.num_direct_conns_added.get(), 1);
3252        // assert_eq!(m.socket.connection_became_direct.get(), 1);
3253        // assert_eq!(m.socket.endpoints_contacted_directly.get(), 1);
3254        // assert_eq!(m.socket.connection_handshake_success.get(), 1);
3255        assert!(m.socket.recv_datagrams.get() > 0);
3256
3257        // test openmetrics encoding with labeled subregistries per endpoint
3258        fn register_endpoint(registry: &mut Registry, endpoint: &Endpoint) {
3259            let id = endpoint.id().fmt_short();
3260            let sub_registry = registry.sub_registry_with_label("id", id.to_string());
3261            sub_registry.register_all(endpoint.metrics());
3262        }
3263        let mut registry = Registry::default();
3264        register_endpoint(&mut registry, &client);
3265        register_endpoint(&mut registry, &server);
3266        // let s = registry.encode_openmetrics_to_string().anyerr()?;
3267        // assert!(s.contains(r#"socket_endpoints_contacted_directly_total{id="3b6a27bcce"} 1"#));
3268        // assert!(s.contains(r#"socket_endpoints_contacted_directly_total{id="8a88e3dd74"} 1"#));
3269        Ok(())
3270    }
3271
3272    /// Configures the accept side to take `accept_alpns` ALPNs, then connects to it with `primary_connect_alpn`
3273    /// with `secondary_connect_alpns` set, and finally returns the negotiated ALPN.
3274    async fn alpn_connection_test(
3275        accept_alpns: Vec<Vec<u8>>,
3276        primary_connect_alpn: &[u8],
3277        secondary_connect_alpns: Vec<Vec<u8>>,
3278    ) -> Result<Vec<u8>> {
3279        let client = Endpoint::bind(presets::Minimal).await?;
3280        let server = Endpoint::builder(presets::Minimal)
3281            .alpns(accept_alpns)
3282            .bind()
3283            .await?;
3284        let server_addr = server.addr();
3285        let server_task = tokio::spawn({
3286            let server = server.clone();
3287            async move {
3288                let incoming = server.accept().await.anyerr()?;
3289                let conn = incoming.await.anyerr()?;
3290                conn.close(0u32.into(), b"bye!");
3291                n0_error::Ok(conn.alpn().to_vec())
3292            }
3293        });
3294
3295        let conn = client
3296            .connect_with_opts(
3297                server_addr,
3298                primary_connect_alpn,
3299                ConnectOptions::new().with_additional_alpns(secondary_connect_alpns),
3300            )
3301            .await?;
3302        let conn = conn.await.anyerr()?;
3303        let client_alpn = conn.alpn();
3304        conn.closed().await;
3305        client.close().await;
3306        server.close().await;
3307
3308        let server_alpn = server_task.await.anyerr()??;
3309
3310        assert_eq!(client_alpn, server_alpn);
3311
3312        Ok(server_alpn.to_vec())
3313    }
3314
3315    #[tokio::test]
3316    #[traced_test]
3317    async fn connect_multiple_alpn_negotiated() -> Result {
3318        const ALPN_ONE: &[u8] = b"alpn/1";
3319        const ALPN_TWO: &[u8] = b"alpn/2";
3320
3321        assert_eq!(
3322            alpn_connection_test(
3323                // Prefer version 2 over version 1 on the accept side
3324                vec![ALPN_TWO.to_vec(), ALPN_ONE.to_vec()],
3325                ALPN_TWO,
3326                vec![ALPN_ONE.to_vec()],
3327            )
3328            .await?,
3329            ALPN_TWO.to_vec(),
3330            "accept side prefers version 2 over 1"
3331        );
3332
3333        assert_eq!(
3334            alpn_connection_test(
3335                // Only support the old version
3336                vec![ALPN_ONE.to_vec()],
3337                ALPN_TWO,
3338                vec![ALPN_ONE.to_vec()],
3339            )
3340            .await?,
3341            ALPN_ONE.to_vec(),
3342            "accept side only supports the old version"
3343        );
3344
3345        assert_eq!(
3346            alpn_connection_test(
3347                vec![ALPN_TWO.to_vec(), ALPN_ONE.to_vec()],
3348                ALPN_ONE,
3349                vec![ALPN_TWO.to_vec()],
3350            )
3351            .await?,
3352            ALPN_TWO.to_vec(),
3353            "connect side ALPN order doesn't matter"
3354        );
3355
3356        assert_eq!(
3357            alpn_connection_test(vec![ALPN_TWO.to_vec(), ALPN_ONE.to_vec()], ALPN_ONE, vec![],)
3358                .await?,
3359            ALPN_ONE.to_vec(),
3360            "connect side only supports the old version"
3361        );
3362
3363        Ok(())
3364    }
3365
3366    #[tokio::test]
3367    #[traced_test]
3368    #[cfg(feature = "unstable-net-report")]
3369    async fn watch_net_report() -> Result {
3370        let endpoint = Endpoint::builder(presets::Minimal)
3371            .relay_mode(RelayMode::Staging)
3372            .bind()
3373            .await?;
3374
3375        // can get a first report
3376        endpoint.net_report().updated().await.anyerr()?;
3377
3378        Ok(())
3379    }
3380
3381    /// Tests that initial connection establishment isn't extremely slow compared
3382    /// to subsequent connections.
3383    ///
3384    /// This is a time based test, but uses a very large ratio to reduce flakiness.
3385    /// It also does a number of connections to average out any anomalies.
3386    #[tokio::test]
3387    #[traced_test]
3388    async fn connect_multi_time() -> Result {
3389        let n = 32;
3390
3391        const NOOP_ALPN: &[u8] = b"noop";
3392
3393        #[derive(Debug, Clone)]
3394        struct Noop;
3395
3396        impl ProtocolHandler for Noop {
3397            async fn accept(&self, connection: Connection) -> Result<(), AcceptError> {
3398                connection.closed().await;
3399                Ok(())
3400            }
3401        }
3402
3403        async fn noop_server() -> Result<(Router, EndpointAddr)> {
3404            let endpoint = Endpoint::bind(presets::Minimal).await.anyerr()?;
3405            let addr = endpoint.addr();
3406            let router = Router::builder(endpoint).accept(NOOP_ALPN, Noop).spawn();
3407            Ok((router, addr))
3408        }
3409
3410        let routers = stream::iter(0..n)
3411            .map(|_| noop_server())
3412            .buffered_unordered(32)
3413            .collect::<Vec<_>>()
3414            .await
3415            .into_iter()
3416            .collect::<Result<Vec<_>, _>>()
3417            .anyerr()?;
3418
3419        let addrs = routers
3420            .iter()
3421            .map(|(_, addr)| addr.clone())
3422            .collect::<Vec<_>>();
3423        let ids = addrs.iter().map(|addr| addr.id).collect::<Vec<_>>();
3424        let address_lookup = MemoryLookup::from_endpoint_info(addrs);
3425        let endpoint = Endpoint::builder(presets::Minimal)
3426            .address_lookup(address_lookup)
3427            .bind()
3428            .await
3429            .anyerr()?;
3430        // wait for the endpoint to be initialized. This should not be needed,
3431        // but we don't want to measure endpoint init time but connection time
3432        // from a fully initialized endpoint.
3433        endpoint.addr();
3434        let t0 = Instant::now();
3435        for id in &ids {
3436            let conn = endpoint.connect(*id, NOOP_ALPN).await?;
3437            conn.close(0u32.into(), b"done");
3438        }
3439        let dt0 = t0.elapsed().as_secs_f64();
3440        let t1 = Instant::now();
3441        for id in &ids {
3442            let conn = endpoint.connect(*id, NOOP_ALPN).await?;
3443            conn.close(0u32.into(), b"done");
3444        }
3445        let dt1 = t1.elapsed().as_secs_f64();
3446
3447        assert!(dt0 / dt1 < 20.0, "First round: {dt0}s, second round {dt1}s");
3448        Ok(())
3449    }
3450
3451    #[tokio::test]
3452    async fn test_custom_relay() -> Result {
3453        let _ep = Endpoint::builder(presets::Minimal)
3454            .relay_mode(RelayMode::custom([RelayUrl::from_str(
3455                "https://use1-1.relay.n0.iroh.link.",
3456            )?]))
3457            .bind()
3458            .await?;
3459
3460        let relays = RelayMap::try_from_iter([
3461            "https://use1-1.relay.n0.iroh.link/",
3462            "https://euc1-1.relay.n0.iroh.link/",
3463        ])?;
3464        let _ep = Endpoint::builder(presets::Minimal)
3465            .relay_mode(RelayMode::Custom(relays))
3466            .bind()
3467            .await?;
3468
3469        Ok(())
3470    }
3471
3472    /// Testing bind_addr: Clear IP transports and add single IPv4 bind
3473    #[tokio::test]
3474    #[traced_test]
3475    async fn test_bind_addr_clear() -> Result {
3476        let ep = Endpoint::builder(presets::Minimal)
3477            .clear_ip_transports()
3478            .bind_addr((Ipv4Addr::LOCALHOST, 0))?
3479            .bind()
3480            .await?;
3481        let bound_sockets = ep.bound_sockets();
3482        assert_eq!(bound_sockets.len(), 1);
3483        assert_eq!(bound_sockets[0].ip(), IpAddr::V4(Ipv4Addr::LOCALHOST));
3484        ep.close().await;
3485        Ok(())
3486    }
3487
3488    /// Testing bind_addr: Do not clear IP transports and add single non-default IPv4 bind
3489    ///
3490    /// This will bind two sockets: default wildcard bind for IPv6, and our
3491    /// manually-added IPv4 bind.
3492    #[tokio::test]
3493    #[traced_test]
3494    async fn test_bind_addr_no_clear() -> Result {
3495        let ep = Endpoint::builder(presets::Minimal)
3496            .bind_addr((Ipv4Addr::LOCALHOST, 0))?
3497            .bind()
3498            .await?;
3499        let bound_sockets = ep.bound_sockets();
3500        assert_eq!(bound_sockets.len(), 2);
3501        assert_eq!(bound_sockets.iter().filter(|x| x.is_ipv4()).count(), 1);
3502        assert_eq!(bound_sockets.iter().filter(|x| x.is_ipv6()).count(), 1);
3503        // Test that our manually added socket is there
3504        assert!(
3505            bound_sockets
3506                .iter()
3507                .any(|x| x.ip() == IpAddr::V4(Ipv4Addr::LOCALHOST))
3508        );
3509        ep.close().await;
3510        Ok(())
3511    }
3512
3513    // Testing bind_addr: Do not clear IP transports and add single default IPv4 bind.
3514    //
3515    // This replaces the default IPv4 bind added by the builder,
3516    // but keeps the default wildcard IPv6 bind.
3517    #[tokio::test]
3518    #[traced_test]
3519    async fn test_bind_addr_default() -> Result {
3520        let ep = Endpoint::builder(presets::Minimal)
3521            .bind_addr_with_opts(
3522                (Ipv4Addr::LOCALHOST, 0),
3523                BindOpts::default().set_is_default_route(true),
3524            )?
3525            .bind()
3526            .await?;
3527        let bound_sockets = ep.bound_sockets();
3528        assert_eq!(bound_sockets.len(), 2);
3529        assert_eq!(bound_sockets.iter().filter(|x| x.is_ipv4()).count(), 1);
3530        assert_eq!(bound_sockets.iter().filter(|x| x.is_ipv6()).count(), 1);
3531        assert!(
3532            bound_sockets
3533                .iter()
3534                .any(|x| x.ip() == IpAddr::V4(Ipv4Addr::LOCALHOST))
3535        );
3536        ep.close().await;
3537        drop(ep);
3538
3539        Ok(())
3540    }
3541
3542    /// Testing bind_addr: Do not clear IP transports and add single IPv4 bind with a non-zero prefix len
3543    ///
3544    /// This will bind three sockets: default wildcard bind for IPv4 and IPv6, and our
3545    /// manually-added IPv4 bind.
3546    #[tokio::test]
3547    #[traced_test]
3548    async fn test_bind_addr_nonzero_prefix() -> Result {
3549        let ep = Endpoint::builder(presets::Minimal)
3550            .bind_addr_with_opts(
3551                (Ipv4Addr::LOCALHOST, 0),
3552                BindOpts::default().set_prefix_len(32),
3553            )?
3554            .bind()
3555            .await?;
3556        let bound_sockets = ep.bound_sockets();
3557        assert_eq!(bound_sockets.len(), 3);
3558        assert_eq!(bound_sockets.iter().filter(|x| x.is_ipv4()).count(), 2);
3559        assert_eq!(bound_sockets.iter().filter(|x| x.is_ipv6()).count(), 1);
3560        // Test that the default wildcard socket is there
3561        assert!(
3562            bound_sockets
3563                .iter()
3564                .any(|x| x.ip() == IpAddr::V4(Ipv4Addr::UNSPECIFIED))
3565        );
3566        // Test that our manually added socket is there
3567        assert!(
3568            bound_sockets
3569                .iter()
3570                .any(|x| x.ip() == IpAddr::V4(Ipv4Addr::LOCALHOST))
3571        );
3572        ep.close().await;
3573        Ok(())
3574    }
3575
3576    /// Bind on an unusable port with the default opts.
3577    ///
3578    /// Binding the endpoint fails with an AddrInUse error.
3579    #[tokio::test]
3580    #[traced_test]
3581    async fn test_bind_addr_badport() -> Result {
3582        let socket = std::net::UdpSocket::bind((Ipv4Addr::LOCALHOST, 0))?;
3583        let port = socket.local_addr()?.port();
3584
3585        let res = Endpoint::builder(presets::Minimal)
3586            .clear_ip_transports()
3587            .bind_addr((Ipv4Addr::LOCALHOST, port))?
3588            .bind()
3589            .await;
3590
3591        assert!(matches!(
3592            res,
3593            Err(BindError::Sockets {
3594                source: io_error,
3595                ..
3596            })
3597            if io_error.kind() == io::ErrorKind::AddrInUse
3598        ));
3599        Ok(())
3600    }
3601
3602    /// Bind a non-default route on an unusable port, but set is_required = false.
3603    ///
3604    /// Binding the endpoint succeeds.
3605    #[tokio::test]
3606    #[traced_test]
3607    async fn test_bind_addr_badport_notrequired() -> Result {
3608        let socket = std::net::UdpSocket::bind((Ipv4Addr::LOCALHOST, 0))?;
3609        let port = socket.local_addr()?.port();
3610
3611        let ep = Endpoint::builder(presets::Minimal)
3612            .bind_addr_with_opts(
3613                (Ipv4Addr::LOCALHOST, port),
3614                BindOpts::default()
3615                    .set_prefix_len(32)
3616                    .set_is_required(false),
3617            )?
3618            .bind()
3619            .await?;
3620        let bound_sockets = ep.bound_sockets();
3621        // just the default wildcard binds
3622        assert_eq!(bound_sockets.len(), 2);
3623        // our requested bind addr is not included because it failed to bind
3624        assert!(
3625            !bound_sockets
3626                .iter()
3627                .any(|x| x.ip() == IpAddr::V4(Ipv4Addr::LOCALHOST))
3628        );
3629        Ok(())
3630    }
3631
3632    /// Bind on a default route on an unusable port, but set is_required = false.
3633    ///
3634    /// Binding the endpoint succeeds.
3635    #[tokio::test]
3636    #[traced_test]
3637    async fn test_bind_addr_badport_default_notrequired() -> Result {
3638        let socket = std::net::UdpSocket::bind((Ipv4Addr::LOCALHOST, 0))?;
3639        let port = socket.local_addr()?.port();
3640
3641        let ep = Endpoint::builder(presets::Minimal)
3642            .bind_addr_with_opts(
3643                (Ipv4Addr::LOCALHOST, port),
3644                BindOpts::default().set_is_required(false),
3645            )?
3646            .bind()
3647            .await?;
3648        let bound_sockets = ep.bound_sockets();
3649        // just the IPv6 default, but no IPv4 bind at all because we replaced the default
3650        // with a bind with an unusable port and set it to not be required.
3651        assert_eq!(bound_sockets.len(), 1);
3652        assert!(bound_sockets[0].is_ipv6());
3653        Ok(())
3654    }
3655
3656    /// Bind on an unusable port, with is_required = false, and no other transports.
3657    ///
3658    /// Binding the endpoint fails with "no valid address available".
3659    #[tokio::test]
3660    #[traced_test]
3661    async fn test_bind_addr_badport_notrequired_no_other_transports() -> Result {
3662        let socket = std::net::UdpSocket::bind((Ipv4Addr::LOCALHOST, 0))?;
3663        let port = socket.local_addr()?.port();
3664
3665        let res = Endpoint::builder(presets::Minimal)
3666            .clear_ip_transports()
3667            .bind_addr_with_opts(
3668                (Ipv4Addr::LOCALHOST, port),
3669                BindOpts::default().set_is_required(false),
3670            )?
3671            .bind()
3672            .await;
3673
3674        assert!(matches!(
3675            res,
3676            Err(BindError::CreateQuicEndpoint {
3677                source: io_error,
3678                ..
3679            })
3680            if io_error.kind() == io::ErrorKind::Other && io_error.to_string() == "no valid address available"
3681        ));
3682        Ok(())
3683    }
3684
3685    /// Bind with prefix len 0 but set the route as non-default.
3686    #[tokio::test]
3687    #[traced_test]
3688    async fn test_bind_addr_prefix_len_0_not_default() -> Result {
3689        let ep = Endpoint::builder(presets::Minimal)
3690            .bind_addr_with_opts(
3691                (Ipv4Addr::LOCALHOST, 0),
3692                BindOpts::default().set_is_default_route(false),
3693            )?
3694            .bind()
3695            .await?;
3696        let bound_sockets = ep.bound_sockets();
3697        // The two default wildcard binds plus our additional route (which does not replace the default route
3698        // because we set is_default_route to false explicitly).
3699        assert_eq!(bound_sockets.len(), 3);
3700        assert!(
3701            bound_sockets
3702                .iter()
3703                .any(|x| x.ip() == IpAddr::V6(Ipv6Addr::UNSPECIFIED))
3704        );
3705        assert!(
3706            bound_sockets
3707                .iter()
3708                .any(|x| x.ip() == IpAddr::V4(Ipv4Addr::UNSPECIFIED))
3709        );
3710        assert!(
3711            bound_sockets
3712                .iter()
3713                .any(|x| x.ip() == IpAddr::V4(Ipv4Addr::LOCALHOST))
3714        );
3715        Ok(())
3716    }
3717
3718    #[ignore = "flaky"]
3719    #[tokio::test]
3720    #[traced_test]
3721    async fn connect_via_relay_becomes_direct_and_sends_direct() -> Result {
3722        let (relay_map, relay_url, _relay_server_guard) = run_relay_server().await?;
3723        let qlog = Arc::new(QlogFileGroup::from_env(
3724            "connect_via_relay_becomes_direct_and_sends_direct",
3725        ));
3726        let transfer_size = 1_000_000;
3727
3728        async fn collect_stats(mut events: PathEventStream) -> BTreeMap<TransportAddr, PathStats> {
3729            let mut stats = BTreeMap::new();
3730            while let Some(event) = events.next().await {
3731                if let PathEvent::Closed {
3732                    remote_addr,
3733                    last_stats,
3734                    ..
3735                } = event
3736                {
3737                    stats.insert(remote_addr, *last_stats);
3738                }
3739            }
3740            stats
3741        }
3742
3743        let client = Endpoint::builder(presets::Minimal)
3744            .relay_mode(RelayMode::Custom(relay_map.clone()))
3745            .ca_tls_config(CaTlsConfig::insecure_skip_verify())
3746            .transport_config(qlog.create("client")?)
3747            .bind()
3748            .await?;
3749        let server = Endpoint::builder(presets::Minimal)
3750            .relay_mode(RelayMode::Custom(relay_map))
3751            .ca_tls_config(CaTlsConfig::insecure_skip_verify())
3752            .transport_config(qlog.create("server")?)
3753            .alpns(vec![TEST_ALPN.to_vec()])
3754            .bind()
3755            .await?;
3756        let server_addr = EndpointAddr::new(server.id()).with_relay_url(relay_url);
3757        let server_task = tokio::spawn(async move {
3758            let incoming = server.accept().await.anyerr()?;
3759            let conn = incoming.await.anyerr()?;
3760            let stats_task = tokio::spawn(collect_stats(conn.path_events()));
3761            let (mut send, mut recv) = conn.accept_bi().await.anyerr()?;
3762            let msg = recv.read_to_end(transfer_size).await.anyerr()?;
3763            send.write_all(&msg).await.anyerr()?;
3764            send.finish().anyerr()?;
3765            conn.closed().await;
3766            let stats = stats_task.await.expect("stats task panicked");
3767            Ok::<_, Error>(stats)
3768        });
3769
3770        let conn = client.connect(server_addr, TEST_ALPN).await?;
3771        let client_stats_task = tokio::spawn(collect_stats(conn.path_events()));
3772        let (mut send, mut recv) = conn.open_bi().await.anyerr()?;
3773        send.write_all(&vec![42u8; transfer_size]).await.anyerr()?;
3774        send.finish().anyerr()?;
3775        recv.read_to_end(transfer_size).await.anyerr()?;
3776        conn.close(0u32.into(), b"thanks, bye!");
3777        client.close().await;
3778        let client_stats = client_stats_task.await.expect("stats task panicked");
3779        let server_stats = server_task.await.anyerr()??;
3780
3781        info!("client stats: {client_stats:#?}");
3782        info!("server stats: {server_stats:#?}");
3783
3784        let client_total_relay_tx = client_stats
3785            .iter()
3786            .filter(|(remote, _stats)| remote.is_relay())
3787            .map(|(_, stats)| stats.udp_tx.bytes)
3788            .sum::<u64>();
3789        let client_total_relay_rx = client_stats
3790            .iter()
3791            .filter(|(remote, _stats)| remote.is_relay())
3792            .map(|(_, stats)| stats.udp_rx.bytes)
3793            .sum::<u64>();
3794        let server_total_relay_tx = server_stats
3795            .iter()
3796            .filter(|(remote, _stats)| remote.is_relay())
3797            .map(|(_, stats)| stats.udp_tx.bytes)
3798            .sum::<u64>();
3799        let server_total_relay_rx = server_stats
3800            .iter()
3801            .filter(|(remote, _stats)| remote.is_relay())
3802            .map(|(_, stats)| stats.udp_rx.bytes)
3803            .sum::<u64>();
3804
3805        info!(?client_total_relay_tx, "total");
3806        info!(?client_total_relay_rx, "total");
3807        info!(?server_total_relay_tx, "total");
3808        info!(?server_total_relay_rx, "total");
3809
3810        // We should send/receive only the minorty of traffic via the relay.
3811        assert!(client_total_relay_tx < transfer_size as u64 / 2);
3812        assert!(client_total_relay_rx < transfer_size as u64 / 2);
3813        assert!(server_total_relay_tx < transfer_size as u64 / 2);
3814        assert!(server_total_relay_rx < transfer_size as u64 / 2);
3815
3816        Ok(())
3817    }
3818
3819    /// Tests that correct logs are emitted when connecting two endpoints with same secret
3820    /// keys to a relay.
3821    #[tokio::test]
3822    #[traced_test]
3823    async fn same_endpoint_id_relay() -> Result {
3824        let (relay_map, relay_url, _relay_server_guard) = run_relay_server().await?;
3825        let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(1u64);
3826        let secret_key = SecretKey::from_bytes(&rng.random());
3827
3828        let client = Endpoint::builder(presets::Minimal)
3829            .relay_mode(RelayMode::Custom(relay_map.clone()))
3830            .ca_tls_config(CaTlsConfig::insecure_skip_verify())
3831            .bind()
3832            .instrument(error_span!("ep-client"))
3833            .await?;
3834
3835        info!("client {}", client.id());
3836
3837        // bind ep1 and wait until connected to relay.
3838        let ep1 = Endpoint::builder(presets::Minimal)
3839            .relay_mode(RelayMode::Custom(relay_map.clone()))
3840            .secret_key(secret_key.clone())
3841            .ca_tls_config(CaTlsConfig::insecure_skip_verify())
3842            .alpns(vec![TEST_ALPN.to_vec()])
3843            .bind()
3844            .instrument(error_span!("ep1"))
3845            .await?;
3846        info!("ep1 bound {:?}", ep1.id());
3847        ep1.online().await;
3848        info!("ep1 online");
3849
3850        let addr = EndpointAddr::new(secret_key.public()).with_relay_url(relay_url.clone());
3851
3852        tokio::try_join!(
3853            async {
3854                let conn = client.connect(addr.clone(), TEST_ALPN).await?;
3855                let reason = conn.closed().await;
3856                assert!(is_application_closed(&reason, 1));
3857                n0_error::Ok(())
3858            },
3859            async {
3860                let conn = ep1.accept().await.unwrap().await?;
3861                conn.close(1u32.into(), b"bye");
3862                n0_error::Ok(())
3863            }
3864        )?;
3865        info!("client connected to ep1");
3866
3867        // now start second endpoint with same secret key
3868        let ep2 = Endpoint::builder(presets::Minimal)
3869            .relay_mode(RelayMode::Custom(relay_map))
3870            .secret_key(secret_key.clone())
3871            .ca_tls_config(CaTlsConfig::insecure_skip_verify())
3872            .alpns(vec![TEST_ALPN.to_vec()])
3873            .bind()
3874            .instrument(error_span!("ep2"))
3875            .await?;
3876        info!("ep2 bound {:?}", ep2.id());
3877        ep2.online().await;
3878        println!("ep2 online");
3879
3880        // `online` does not mean that the connection to the home relay was *established*,
3881        // only that the home relay was *chosen* based on the net report probes.
3882        // We need to wait for the connection to be established though, to be sure that new packets
3883        // will be routed to the new endpoint and not to the old endpoint anymore.
3884        // We don't expose being connected to the home relay on the endpoint currently,
3885        // so we resort to log assertions.
3886        // If you think this all wasn't sad enough already,
3887        // https://github.com/tokio-rs/tracing/issues/1372 means we need to look for the
3888        // repeated `id` field.
3889        // TODO(Frando): Replace once we add a proper API for this.
3890        let expected_log_line = format!(
3891            "ep2:endpoint{{id={} id={}}}:relay-actor:active-relay{{url={relay_url}}}:connected: iroh::_events::relay::connected",
3892            ep2.id().fmt_short(),
3893            ep2.id().fmt_short(),
3894        );
3895        tokio::time::timeout(Duration::from_secs(5), async {
3896            while !logs_contain(&expected_log_line) {
3897                tokio::time::sleep(Duration::from_millis(10)).await
3898            }
3899        })
3900        .await
3901        .std_context("relay connection did not establish in time")?;
3902
3903        tokio::try_join!(
3904            async {
3905                let conn = client.connect(addr.clone(), TEST_ALPN).await?;
3906                let reason = conn.closed().await;
3907                assert!(is_application_closed(&reason, 1));
3908                n0_error::Ok(())
3909            },
3910            async {
3911                let conn = ep2.accept().await.unwrap().await?;
3912                conn.close(1u32.into(), b"bye");
3913                n0_error::Ok(())
3914            }
3915        )?;
3916        println!("client connected to ep2");
3917
3918        // assert that ep1 did not receive a connection
3919        assert!(now_or_never(ep1.accept()).is_none());
3920
3921        // We assert that we get the warn log once for endpoint 1, and not at all for endpoint 2.
3922        logs_assert(|logs| {
3923            let expected_line = |line: &str| {
3924                line.contains("WARN") && line.contains("Another endpoint connected with the same endpoint id. No more messages will be received")
3925            };
3926            let count_line_ep1 = logs
3927                .iter()
3928                .filter(|line| line.contains(":ep1:") && expected_line(line))
3929                .count();
3930            let count_line_ep2 = logs
3931                .iter()
3932                .filter(|line| line.contains(":ep2:") && expected_line(line))
3933                .count();
3934            if count_line_ep1 == 1 && count_line_ep2 == 0 {
3935                Ok(())
3936            } else {
3937                Err("Logs don't match expectations".to_string())
3938            }
3939        });
3940        tokio::join!(ep1.close(), ep2.close(), client.close());
3941        Ok(())
3942    }
3943
3944    fn is_application_closed(close_reason: &ConnectionError, code: u32) -> bool {
3945        matches!(
3946            close_reason,
3947            ConnectionError::ApplicationClosed(f) if f.error_code ==code.into()
3948        )
3949    }
3950
3951    #[tokio::test]
3952    #[traced_test]
3953    async fn test_closed_endpoint_behaviour() -> Result {
3954        // create endpoint
3955        // call endpoint.close
3956        // ensure methods behave in the expected way
3957        info!("Creating endpoint");
3958        let ep = Endpoint::builder(presets::N0).bind().await?;
3959        let closed = ep.closed();
3960        info!("Closing endpoint");
3961        let now = Instant::now();
3962        ep.close().await;
3963        info!("Endpoint closed in {:?}", now.elapsed());
3964
3965        // Assert that the `closed` cancellation token is now cancelled
3966        assert_eq!(now_or_never(closed), Some(()));
3967
3968        info!("Set ALPNS fails silently");
3969        ep.set_alpns(vec![b"test".into()]);
3970
3971        info!("Insert Relay returns None");
3972        let relay_config = crate::defaults::staging::default_na_east_relay();
3973        assert!(
3974            ep.insert_relay("localhost:300".parse()?, Arc::new(relay_config))
3975                .await
3976                .is_none()
3977        );
3978
3979        info!("Remove Relay returns None");
3980        assert!(ep.remove_relay(&"localhost:300".parse()?).await.is_none());
3981
3982        info!("Connecting");
3983        let mut rng = ChaCha8Rng::seed_from_u64(41);
3984        let ep_id = SecretKey::from_bytes(&rng.random()).public();
3985
3986        // should likely be an error that states that the
3987        // endpoint is closed instead:
3988        if let ConnectError::Connect { source, .. } = ep.connect(ep_id, b"test").await.unwrap_err()
3989        {
3990            assert!(matches!(
3991                source,
3992                ConnectWithOptsError::EndpointClosed { .. }
3993            ));
3994        } else {
3995            panic!("unexpected error for connect");
3996        }
3997
3998        info!("Accepting!");
3999        assert!(ep.accept().await.is_none());
4000
4001        // this should work
4002        info!("Addr: {:?}", ep.addr());
4003
4004        // create watchers to verify they terminate after the endpoint is dropped.
4005        let mut addrs = ep.watch_addr().stream();
4006
4007        #[cfg(feature = "unstable-net-report")]
4008        let mut net_reports = {
4009            let net_reports = ep.net_report().stream();
4010
4011            // returns None
4012            let net_report = ep.net_report().get();
4013            info!("last Net report {net_report:?}");
4014            net_reports
4015        };
4016
4017        // this should work
4018        let sockets = ep.bound_sockets();
4019        info!("Sockets: {sockets:?}");
4020
4021        // these should return errors
4022        assert!(ep.dns_resolver().is_err());
4023        assert!(ep.address_lookup().is_err());
4024
4025        #[cfg(feature = "metrics")]
4026        {
4027            // this should work
4028            let metrics = ep.metrics();
4029            info!("Metrics: {metrics:?}");
4030        }
4031
4032        // this should return none
4033        assert!(ep.remote_info(ep_id).await.is_none());
4034
4035        // this should fail silently
4036        ep.network_change().await;
4037
4038        // this should fail silently
4039        ep.set_user_data_for_address_lookup(Some(
4040            UserData::try_from("TEST".to_string()).expect("valid string"),
4041        ));
4042        drop(ep);
4043        // now that the endpoint is dropped, all watchers should terminate.
4044        tokio::time::timeout(Duration::from_secs(1), async {
4045            while let Some(addr) = addrs.next().await {
4046                info!("Addrs stream: {addr:?}");
4047            }
4048
4049            #[cfg(feature = "unstable-net-report")]
4050            while let Some(net_report) = net_reports.next().await {
4051                info!("Net report stream: {net_report:?}");
4052            }
4053        })
4054        .await
4055        .expect("watchers not closed");
4056
4057        info!("Done!");
4058        Ok(())
4059    }
4060
4061    #[tokio::test]
4062    #[traced_test]
4063    async fn test_closed_endpoint_unpolled_accept_fut() -> Result {
4064        info!("Creating endpoint");
4065        let ep = Endpoint::builder(presets::N0).bind().await?;
4066
4067        info!("Get accept future");
4068        let accept_fut = ep.accept();
4069
4070        info!("Closing endpoint");
4071        let now = Instant::now();
4072        tokio::time::timeout(Duration::from_secs(5), ep.close())
4073            .await
4074            .expect("Endpoint closes in a reasonable time");
4075        info!("Endpoint closed in {:?}", now.elapsed());
4076
4077        info!("Accept future returns None after the endpoint has closed");
4078        let incoming = accept_fut.await;
4079        assert!(incoming.is_none());
4080        Ok(())
4081    }
4082
4083    #[tokio::test]
4084    #[traced_test]
4085    async fn test_closed_endpoint_polled_accept_fut() -> Result {
4086        info!("Creating endpoint");
4087        let ep = Endpoint::builder(presets::N0).bind().await?;
4088
4089        info!("Run an accept task");
4090        let ep2 = ep.clone();
4091        let accept_task = tokio::spawn(async move {
4092            info!("Waiting on Accept");
4093            let res = ep2.accept().await;
4094            info!("Accept await has returned");
4095            res
4096        });
4097
4098        // Try to ensure the accept future is polled at least once.
4099        tokio::time::sleep(Duration::from_millis(10)).await;
4100
4101        info!("Closing the endpoint");
4102        tokio::time::timeout(Duration::from_secs(5), ep.close())
4103            .await
4104            .expect("Endpoint closes in a reasonable time");
4105        info!("Endpoint closed");
4106
4107        info!("Await the accept task");
4108        let incoming = accept_task.await.expect("accept task panicked");
4109        assert!(incoming.is_none());
4110
4111        Ok(())
4112    }
4113
4114    #[tokio::test]
4115    #[traced_test]
4116    async fn test_endpoint_online_add_relay() -> Result {
4117        let ep = Endpoint::builder(presets::Minimal)
4118            .relay_mode(RelayMode::Custom(RelayMap::empty()))
4119            .ca_tls_config(CaTlsConfig::insecure_skip_verify())
4120            .bind()
4121            .await?;
4122        // should not come online without relays.
4123        let res = tokio::time::timeout(Duration::from_millis(500), ep.online()).await;
4124        assert!(res.is_err());
4125
4126        // should come online after a relay is added.
4127        let (relay_map, relay_url, _relay_server_guard) = run_relay_server().await?;
4128        ep.insert_relay(relay_url.clone(), relay_map.get(&relay_url).unwrap())
4129            .await;
4130        let res = tokio::time::timeout(Duration::from_millis(1000), ep.online()).await;
4131        assert!(res.is_ok());
4132
4133        // online should still return after endpoint close, if the endpoint was last online
4134        let ep_clone = ep.clone();
4135        let task = tokio::task::spawn(async move {
4136            tokio::time::timeout(Duration::from_millis(500), ep_clone.online()).await
4137        });
4138        ep.close().await;
4139        let res = task.await.unwrap();
4140        assert!(res.is_ok());
4141        Ok(())
4142    }
4143
4144    #[tokio::test]
4145    #[traced_test]
4146    async fn test_endpoint_online_close() -> Result {
4147        let ep = Endpoint::bind(presets::Minimal).await?;
4148        // should not come online without relays.
4149        let res = tokio::time::timeout(Duration::from_millis(500), ep.online()).await;
4150        assert!(res.is_err());
4151
4152        // online should remain pending after the endpoint is closed.
4153        let ep_clone = ep.clone();
4154        let task = tokio::task::spawn(async move {
4155            tokio::time::timeout(Duration::from_millis(500), ep_clone.online()).await
4156        });
4157        ep.close().await;
4158        let res = task.await.unwrap();
4159        assert!(res.is_err());
4160        Ok(())
4161    }
4162
4163    /// Verifies that an endpoint configured with [`RelayConfig::with_auth_token`]
4164    /// is admitted to a relay whose access control checks the token only when
4165    /// the token matches.
4166    ///
4167    /// Also verifies that [`RelayStatus::auth_denied_reason`] works correctly.
4168    #[tokio::test]
4169    #[traced_test]
4170    async fn test_endpoint_relay_auth_token() -> Result {
4171        const TOKEN: &str = "valid-token";
4172        const DENIAL_REASON: &str = "this token is no good";
4173
4174        /// Admits a connection only if it carries the expected auth token.
4175        #[derive(Debug)]
4176        struct TokenAccess(&'static str);
4177
4178        impl iroh_relay::server::AccessControl for TokenAccess {
4179            async fn on_connect(&self, request: &iroh_relay::server::ClientRequest) -> Access {
4180                if request.auth_token().as_deref() == Some(self.0) {
4181                    Access::Allow
4182                } else {
4183                    Access::Deny {
4184                        reason: Some(DENIAL_REASON.to_string()),
4185                    }
4186                }
4187            }
4188        }
4189
4190        let access = Arc::new(TokenAccess(TOKEN));
4191        let (_relay_map, relay_url, _guard) = run_relay_server_with_access(false, access).await?;
4192
4193        // Wrong token: the connection attempt fails, and the status reports the
4194        // relay-side denial both as an error and as an authentication failure.
4195        let bad_map: RelayMap = RelayConfig::new(relay_url.clone(), None)
4196            .with_auth_token("wrong-token")
4197            .into();
4198        let bad_ep = Endpoint::builder(presets::Minimal)
4199            .relay_mode(RelayMode::Custom(bad_map))
4200            .ca_tls_config(CaTlsConfig::insecure_skip_verify())
4201            .bind()
4202            .await?;
4203        let mut stream = bad_ep.home_relay_status().stream();
4204        let (auth_err, auth_denied_reason) = tokio::time::timeout(Duration::from_secs(5), async {
4205            while let Some(status) = stream.next().await {
4206                if let Some(relay) = status.iter().find(|s| s.last_error().is_some()) {
4207                    let err = relay.last_error().expect("checked above");
4208                    return (
4209                        format!("{err:#}"),
4210                        relay.auth_denied_reason().map(ToOwned::to_owned),
4211                    );
4212                }
4213            }
4214            panic!("home relay stream ended");
4215        })
4216        .await
4217        .std_context("waiting for auth error")?;
4218        assert!(
4219            auth_err.contains(DENIAL_REASON),
4220            "expected {DENIAL_REASON:?} in error, got: {auth_err}"
4221        );
4222        assert_eq!(
4223            auth_denied_reason.as_deref(),
4224            Some(DENIAL_REASON),
4225            "auth_denied_reason did not recognise a relay-side denial (error was: {auth_err})"
4226        );
4227
4228        // Correct token: the endpoint reaches the connected state.
4229        let good_map: RelayMap = RelayConfig::new(relay_url, None)
4230            .with_auth_token(TOKEN)
4231            .into();
4232        let good_ep = Endpoint::builder(presets::Minimal)
4233            .relay_mode(RelayMode::Custom(good_map))
4234            .ca_tls_config(CaTlsConfig::insecure_skip_verify())
4235            .bind()
4236            .await?;
4237        tokio::time::timeout(Duration::from_secs(5), good_ep.online())
4238            .await
4239            .std_context("waiting for endpoint to come online")?;
4240
4241        Ok(())
4242    }
4243}