iroh/
endpoint.rs

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