iroh/
endpoint.rs

1//! The [`Endpoint`] allows establishing connections to other iroh nodes.
2//!
3//! The [`Endpoint`] is the main API interface to manage a local iroh node.  It allows
4//! connecting to and accepting connections from other nodes.  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 nodes.
10//! - [`Builder`] to create an [`Endpoint`].
11//!
12//! [module docs]: crate
13
14use std::{
15    any::Any,
16    collections::BTreeSet,
17    future::{Future, IntoFuture},
18    net::{IpAddr, SocketAddr, SocketAddrV4, SocketAddrV6},
19    pin::Pin,
20    sync::Arc,
21    task::Poll,
22};
23
24use ed25519_dalek::{VerifyingKey, pkcs8::DecodePublicKey};
25use iroh_base::{NodeAddr, NodeId, RelayUrl, SecretKey};
26use iroh_relay::RelayMap;
27use n0_future::{Stream, time::Duration};
28use n0_watcher::Watcher;
29use nested_enum_utils::common_fields;
30use pin_project::pin_project;
31use snafu::{ResultExt, Snafu, ensure};
32use tracing::{debug, instrument, trace, warn};
33use url::Url;
34
35#[cfg(wasm_browser)]
36use crate::discovery::pkarr::PkarrResolver;
37#[cfg(not(wasm_browser))]
38use crate::{discovery::dns::DnsDiscovery, dns::DnsResolver};
39use crate::{
40    discovery::{
41        ConcurrentDiscovery, Discovery, DiscoveryContext, DiscoveryError, DiscoveryItem,
42        DiscoverySubscribers, DiscoveryTask, DynIntoDiscovery, IntoDiscovery, IntoDiscoveryError,
43        Lagged, UserData, pkarr::PkarrPublisher,
44    },
45    magicsock::{self, Handle, NodeIdMappedAddr, OwnAddressSnafu},
46    metrics::EndpointMetrics,
47    net_report::Report,
48    tls,
49};
50
51mod rtt_actor;
52
53// Missing still: SendDatagram and ConnectionClose::frame_type's Type.
54pub use quinn::{
55    AcceptBi, AcceptUni, AckFrequencyConfig, ApplicationClose, Chunk, ClosedStream,
56    ConnectionClose, ConnectionError, ConnectionStats, MtuDiscoveryConfig, OpenBi, OpenUni,
57    ReadDatagram, ReadError, ReadExactError, ReadToEndError, RecvStream, ResetError, RetryError,
58    SendDatagramError, SendStream, ServerConfig, StoppedError, StreamId, TransportConfig, VarInt,
59    WeakConnectionHandle, WriteError,
60};
61pub use quinn_proto::{
62    FrameStats, PathStats, TransportError, TransportErrorCode, UdpStats, Written,
63    congestion::{Controller, ControllerFactory},
64    crypto::{
65        AeadKey, CryptoError, ExportKeyingMaterialError, HandshakeTokenKey,
66        ServerConfig as CryptoServerConfig, UnsupportedVersion,
67    },
68};
69
70use self::rtt_actor::RttMessage;
71pub use super::magicsock::{
72    AddNodeAddrError, ConnectionType, ControlMsg, DirectAddr, DirectAddrInfo, DirectAddrType,
73    RemoteInfo, Source,
74};
75
76/// The delay to fall back to discovery when direct addresses fail.
77///
78/// When a connection is attempted with a [`NodeAddr`] containing direct addresses the
79/// [`Endpoint`] assumes one of those addresses probably works.  If after this delay there
80/// is still no connection the configured [`Discovery`] will be used however.
81const DISCOVERY_WAIT_PERIOD: Duration = Duration::from_millis(500);
82
83/// Defines the mode of path selection for all traffic flowing through
84/// the endpoint.
85#[cfg(any(test, feature = "test-utils"))]
86#[derive(Debug, Default, Copy, Clone, PartialEq, Eq)]
87pub enum PathSelection {
88    /// Uses all available paths
89    #[default]
90    All,
91    /// Forces all traffic to go exclusively through relays
92    RelayOnly,
93}
94
95/// Builder for [`Endpoint`].
96///
97/// By default the endpoint will generate a new random [`SecretKey`], which will result in a
98/// new [`NodeId`].
99///
100/// To create the [`Endpoint`] call [`Builder::bind`].
101#[derive(Debug)]
102pub struct Builder {
103    secret_key: Option<SecretKey>,
104    relay_mode: RelayMode,
105    alpn_protocols: Vec<Vec<u8>>,
106    transport_config: quinn::TransportConfig,
107    keylog: bool,
108    discovery: Vec<Box<dyn DynIntoDiscovery>>,
109    discovery_user_data: Option<UserData>,
110    proxy_url: Option<Url>,
111    /// List of known nodes. See [`Builder::known_nodes`].
112    node_map: Option<Vec<NodeAddr>>,
113    #[cfg(not(wasm_browser))]
114    dns_resolver: Option<DnsResolver>,
115    #[cfg(any(test, feature = "test-utils"))]
116    insecure_skip_relay_cert_verify: bool,
117    addr_v4: Option<SocketAddrV4>,
118    addr_v6: Option<SocketAddrV6>,
119    #[cfg(any(test, feature = "test-utils"))]
120    path_selection: PathSelection,
121}
122
123impl Default for Builder {
124    fn default() -> Self {
125        let mut transport_config = quinn::TransportConfig::default();
126        transport_config.keep_alive_interval(Some(Duration::from_secs(1)));
127        Self {
128            secret_key: Default::default(),
129            relay_mode: default_relay_mode(),
130            alpn_protocols: Default::default(),
131            transport_config,
132            keylog: Default::default(),
133            discovery: Default::default(),
134            discovery_user_data: Default::default(),
135            proxy_url: None,
136            node_map: None,
137            #[cfg(not(wasm_browser))]
138            dns_resolver: None,
139            #[cfg(any(test, feature = "test-utils"))]
140            insecure_skip_relay_cert_verify: false,
141            addr_v4: None,
142            addr_v6: None,
143            #[cfg(any(test, feature = "test-utils"))]
144            path_selection: PathSelection::default(),
145        }
146    }
147}
148
149impl Builder {
150    // The ordering of public methods is reflected directly in the documentation.  This is
151    // roughly ordered by what is most commonly needed by users.
152
153    // # The final constructor that everyone needs.
154
155    /// Binds the magic endpoint.
156    pub async fn bind(self) -> Result<Endpoint, BindError> {
157        let relay_map = self.relay_mode.relay_map();
158        let secret_key = self
159            .secret_key
160            .unwrap_or_else(|| SecretKey::generate(rand::rngs::OsRng));
161        let static_config = StaticConfig {
162            transport_config: Arc::new(self.transport_config),
163            tls_config: tls::TlsConfig::new(secret_key.clone()),
164            keylog: self.keylog,
165        };
166        let server_config = static_config.create_server_config(self.alpn_protocols);
167
168        #[cfg(not(wasm_browser))]
169        let dns_resolver = self.dns_resolver.unwrap_or_default();
170
171        let discovery: Option<Box<dyn Discovery>> = {
172            let context = DiscoveryContext {
173                secret_key: &secret_key,
174                #[cfg(not(wasm_browser))]
175                dns_resolver: &dns_resolver,
176            };
177            let discovery = self
178                .discovery
179                .into_iter()
180                .map(|builder| builder.into_discovery(&context))
181                .collect::<Result<Vec<_>, IntoDiscoveryError>>()?;
182            match discovery.len() {
183                0 => None,
184                1 => Some(discovery.into_iter().next().expect("checked length")),
185                _ => Some(Box::new(ConcurrentDiscovery::from_services(discovery))),
186            }
187        };
188
189        let metrics = EndpointMetrics::default();
190
191        let msock_opts = magicsock::Options {
192            addr_v4: self.addr_v4,
193            addr_v6: self.addr_v6,
194            secret_key,
195            relay_map,
196            node_map: self.node_map,
197            discovery,
198            discovery_user_data: self.discovery_user_data,
199            proxy_url: self.proxy_url,
200            #[cfg(not(wasm_browser))]
201            dns_resolver,
202            server_config,
203            #[cfg(any(test, feature = "test-utils"))]
204            insecure_skip_relay_cert_verify: self.insecure_skip_relay_cert_verify,
205            #[cfg(any(test, feature = "test-utils"))]
206            path_selection: self.path_selection,
207            metrics,
208        };
209
210        Endpoint::bind(static_config, msock_opts).await
211    }
212
213    // # The very common methods everyone basically needs.
214
215    /// Sets the IPv4 bind address.
216    ///
217    /// Setting the port to `0` will use a random port.
218    /// If the port specified is already in use, it will fallback to choosing a random port.
219    ///
220    /// By default will use `0.0.0.0:0` to bind to.
221    pub fn bind_addr_v4(mut self, addr: SocketAddrV4) -> Self {
222        self.addr_v4.replace(addr);
223        self
224    }
225
226    /// Sets the IPv6 bind address.
227    ///
228    /// Setting the port to `0` will use a random port.
229    /// If the port specified is already in use, it will fallback to choosing a random port.
230    ///
231    /// By default will use `[::]:0` to bind to.
232    pub fn bind_addr_v6(mut self, addr: SocketAddrV6) -> Self {
233        self.addr_v6.replace(addr);
234        self
235    }
236
237    /// Sets a secret key to authenticate with other peers.
238    ///
239    /// This secret key's public key will be the [`PublicKey`] of this endpoint and thus
240    /// also its [`NodeId`]
241    ///
242    /// If not set, a new secret key will be generated.
243    ///
244    /// [`PublicKey`]: iroh_base::PublicKey
245    pub fn secret_key(mut self, secret_key: SecretKey) -> Self {
246        self.secret_key = Some(secret_key);
247        self
248    }
249
250    /// Sets the [ALPN] protocols that this endpoint will accept on incoming connections.
251    ///
252    /// Not setting this will still allow creating connections, but to accept incoming
253    /// connections at least one [ALPN] must be set.
254    ///
255    /// [ALPN]: https://en.wikipedia.org/wiki/Application-Layer_Protocol_Negotiation
256    pub fn alpns(mut self, alpn_protocols: Vec<Vec<u8>>) -> Self {
257        self.alpn_protocols = alpn_protocols;
258        self
259    }
260
261    // # Methods for common customisation items.
262
263    /// Sets the relay servers to assist in establishing connectivity.
264    ///
265    /// Relay servers are used to establish initial connection with another iroh node.
266    /// They also perform various functions related to hole punching, see the [crate docs]
267    /// for more details.
268    ///
269    /// By default the [number 0] relay servers are used, see [`RelayMode::Default`].
270    ///
271    /// When using [RelayMode::Custom], the provided `relay_map` must contain at least one
272    /// configured relay node.  If an invalid RelayMap is provided [`bind`]
273    /// will result in an error.
274    ///
275    /// [`bind`]: Builder::bind
276    /// [crate docs]: crate
277    /// [number 0]: https://n0.computer
278    pub fn relay_mode(mut self, relay_mode: RelayMode) -> Self {
279        self.relay_mode = relay_mode;
280        self
281    }
282
283    /// Removes all discovery services from the builder.
284    pub fn clear_discovery(mut self) -> Self {
285        self.discovery.clear();
286        self
287    }
288
289    /// Optionally sets a discovery mechanism for this endpoint.
290    ///
291    /// If you want to combine multiple discovery services, you can use
292    /// [`Builder::add_discovery`] instead. This will internally create a
293    /// [`crate::discovery::ConcurrentDiscovery`].
294    ///
295    /// If no discovery service is set, connecting to a node without providing its
296    /// direct addresses or relay URLs will fail.
297    ///
298    /// See the documentation of the [`Discovery`] trait for details.
299    pub fn discovery(mut self, discovery: impl IntoDiscovery) -> Self {
300        self.discovery.clear();
301        self.discovery.push(Box::new(discovery));
302        self
303    }
304
305    /// Adds a discovery mechanism for this endpoint.
306    ///
307    /// The function `discovery`
308    /// will be called on endpoint creation with the configured secret key of
309    /// the endpoint. Discovery services that need to publish information need
310    /// to use this secret key to sign the information.
311    ///
312    /// If you add multiple discovery services, they will be combined using a
313    /// [`crate::discovery::ConcurrentDiscovery`].
314    ///
315    /// If no discovery service is set, connecting to a node without providing its
316    /// direct addresses or relay URLs will fail.
317    ///
318    /// To clear all discovery services, use [`Builder::clear_discovery`].
319    ///
320    /// See the documentation of the [`Discovery`] trait for details.
321    pub fn add_discovery(mut self, discovery: impl IntoDiscovery) -> Self {
322        self.discovery.push(Box::new(discovery));
323        self
324    }
325
326    /// Configures the endpoint to use the default n0 DNS discovery service.
327    ///
328    /// The default discovery service publishes to and resolves from the
329    /// n0.computer dns server `iroh.link`.
330    ///
331    /// This is equivalent to adding both a [`crate::discovery::pkarr::PkarrPublisher`]
332    /// and a [`crate::discovery::dns::DnsDiscovery`], both configured to use the
333    /// n0.computer dns server.
334    ///
335    /// This will by default use [`N0_DNS_PKARR_RELAY_PROD`].
336    /// When in tests, or when the `test-utils` feature is enabled, this will use the
337    /// [`N0_DNS_PKARR_RELAY_STAGING`].
338    ///
339    /// [`N0_DNS_PKARR_RELAY_PROD`]: crate::discovery::pkarr::N0_DNS_PKARR_RELAY_PROD
340    /// [`N0_DNS_PKARR_RELAY_STAGING`]: crate::discovery::pkarr::N0_DNS_PKARR_RELAY_STAGING
341    pub fn discovery_n0(mut self) -> Self {
342        self = self.add_discovery(PkarrPublisher::n0_dns());
343        // Resolve using HTTPS requests to our DNS server's /pkarr path in browsers
344        #[cfg(wasm_browser)]
345        {
346            self = self.add_discovery(PkarrResolver::n0_dns());
347        }
348        // Resolve using DNS queries outside browsers.
349        #[cfg(not(wasm_browser))]
350        {
351            self = self.add_discovery(DnsDiscovery::n0_dns());
352        }
353        self
354    }
355
356    #[cfg(feature = "discovery-pkarr-dht")]
357    /// Configures the endpoint to also use the mainline DHT with default settings.
358    ///
359    /// This is equivalent to adding a [`crate::discovery::pkarr::dht::DhtDiscovery`]
360    /// with default settings. Note that DhtDiscovery has various more advanced
361    /// configuration options. If you need any of those, you should manually
362    /// create a DhtDiscovery and add it with [`Builder::add_discovery`].
363    pub fn discovery_dht(mut self) -> Self {
364        self = self.add_discovery(crate::discovery::pkarr::dht::DhtDiscovery::builder());
365        self
366    }
367
368    #[cfg(feature = "discovery-local-network")]
369    /// Configures the endpoint to also use local network discovery.
370    ///
371    /// This is equivalent to adding a [`crate::discovery::mdns::MdnsDiscovery`]
372    /// with default settings. Note that MdnsDiscovery has various more advanced
373    /// configuration options. If you need any of those, you should manually
374    /// create a MdnsDiscovery and add it with [`Builder::add_discovery`].
375    pub fn discovery_local_network(mut self) -> Self {
376        self = self.add_discovery(crate::discovery::mdns::MdnsDiscovery::builder());
377        self
378    }
379
380    /// Sets the initial user-defined data to be published in discovery services for this node.
381    ///
382    /// When using discovery services, this string of [`UserData`] will be published together
383    /// with the node's addresses and relay URL. When other nodes discover this node,
384    /// they retrieve the [`UserData`] in addition to the addressing info.
385    ///
386    /// Iroh itself does not interpret the user-defined data in any way, it is purely left
387    /// for applications to parse and use.
388    pub fn user_data_for_discovery(mut self, user_data: UserData) -> Self {
389        self.discovery_user_data = Some(user_data);
390        self
391    }
392
393    /// Optionally set a list of known nodes.
394    pub fn known_nodes(mut self, nodes: Vec<NodeAddr>) -> Self {
395        self.node_map = Some(nodes);
396        self
397    }
398
399    // # Methods for more specialist customisation.
400
401    /// Sets a custom [`quinn::TransportConfig`] for this endpoint.
402    ///
403    /// The transport config contains parameters governing the QUIC state machine.
404    ///
405    /// If unset, the default config is used. Default values should be suitable for most
406    /// internet applications. Applications protocols which forbid remotely-initiated
407    /// streams should set `max_concurrent_bidi_streams` and `max_concurrent_uni_streams` to
408    /// zero.
409    ///
410    /// Please be aware that changing some settings may have adverse effects on establishing
411    /// and maintaining direct connections.
412    pub fn transport_config(mut self, transport_config: quinn::TransportConfig) -> Self {
413        self.transport_config = transport_config;
414        self
415    }
416
417    /// Optionally sets a custom DNS resolver to use for this endpoint.
418    ///
419    /// The DNS resolver is used to resolve relay hostnames, and node addresses if
420    /// [`crate::discovery::dns::DnsDiscovery`] is configured.
421    ///
422    /// By default, a new DNS resolver is created which is configured to use the
423    /// host system's DNS configuration. You can pass a custom instance of [`DnsResolver`]
424    /// here to use a differently configured DNS resolver for this endpoint, or to share
425    /// a [`DnsResolver`] between multiple endpoints.
426    #[cfg(not(wasm_browser))]
427    pub fn dns_resolver(mut self, dns_resolver: DnsResolver) -> Self {
428        self.dns_resolver = Some(dns_resolver);
429        self
430    }
431
432    /// Sets an explicit proxy url to proxy all HTTP(S) traffic through.
433    pub fn proxy_url(mut self, url: Url) -> Self {
434        self.proxy_url.replace(url);
435        self
436    }
437
438    /// Sets the proxy url from the environment, in this order:
439    ///
440    /// - `HTTP_PROXY`
441    /// - `http_proxy`
442    /// - `HTTPS_PROXY`
443    /// - `https_proxy`
444    pub fn proxy_from_env(mut self) -> Self {
445        self.proxy_url = proxy_url_from_env();
446        self
447    }
448
449    /// Enables saving the TLS pre-master key for connections.
450    ///
451    /// This key should normally remain secret but can be useful to debug networking issues
452    /// by decrypting captured traffic.
453    ///
454    /// If *keylog* is `true` then setting the `SSLKEYLOGFILE` environment variable to a
455    /// filename will result in this file being used to log the TLS pre-master keys.
456    pub fn keylog(mut self, keylog: bool) -> Self {
457        self.keylog = keylog;
458        self
459    }
460
461    /// Skip verification of SSL certificates from relay servers
462    ///
463    /// May only be used in tests.
464    #[cfg(any(test, feature = "test-utils"))]
465    pub fn insecure_skip_relay_cert_verify(mut self, skip_verify: bool) -> Self {
466        self.insecure_skip_relay_cert_verify = skip_verify;
467        self
468    }
469
470    /// This implies we only use the relay to communicate
471    /// and do not attempt to do any hole punching.
472    #[cfg(any(test, feature = "test-utils"))]
473    pub fn path_selection(mut self, path_selection: PathSelection) -> Self {
474        self.path_selection = path_selection;
475        self
476    }
477}
478
479/// Configuration for a [`quinn::Endpoint`] that cannot be changed at runtime.
480#[derive(Debug)]
481struct StaticConfig {
482    tls_config: tls::TlsConfig,
483    transport_config: Arc<quinn::TransportConfig>,
484    keylog: bool,
485}
486
487impl StaticConfig {
488    /// Create a [`quinn::ServerConfig`] with the specified ALPN protocols.
489    fn create_server_config(&self, alpn_protocols: Vec<Vec<u8>>) -> ServerConfig {
490        let quic_server_config = self
491            .tls_config
492            .make_server_config(alpn_protocols, self.keylog);
493        let mut server_config = ServerConfig::with_crypto(Arc::new(quic_server_config));
494        server_config.transport_config(self.transport_config.clone());
495
496        server_config
497    }
498}
499
500/// Controls an iroh node, establishing connections with other nodes.
501///
502/// This is the main API interface to create connections to, and accept connections from
503/// other iroh nodes.  The connections are peer-to-peer and encrypted, a Relay server is
504/// used to make the connections reliable.  See the [crate docs] for a more detailed
505/// overview of iroh.
506///
507/// It is recommended to only create a single instance per application.  This ensures all
508/// the connections made share the same peer-to-peer connections to other iroh nodes,
509/// while still remaining independent connections.  This will result in more optimal network
510/// behaviour.
511///
512/// The endpoint is created using the [`Builder`], which can be created using
513/// [`Endpoint::builder`].
514///
515/// Once an endpoint exists, new connections are typically created using the
516/// [`Endpoint::connect`] and [`Endpoint::accept`] methods.  Once established, the
517/// [`Connection`] gives access to most [QUIC] features.  Individual streams to send data to
518/// the peer are created using the [`Connection::open_bi`], [`Connection::accept_bi`],
519/// [`Connection::open_uni`] and [`Connection::open_bi`] functions.
520///
521/// Note that due to the light-weight properties of streams a stream will only be accepted
522/// once the initiating peer has sent some data on it.
523///
524/// [QUIC]: https://quicwg.org
525#[derive(Clone, Debug)]
526pub struct Endpoint {
527    /// Handle to the magicsocket/actor
528    msock: Handle,
529    /// Handle to the actor that resets the quinn RTT estimator
530    rtt_actor: Arc<rtt_actor::RttHandle>,
531    /// Configuration structs for quinn, holds the transport config, certificate setup, secret key etc.
532    static_config: Arc<StaticConfig>,
533}
534
535#[allow(missing_docs)]
536#[common_fields({
537    backtrace: Option<snafu::Backtrace>,
538    #[snafu(implicit)]
539    span_trace: n0_snafu::SpanTrace,
540})]
541#[derive(Debug, Snafu)]
542#[non_exhaustive]
543pub enum ConnectWithOptsError {
544    #[snafu(transparent)]
545    AddNodeAddr { source: AddNodeAddrError },
546    #[snafu(display("Connecting to ourself is not supported"))]
547    SelfConnect {},
548    #[snafu(display("No addressing information available"))]
549    NoAddress { source: GetMappingAddressError },
550    #[snafu(display("Unable to connect to remote"))]
551    Quinn { source: quinn::ConnectError },
552}
553
554#[allow(missing_docs)]
555#[common_fields({
556    backtrace: Option<snafu::Backtrace>,
557    #[snafu(implicit)]
558    span_trace: n0_snafu::SpanTrace,
559})]
560#[derive(Debug, Snafu)]
561#[non_exhaustive]
562pub enum ConnectError {
563    #[snafu(transparent)]
564    Connect {
565        #[snafu(source(from(ConnectWithOptsError, Box::new)))]
566        source: Box<ConnectWithOptsError>,
567    },
568    #[snafu(transparent)]
569    Connection {
570        #[snafu(source(from(ConnectionError, Box::new)))]
571        source: Box<ConnectionError>,
572    },
573}
574
575#[allow(missing_docs)]
576#[common_fields({
577    backtrace: Option<snafu::Backtrace>,
578    #[snafu(implicit)]
579    span_trace: n0_snafu::SpanTrace,
580})]
581#[derive(Debug, Snafu)]
582#[non_exhaustive]
583pub enum BindError {
584    #[snafu(transparent)]
585    MagicSpawn {
586        source: magicsock::CreateHandleError,
587    },
588    #[snafu(transparent)]
589    Discovery {
590        source: crate::discovery::IntoDiscoveryError,
591    },
592}
593
594#[allow(missing_docs)]
595#[common_fields({
596    backtrace: Option<snafu::Backtrace>,
597    #[snafu(implicit)]
598    span_trace: n0_snafu::SpanTrace,
599})]
600#[derive(Debug, Snafu)]
601#[snafu(module)]
602#[non_exhaustive]
603pub enum GetMappingAddressError {
604    #[snafu(display("Discovery service required due to missing addressing information"))]
605    DiscoveryStart { source: DiscoveryError },
606    #[snafu(display("Discovery service failed"))]
607    Discover { source: DiscoveryError },
608    #[snafu(display("No addressing information found"))]
609    NoAddress {},
610}
611
612impl Endpoint {
613    // The ordering of public methods is reflected directly in the documentation.  This is
614    // roughly ordered by what is most commonly needed by users, but grouped in similar
615    // items.
616
617    // # Methods relating to construction.
618
619    /// Returns the builder for an [`Endpoint`], with a production configuration.
620    pub fn builder() -> Builder {
621        Builder::default()
622    }
623
624    /// Creates a quinn endpoint backed by a magicsock.
625    ///
626    /// This is for internal use, the public interface is the [`Builder`] obtained from
627    /// [Self::builder]. See the methods on the builder for documentation of the parameters.
628    #[instrument("ep", skip_all, fields(me = %static_config.tls_config.secret_key.public().fmt_short()))]
629    async fn bind(
630        static_config: StaticConfig,
631        msock_opts: magicsock::Options,
632    ) -> Result<Self, BindError> {
633        let msock = magicsock::MagicSock::spawn(msock_opts).await?;
634        trace!("created magicsock");
635        debug!(version = env!("CARGO_PKG_VERSION"), "iroh Endpoint created");
636
637        let metrics = msock.metrics.magicsock.clone();
638        let ep = Self {
639            msock,
640            rtt_actor: Arc::new(rtt_actor::RttHandle::new(metrics)),
641            static_config: Arc::new(static_config),
642        };
643        Ok(ep)
644    }
645
646    /// Sets the list of accepted ALPN protocols.
647    ///
648    /// This will only affect new incoming connections.
649    /// Note that this *overrides* the current list of ALPNs.
650    pub fn set_alpns(&self, alpns: Vec<Vec<u8>>) {
651        let server_config = self.static_config.create_server_config(alpns);
652        self.msock.endpoint().set_server_config(Some(server_config));
653    }
654
655    // # Methods for establishing connectivity.
656
657    /// Connects to a remote [`Endpoint`].
658    ///
659    /// A value that can be converted into a [`NodeAddr`] is required. This can be either a
660    /// [`NodeAddr`], a [`NodeId`] or a [`iroh_base::ticket::NodeTicket`].
661    ///
662    /// The [`NodeAddr`] must contain the [`NodeId`] to dial and may also contain a [`RelayUrl`]
663    /// and direct addresses. If direct addresses are provided, they will be used to try and
664    /// establish a direct connection without involving a relay server.
665    ///
666    /// If neither a [`RelayUrl`] or direct addresses are configured in the [`NodeAddr`] it
667    /// may still be possible a connection can be established.  This depends on other calls
668    /// to [`Endpoint::add_node_addr`] which may provide contact information, or via the
669    /// [`Discovery`] service configured using [`Builder::discovery`].  The discovery
670    /// service will also be used if the remote node is not reachable on the provided direct
671    /// addresses and there is no [`RelayUrl`].
672    ///
673    /// If addresses or relay servers are neither provided nor can be discovered, the
674    /// connection attempt will fail with an error.
675    ///
676    /// The `alpn`, or application-level protocol identifier, is also required. The remote
677    /// endpoint must support this `alpn`, otherwise the connection attempt will fail with
678    /// an error.
679    pub async fn connect(
680        &self,
681        node_addr: impl Into<NodeAddr>,
682        alpn: &[u8],
683    ) -> Result<Connection, ConnectError> {
684        let node_addr = node_addr.into();
685        let remote = node_addr.node_id;
686        let connecting = self
687            .connect_with_opts(node_addr, alpn, Default::default())
688            .await?;
689        let conn = connecting.await?;
690
691        debug!(
692            me = %self.node_id().fmt_short(),
693            remote = %remote.fmt_short(),
694            alpn = %String::from_utf8_lossy(alpn),
695            "Connection established."
696        );
697        Ok(conn)
698    }
699
700    /// Starts a connection attempt with a remote [`Endpoint`].
701    ///
702    /// Like [`Endpoint::connect`] (see also its docs for general details), but allows for a more
703    /// advanced connection setup with more customization in two aspects:
704    /// 1. The returned future resolves to a [`Connecting`], which can be further processed into
705    ///    a [`Connection`] by awaiting, or alternatively allows connecting with 0RTT via
706    ///    [`Connecting::into_0rtt`].
707    ///    **Note:** Please read the documentation for `into_0rtt` carefully to assess
708    ///    security concerns.
709    /// 2. The [`TransportConfig`] for the connection can be modified via the provided
710    ///    [`ConnectOptions`].
711    ///    **Note:** Please be aware that changing transport config settings may have adverse effects on
712    ///    establishing and maintaining direct connections.  Carefully test settings you use and
713    ///    consider this currently as still rather experimental.
714    #[instrument(name = "connect", skip_all, fields(
715        me = %self.node_id().fmt_short(),
716        remote = tracing::field::Empty,
717        alpn = String::from_utf8_lossy(alpn).to_string(),
718    ))]
719    pub async fn connect_with_opts(
720        &self,
721        node_addr: impl Into<NodeAddr>,
722        alpn: &[u8],
723        options: ConnectOptions,
724    ) -> Result<Connecting, ConnectWithOptsError> {
725        let node_addr: NodeAddr = node_addr.into();
726        tracing::Span::current().record(
727            "remote",
728            tracing::field::display(node_addr.node_id.fmt_short()),
729        );
730
731        // Connecting to ourselves is not supported.
732        ensure!(node_addr.node_id != self.node_id(), SelfConnectSnafu);
733
734        if !node_addr.is_empty() {
735            self.add_node_addr(node_addr.clone())?;
736        }
737        let node_id = node_addr.node_id;
738        let direct_addresses = node_addr.direct_addresses.clone();
739        let relay_url = node_addr.relay_url.clone();
740
741        // Get the mapped IPv6 address from the magic socket. Quinn will connect to this
742        // address.  Start discovery for this node if it's enabled and we have no valid or
743        // verified address information for this node.  Dropping the discovery cancels any
744        // still running task.
745        let (mapped_addr, _discovery_drop_guard) = self
746            .get_mapping_addr_and_maybe_start_discovery(node_addr)
747            .await
748            .context(NoAddressSnafu)?;
749
750        let transport_config = options
751            .transport_config
752            .unwrap_or(self.static_config.transport_config.clone());
753
754        // Start connecting via quinn. This will time out after 10 seconds if no reachable
755        // address is available.
756
757        debug!(
758            ?mapped_addr,
759            ?direct_addresses,
760            ?relay_url,
761            "Attempting connection..."
762        );
763        let client_config = {
764            let mut alpn_protocols = vec![alpn.to_vec()];
765            alpn_protocols.extend(options.additional_alpns);
766            let quic_client_config = self
767                .static_config
768                .tls_config
769                .make_client_config(alpn_protocols, self.static_config.keylog);
770            let mut client_config = quinn::ClientConfig::new(Arc::new(quic_client_config));
771            client_config.transport_config(transport_config);
772            client_config
773        };
774
775        let server_name = &tls::name::encode(node_id);
776        let connect = self
777            .msock
778            .endpoint()
779            .connect_with(
780                client_config,
781                mapped_addr.private_socket_addr(),
782                server_name,
783            )
784            .context(QuinnSnafu)?;
785
786        Ok(Connecting {
787            inner: connect,
788            ep: self.clone(),
789            remote_node_id: Some(node_id),
790            _discovery_drop_guard,
791        })
792    }
793
794    /// Accepts an incoming connection on the endpoint.
795    ///
796    /// Only connections with the ALPNs configured in [`Builder::alpns`] will be accepted.
797    /// If multiple ALPNs have been configured the ALPN can be inspected before accepting
798    /// the connection using [`Connecting::alpn`].
799    ///
800    /// The returned future will yield `None` if the endpoint is closed by calling
801    /// [`Endpoint::close`].
802    pub fn accept(&self) -> Accept<'_> {
803        Accept {
804            inner: self.msock.endpoint().accept(),
805            ep: self.clone(),
806        }
807    }
808
809    // # Methods for manipulating the internal state about other nodes.
810
811    /// Informs this [`Endpoint`] about addresses of the iroh node.
812    ///
813    /// This updates the local state for the remote node.  If the provided [`NodeAddr`]
814    /// contains a [`RelayUrl`] this will be used as the new relay server for this node.  If
815    /// it contains any new IP endpoints they will also be stored and tried when next
816    /// connecting to this node. Any address that matches this node's direct addresses will be
817    /// silently ignored.
818    ///
819    /// See also [`Endpoint::add_node_addr_with_source`].
820    ///
821    /// # Using node discovery instead
822    ///
823    /// It is strongly advised to use node discovery using the [`StaticProvider`] instead.
824    /// This provides more flexibility and future proofing.
825    ///
826    /// # Errors
827    ///
828    /// Will return an error if we attempt to add our own [`NodeId`] to the node map or
829    /// if the direct addresses are a subset of ours.
830    ///
831    /// [`StaticProvider`]: crate::discovery::static_provider::StaticProvider
832    pub fn add_node_addr(&self, node_addr: NodeAddr) -> Result<(), AddNodeAddrError> {
833        self.add_node_addr_inner(node_addr, magicsock::Source::App)
834    }
835
836    /// Informs this [`Endpoint`] about addresses of the iroh node, noting the source.
837    ///
838    /// This updates the local state for the remote node.  If the provided [`NodeAddr`] contains a
839    /// [`RelayUrl`] this will be used as the new relay server for this node.  If it contains any
840    /// new IP endpoints they will also be stored and tried when next connecting to this node. Any
841    /// address that matches this node's direct addresses will be silently ignored. The *source* is
842    /// used for logging exclusively and will not be stored.
843    ///
844    /// # Using node discovery instead
845    ///
846    /// It is strongly advised to use node discovery using the [`StaticProvider`] instead.
847    /// This provides more flexibility and future proofing.
848    ///
849    /// # Errors
850    ///
851    /// Will return an error if we attempt to add our own [`NodeId`] to the node map or
852    /// if the direct addresses are a subset of ours.
853    ///
854    /// [`StaticProvider`]: crate::discovery::static_provider::StaticProvider
855    pub fn add_node_addr_with_source(
856        &self,
857        node_addr: NodeAddr,
858        source: &'static str,
859    ) -> Result<(), AddNodeAddrError> {
860        self.add_node_addr_inner(
861            node_addr,
862            magicsock::Source::NamedApp {
863                name: source.into(),
864            },
865        )
866    }
867
868    fn add_node_addr_inner(
869        &self,
870        node_addr: NodeAddr,
871        source: magicsock::Source,
872    ) -> Result<(), AddNodeAddrError> {
873        // Connecting to ourselves is not supported.
874        snafu::ensure!(node_addr.node_id != self.node_id(), OwnAddressSnafu);
875        self.msock.add_node_addr(node_addr, source)
876    }
877
878    // # Getter methods for properties of this Endpoint itself.
879
880    /// Returns the secret_key of this endpoint.
881    pub fn secret_key(&self) -> &SecretKey {
882        &self.static_config.tls_config.secret_key
883    }
884
885    /// Returns the node id of this endpoint.
886    ///
887    /// This ID is the unique addressing information of this node and other peers must know
888    /// it to be able to connect to this node.
889    pub fn node_id(&self) -> NodeId {
890        self.static_config.tls_config.secret_key.public()
891    }
892
893    /// Returns a [`Watcher`] for the current [`NodeAddr`] for this endpoint.
894    ///
895    /// The observed [`NodeAddr`] will have the current [`RelayUrl`] and direct addresses
896    /// as they would be returned by [`Endpoint::home_relay`] and [`Endpoint::direct_addresses`].
897    ///
898    /// Use [`Watcher::initialized`] to wait for a [`NodeAddr`] that is ready to be connected to:
899    ///
900    /// ```no_run
901    /// # async fn wrapper() -> n0_snafu::Result {
902    /// use iroh::{Endpoint, Watcher};
903    ///
904    /// let endpoint = Endpoint::builder()
905    ///     .alpns(vec![b"my-alpn".to_vec()])
906    ///     .bind()
907    ///     .await?;
908    /// let node_addr = endpoint.node_addr().initialized().await;
909    /// # let _ = node_addr;
910    /// # Ok(())
911    /// # }
912    /// ```
913    #[cfg(not(wasm_browser))]
914    pub fn node_addr(&self) -> impl n0_watcher::Watcher<Value = Option<NodeAddr>> + use<> {
915        let watch_addrs = self.direct_addresses();
916        let watch_relay = self.home_relay();
917        let node_id = self.node_id();
918
919        watch_addrs
920            .or(watch_relay)
921            .map(move |(addrs, mut relays)| match addrs {
922                Some(addrs) => Some(NodeAddr::from_parts(
923                    node_id,
924                    relays.pop(),
925                    addrs.into_iter().map(|x| x.addr),
926                )),
927                None => relays.pop().map(|relay_url| {
928                    NodeAddr::from_parts(node_id, Some(relay_url), std::iter::empty())
929                }),
930            })
931            .expect("watchable is alive - cannot be disconnected yet")
932    }
933
934    /// Returns a [`Watcher`] for the current [`NodeAddr`] for this endpoint.
935    ///
936    /// When compiled to Wasm, this function returns a watcher that initializes
937    /// with a [`NodeAddr`] that only contains a relay URL, but no direct addresses,
938    /// as there are no APIs for directly using sockets in browsers.
939    #[cfg(wasm_browser)]
940    pub fn node_addr(&self) -> impl n0_watcher::Watcher<Value = Option<NodeAddr>> + use<> {
941        // In browsers, there will never be any direct addresses, so we wait
942        // for the home relay instead. This makes the `NodeAddr` have *some* way
943        // of connecting to us.
944        let watch_relay = self.home_relay();
945        let node_id = self.node_id();
946        watch_relay
947            .map(move |mut relays| {
948                relays.pop().map(|relay_url| {
949                    NodeAddr::from_parts(node_id, Some(relay_url), std::iter::empty())
950                })
951            })
952            .expect("watchable is alive - cannot be disconnected yet")
953    }
954
955    /// Returns a [`Watcher`] for the [`RelayUrl`] of the Relay server used as home relay.
956    ///
957    /// Every endpoint has a home Relay server which it chooses as the server with the
958    /// lowest latency out of the configured servers provided by [`Builder::relay_mode`].
959    /// This is the server other iroh nodes can use to reliably establish a connection
960    /// to this node.
961    ///
962    /// The watcher stores `None` if we are not connected to any Relay server.
963    ///
964    /// Note that this will store `None` right after the [`Endpoint`] is created since it takes
965    /// some time to connect to find and connect to the home relay server.
966    ///
967    /// # Examples
968    ///
969    /// To wait for a home relay connection to be established, use [`Watcher::initialized`]:
970    /// ```no_run
971    /// use iroh::{Endpoint, Watcher};
972    ///
973    /// # let rt = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
974    /// # rt.block_on(async move {
975    /// let mep = Endpoint::builder().bind().await.unwrap();
976    /// let _relay_url = mep.home_relay().initialized().await;
977    /// # });
978    /// ```
979    pub fn home_relay(&self) -> impl n0_watcher::Watcher<Value = Vec<RelayUrl>> + use<> {
980        self.msock.home_relay()
981    }
982
983    /// Returns a [`Watcher`] for the direct addresses of this [`Endpoint`].
984    ///
985    /// The direct addresses of the [`Endpoint`] are those that could be used by other
986    /// iroh nodes to establish direct connectivity, depending on the network
987    /// situation. The yielded lists of direct addresses contain both the locally-bound
988    /// addresses and the [`Endpoint`]'s publicly reachable addresses discovered through
989    /// mechanisms such as [QAD] and port mapping.  Hence usually only a subset of these
990    /// will be applicable to a certain remote iroh node.
991    ///
992    /// The [`Endpoint`] continuously monitors the direct addresses for changes as its own
993    /// location in the network might change.  Whenever changes are detected this stream
994    /// will yield a new list of direct addresses.
995    ///
996    /// When issuing the first call to this method the first direct address discovery might
997    /// still be underway, in this case the [`Watcher`] might not be initialized with [`Some`]
998    /// value yet.  Once the first set of local direct addresses are discovered the [`Watcher`]
999    /// will always return [`Some`] set of direct addresses immediately, which are the most
1000    /// recently discovered direct addresses.
1001    ///
1002    /// # Examples
1003    ///
1004    /// To get the first set of direct addresses use [`Watcher::initialized`]:
1005    /// ```no_run
1006    /// use iroh::{Endpoint, Watcher as _};
1007    ///
1008    /// # let rt = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
1009    /// # rt.block_on(async move {
1010    /// let ep = Endpoint::builder().bind().await.unwrap();
1011    /// let _addrs = ep.direct_addresses().initialized().await;
1012    /// # });
1013    /// ```
1014    ///
1015    /// [QAD]: https://www.ietf.org/archive/id/draft-ietf-quic-address-discovery-00.html
1016    pub fn direct_addresses(&self) -> n0_watcher::Direct<Option<BTreeSet<DirectAddr>>> {
1017        self.msock.direct_addresses()
1018    }
1019
1020    /// Returns a [`Watcher`] for any net-reports run from this [`Endpoint`].
1021    ///
1022    /// A `net-report` checks the network conditions of the [`Endpoint`], such as
1023    /// whether it is connected to the internet via Ipv4 and/or Ipv6, its NAT
1024    /// status, its latency to the relay servers, and its public addresses.
1025    ///
1026    /// The [`Endpoint`] continuously runs `net-reports` to monitor if network
1027    /// conditions have changed. This [`Watcher`] will return the latest result
1028    /// of the `net-report`.
1029    ///
1030    /// When issuing the first call to this method the first report might
1031    /// still be underway, in this case the [`Watcher`] might not be initialized
1032    /// with [`Some`] value yet.  Once the net-report has been successfully
1033    /// run, the [`Watcher`] will always return [`Some`] report immediately, which
1034    /// is the most recently run `net-report`.
1035    ///
1036    /// # Examples
1037    ///
1038    /// To get the first report use [`Watcher::initialized`]:
1039    /// ```no_run
1040    /// use iroh::{Endpoint, Watcher as _};
1041    ///
1042    /// # let rt = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
1043    /// # rt.block_on(async move {
1044    /// let ep = Endpoint::builder().bind().await.unwrap();
1045    /// let _report = ep.net_report().initialized().await;
1046    /// # });
1047    /// ```
1048    #[doc(hidden)]
1049    pub fn net_report(&self) -> impl Watcher<Value = Option<Report>> + use<> {
1050        self.msock.net_report()
1051    }
1052
1053    /// Returns the local socket addresses on which the underlying sockets are bound.
1054    ///
1055    /// The [`Endpoint`] always binds on an IPv4 address and also tries to bind on an IPv6
1056    /// address if available.
1057    pub fn bound_sockets(&self) -> Vec<SocketAddr> {
1058        self.msock
1059            .local_addr()
1060            .into_iter()
1061            .filter_map(|addr| addr.into_socket_addr())
1062            .collect()
1063    }
1064
1065    // # Getter methods for information about other nodes.
1066
1067    /// Returns information about the remote node identified by a [`NodeId`].
1068    ///
1069    /// The [`Endpoint`] keeps some information about remote iroh nodes, which it uses to find
1070    /// the best path to a node. Having information on a remote node, however, does not mean we have
1071    /// ever connected to it to or even whether a connection is even possible. The information about a
1072    /// remote node will change over time, as the [`Endpoint`] learns more about the node. Future
1073    /// calls may return different information. Furthermore, node information may even be
1074    /// completely evicted as it becomes stale.
1075    ///
1076    /// See also [`Endpoint::remote_info_iter`] which returns information on all nodes known
1077    /// by this [`Endpoint`].
1078    pub fn remote_info(&self, node_id: NodeId) -> Option<RemoteInfo> {
1079        self.msock.remote_info(node_id)
1080    }
1081
1082    /// Returns information about all the remote nodes this [`Endpoint`] knows about.
1083    ///
1084    /// This returns the same information as [`Endpoint::remote_info`] for each node known to this
1085    /// [`Endpoint`].
1086    ///
1087    /// The [`Endpoint`] keeps some information about remote iroh nodes, which it uses to find
1088    /// the best path to a node. This returns all the nodes it knows about, regardless of whether a
1089    /// connection was ever made or is even possible.
1090    ///
1091    /// See also [`Endpoint::remote_info`] to only retrieve information about a single node.
1092    pub fn remote_info_iter(&self) -> impl Iterator<Item = RemoteInfo> + use<> {
1093        self.msock.list_remote_infos().into_iter()
1094    }
1095
1096    /// Returns a stream of all remote nodes discovered through the endpoint's discovery services.
1097    ///
1098    /// Whenever a node is discovered via the endpoint's discovery service, the corresponding
1099    /// [`DiscoveryItem`] is yielded from this stream. This includes nodes discovered actively
1100    /// through [`Discovery::resolve`], which is invoked automatically when calling
1101    /// [`Endpoint::connect`] for a [`NodeId`] unknown to the endpoint. It also includes
1102    /// nodes that the endpoint discovers passively from discovery services that implement
1103    /// [`Discovery::subscribe`], which e.g. [`MdnsDiscovery`] does.
1104    ///
1105    /// The stream does not yield information about nodes that are added manually to the endpoint's
1106    /// addressbook by calling [`Endpoint::add_node_addr`] or by supplying a full [`NodeAddr`] to
1107    /// [`Endpoint::connect`]. It also does not yield information about nodes that we only
1108    /// know about because they connected to us. When using the [`StaticProvider`] discovery,
1109    /// discovery info is only emitted once connecting to a node added to the static provider, not
1110    /// at the time of adding it to the static provider.
1111    ///
1112    /// The stream should be processed in a loop. If the stream is not processed fast enough,
1113    /// [`Lagged`] may be yielded, indicating that items were missed.
1114    ///
1115    /// See also [`Endpoint::remote_info_iter`], which returns an iterator over all remotes
1116    /// the endpoint knows about at a specific point in time.
1117    ///
1118    /// [`MdnsDiscovery`]: crate::discovery::mdns::MdnsDiscovery
1119    /// [`StaticProvider`]: crate::discovery::static_provider::StaticProvider
1120    pub fn discovery_stream(&self) -> impl Stream<Item = Result<DiscoveryItem, Lagged>> + use<> {
1121        self.msock.discovery_subscribers().subscribe()
1122    }
1123
1124    // # Methods for less common getters.
1125    //
1126    // Partially they return things passed into the builder.
1127
1128    /// Returns a [`Watcher`] that reports the current connection type and any changes for
1129    /// given remote node.
1130    ///
1131    /// This watcher allows observing a stream of [`ConnectionType`] items by calling
1132    /// [`Watcher::stream()`]. If the underlying connection to a remote node changes, it will
1133    /// yield a new item.  These connection changes are when the connection switches between
1134    /// using the Relay server and a direct connection.
1135    ///
1136    /// Note that this does not guarantee each connection change is yielded in the stream.
1137    /// If the connection type changes several times before this stream is polled, only the
1138    /// last recorded state is returned.  This can be observed e.g. right at the start of a
1139    /// connection when the switch from a relayed to a direct connection can be so fast that
1140    /// the relayed state is never exposed.
1141    ///
1142    /// If there is currently a connection with the remote node, then using [`Watcher::get`]
1143    /// will immediately return either [`ConnectionType::Relay`], [`ConnectionType::Direct`]
1144    /// or [`ConnectionType::Mixed`].
1145    ///
1146    /// It is possible for the connection type to be [`ConnectionType::None`] if you've
1147    /// recently connected to this node id but previous methods of reaching the node have
1148    /// become inaccessible.
1149    ///
1150    /// Will return `None` if we do not have any address information for the given `node_id`.
1151    pub fn conn_type(&self, node_id: NodeId) -> Option<n0_watcher::Direct<ConnectionType>> {
1152        self.msock.conn_type(node_id)
1153    }
1154
1155    /// Returns the DNS resolver used in this [`Endpoint`].
1156    ///
1157    /// See [`Builder::dns_resolver`].
1158    #[cfg(not(wasm_browser))]
1159    pub fn dns_resolver(&self) -> &DnsResolver {
1160        self.msock.dns_resolver()
1161    }
1162
1163    /// Returns the discovery mechanism, if configured.
1164    ///
1165    /// See [`Builder::discovery`].
1166    pub fn discovery(&self) -> Option<&dyn Discovery> {
1167        self.msock.discovery()
1168    }
1169
1170    /// Returns metrics collected for this endpoint.
1171    ///
1172    /// The endpoint internally collects various metrics about its operation.
1173    /// The returned [`EndpointMetrics`] struct contains all of these metrics.
1174    ///
1175    /// You can access individual metrics directly by using the public fields:
1176    /// ```rust
1177    /// # use std::collections::BTreeMap;
1178    /// # use iroh::endpoint::Endpoint;
1179    /// # async fn wrapper() -> n0_snafu::Result {
1180    /// let endpoint = Endpoint::builder().bind().await?;
1181    /// assert_eq!(endpoint.metrics().magicsock.recv_datagrams.get(), 0);
1182    /// # Ok(())
1183    /// # }
1184    /// ```
1185    ///
1186    /// [`EndpointMetrics`] implements [`MetricsGroupSet`], and each field
1187    /// implements [`MetricsGroup`]. These traits provide methods to iterate over
1188    /// the groups in the set, and over the individual metrics in each group, without having
1189    /// to access each field manually. With these methods, it is straightforward to collect
1190    /// all metrics into a map or push their values to a metrics collector.
1191    ///
1192    /// For example, the following snippet collects all metrics into a map:
1193    /// ```rust
1194    /// # use std::collections::BTreeMap;
1195    /// # use iroh_metrics::{Metric, MetricsGroup, MetricValue, MetricsGroupSet};
1196    /// # use iroh::endpoint::Endpoint;
1197    /// # async fn wrapper() -> n0_snafu::Result {
1198    /// let endpoint = Endpoint::builder().bind().await?;
1199    /// let metrics: BTreeMap<String, MetricValue> = endpoint
1200    ///     .metrics()
1201    ///     .iter()
1202    ///     .map(|(group, metric)| {
1203    ///         let name = [group, metric.name()].join(":");
1204    ///         (name, metric.value())
1205    ///     })
1206    ///     .collect();
1207    ///
1208    /// assert_eq!(metrics["magicsock:recv_datagrams"], MetricValue::Counter(0));
1209    /// # Ok(())
1210    /// # }
1211    /// ```
1212    ///
1213    /// The metrics can also be encoded into the OpenMetrics text format, as used by Prometheus.
1214    /// To do so, use the [`iroh_metrics::Registry`], add the endpoint metrics to the
1215    /// registry with [`Registry::register_all`], and encode the metrics to a string with
1216    /// [`encode_openmetrics_to_string`]:
1217    /// ```rust
1218    /// # use iroh_metrics::{Registry, MetricsSource};
1219    /// # use iroh::endpoint::Endpoint;
1220    /// # async fn wrapper() -> n0_snafu::Result {
1221    /// let endpoint = Endpoint::builder().bind().await?;
1222    /// let mut registry = Registry::default();
1223    /// registry.register_all(endpoint.metrics());
1224    /// let s = registry.encode_openmetrics_to_string()?;
1225    /// assert!(s.contains(r#"TYPE magicsock_recv_datagrams counter"#));
1226    /// assert!(s.contains(r#"magicsock_recv_datagrams_total 0"#));
1227    /// # Ok(())
1228    /// # }
1229    /// ```
1230    ///
1231    /// Through a registry, you can also add labels or prefixes to metrics with
1232    /// [`Registry::sub_registry_with_label`] or [`Registry::sub_registry_with_prefix`].
1233    /// Furthermore, [`iroh_metrics::service`] provides functions to easily start services
1234    /// to serve the metrics with a HTTP server, dump them to a file, or push them
1235    /// to a Prometheus gateway.
1236    ///
1237    /// For example, the following snippet launches an HTTP server that serves the metrics in the
1238    /// OpenMetrics text format:
1239    /// ```no_run
1240    /// # use std::{sync::{Arc, RwLock}, time::Duration};
1241    /// # use iroh_metrics::{Registry, MetricsSource};
1242    /// # use iroh::endpoint::Endpoint;
1243    /// # use n0_snafu::ResultExt;
1244    /// # async fn wrapper() -> n0_snafu::Result {
1245    /// // Create a registry, wrapped in a read-write lock so that we can register and serve
1246    /// // the metrics independently.
1247    /// let registry = Arc::new(RwLock::new(Registry::default()));
1248    /// // Spawn a task to serve the metrics on an OpenMetrics HTTP endpoint.
1249    /// let metrics_task = tokio::task::spawn({
1250    ///     let registry = registry.clone();
1251    ///     async move {
1252    ///         let addr = "0.0.0.0:9100".parse().unwrap();
1253    ///         iroh_metrics::service::start_metrics_server(addr, registry).await
1254    ///     }
1255    /// });
1256    ///
1257    /// // Spawn an endpoint and add the metrics to the registry.
1258    /// let endpoint = Endpoint::builder().bind().await?;
1259    /// registry.write().unwrap().register_all(endpoint.metrics());
1260    ///
1261    /// // Wait for the metrics server to bind, then fetch the metrics via HTTP.
1262    /// tokio::time::sleep(Duration::from_millis(500));
1263    /// let res = reqwest::get("http://localhost:9100/metrics")
1264    ///     .await
1265    ///     .context("get")?
1266    ///     .text()
1267    ///     .await
1268    ///     .context("text")?;
1269    ///
1270    /// assert!(res.contains(r#"TYPE magicsock_recv_datagrams counter"#));
1271    /// assert!(res.contains(r#"magicsock_recv_datagrams_total 0"#));
1272    /// # metrics_task.abort();
1273    /// # Ok(())
1274    /// # }
1275    /// ```
1276    ///
1277    /// [`Registry`]: iroh_metrics::Registry
1278    /// [`Registry::register_all`]: iroh_metrics::Registry::register_all
1279    /// [`Registry::sub_registry_with_label`]: iroh_metrics::Registry::sub_registry_with_label
1280    /// [`Registry::sub_registry_with_prefix`]: iroh_metrics::Registry::sub_registry_with_prefix
1281    /// [`encode_openmetrics_to_string`]: iroh_metrics::MetricsSource::encode_openmetrics_to_string
1282    /// [`MetricsGroup`]: iroh_metrics::MetricsGroup
1283    /// [`MetricsGroupSet`]: iroh_metrics::MetricsGroupSet
1284    #[cfg(feature = "metrics")]
1285    pub fn metrics(&self) -> &EndpointMetrics {
1286        &self.msock.metrics
1287    }
1288
1289    // # Methods for less common state updates.
1290
1291    /// Notifies the system of potential network changes.
1292    ///
1293    /// On many systems iroh is able to detect network changes by itself, however
1294    /// some systems like android do not expose this functionality to native code.
1295    /// Android does however provide this functionality to Java code.  This
1296    /// function allows for notifying iroh of any potential network changes like
1297    /// this.
1298    ///
1299    /// Even when the network did not change, or iroh was already able to detect
1300    /// the network change itself, there is no harm in calling this function.
1301    pub async fn network_change(&self) {
1302        self.msock.network_change().await;
1303    }
1304
1305    // # Methods to update internal state.
1306
1307    /// Sets the initial user-defined data to be published in discovery services for this node.
1308    ///
1309    /// If the user-defined data passed to this function is different to the previous one,
1310    /// the endpoint will republish its node info to the configured discovery services.
1311    ///
1312    /// See also [`Builder::user_data_for_discovery`] for setting an initial value when
1313    /// building the endpoint.
1314    pub fn set_user_data_for_discovery(&self, user_data: Option<UserData>) {
1315        self.msock.set_user_data_for_discovery(user_data);
1316    }
1317
1318    // # Methods for terminating the endpoint.
1319
1320    /// Closes the QUIC endpoint and the magic socket.
1321    ///
1322    /// This will close any remaining open [`Connection`]s with an error code
1323    /// of `0` and an empty reason.  Though it is best practice to close those
1324    /// explicitly before with a custom error code and reason.
1325    ///
1326    /// It will then make a best effort to wait for all close notifications to be
1327    /// acknowledged by the peers, re-transmitting them if needed. This ensures the
1328    /// peers are aware of the closed connections instead of having to wait for a timeout
1329    /// on the connection. Once all connections are closed or timed out, the future
1330    /// finishes.
1331    ///
1332    /// The maximum time-out that this future will wait for depends on QUIC transport
1333    /// configurations of non-drained connections at the time of calling, and their current
1334    /// estimates of round trip time. With default parameters and a conservative estimate
1335    /// of round trip time, this call's future should take 3 seconds to resolve in cases of
1336    /// bad connectivity or failed connections. In the usual case, this call's future should
1337    /// return much more quickly.
1338    ///
1339    /// It is highly recommended you *do* wait for this close call to finish, if possible.
1340    /// Not doing so will make connections that were still open while closing the endpoint
1341    /// time out on the remote end. Thus remote ends will assume connections to have failed
1342    /// even if all application data was transmitted successfully.
1343    ///
1344    /// Note: Someone used to closing TCP sockets might wonder why it is necessary to wait
1345    /// for timeouts when closing QUIC endpoints, while they don't have to do this for TCP
1346    /// sockets. This is due to QUIC and its acknowledgments being implemented in user-land,
1347    /// while TCP sockets usually get closed and drained by the operating system in the
1348    /// kernel during the "Time-Wait" period of the TCP socket.
1349    ///
1350    /// Be aware however that the underlying UDP sockets are only closed once all clones of
1351    /// the the respective [`Endpoint`] are dropped.
1352    pub async fn close(&self) {
1353        if self.is_closed() {
1354            return;
1355        }
1356
1357        tracing::debug!("Connections closed");
1358        self.msock.close().await;
1359    }
1360
1361    /// Check if this endpoint is still alive, or already closed.
1362    pub fn is_closed(&self) -> bool {
1363        self.msock.is_closed()
1364    }
1365
1366    // # Remaining private methods
1367
1368    /// Return the quic mapped address for this `node_id` and possibly start discovery
1369    /// services if discovery is enabled on this magic endpoint.
1370    ///
1371    /// This will launch discovery in all cases except if:
1372    /// 1) we do not have discovery enabled
1373    /// 2) we have discovery enabled, but already have at least one verified, unexpired
1374    ///    addresses for this `node_id`
1375    ///
1376    /// # Errors
1377    ///
1378    /// This method may fail if we have no way of dialing the node. This can occur if
1379    /// we were given no dialing information in the [`NodeAddr`] and no discovery
1380    /// services were configured or if discovery failed to fetch any dialing information.
1381    async fn get_mapping_addr_and_maybe_start_discovery(
1382        &self,
1383        node_addr: NodeAddr,
1384    ) -> Result<(NodeIdMappedAddr, Option<DiscoveryTask>), GetMappingAddressError> {
1385        let node_id = node_addr.node_id;
1386
1387        // Only return a mapped addr if we have some way of dialing this node, in other
1388        // words, we have either a relay URL or at least one direct address.
1389        let addr = if self.msock.has_send_address(node_id) {
1390            self.msock.get_mapping_addr(node_id)
1391        } else {
1392            None
1393        };
1394        match addr {
1395            Some(addr) => {
1396                // We have some way of dialing this node, but that doesn't actually mean
1397                // we can actually connect to any of these addresses.
1398                // Therefore, we will invoke the discovery service if we haven't received from the
1399                // endpoint on any of the existing paths recently.
1400                // If the user provided addresses in this connect call, we will add a delay
1401                // followed by a recheck before starting the discovery, to give the magicsocket a
1402                // chance to test the newly provided addresses.
1403                let delay = (!node_addr.is_empty()).then_some(DISCOVERY_WAIT_PERIOD);
1404                let discovery = DiscoveryTask::maybe_start_after_delay(self, node_id, delay)
1405                    .ok()
1406                    .flatten();
1407                Ok((addr, discovery))
1408            }
1409
1410            None => {
1411                // We have no known addresses or relay URLs for this node.
1412                // So, we start a discovery task and wait for the first result to arrive, and
1413                // only then continue, because otherwise we wouldn't have any
1414                // path to the remote endpoint.
1415                let res = DiscoveryTask::start(self.clone(), node_id);
1416                let mut discovery = res.context(get_mapping_address_error::DiscoveryStartSnafu)?;
1417                discovery
1418                    .first_arrived()
1419                    .await
1420                    .context(get_mapping_address_error::DiscoverSnafu)?;
1421                if let Some(addr) = self.msock.get_mapping_addr(node_id) {
1422                    Ok((addr, Some(discovery)))
1423                } else {
1424                    Err(get_mapping_address_error::NoAddressSnafu.build())
1425                }
1426            }
1427        }
1428    }
1429
1430    /// Returns a reference to the subscribers channel for discovery events.
1431    pub(crate) fn discovery_subscribers(&self) -> &DiscoverySubscribers {
1432        self.msock.discovery_subscribers()
1433    }
1434
1435    #[cfg(test)]
1436    pub(crate) fn magic_sock(&self) -> Handle {
1437        self.msock.clone()
1438    }
1439    #[cfg(test)]
1440    pub(crate) fn endpoint(&self) -> &quinn::Endpoint {
1441        self.msock.endpoint()
1442    }
1443}
1444
1445/// Options for the [`Endpoint::connect_with_opts`] function.
1446#[derive(Default, Debug, Clone)]
1447pub struct ConnectOptions {
1448    transport_config: Option<Arc<TransportConfig>>,
1449    additional_alpns: Vec<Vec<u8>>,
1450}
1451
1452impl ConnectOptions {
1453    /// Initializes new connection options.
1454    ///
1455    /// By default, the connection will use the same options
1456    /// as [`Endpoint::connect`], e.g. a default [`TransportConfig`].
1457    pub fn new() -> Self {
1458        Self::default()
1459    }
1460
1461    /// Sets the QUIC transport config options for this connection.
1462    pub fn with_transport_config(mut self, transport_config: Arc<TransportConfig>) -> Self {
1463        self.transport_config = Some(transport_config);
1464        self
1465    }
1466
1467    /// Sets [ALPN] identifiers that should be signaled as supported on connection, *in
1468    /// addition* to the main [ALPN] identifier used in [`Endpoint::connect_with_opts`].
1469    ///
1470    /// This allows connecting to servers that may only support older versions of your
1471    /// protocol. In this case, you would add the older [ALPN] identifiers with this
1472    /// function.
1473    ///
1474    /// You'll know the final negotiated [ALPN] identifier once your connection was
1475    /// established using [`Connection::alpn`], or even slightly earlier in the
1476    /// handshake by using [`Connecting::alpn`].
1477    /// The negotiated [ALPN] identifier may be any of the [ALPN] identifiers in this
1478    /// list or the main [ALPN] used in [`Endpoint::connect_with_opts`].
1479    ///
1480    /// The [ALPN] identifier order on the connect side doesn't matter, since it's the
1481    /// accept side that determines the protocol.
1482    ///
1483    /// For setting the supported [ALPN] identifiers on the accept side, see the endpoint
1484    /// builder's [`Builder::alpns`] function.
1485    ///
1486    /// [ALPN]: https://en.wikipedia.org/wiki/Application-Layer_Protocol_Negotiation
1487    pub fn with_additional_alpns(mut self, alpns: Vec<Vec<u8>>) -> Self {
1488        self.additional_alpns = alpns;
1489        self
1490    }
1491}
1492
1493/// Future produced by [`Endpoint::accept`].
1494#[derive(derive_more::Debug)]
1495#[pin_project]
1496pub struct Accept<'a> {
1497    #[pin]
1498    #[debug("quinn::Accept")]
1499    inner: quinn::Accept<'a>,
1500    ep: Endpoint,
1501}
1502
1503impl Future for Accept<'_> {
1504    type Output = Option<Incoming>;
1505
1506    fn poll(self: Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> Poll<Self::Output> {
1507        let this = self.project();
1508        match this.inner.poll(cx) {
1509            Poll::Pending => Poll::Pending,
1510            Poll::Ready(None) => Poll::Ready(None),
1511            Poll::Ready(Some(inner)) => Poll::Ready(Some(Incoming {
1512                inner,
1513                ep: this.ep.clone(),
1514            })),
1515        }
1516    }
1517}
1518
1519/// An incoming connection for which the server has not yet begun its parts of the
1520/// handshake.
1521#[derive(Debug)]
1522pub struct Incoming {
1523    inner: quinn::Incoming,
1524    ep: Endpoint,
1525}
1526
1527impl Incoming {
1528    /// Attempts to accept this incoming connection (an error may still occur).
1529    ///
1530    /// Errors occurring here are likely not caused by the application or remote.  The QUIC
1531    /// connection listens on a normal UDP socket and any reachable network endpoint can
1532    /// send datagrams to it, solicited or not.  Even if the first few bytes look like a
1533    /// QUIC packet, it might not even be a QUIC packet that is being received.
1534    ///
1535    /// Thus it is common to simply log the errors here and accept them as something which
1536    /// can happen.
1537    pub fn accept(self) -> Result<Connecting, ConnectionError> {
1538        self.inner.accept().map(|conn| Connecting {
1539            inner: conn,
1540            ep: self.ep,
1541            remote_node_id: None,
1542            _discovery_drop_guard: None,
1543        })
1544    }
1545
1546    /// Accepts this incoming connection using a custom configuration.
1547    ///
1548    /// See [`accept()`] for more details.
1549    ///
1550    /// [`accept()`]: Incoming::accept
1551    pub fn accept_with(
1552        self,
1553        server_config: Arc<ServerConfig>,
1554    ) -> Result<Connecting, ConnectionError> {
1555        self.inner
1556            .accept_with(server_config)
1557            .map(|conn| Connecting {
1558                inner: conn,
1559                ep: self.ep,
1560                remote_node_id: None,
1561                _discovery_drop_guard: None,
1562            })
1563    }
1564
1565    /// Rejects this incoming connection attempt.
1566    pub fn refuse(self) {
1567        self.inner.refuse()
1568    }
1569
1570    /// Responds with a retry packet.
1571    ///
1572    /// This requires the client to retry with address validation.
1573    ///
1574    /// Errors if `remote_address_validated()` is true.
1575    #[allow(clippy::result_large_err)]
1576    pub fn retry(self) -> Result<(), RetryError> {
1577        self.inner.retry()
1578    }
1579
1580    /// Ignores this incoming connection attempt, not sending any packet in response.
1581    pub fn ignore(self) {
1582        self.inner.ignore()
1583    }
1584
1585    /// Returns the local IP address which was used when the peer established the
1586    /// connection.
1587    pub fn local_ip(&self) -> Option<IpAddr> {
1588        self.inner.local_ip()
1589    }
1590
1591    /// Returns the peer's UDP address.
1592    pub fn remote_address(&self) -> SocketAddr {
1593        self.inner.remote_address()
1594    }
1595
1596    /// Whether the socket address that is initiating this connection has been validated.
1597    ///
1598    /// This means that the sender of the initial packet has proved that they can receive
1599    /// traffic sent to `self.remote_address()`.
1600    pub fn remote_address_validated(&self) -> bool {
1601        self.inner.remote_address_validated()
1602    }
1603}
1604
1605impl IntoFuture for Incoming {
1606    type Output = Result<Connection, ConnectionError>;
1607    type IntoFuture = IncomingFuture;
1608
1609    fn into_future(self) -> Self::IntoFuture {
1610        IncomingFuture {
1611            inner: self.inner.into_future(),
1612            ep: self.ep,
1613        }
1614    }
1615}
1616
1617/// Adaptor to let [`Incoming`] be `await`ed like a [`Connecting`].
1618#[derive(Debug)]
1619#[pin_project]
1620pub struct IncomingFuture {
1621    #[pin]
1622    inner: quinn::IncomingFuture,
1623    ep: Endpoint,
1624}
1625
1626impl Future for IncomingFuture {
1627    type Output = Result<Connection, ConnectionError>;
1628
1629    fn poll(self: Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> Poll<Self::Output> {
1630        let this = self.project();
1631        match this.inner.poll(cx) {
1632            Poll::Pending => Poll::Pending,
1633            Poll::Ready(Err(err)) => Poll::Ready(Err(err)),
1634            Poll::Ready(Ok(inner)) => {
1635                let conn = Connection { inner };
1636                try_send_rtt_msg(&conn, this.ep, None);
1637                Poll::Ready(Ok(conn))
1638            }
1639        }
1640    }
1641}
1642
1643/// In-progress connection attempt future
1644#[derive(derive_more::Debug)]
1645#[pin_project]
1646pub struct Connecting {
1647    #[pin]
1648    inner: quinn::Connecting,
1649    ep: Endpoint,
1650    remote_node_id: Option<NodeId>,
1651    /// We run discovery as long as we haven't established a connection yet.
1652    #[debug("Option<DiscoveryTask>")]
1653    _discovery_drop_guard: Option<DiscoveryTask>,
1654}
1655
1656#[allow(missing_docs)]
1657#[common_fields({
1658    backtrace: Option<snafu::Backtrace>,
1659    #[snafu(implicit)]
1660    span_trace: n0_snafu::SpanTrace,
1661})]
1662#[derive(Debug, Snafu)]
1663#[non_exhaustive]
1664pub enum AlpnError {
1665    #[snafu(transparent)]
1666    ConnectionError { source: ConnectionError },
1667    #[snafu(display("No ALPN available"))]
1668    Unavailable {},
1669    #[snafu(display("Unknown handshake type"))]
1670    UnknownHandshake {},
1671}
1672
1673impl Connecting {
1674    /// Converts this [`Connecting`] into a 0-RTT or 0.5-RTT connection at the cost of weakened
1675    /// security.
1676    ///
1677    /// Returns `Ok` immediately if the local endpoint is able to attempt sending 0/0.5-RTT data.
1678    /// If so, the returned [`Connection`] can be used to send application data without waiting for
1679    /// the rest of the handshake to complete, at the cost of weakened cryptographic security
1680    /// guarantees. The returned [`ZeroRttAccepted`] future resolves when the handshake does
1681    /// complete, at which point subsequently opened streams and written data will have full
1682    /// cryptographic protection.
1683    ///
1684    /// Once the [`ZeroRttAccepted`] future completed, a full handshake has been carried through
1685    /// and any data sent and any streams opened on the [`Connection`] will operate with the same
1686    /// security as on normal 1-RTT connections.
1687    ///
1688    /// ## Outgoing
1689    ///
1690    /// For outgoing connections, the initial attempt to convert to a [`Connection`] which sends
1691    /// 0-RTT data will attempt to resume a previous TLS session. However, **the remote endpoint
1692    /// may not actually _accept_ the 0-RTT data**--yet still accept the connection attempt in
1693    /// general. This possibility is conveyed through the [`ZeroRttAccepted`] future--when the
1694    /// handshake completes, it resolves to true if the 0-RTT data was accepted and false if it was
1695    /// rejected. If it was rejected, the existence of streams opened and other application data
1696    /// sent prior to the handshake completing will not be conveyed to the remote application, and
1697    /// local operations on them will return `ZeroRttRejected` errors.
1698    ///
1699    /// A server may reject 0-RTT data at its discretion, but accepting 0-RTT data requires the
1700    /// relevant resumption state to be stored in the server, which servers may limit or lose for
1701    /// various reasons including not persisting resumption state across server restarts.
1702    ///
1703    /// ## Incoming
1704    ///
1705    /// For incoming connections, conversion to 0.5-RTT will always fully succeed. `into_0rtt` will
1706    /// always return `Ok` and the [`ZeroRttAccepted`] will always resolve to true.
1707    ///
1708    /// ## Security
1709    ///
1710    /// On outgoing connections, this enables transmission of 0-RTT data, which is vulnerable to
1711    /// replay attacks, and should therefore never invoke non-idempotent operations.
1712    ///
1713    /// On incoming connections, this enables transmission of 0.5-RTT data, which may be sent
1714    /// before TLS client authentication has occurred, and should therefore not be used to send
1715    /// data for which client authentication is being used.
1716    ///
1717    /// You can use [`RecvStream::is_0rtt`] to check whether a stream has been opened in 0-RTT
1718    /// and thus whether parts of the stream are operating under this reduced security level.
1719    #[allow(clippy::result_large_err)]
1720    pub fn into_0rtt(self) -> Result<(Connection, ZeroRttAccepted), Self> {
1721        match self.inner.into_0rtt() {
1722            Ok((inner, zrtt_accepted)) => {
1723                let conn = Connection { inner };
1724                let zrtt_accepted = ZeroRttAccepted {
1725                    inner: zrtt_accepted,
1726                    _discovery_drop_guard: self._discovery_drop_guard,
1727                };
1728                // This call is why `self.remote_node_id` was introduced.
1729                // When we `Connecting::into_0rtt`, then we don't yet have `handshake_data`
1730                // in our `Connection`, thus `try_send_rtt_msg` won't be able to pick up
1731                // `Connection::remote_node_id`.
1732                // Instead, we provide `self.remote_node_id` here - we know it in advance,
1733                // after all.
1734                try_send_rtt_msg(&conn, &self.ep, self.remote_node_id);
1735                Ok((conn, zrtt_accepted))
1736            }
1737            Err(inner) => Err(Self {
1738                inner,
1739                ep: self.ep,
1740                remote_node_id: self.remote_node_id,
1741                _discovery_drop_guard: self._discovery_drop_guard,
1742            }),
1743        }
1744    }
1745
1746    /// Parameters negotiated during the handshake
1747    pub async fn handshake_data(&mut self) -> Result<Box<dyn Any>, ConnectionError> {
1748        self.inner.handshake_data().await
1749    }
1750
1751    /// Extracts the ALPN protocol from the peer's handshake data.
1752    pub async fn alpn(&mut self) -> Result<Vec<u8>, AlpnError> {
1753        let data = self.handshake_data().await?;
1754        match data.downcast::<quinn::crypto::rustls::HandshakeData>() {
1755            Ok(data) => match data.protocol {
1756                Some(protocol) => Ok(protocol),
1757                None => Err(UnavailableSnafu.build()),
1758            },
1759            Err(_) => Err(UnknownHandshakeSnafu.build()),
1760        }
1761    }
1762}
1763
1764impl Future for Connecting {
1765    type Output = Result<Connection, ConnectionError>;
1766
1767    fn poll(self: Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> Poll<Self::Output> {
1768        let this = self.project();
1769        match this.inner.poll(cx) {
1770            Poll::Pending => Poll::Pending,
1771            Poll::Ready(Err(err)) => Poll::Ready(Err(err)),
1772            Poll::Ready(Ok(inner)) => {
1773                let conn = Connection { inner };
1774                try_send_rtt_msg(&conn, this.ep, *this.remote_node_id);
1775                Poll::Ready(Ok(conn))
1776            }
1777        }
1778    }
1779}
1780
1781/// Future that completes when a connection is fully established.
1782///
1783/// For clients, the resulting value indicates if 0-RTT was accepted. For servers, the resulting
1784/// value is meaningless.
1785#[derive(derive_more::Debug)]
1786#[debug("ZeroRttAccepted")]
1787pub struct ZeroRttAccepted {
1788    inner: quinn::ZeroRttAccepted,
1789    /// When we call `Connecting::into_0rtt`, we don't want to stop discovery, so we transfer the task
1790    /// to this future.
1791    /// When `quinn::ZeroRttAccepted` resolves, we've successfully received data from the remote.
1792    /// Thus, that's the right time to drop discovery to preserve the behaviour similar to
1793    /// `Connecting` -> `Connection` without 0-RTT.
1794    /// Should we eventually decide to keep the discovery task alive for the duration of the whole
1795    /// `Connection`, then this task should be transferred to the `Connection` instead of here.
1796    _discovery_drop_guard: Option<DiscoveryTask>,
1797}
1798
1799impl Future for ZeroRttAccepted {
1800    type Output = bool;
1801    fn poll(mut self: Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> Poll<Self::Output> {
1802        Pin::new(&mut self.inner).poll(cx)
1803    }
1804}
1805
1806/// A QUIC connection.
1807///
1808/// If all references to a connection (including every clone of the Connection handle,
1809/// streams of incoming streams, and the various stream types) have been dropped, then the
1810/// connection will be automatically closed with an error_code of 0 and an empty reason. You
1811/// can also close the connection explicitly by calling [`Connection::close`].
1812///
1813/// Closing the connection immediately abandons efforts to deliver data to the peer. Upon
1814/// receiving CONNECTION_CLOSE the peer may drop any stream data not yet delivered to the
1815/// application. [`Connection::close`] describes in more detail how to gracefully close a
1816/// connection without losing application data.
1817///
1818/// May be cloned to obtain another handle to the same connection.
1819#[derive(Debug, Clone)]
1820pub struct Connection {
1821    inner: quinn::Connection,
1822}
1823
1824#[allow(missing_docs)]
1825#[derive(Debug, Snafu)]
1826#[snafu(display("Protocol error: no remote id available"))]
1827pub struct RemoteNodeIdError {
1828    backtrace: Option<snafu::Backtrace>,
1829}
1830
1831impl Connection {
1832    /// Initiates a new outgoing unidirectional stream.
1833    ///
1834    /// Streams are cheap and instantaneous to open unless blocked by flow control. As a
1835    /// consequence, the peer won’t be notified that a stream has been opened until the
1836    /// stream is actually used.
1837    #[inline]
1838    pub fn open_uni(&self) -> OpenUni<'_> {
1839        self.inner.open_uni()
1840    }
1841
1842    /// Initiates a new outgoing bidirectional stream.
1843    ///
1844    /// Streams are cheap and instantaneous to open unless blocked by flow control. As a
1845    /// consequence, the peer won't be notified that a stream has been opened until the
1846    /// stream is actually used. Calling [`open_bi`] then waiting on the [`RecvStream`]
1847    /// without writing anything to [`SendStream`] will never succeed.
1848    ///
1849    /// [`open_bi`]: Connection::open_bi
1850    #[inline]
1851    pub fn open_bi(&self) -> OpenBi<'_> {
1852        self.inner.open_bi()
1853    }
1854
1855    /// Accepts the next incoming uni-directional stream.
1856    #[inline]
1857    pub fn accept_uni(&self) -> AcceptUni<'_> {
1858        self.inner.accept_uni()
1859    }
1860
1861    /// Accept the next incoming bidirectional stream.
1862    ///
1863    /// **Important Note**: The peer that calls [`open_bi`] must write to its [`SendStream`]
1864    /// before the peer `Connection` is able to accept the stream using
1865    /// `accept_bi()`. Calling [`open_bi`] then waiting on the [`RecvStream`] without
1866    /// writing anything to the connected [`SendStream`] will never succeed.
1867    ///
1868    /// [`open_bi`]: Connection::open_bi
1869    #[inline]
1870    pub fn accept_bi(&self) -> AcceptBi<'_> {
1871        self.inner.accept_bi()
1872    }
1873
1874    /// Receives an application datagram.
1875    #[inline]
1876    pub fn read_datagram(&self) -> ReadDatagram<'_> {
1877        self.inner.read_datagram()
1878    }
1879
1880    /// Wait for the connection to be closed for any reason.
1881    ///
1882    /// Despite the return type's name, closed connections are often not an error condition
1883    /// at the application layer. Cases that might be routine include
1884    /// [`ConnectionError::LocallyClosed`] and [`ConnectionError::ApplicationClosed`].
1885    #[inline]
1886    pub async fn closed(&self) -> ConnectionError {
1887        self.inner.closed().await
1888    }
1889
1890    /// If the connection is closed, the reason why.
1891    ///
1892    /// Returns `None` if the connection is still open.
1893    #[inline]
1894    pub fn close_reason(&self) -> Option<ConnectionError> {
1895        self.inner.close_reason()
1896    }
1897
1898    /// Closes the connection immediately.
1899    ///
1900    /// Pending operations will fail immediately with [`ConnectionError::LocallyClosed`]. No
1901    /// more data is sent to the peer and the peer may drop buffered data upon receiving the
1902    /// CONNECTION_CLOSE frame.
1903    ///
1904    /// `error_code` and `reason` are not interpreted, and are provided directly to the
1905    /// peer.
1906    ///
1907    /// `reason` will be truncated to fit in a single packet with overhead; to improve odds
1908    /// that it is preserved in full, it should be kept under 1KiB.
1909    ///
1910    /// # Gracefully closing a connection
1911    ///
1912    /// Only the peer last receiving application data can be certain that all data is
1913    /// delivered. The only reliable action it can then take is to close the connection,
1914    /// potentially with a custom error code. The delivery of the final CONNECTION_CLOSE
1915    /// frame is very likely if both endpoints stay online long enough, calling
1916    /// [`Endpoint::close`] will wait to provide sufficient time. Otherwise, the remote peer
1917    /// will time out the connection, provided that the idle timeout is not disabled.
1918    ///
1919    /// The sending side can not guarantee all stream data is delivered to the remote
1920    /// application. It only knows the data is delivered to the QUIC stack of the remote
1921    /// endpoint. Once the local side sends a CONNECTION_CLOSE frame in response to calling
1922    /// [`close`] the remote endpoint may drop any data it received but is as yet
1923    /// undelivered to the application, including data that was acknowledged as received to
1924    /// the local endpoint.
1925    ///
1926    /// [`close`]: Connection::close
1927    #[inline]
1928    pub fn close(&self, error_code: VarInt, reason: &[u8]) {
1929        self.inner.close(error_code, reason)
1930    }
1931
1932    /// Transmits `data` as an unreliable, unordered application datagram.
1933    ///
1934    /// Application datagrams are a low-level primitive. They may be lost or delivered out
1935    /// of order, and `data` must both fit inside a single QUIC packet and be smaller than
1936    /// the maximum dictated by the peer.
1937    #[inline]
1938    pub fn send_datagram(&self, data: bytes::Bytes) -> Result<(), SendDatagramError> {
1939        self.inner.send_datagram(data)
1940    }
1941
1942    // TODO: It seems `SendDatagram` is not yet exposed by quinn.  This has been fixed
1943    //       upstream and will be in the next release.
1944    // /// Transmits `data` as an unreliable, unordered application datagram
1945    // ///
1946    // /// Unlike [`send_datagram()`], this method will wait for buffer space during congestion
1947    // /// conditions, which effectively prioritizes old datagrams over new datagrams.
1948    // ///
1949    // /// See [`send_datagram()`] for details.
1950    // ///
1951    // /// [`send_datagram()`]: Connection::send_datagram
1952    // #[inline]
1953    // pub fn send_datagram_wait(&self, data: bytes::Bytes) -> SendDatagram<'_> {
1954    //     self.inner.send_datagram_wait(data)
1955    // }
1956
1957    /// Computes the maximum size of datagrams that may be passed to [`send_datagram`].
1958    ///
1959    /// Returns `None` if datagrams are unsupported by the peer or disabled locally.
1960    ///
1961    /// This may change over the lifetime of a connection according to variation in the path
1962    /// MTU estimate. The peer can also enforce an arbitrarily small fixed limit, but if the
1963    /// peer's limit is large this is guaranteed to be a little over a kilobyte at minimum.
1964    ///
1965    /// Not necessarily the maximum size of received datagrams.
1966    ///
1967    /// [`send_datagram`]: Self::send_datagram
1968    #[inline]
1969    pub fn max_datagram_size(&self) -> Option<usize> {
1970        self.inner.max_datagram_size()
1971    }
1972
1973    /// Bytes available in the outgoing datagram buffer.
1974    ///
1975    /// When greater than zero, calling [`send_datagram`] with a
1976    /// datagram of at most this size is guaranteed not to cause older datagrams to be
1977    /// dropped.
1978    ///
1979    /// [`send_datagram`]: Self::send_datagram
1980    #[inline]
1981    pub fn datagram_send_buffer_space(&self) -> usize {
1982        self.inner.datagram_send_buffer_space()
1983    }
1984
1985    /// Current best estimate of this connection's latency (round-trip-time).
1986    #[inline]
1987    pub fn rtt(&self) -> Duration {
1988        self.inner.rtt()
1989    }
1990
1991    /// Returns connection statistics.
1992    #[inline]
1993    pub fn stats(&self) -> ConnectionStats {
1994        self.inner.stats()
1995    }
1996
1997    /// Current state of the congestion control algorithm, for debugging purposes.
1998    #[inline]
1999    pub fn congestion_state(&self) -> Box<dyn quinn_proto::congestion::Controller> {
2000        self.inner.congestion_state()
2001    }
2002
2003    /// Parameters negotiated during the handshake.
2004    ///
2005    /// Guaranteed to return `Some` on fully established connections or after
2006    /// [`Connecting::handshake_data()`] succeeds. See that method's documentations for
2007    /// details on the returned value.
2008    ///
2009    /// [`Connection::handshake_data()`]: crate::endpoint::Connecting::handshake_data
2010    #[inline]
2011    pub fn handshake_data(&self) -> Option<Box<dyn Any>> {
2012        self.inner.handshake_data()
2013    }
2014
2015    /// Extracts the ALPN protocol from the peer's handshake data.
2016    pub fn alpn(&self) -> Option<Vec<u8>> {
2017        let data = self.handshake_data()?;
2018        match data.downcast::<quinn::crypto::rustls::HandshakeData>() {
2019            Ok(data) => data.protocol,
2020            Err(_) => None,
2021        }
2022    }
2023
2024    /// Cryptographic identity of the peer.
2025    ///
2026    /// The dynamic type returned is determined by the configured [`Session`]. For the
2027    /// default `rustls` session, the return value can be [`downcast`] to a
2028    /// <code>Vec<[rustls::pki_types::CertificateDer]></code>
2029    ///
2030    /// [`Session`]: quinn_proto::crypto::Session
2031    /// [`downcast`]: Box::downcast
2032    #[inline]
2033    pub fn peer_identity(&self) -> Option<Box<dyn Any>> {
2034        self.inner.peer_identity()
2035    }
2036
2037    /// Returns the [`NodeId`] from the peer's TLS certificate.
2038    ///
2039    /// The [`PublicKey`] of a node is also known as a [`NodeId`].  This [`PublicKey`] is
2040    /// included in the TLS certificate presented during the handshake when connecting.
2041    /// This function allows you to get the [`NodeId`] of the remote node of this
2042    /// connection.
2043    ///
2044    /// [`PublicKey`]: iroh_base::PublicKey
2045    // TODO: Would be nice if this could be infallible.
2046    pub fn remote_node_id(&self) -> Result<NodeId, RemoteNodeIdError> {
2047        let data = self.peer_identity();
2048        match data {
2049            None => {
2050                warn!("no peer certificate found");
2051                Err(RemoteNodeIdSnafu.build())
2052            }
2053            Some(data) => match data.downcast::<Vec<rustls::pki_types::CertificateDer>>() {
2054                Ok(certs) => {
2055                    if certs.len() != 1 {
2056                        warn!(
2057                            "expected a single peer certificate, but {} found",
2058                            certs.len()
2059                        );
2060                        return Err(RemoteNodeIdSnafu.build());
2061                    }
2062
2063                    let peer_id = VerifyingKey::from_public_key_der(&certs[0])
2064                        .map_err(|_| RemoteNodeIdSnafu.build())?
2065                        .into();
2066                    Ok(peer_id)
2067                }
2068                Err(err) => {
2069                    warn!("invalid peer certificate: {:?}", err);
2070                    Err(RemoteNodeIdSnafu.build())
2071                }
2072            },
2073        }
2074    }
2075
2076    /// A stable identifier for this connection.
2077    ///
2078    /// Peer addresses and connection IDs can change, but this value will remain fixed for
2079    /// the lifetime of the connection.
2080    #[inline]
2081    pub fn stable_id(&self) -> usize {
2082        self.inner.stable_id()
2083    }
2084
2085    /// Derives keying material from this connection's TLS session secrets.
2086    ///
2087    /// When both peers call this method with the same `label` and `context`
2088    /// arguments and `output` buffers of equal length, they will get the
2089    /// same sequence of bytes in `output`. These bytes are cryptographically
2090    /// strong and pseudorandom, and are suitable for use as keying material.
2091    ///
2092    /// See [RFC5705](https://tools.ietf.org/html/rfc5705) for more information.
2093    #[inline]
2094    pub fn export_keying_material(
2095        &self,
2096        output: &mut [u8],
2097        label: &[u8],
2098        context: &[u8],
2099    ) -> Result<(), quinn_proto::crypto::ExportKeyingMaterialError> {
2100        self.inner.export_keying_material(output, label, context)
2101    }
2102
2103    /// Modifies the number of unidirectional streams that may be concurrently opened.
2104    ///
2105    /// No streams may be opened by the peer unless fewer than `count` are already
2106    /// open. Large `count`s increase both minimum and worst-case memory consumption.
2107    #[inline]
2108    pub fn set_max_concurrent_uni_streams(&self, count: VarInt) {
2109        self.inner.set_max_concurrent_uni_streams(count)
2110    }
2111
2112    /// See [`quinn_proto::TransportConfig::receive_window`].
2113    #[inline]
2114    pub fn set_receive_window(&self, receive_window: VarInt) {
2115        self.inner.set_receive_window(receive_window)
2116    }
2117
2118    /// Modifies the number of bidirectional streams that may be concurrently opened.
2119    ///
2120    /// No streams may be opened by the peer unless fewer than `count` are already
2121    /// open. Large `count`s increase both minimum and worst-case memory consumption.
2122    #[inline]
2123    pub fn set_max_concurrent_bi_streams(&self, count: VarInt) {
2124        self.inner.set_max_concurrent_bi_streams(count)
2125    }
2126}
2127
2128/// Try send a message to the rtt-actor.
2129///
2130/// If we can't notify the actor that will impact performance a little, but we can still
2131/// function.
2132fn try_send_rtt_msg(conn: &Connection, magic_ep: &Endpoint, remote_node_id: Option<NodeId>) {
2133    // If we can't notify the rtt-actor that's not great but not critical.
2134    let Some(node_id) = remote_node_id.or_else(|| conn.remote_node_id().ok()) else {
2135        warn!(?conn, "failed to get remote node id");
2136        return;
2137    };
2138    let Some(conn_type_changes) = magic_ep.conn_type(node_id) else {
2139        warn!(?conn, "failed to create conn_type stream");
2140        return;
2141    };
2142    let rtt_msg = RttMessage::NewConnection {
2143        connection: conn.inner.weak_handle(),
2144        conn_type_changes: conn_type_changes.stream(),
2145        node_id,
2146    };
2147    if let Err(err) = magic_ep.rtt_actor.msg_tx.try_send(rtt_msg) {
2148        warn!(?conn, "rtt-actor not reachable: {err:#}");
2149    }
2150}
2151
2152/// Read a proxy url from the environment, in this order
2153///
2154/// - `HTTP_PROXY`
2155/// - `http_proxy`
2156/// - `HTTPS_PROXY`
2157/// - `https_proxy`
2158fn proxy_url_from_env() -> Option<Url> {
2159    if let Some(url) = std::env::var("HTTP_PROXY")
2160        .ok()
2161        .and_then(|s| s.parse::<Url>().ok())
2162    {
2163        if is_cgi() {
2164            warn!("HTTP_PROXY environment variable ignored in CGI");
2165        } else {
2166            return Some(url);
2167        }
2168    }
2169    if let Some(url) = std::env::var("http_proxy")
2170        .ok()
2171        .and_then(|s| s.parse::<Url>().ok())
2172    {
2173        return Some(url);
2174    }
2175    if let Some(url) = std::env::var("HTTPS_PROXY")
2176        .ok()
2177        .and_then(|s| s.parse::<Url>().ok())
2178    {
2179        return Some(url);
2180    }
2181    if let Some(url) = std::env::var("https_proxy")
2182        .ok()
2183        .and_then(|s| s.parse::<Url>().ok())
2184    {
2185        return Some(url);
2186    }
2187
2188    None
2189}
2190
2191/// Configuration of the relay servers for an [`Endpoint`].
2192#[derive(Debug, Clone, PartialEq, Eq)]
2193pub enum RelayMode {
2194    /// Disable relay servers completely.
2195    Disabled,
2196    /// Use the default relay map, with production relay servers from n0.
2197    ///
2198    /// See [`crate::defaults::prod`] for the severs used.
2199    Default,
2200    /// Use the staging relay servers from n0.
2201    Staging,
2202    /// Use a custom relay map.
2203    Custom(RelayMap),
2204}
2205
2206impl RelayMode {
2207    /// Returns the relay map for this mode.
2208    pub fn relay_map(&self) -> RelayMap {
2209        match self {
2210            RelayMode::Disabled => RelayMap::empty(),
2211            RelayMode::Default => crate::defaults::prod::default_relay_map(),
2212            RelayMode::Staging => crate::defaults::staging::default_relay_map(),
2213            RelayMode::Custom(relay_map) => relay_map.clone(),
2214        }
2215    }
2216}
2217
2218/// Environment variable to force the use of staging relays.
2219pub const ENV_FORCE_STAGING_RELAYS: &str = "IROH_FORCE_STAGING_RELAYS";
2220
2221/// Returns `true` if the use of staging relays is forced.
2222pub fn force_staging_infra() -> bool {
2223    matches!(std::env::var(ENV_FORCE_STAGING_RELAYS), Ok(value) if !value.is_empty())
2224}
2225
2226/// Returns the default relay mode.
2227///
2228/// If the `IROH_FORCE_STAGING_RELAYS` environment variable is non empty, it will return `RelayMode::Staging`.
2229/// Otherwise, it will return `RelayMode::Default`.
2230pub fn default_relay_mode() -> RelayMode {
2231    // Use staging in testing
2232    match force_staging_infra() {
2233        true => RelayMode::Staging,
2234        false => RelayMode::Default,
2235    }
2236}
2237
2238/// Check if we are being executed in a CGI context.
2239///
2240/// If so, a malicious client can send the `Proxy:` header, and it will
2241/// be in the `HTTP_PROXY` env var. So we don't use it :)
2242fn is_cgi() -> bool {
2243    std::env::var_os("REQUEST_METHOD").is_some()
2244}
2245
2246// TODO: These tests could still be flaky, lets fix that:
2247// https://github.com/n0-computer/iroh/issues/1183
2248#[cfg(test)]
2249mod tests {
2250    use std::{
2251        net::SocketAddr,
2252        time::{Duration, Instant},
2253    };
2254
2255    use iroh_base::{NodeAddr, NodeId, SecretKey};
2256    use n0_future::{StreamExt, task::AbortOnDropHandle};
2257    use n0_snafu::{Error, Result, ResultExt};
2258    use n0_watcher::Watcher;
2259    use quinn::ConnectionError;
2260    use rand::SeedableRng;
2261    use tracing::{Instrument, error_span, info, info_span};
2262    use tracing_test::traced_test;
2263
2264    use super::Endpoint;
2265    use crate::{
2266        RelayMode,
2267        endpoint::{ConnectOptions, Connection, ConnectionType, RemoteInfo},
2268        test_utils::{run_relay_server, run_relay_server_with},
2269    };
2270
2271    const TEST_ALPN: &[u8] = b"n0/iroh/test";
2272
2273    #[tokio::test]
2274    #[traced_test]
2275    async fn test_connect_self() -> Result {
2276        let ep = Endpoint::builder()
2277            .alpns(vec![TEST_ALPN.to_vec()])
2278            .bind()
2279            .await
2280            .unwrap();
2281        let my_addr = ep.node_addr().initialized().await;
2282        let res = ep.connect(my_addr.clone(), TEST_ALPN).await;
2283        assert!(res.is_err());
2284        let err = res.err().unwrap();
2285        assert!(err.to_string().starts_with("Connecting to ourself"));
2286
2287        let res = ep.add_node_addr(my_addr);
2288        assert!(res.is_err());
2289        let err = res.err().unwrap();
2290        assert!(err.to_string().starts_with("Adding our own address"));
2291        Ok(())
2292    }
2293
2294    #[tokio::test]
2295    #[traced_test]
2296    async fn endpoint_connect_close() -> Result {
2297        let (relay_map, relay_url, _guard) = run_relay_server().await?;
2298        let server_secret_key = SecretKey::generate(rand::thread_rng());
2299        let server_peer_id = server_secret_key.public();
2300
2301        // Wait for the endpoint to be started to make sure it's up before clients try to connect
2302        let ep = Endpoint::builder()
2303            .secret_key(server_secret_key)
2304            .alpns(vec![TEST_ALPN.to_vec()])
2305            .relay_mode(RelayMode::Custom(relay_map.clone()))
2306            .insecure_skip_relay_cert_verify(true)
2307            .bind()
2308            .await?;
2309        // Wait for the endpoint to be reachable via relay
2310        ep.home_relay().initialized().await;
2311
2312        let server = tokio::spawn(
2313            async move {
2314                info!("accepting connection");
2315                let incoming = ep.accept().await.e()?;
2316                let conn = incoming.await.e()?;
2317                let mut stream = conn.accept_uni().await.e()?;
2318                let mut buf = [0u8; 5];
2319                stream.read_exact(&mut buf).await.e()?;
2320                info!("Accepted 1 stream, received {buf:?}.  Closing now.");
2321                // close the connection
2322                conn.close(7u8.into(), b"bye");
2323
2324                let res = conn.accept_uni().await;
2325                assert_eq!(res.unwrap_err(), quinn::ConnectionError::LocallyClosed);
2326
2327                let res = stream.read_to_end(10).await;
2328                assert_eq!(
2329                    res.unwrap_err(),
2330                    quinn::ReadToEndError::Read(quinn::ReadError::ConnectionLost(
2331                        quinn::ConnectionError::LocallyClosed
2332                    ))
2333                );
2334                info!("server test completed");
2335                Ok::<_, Error>(())
2336            }
2337            .instrument(info_span!("test-server")),
2338        );
2339
2340        let client = tokio::spawn(
2341            async move {
2342                let ep = Endpoint::builder()
2343                    .alpns(vec![TEST_ALPN.to_vec()])
2344                    .relay_mode(RelayMode::Custom(relay_map))
2345                    .insecure_skip_relay_cert_verify(true)
2346                    .bind()
2347                    .await?;
2348                info!("client connecting");
2349                let node_addr = NodeAddr::new(server_peer_id).with_relay_url(relay_url);
2350                let conn = ep.connect(node_addr, TEST_ALPN).await?;
2351                let mut stream = conn.open_uni().await.e()?;
2352
2353                // First write is accepted by server.  We need this bit of synchronisation
2354                // because if the server closes after simply accepting the connection we can
2355                // not be sure our .open_uni() call would succeed as it may already receive
2356                // the error.
2357                stream.write_all(b"hello").await.e()?;
2358
2359                info!("waiting for closed");
2360                // Remote now closes the connection, we should see an error sometime soon.
2361                let err = conn.closed().await;
2362                let expected_err =
2363                    quinn::ConnectionError::ApplicationClosed(quinn::ApplicationClose {
2364                        error_code: 7u8.into(),
2365                        reason: b"bye".to_vec().into(),
2366                    });
2367                assert_eq!(err, expected_err);
2368
2369                info!("opening new - expect it to fail");
2370                let res = conn.open_uni().await;
2371                assert_eq!(res.unwrap_err(), expected_err);
2372                info!("client test completed");
2373                Ok::<_, Error>(())
2374            }
2375            .instrument(info_span!("test-client")),
2376        );
2377
2378        let (server, client) = tokio::time::timeout(
2379            Duration::from_secs(30),
2380            n0_future::future::zip(server, client),
2381        )
2382        .await
2383        .e()?;
2384        server.e()??;
2385        client.e()??;
2386        Ok(())
2387    }
2388
2389    /// Test that peers are properly restored
2390    #[tokio::test]
2391    #[traced_test]
2392    async fn restore_peers() -> Result {
2393        let secret_key = SecretKey::generate(rand::thread_rng());
2394
2395        /// Create an endpoint for the test.
2396        async fn new_endpoint(
2397            secret_key: SecretKey,
2398            nodes: Option<Vec<NodeAddr>>,
2399        ) -> Result<Endpoint> {
2400            let mut transport_config = quinn::TransportConfig::default();
2401            transport_config.max_idle_timeout(Some(Duration::from_secs(10).try_into().unwrap()));
2402
2403            let mut builder = Endpoint::builder()
2404                .secret_key(secret_key.clone())
2405                .transport_config(transport_config);
2406            if let Some(nodes) = nodes {
2407                builder = builder.known_nodes(nodes);
2408            }
2409            Ok(builder.alpns(vec![TEST_ALPN.to_vec()]).bind().await?)
2410        }
2411
2412        // create the peer that will be added to the peer map
2413        let peer_id = SecretKey::generate(rand::thread_rng()).public();
2414        let direct_addr: SocketAddr =
2415            (std::net::IpAddr::V4(std::net::Ipv4Addr::LOCALHOST), 8758u16).into();
2416        let node_addr = NodeAddr::new(peer_id).with_direct_addresses([direct_addr]);
2417
2418        info!("setting up first endpoint");
2419        // first time, create a magic endpoint without peers but a peers file and add addressing
2420        // information for a peer
2421        let endpoint = new_endpoint(secret_key.clone(), None).await?;
2422        assert_eq!(endpoint.remote_info_iter().count(), 0);
2423        endpoint.add_node_addr(node_addr.clone())?;
2424
2425        // Grab the current addrs
2426        let node_addrs: Vec<NodeAddr> = endpoint.remote_info_iter().map(Into::into).collect();
2427        assert_eq!(node_addrs.len(), 1);
2428        assert_eq!(node_addrs[0], node_addr);
2429
2430        info!("closing endpoint");
2431        // close the endpoint and restart it
2432        endpoint.close().await;
2433
2434        info!("restarting endpoint");
2435        // now restart it and check the addressing info of the peer
2436        let endpoint = new_endpoint(secret_key, Some(node_addrs)).await?;
2437        let RemoteInfo { mut addrs, .. } = endpoint.remote_info(peer_id).e()?;
2438        let conn_addr = addrs.pop().unwrap().addr;
2439        assert_eq!(conn_addr, direct_addr);
2440        Ok(())
2441    }
2442
2443    #[tokio::test]
2444    #[traced_test]
2445    async fn endpoint_relay_connect_loop() -> Result {
2446        let test_start = Instant::now();
2447        let n_clients = 5;
2448        let n_chunks_per_client = 2;
2449        let chunk_size = 10;
2450        let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(42);
2451        let (relay_map, relay_url, _relay_guard) = run_relay_server().await.unwrap();
2452        let server_secret_key = SecretKey::generate(&mut rng);
2453        let server_node_id = server_secret_key.public();
2454
2455        // Make sure the server is bound before having clients connect to it:
2456        let ep = Endpoint::builder()
2457            .insecure_skip_relay_cert_verify(true)
2458            .secret_key(server_secret_key)
2459            .alpns(vec![TEST_ALPN.to_vec()])
2460            .relay_mode(RelayMode::Custom(relay_map.clone()))
2461            .bind()
2462            .await?;
2463        // Also make sure the server has a working relay connection
2464        ep.home_relay().initialized().await;
2465
2466        info!(time = ?test_start.elapsed(), "test setup done");
2467
2468        // The server accepts the connections of the clients sequentially.
2469        let server = tokio::spawn(
2470            async move {
2471                let eps = ep.bound_sockets();
2472
2473                info!(me = %ep.node_id().fmt_short(), eps = ?eps, "server listening on");
2474                for i in 0..n_clients {
2475                    let round_start = Instant::now();
2476                    info!("[server] round {i}");
2477                    let incoming = ep.accept().await.e()?;
2478                    let conn = incoming.await.e()?;
2479                    let node_id = conn.remote_node_id()?;
2480                    info!(%i, peer = %node_id.fmt_short(), "accepted connection");
2481                    let (mut send, mut recv) = conn.accept_bi().await.e()?;
2482                    let mut buf = vec![0u8; chunk_size];
2483                    for _i in 0..n_chunks_per_client {
2484                        recv.read_exact(&mut buf).await.e()?;
2485                        send.write_all(&buf).await.e()?;
2486                    }
2487                    send.finish().e()?;
2488                    conn.closed().await; // we're the last to send data, so we wait for the other side to close
2489                    info!(%i, peer = %node_id.fmt_short(), "finished");
2490                    info!("[server] round {i} done in {:?}", round_start.elapsed());
2491                }
2492                Ok::<_, Error>(())
2493            }
2494            .instrument(error_span!("server")),
2495        );
2496
2497        let start = Instant::now();
2498
2499        for i in 0..n_clients {
2500            let round_start = Instant::now();
2501            info!("[client] round {i}");
2502            let client_secret_key = SecretKey::generate(&mut rng);
2503            async {
2504                info!("client binding");
2505                let ep = Endpoint::builder()
2506                    .alpns(vec![TEST_ALPN.to_vec()])
2507                    .insecure_skip_relay_cert_verify(true)
2508                    .relay_mode(RelayMode::Custom(relay_map.clone()))
2509                    .secret_key(client_secret_key)
2510                    .bind()
2511                    .await?;
2512                let eps = ep.bound_sockets();
2513
2514                info!(me = %ep.node_id().fmt_short(), eps=?eps, "client bound");
2515                let node_addr = NodeAddr::new(server_node_id).with_relay_url(relay_url.clone());
2516                info!(to = ?node_addr, "client connecting");
2517                let conn = ep.connect(node_addr, TEST_ALPN).await.e()?;
2518                info!("client connected");
2519                let (mut send, mut recv) = conn.open_bi().await.e()?;
2520
2521                for i in 0..n_chunks_per_client {
2522                    let mut buf = vec![i; chunk_size];
2523                    send.write_all(&buf).await.e()?;
2524                    recv.read_exact(&mut buf).await.e()?;
2525                    assert_eq!(buf, vec![i; chunk_size]);
2526                }
2527                // we're the last to receive data, so we close
2528                conn.close(0u32.into(), b"bye!");
2529                info!("client finished");
2530                ep.close().await;
2531                info!("client closed");
2532                Ok::<_, Error>(())
2533            }
2534            .instrument(error_span!("client", %i))
2535            .await?;
2536            info!("[client] round {i} done in {:?}", round_start.elapsed());
2537        }
2538
2539        server.await.e()??;
2540
2541        // We appear to have seen this being very slow at times.  So ensure we fail if this
2542        // test is too slow.  We're only making two connections transferring very little
2543        // data, this really shouldn't take long.
2544        if start.elapsed() > Duration::from_secs(15) {
2545            panic!("Test too slow, something went wrong");
2546        }
2547
2548        Ok(())
2549    }
2550
2551    #[tokio::test]
2552    #[traced_test]
2553    async fn endpoint_send_relay() -> Result {
2554        let (relay_map, _relay_url, _guard) = run_relay_server().await?;
2555        let client = Endpoint::builder()
2556            .insecure_skip_relay_cert_verify(true)
2557            .relay_mode(RelayMode::Custom(relay_map.clone()))
2558            .bind()
2559            .await?;
2560        let server = Endpoint::builder()
2561            .insecure_skip_relay_cert_verify(true)
2562            .relay_mode(RelayMode::Custom(relay_map))
2563            .alpns(vec![TEST_ALPN.to_vec()])
2564            .bind()
2565            .await?;
2566
2567        let task = tokio::spawn({
2568            let server = server.clone();
2569            async move {
2570                let Some(conn) = server.accept().await else {
2571                    snafu::whatever!("Expected an incoming connection");
2572                };
2573                let conn = conn.await.e()?;
2574                let (mut send, mut recv) = conn.accept_bi().await.e()?;
2575                let data = recv.read_to_end(1000).await.e()?;
2576                send.write_all(&data).await.e()?;
2577                send.finish().e()?;
2578                conn.closed().await;
2579
2580                Ok::<_, Error>(())
2581            }
2582        });
2583
2584        let addr = server.node_addr().initialized().await;
2585        let conn = client.connect(addr, TEST_ALPN).await?;
2586        let (mut send, mut recv) = conn.open_bi().await.e()?;
2587        send.write_all(b"Hello, world!").await.e()?;
2588        send.finish().e()?;
2589        let data = recv.read_to_end(1000).await.e()?;
2590        conn.close(0u32.into(), b"bye!");
2591
2592        task.await.e()??;
2593
2594        client.close().await;
2595        server.close().await;
2596
2597        assert_eq!(&data, b"Hello, world!");
2598
2599        Ok(())
2600    }
2601
2602    #[tokio::test]
2603    #[traced_test]
2604    async fn endpoint_bidi_send_recv() -> Result {
2605        let ep1 = Endpoint::builder()
2606            .alpns(vec![TEST_ALPN.to_vec()])
2607            .relay_mode(RelayMode::Disabled);
2608
2609        let ep1 = ep1.bind().await?;
2610        let ep2 = Endpoint::builder()
2611            .alpns(vec![TEST_ALPN.to_vec()])
2612            .relay_mode(RelayMode::Disabled);
2613
2614        let ep2 = ep2.bind().await?;
2615
2616        let ep1_nodeaddr = ep1.node_addr().initialized().await;
2617        let ep2_nodeaddr = ep2.node_addr().initialized().await;
2618        ep1.add_node_addr(ep2_nodeaddr.clone())?;
2619        ep2.add_node_addr(ep1_nodeaddr.clone())?;
2620        let ep1_nodeid = ep1.node_id();
2621        let ep2_nodeid = ep2.node_id();
2622        eprintln!("node id 1 {ep1_nodeid}");
2623        eprintln!("node id 2 {ep2_nodeid}");
2624
2625        async fn connect_hello(ep: Endpoint, dst: NodeAddr) -> Result {
2626            let conn = ep.connect(dst, TEST_ALPN).await?;
2627            let (mut send, mut recv) = conn.open_bi().await.e()?;
2628            info!("sending hello");
2629            send.write_all(b"hello").await.e()?;
2630            send.finish().e()?;
2631            info!("receiving world");
2632            let m = recv.read_to_end(100).await.e()?;
2633            assert_eq!(m, b"world");
2634            conn.close(1u8.into(), b"done");
2635            Ok(())
2636        }
2637
2638        async fn accept_world(ep: Endpoint, src: NodeId) -> Result {
2639            let incoming = ep.accept().await.e()?;
2640            let mut iconn = incoming.accept().e()?;
2641            let alpn = iconn.alpn().await?;
2642            let conn = iconn.await.e()?;
2643            let node_id = conn.remote_node_id()?;
2644            assert_eq!(node_id, src);
2645            assert_eq!(alpn, TEST_ALPN);
2646            let (mut send, mut recv) = conn.accept_bi().await.e()?;
2647            info!("receiving hello");
2648            let m = recv.read_to_end(100).await.e()?;
2649            assert_eq!(m, b"hello");
2650            info!("sending hello");
2651            send.write_all(b"world").await.e()?;
2652            send.finish().e()?;
2653            match conn.closed().await {
2654                ConnectionError::ApplicationClosed(closed) => {
2655                    assert_eq!(closed.error_code, 1u8.into());
2656                    Ok(())
2657                }
2658                _ => panic!("wrong close error"),
2659            }
2660        }
2661
2662        let p1_accept = tokio::spawn(accept_world(ep1.clone(), ep2_nodeid).instrument(info_span!(
2663            "p1_accept",
2664            ep1 = %ep1.node_id().fmt_short(),
2665            dst = %ep2_nodeid.fmt_short(),
2666        )));
2667        let p2_accept = tokio::spawn(accept_world(ep2.clone(), ep1_nodeid).instrument(info_span!(
2668            "p2_accept",
2669            ep2 = %ep2.node_id().fmt_short(),
2670            dst = %ep1_nodeid.fmt_short(),
2671        )));
2672        let p1_connect = tokio::spawn(connect_hello(ep1.clone(), ep2_nodeaddr).instrument(
2673            info_span!(
2674                "p1_connect",
2675                ep1 = %ep1.node_id().fmt_short(),
2676                dst = %ep2_nodeid.fmt_short(),
2677            ),
2678        ));
2679        let p2_connect = tokio::spawn(connect_hello(ep2.clone(), ep1_nodeaddr).instrument(
2680            info_span!(
2681                "p2_connect",
2682                ep2 = %ep2.node_id().fmt_short(),
2683                dst = %ep1_nodeid.fmt_short(),
2684            ),
2685        ));
2686
2687        p1_accept.await.e()??;
2688        p2_accept.await.e()??;
2689        p1_connect.await.e()??;
2690        p2_connect.await.e()??;
2691
2692        Ok(())
2693    }
2694
2695    #[tokio::test]
2696    #[traced_test]
2697    async fn endpoint_conn_type_becomes_direct() -> Result {
2698        const TIMEOUT: Duration = std::time::Duration::from_secs(15);
2699        let (relay_map, _relay_url, _relay_guard) = run_relay_server().await?;
2700        let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(42);
2701        let ep1_secret_key = SecretKey::generate(&mut rng);
2702        let ep2_secret_key = SecretKey::generate(&mut rng);
2703        let ep1 = Endpoint::builder()
2704            .secret_key(ep1_secret_key)
2705            .insecure_skip_relay_cert_verify(true)
2706            .alpns(vec![TEST_ALPN.to_vec()])
2707            .relay_mode(RelayMode::Custom(relay_map.clone()))
2708            .bind()
2709            .await?;
2710        let ep2 = Endpoint::builder()
2711            .secret_key(ep2_secret_key)
2712            .insecure_skip_relay_cert_verify(true)
2713            .alpns(vec![TEST_ALPN.to_vec()])
2714            .relay_mode(RelayMode::Custom(relay_map))
2715            .bind()
2716            .await?;
2717
2718        async fn wait_for_conn_type_direct(ep: &Endpoint, node_id: NodeId) -> Result {
2719            let mut stream = ep.conn_type(node_id).expect("connection exists").stream();
2720            let src = ep.node_id().fmt_short();
2721            let dst = node_id.fmt_short();
2722            while let Some(conn_type) = stream.next().await {
2723                tracing::info!(me = %src, dst = %dst, conn_type = ?conn_type);
2724                if matches!(conn_type, ConnectionType::Direct(_)) {
2725                    return Ok(());
2726                }
2727            }
2728            snafu::whatever!("conn_type stream ended before `ConnectionType::Direct`");
2729        }
2730
2731        async fn accept(ep: &Endpoint) -> Result<Connection> {
2732            let incoming = ep.accept().await.expect("ep closed");
2733            let conn = incoming.await.e()?;
2734            let node_id = conn.remote_node_id()?;
2735            tracing::info!(node_id=%node_id.fmt_short(), "accepted connection");
2736            Ok(conn)
2737        }
2738
2739        let ep1_nodeid = ep1.node_id();
2740        let ep2_nodeid = ep2.node_id();
2741
2742        let ep1_nodeaddr = ep1.node_addr().initialized().await;
2743        tracing::info!(
2744            "node id 1 {ep1_nodeid}, relay URL {:?}",
2745            ep1_nodeaddr.relay_url()
2746        );
2747        tracing::info!("node id 2 {ep2_nodeid}");
2748
2749        let ep1_side = tokio::time::timeout(TIMEOUT, async move {
2750            let conn = accept(&ep1).await?;
2751            let mut send = conn.open_uni().await.e()?;
2752            wait_for_conn_type_direct(&ep1, ep2_nodeid).await?;
2753            send.write_all(b"Conn is direct").await.e()?;
2754            send.finish().e()?;
2755            conn.closed().await;
2756            Ok::<(), Error>(())
2757        });
2758
2759        let ep2_side = tokio::time::timeout(TIMEOUT, async move {
2760            let conn = ep2.connect(ep1_nodeaddr, TEST_ALPN).await?;
2761            let mut recv = conn.accept_uni().await.e()?;
2762            wait_for_conn_type_direct(&ep2, ep1_nodeid).await?;
2763            let read = recv.read_to_end(100).await.e()?;
2764            assert_eq!(read, b"Conn is direct".to_vec());
2765            conn.close(0u32.into(), b"done");
2766            conn.closed().await;
2767            Ok::<(), Error>(())
2768        });
2769
2770        let res_ep1 = AbortOnDropHandle::new(tokio::spawn(ep1_side));
2771        let res_ep2 = AbortOnDropHandle::new(tokio::spawn(ep2_side));
2772
2773        let (r1, r2) = tokio::try_join!(res_ep1, res_ep2).e()?;
2774        r1.e()??;
2775        r2.e()??;
2776
2777        Ok(())
2778    }
2779
2780    #[tokio::test]
2781    #[traced_test]
2782    async fn test_direct_addresses_no_qad_relay() -> Result {
2783        let (relay_map, _, _guard) = run_relay_server_with(false).await.unwrap();
2784
2785        let ep = Endpoint::builder()
2786            .alpns(vec![TEST_ALPN.to_vec()])
2787            .relay_mode(RelayMode::Custom(relay_map))
2788            .insecure_skip_relay_cert_verify(true)
2789            .bind()
2790            .await?;
2791
2792        tokio::time::timeout(Duration::from_secs(10), ep.direct_addresses().initialized())
2793            .await
2794            .e()?;
2795        Ok(())
2796    }
2797
2798    async fn spawn_0rtt_server(secret_key: SecretKey, log_span: tracing::Span) -> Result<Endpoint> {
2799        let server = Endpoint::builder()
2800            .secret_key(secret_key)
2801            .alpns(vec![TEST_ALPN.to_vec()])
2802            .relay_mode(RelayMode::Disabled)
2803            .bind()
2804            .await?;
2805
2806        // Gets aborted via the endpoint closing causing an `Err`
2807        // a simple echo server
2808        tokio::spawn({
2809            let server = server.clone();
2810            async move {
2811                while let Some(incoming) = server.accept().await {
2812                    let connecting = incoming.accept().e()?;
2813                    let conn = match connecting.into_0rtt() {
2814                        Ok((conn, _)) => {
2815                            info!("0rtt accepted");
2816                            conn
2817                        }
2818                        Err(connecting) => {
2819                            info!("0rtt denied");
2820                            connecting.await.e()?
2821                        }
2822                    };
2823                    let (mut send, mut recv) = conn.accept_bi().await.e()?;
2824                    let data = recv.read_to_end(10_000_000).await.e()?;
2825                    send.write_all(&data).await.e()?;
2826                    send.finish().e()?;
2827
2828                    // Stay alive until the other side closes the connection.
2829                    conn.closed().await;
2830                }
2831                Ok::<_, Error>(())
2832            }
2833            .instrument(log_span)
2834        });
2835
2836        Ok(server)
2837    }
2838
2839    async fn connect_client_0rtt_expect_err(client: &Endpoint, server_addr: NodeAddr) -> Result {
2840        let conn = client
2841            .connect_with_opts(server_addr, TEST_ALPN, ConnectOptions::new())
2842            .await?
2843            .into_0rtt()
2844            .expect_err("expected 0rtt to fail")
2845            .await
2846            .e()?;
2847
2848        let (mut send, mut recv) = conn.open_bi().await.e()?;
2849        send.write_all(b"hello").await.e()?;
2850        send.finish().e()?;
2851        let received = recv.read_to_end(1_000).await.e()?;
2852        assert_eq!(&received, b"hello");
2853        conn.close(0u32.into(), b"thx");
2854        Ok(())
2855    }
2856
2857    async fn connect_client_0rtt_expect_ok(
2858        client: &Endpoint,
2859        server_addr: NodeAddr,
2860        expect_server_accepts: bool,
2861    ) -> Result {
2862        let (conn, accepted_0rtt) = client
2863            .connect_with_opts(server_addr, TEST_ALPN, ConnectOptions::new())
2864            .await?
2865            .into_0rtt()
2866            .ok()
2867            .e()?;
2868
2869        // This is how we send data in 0-RTT:
2870        let (mut send, recv) = conn.open_bi().await.e()?;
2871        send.write_all(b"hello").await.e()?;
2872        send.finish().e()?;
2873        // When this resolves, we've gotten a response from the server about whether the 0-RTT data above was accepted:
2874        let accepted = accepted_0rtt.await;
2875        assert_eq!(accepted, expect_server_accepts);
2876        let mut recv = if accepted {
2877            recv
2878        } else {
2879            // in this case we need to re-send data by re-creating the connection.
2880            let (mut send, recv) = conn.open_bi().await.e()?;
2881            send.write_all(b"hello").await.e()?;
2882            send.finish().e()?;
2883            recv
2884        };
2885        let received = recv.read_to_end(1_000).await.e()?;
2886        assert_eq!(&received, b"hello");
2887        conn.close(0u32.into(), b"thx");
2888        Ok(())
2889    }
2890
2891    #[tokio::test]
2892    #[traced_test]
2893    async fn test_0rtt() -> Result {
2894        let client = Endpoint::builder()
2895            .relay_mode(RelayMode::Disabled)
2896            .bind()
2897            .await?;
2898        let server = spawn_0rtt_server(
2899            SecretKey::generate(rand::thread_rng()),
2900            info_span!("server"),
2901        )
2902        .await?;
2903
2904        connect_client_0rtt_expect_err(&client, server.node_addr().initialized().await).await?;
2905        // The second 0rtt attempt should work
2906        connect_client_0rtt_expect_ok(&client, server.node_addr().initialized().await, true)
2907            .await?;
2908
2909        client.close().await;
2910        server.close().await;
2911
2912        Ok(())
2913    }
2914
2915    // We have this test, as this would've failed at some point.
2916    // This effectively tests that we correctly categorize the TLS session tickets we
2917    // receive into the respective "bucket" for the recipient.
2918    #[tokio::test]
2919    #[traced_test]
2920    async fn test_0rtt_non_consecutive() -> Result {
2921        let client = Endpoint::builder()
2922            .relay_mode(RelayMode::Disabled)
2923            .bind()
2924            .await?;
2925        let server = spawn_0rtt_server(
2926            SecretKey::generate(rand::thread_rng()),
2927            info_span!("server"),
2928        )
2929        .await?;
2930
2931        connect_client_0rtt_expect_err(&client, server.node_addr().initialized().await).await?;
2932
2933        // connecting with another endpoint should not interfere with our
2934        // TLS session ticket cache for the first endpoint:
2935        let another = spawn_0rtt_server(
2936            SecretKey::generate(rand::thread_rng()),
2937            info_span!("another"),
2938        )
2939        .await?;
2940        connect_client_0rtt_expect_err(&client, another.node_addr().initialized().await).await?;
2941        another.close().await;
2942
2943        connect_client_0rtt_expect_ok(&client, server.node_addr().initialized().await, true)
2944            .await?;
2945
2946        client.close().await;
2947        server.close().await;
2948
2949        Ok(())
2950    }
2951
2952    // Test whether 0-RTT is possible after a restart:
2953    #[tokio::test]
2954    #[traced_test]
2955    async fn test_0rtt_after_server_restart() -> Result {
2956        let client = Endpoint::builder()
2957            .relay_mode(RelayMode::Disabled)
2958            .bind()
2959            .await?;
2960        let server_key = SecretKey::generate(rand::thread_rng());
2961        let server = spawn_0rtt_server(server_key.clone(), info_span!("server-initial")).await?;
2962
2963        connect_client_0rtt_expect_err(&client, server.node_addr().initialized().await).await?;
2964        connect_client_0rtt_expect_ok(&client, server.node_addr().initialized().await, true)
2965            .await?;
2966
2967        server.close().await;
2968
2969        let server = spawn_0rtt_server(server_key, info_span!("server-restart")).await?;
2970
2971        // we expect the client to *believe* it can 0-RTT connect to the server (hence expect_ok),
2972        // but the server will reject the early data because it discarded necessary state
2973        // to decrypt it when restarting.
2974        connect_client_0rtt_expect_ok(&client, server.node_addr().initialized().await, false)
2975            .await?;
2976
2977        client.close().await;
2978
2979        Ok(())
2980    }
2981
2982    #[cfg_attr(target_os = "windows", ignore = "flaky")]
2983    #[tokio::test]
2984    #[traced_test]
2985    async fn graceful_close() -> Result {
2986        let client = Endpoint::builder().bind().await?;
2987        let server = Endpoint::builder()
2988            .alpns(vec![TEST_ALPN.to_vec()])
2989            .bind()
2990            .await?;
2991        let server_addr = server.node_addr().initialized().await;
2992        let server_task = tokio::spawn(async move {
2993            let incoming = server.accept().await.e()?;
2994            let conn = incoming.await.e()?;
2995            let (mut send, mut recv) = conn.accept_bi().await.e()?;
2996            let msg = recv.read_to_end(1_000).await.e()?;
2997            send.write_all(&msg).await.e()?;
2998            send.finish().e()?;
2999            let close_reason = conn.closed().await;
3000            Ok::<_, Error>(close_reason)
3001        });
3002
3003        let conn = client.connect(server_addr, TEST_ALPN).await?;
3004        let (mut send, mut recv) = conn.open_bi().await.e()?;
3005        send.write_all(b"Hello, world!").await.e()?;
3006        send.finish().e()?;
3007        recv.read_to_end(1_000).await.e()?;
3008        conn.close(42u32.into(), b"thanks, bye!");
3009        client.close().await;
3010
3011        let close_err = server_task.await.e()??;
3012        let ConnectionError::ApplicationClosed(app_close) = close_err else {
3013            panic!("Unexpected close reason: {close_err:?}");
3014        };
3015
3016        assert_eq!(app_close.error_code, 42u32.into());
3017        assert_eq!(app_close.reason.as_ref(), b"thanks, bye!");
3018
3019        Ok(())
3020    }
3021
3022    #[cfg(feature = "metrics")]
3023    #[tokio::test]
3024    #[traced_test]
3025    async fn metrics_smoke() -> Result {
3026        use iroh_metrics::{MetricsSource, Registry};
3027
3028        let secret_key = SecretKey::from_bytes(&[0u8; 32]);
3029        let client = Endpoint::builder()
3030            .secret_key(secret_key)
3031            .relay_mode(RelayMode::Disabled)
3032            .bind()
3033            .await?;
3034        let secret_key = SecretKey::from_bytes(&[1u8; 32]);
3035        let server = Endpoint::builder()
3036            .secret_key(secret_key)
3037            .relay_mode(RelayMode::Disabled)
3038            .alpns(vec![TEST_ALPN.to_vec()])
3039            .bind()
3040            .await?;
3041        let server_addr = server.node_addr().initialized().await;
3042        let server_task = tokio::task::spawn(async move {
3043            let conn = server.accept().await.e()?.accept().e()?.await.e()?;
3044            let mut uni = conn.accept_uni().await.e()?;
3045            uni.read_to_end(10).await.e()?;
3046            drop(conn);
3047            Ok::<_, Error>(server)
3048        });
3049        let conn = client.connect(server_addr, TEST_ALPN).await?;
3050        let mut uni = conn.open_uni().await.e()?;
3051        uni.write_all(b"helloworld").await.e()?;
3052        uni.finish().e()?;
3053        conn.closed().await;
3054        drop(conn);
3055        let server = server_task.await.e()??;
3056
3057        let m = client.metrics();
3058        assert_eq!(m.magicsock.num_direct_conns_added.get(), 1);
3059        assert_eq!(m.magicsock.connection_became_direct.get(), 1);
3060        assert_eq!(m.magicsock.connection_handshake_success.get(), 1);
3061        assert_eq!(m.magicsock.nodes_contacted_directly.get(), 1);
3062        assert!(m.magicsock.recv_datagrams.get() > 0);
3063
3064        let m = server.metrics();
3065        assert_eq!(m.magicsock.num_direct_conns_added.get(), 1);
3066        assert_eq!(m.magicsock.connection_became_direct.get(), 1);
3067        assert_eq!(m.magicsock.nodes_contacted_directly.get(), 1);
3068        assert_eq!(m.magicsock.connection_handshake_success.get(), 1);
3069        assert!(m.magicsock.recv_datagrams.get() > 0);
3070
3071        // test openmetrics encoding with labeled subregistries per endpoint
3072        fn register_endpoint(registry: &mut Registry, endpoint: &Endpoint) {
3073            let id = endpoint.node_id().fmt_short();
3074            let sub_registry = registry.sub_registry_with_label("id", id);
3075            sub_registry.register_all(endpoint.metrics());
3076        }
3077        let mut registry = Registry::default();
3078        register_endpoint(&mut registry, &client);
3079        register_endpoint(&mut registry, &server);
3080        let s = registry.encode_openmetrics_to_string()?;
3081        assert!(s.contains(r#"magicsock_nodes_contacted_directly_total{id="3b6a27bcce"} 1"#));
3082        assert!(s.contains(r#"magicsock_nodes_contacted_directly_total{id="8a88e3dd74"} 1"#));
3083        Ok(())
3084    }
3085
3086    /// Configures the accept side to take `accept_alpns` ALPNs, then connects to it with `primary_connect_alpn`
3087    /// with `secondary_connect_alpns` set, and finally returns the negotiated ALPN.
3088    async fn alpn_connection_test(
3089        accept_alpns: Vec<Vec<u8>>,
3090        primary_connect_alpn: &[u8],
3091        secondary_connect_alpns: Vec<Vec<u8>>,
3092    ) -> Result<Option<Vec<u8>>> {
3093        let client = Endpoint::builder()
3094            .relay_mode(RelayMode::Disabled)
3095            .bind()
3096            .await?;
3097        let server = Endpoint::builder()
3098            .relay_mode(RelayMode::Disabled)
3099            .alpns(accept_alpns)
3100            .bind()
3101            .await?;
3102        let server_addr = server.node_addr().initialized().await;
3103        let server_task = tokio::spawn({
3104            let server = server.clone();
3105            async move {
3106                let incoming = server.accept().await.e()?;
3107                let conn = incoming.await.e()?;
3108                conn.close(0u32.into(), b"bye!");
3109                Ok::<_, n0_snafu::Error>(conn.alpn())
3110            }
3111        });
3112
3113        let conn = client
3114            .connect_with_opts(
3115                server_addr,
3116                primary_connect_alpn,
3117                ConnectOptions::new().with_additional_alpns(secondary_connect_alpns),
3118            )
3119            .await?;
3120        let conn = conn.await.e()?;
3121        let client_alpn = conn.alpn();
3122        conn.closed().await;
3123        client.close().await;
3124        server.close().await;
3125
3126        let server_alpn = server_task.await.e()??;
3127
3128        assert_eq!(client_alpn, server_alpn);
3129
3130        Ok(server_alpn)
3131    }
3132
3133    #[tokio::test]
3134    #[traced_test]
3135    async fn connect_multiple_alpn_negotiated() -> Result {
3136        const ALPN_ONE: &[u8] = b"alpn/1";
3137        const ALPN_TWO: &[u8] = b"alpn/2";
3138
3139        assert_eq!(
3140            alpn_connection_test(
3141                // Prefer version 2 over version 1 on the accept side
3142                vec![ALPN_TWO.to_vec(), ALPN_ONE.to_vec()],
3143                ALPN_TWO,
3144                vec![ALPN_ONE.to_vec()],
3145            )
3146            .await?,
3147            Some(ALPN_TWO.to_vec()),
3148            "accept side prefers version 2 over 1"
3149        );
3150
3151        assert_eq!(
3152            alpn_connection_test(
3153                // Only support the old version
3154                vec![ALPN_ONE.to_vec()],
3155                ALPN_TWO,
3156                vec![ALPN_ONE.to_vec()],
3157            )
3158            .await?,
3159            Some(ALPN_ONE.to_vec()),
3160            "accept side only supports the old version"
3161        );
3162
3163        assert_eq!(
3164            alpn_connection_test(
3165                vec![ALPN_TWO.to_vec(), ALPN_ONE.to_vec()],
3166                ALPN_ONE,
3167                vec![ALPN_TWO.to_vec()],
3168            )
3169            .await?,
3170            Some(ALPN_TWO.to_vec()),
3171            "connect side ALPN order doesn't matter"
3172        );
3173
3174        assert_eq!(
3175            alpn_connection_test(vec![ALPN_TWO.to_vec(), ALPN_ONE.to_vec()], ALPN_ONE, vec![],)
3176                .await?,
3177            Some(ALPN_ONE.to_vec()),
3178            "connect side only supports the old version"
3179        );
3180
3181        Ok(())
3182    }
3183
3184    #[tokio::test]
3185    #[traced_test]
3186    async fn watch_net_report() -> Result {
3187        let endpoint = Endpoint::builder()
3188            .relay_mode(RelayMode::Staging)
3189            .bind()
3190            .await?;
3191
3192        // can get a first report
3193        endpoint.net_report().updated().await?;
3194
3195        Ok(())
3196    }
3197}