iroh/endpoint/
connection.rs

1//! The [`Connection`] wraps a `noq::Connection`.
2//!
3//! The [`Connection`] is how you send data to and receive data from the remote endpoint.
4//!
5//! There are many transitions states between attempting to start a connection and
6//! receiving a cryptographically secure connection.
7//!
8//! The main items in this module are:
9//!
10//! - [`Connection`] to create streams to talk to a remote endpoint.
11//! - [`Connecting`] for operating on connections that haven't finished their handshake yet.
12//! - [`Incoming`] to accept or reject an incoming connection.
13//! - [`OutgoingZeroRttConnection`] to attempt to send 0-RTT data before the cryptographic
14//!   handshake has completed.
15//! - [`IncomingZeroRttConnection`] to attempt to read 0-RTT or send 0.5-RTT data before the cryptographic
16//!   handshake has completed.
17//!
18//! [module docs]: crate
19use std::{
20    any::Any,
21    future::{Future, IntoFuture},
22    net::SocketAddr,
23    pin::Pin,
24    sync::Arc,
25    task::Poll,
26};
27
28use bytes::Bytes;
29use ed25519_dalek::{VerifyingKey, pkcs8::DecodePublicKey};
30use futures_util::{FutureExt, future::Shared};
31use iroh_base::{EndpointId, RelayUrl};
32use n0_error::{e, stack_error};
33use n0_future::{TryFutureExt, future::Boxed as BoxFuture, time::Duration};
34use noq::WeakConnectionHandle as NoqWeakConnectionHandle;
35use pin_project::pin_project;
36use tracing::{error, event, warn};
37
38use super::quic::DecryptedInitial;
39use crate::{
40    Endpoint,
41    endpoint::{
42        AfterHandshakeOutcome,
43        quic::{
44            AcceptBi, AcceptUni, Closed, ConnectionError, ConnectionStats, Controller,
45            ExportKeyingMaterialError, OpenBi, OpenUni, PathId, ReadDatagram, ReadManyDatagrams,
46            SendDatagram, SendDatagramError, ServerConfig, Side, VarInt,
47        },
48    },
49    socket::{
50        RemoteStateActorStoppedError,
51        remote_map::{PathEventStream, PathList, PathListStream, PathStateReceiver},
52        transports::{self, LocalTransportAddr},
53    },
54};
55
56/// The remote address for an incoming connection.
57///
58/// When the incoming connection is a direct connection, this is a SocketAddr.
59/// When it is a relay connection, we know both the relay URL and the endpoint ID.
60#[derive(Debug, Clone, PartialEq, Eq)]
61#[non_exhaustive]
62pub enum IncomingAddr {
63    /// A direct connection from an IP address.
64    Ip(SocketAddr),
65    /// A connection via a relay.
66    Relay {
67        /// The URL of the relay.
68        url: RelayUrl,
69        /// The endpoint ID of the remote peer.
70        endpoint_id: EndpointId,
71    },
72    /// A connection via a custom transport.
73    Custom(iroh_base::CustomAddr),
74}
75
76impl From<IncomingAddr> for iroh_base::TransportAddr {
77    fn from(addr: IncomingAddr) -> Self {
78        match addr {
79            IncomingAddr::Ip(addr) => Self::Ip(addr),
80            IncomingAddr::Relay { url, .. } => Self::Relay(url),
81            IncomingAddr::Custom(addr) => Self::Custom(addr),
82        }
83    }
84}
85
86impl From<transports::Addr> for IncomingAddr {
87    fn from(addr: transports::Addr) -> Self {
88        match addr {
89            transports::Addr::Ip(addr) => Self::Ip(addr),
90            transports::Addr::Relay(url, endpoint_id) => Self::Relay { url, endpoint_id },
91            transports::Addr::Custom(addr) => Self::Custom(addr),
92        }
93    }
94}
95
96/// Future produced by [`Endpoint::accept`].
97#[derive(derive_more::Debug)]
98#[pin_project]
99pub struct Accept<'a> {
100    #[pin]
101    #[debug("noq::Accept")]
102    pub(crate) inner: noq::Accept<'a>,
103    pub(crate) ep: Endpoint,
104}
105
106impl Future for Accept<'_> {
107    type Output = Option<Incoming>;
108
109    fn poll(self: Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> Poll<Self::Output> {
110        let this = self.project();
111        match this.inner.poll(cx) {
112            Poll::Pending => Poll::Pending,
113            Poll::Ready(None) => Poll::Ready(None),
114            Poll::Ready(Some(inner)) => {
115                let incoming = Incoming {
116                    inner,
117                    ep: this.ep.clone(),
118                };
119                event!(
120                    target: "iroh::_events::conn::incoming",
121                    tracing::Level::DEBUG,
122                    remote_addr = ?incoming.remote_addr(),
123                );
124                Poll::Ready(Some(incoming))
125            }
126        }
127    }
128}
129
130/// An incoming connection for which the server has not yet begun its parts of the
131/// handshake.
132#[derive(Debug)]
133pub struct Incoming {
134    inner: noq::Incoming,
135    ep: Endpoint,
136}
137
138impl Incoming {
139    /// Attempts to accept this incoming connection (an error may still occur).
140    ///
141    /// Errors occurring here are likely not caused by the application or remote.  The QUIC
142    /// connection listens on a normal UDP socket and any reachable network endpoint can
143    /// send datagrams to it, solicited or not.  Even if the first few bytes look like a
144    /// QUIC packet, it might not even be a QUIC packet that is being received.
145    ///
146    /// Thus it is common to simply log the errors here and accept them as something which
147    /// can happen.
148    pub fn accept(self) -> Result<Accepting, ConnectionError> {
149        self.inner
150            .accept()
151            .map(|conn| Accepting::new(conn, self.ep))
152    }
153
154    /// Accepts this incoming connection using a custom configuration.
155    ///
156    /// Use the [`Endpoint::create_server_config_builder`] method to create a [`ServerConfigBuilder`]
157    /// to customize a [`ServerConfig`].
158    ///
159    /// See [`accept()`] for more details.
160    ///
161    /// [`accept()`]: Incoming::accept
162    /// [`Endpoint::create_server_config_builder`]: crate::Endpoint::create_server_config_builder
163    /// [`ServerConfigBuilder`]: crate::endpoint::ServerConfigBuilder
164    /// [`ServerConfig`]: crate::endpoint::ServerConfig
165    pub fn accept_with(
166        self,
167        server_config: Arc<ServerConfig>,
168    ) -> Result<Accepting, ConnectionError> {
169        self.inner
170            .accept_with(server_config.to_inner_arc())
171            .map(|conn| Accepting::new(conn, self.ep))
172    }
173
174    /// Rejects this incoming connection attempt.
175    pub fn refuse(self) {
176        self.inner.refuse()
177    }
178
179    /// Responds with a retry packet.
180    ///
181    /// This requires the client to retry with address validation.
182    ///
183    /// Errors if `remote_address_validated()` is true.
184    #[allow(clippy::result_large_err)]
185    pub fn retry(self) -> Result<(), RetryError> {
186        self.inner
187            .retry()
188            .map_err(|err| e!(RetryError { err, ep: self.ep }))
189    }
190
191    /// Ignores this incoming connection attempt, not sending any packet in response.
192    pub fn ignore(self) {
193        self.inner.ignore()
194    }
195
196    /// Returns the local address that received this incoming connection.
197    pub fn local_addr(&self) -> LocalTransportAddr {
198        let remote_addr = self.inner.remote_address();
199        let local_ip = self.inner.local_ip();
200        self.ep.inner.to_local_transport_addr(local_ip, remote_addr)
201    }
202
203    /// Returns the remote address of this incoming connection.
204    pub fn remote_addr(&self) -> IncomingAddr {
205        let remote = self.inner.remote_address();
206        self.ep
207            .to_transport_addr(remote)
208            .unwrap_or_else(|| {
209                error!(mapped_addr = ?remote, "Incoming::remote_addr: invalid mapped address");
210                transports::Addr::Ip(remote)
211            })
212            .into()
213    }
214
215    /// Whether the socket address that is initiating this connection has been validated.
216    ///
217    /// This means that the sender of the initial packet has proved that they can receive
218    /// traffic sent to `self.remote_addr()`.
219    pub fn remote_addr_validated(&self) -> bool {
220        self.inner.remote_address_validated()
221    }
222
223    /// Decrypts the Initial packet payload.
224    ///
225    /// This clones and decrypts the packet payload (~1200 bytes).
226    /// Can be used to extract information from the TLS ClientHello without completing the handshake.
227    pub fn decrypt(&self) -> Option<DecryptedInitial> {
228        self.inner.decrypt()
229    }
230}
231
232impl IntoFuture for Incoming {
233    type Output = Result<Connection, ConnectingError>;
234    type IntoFuture = IncomingFuture;
235
236    fn into_future(self) -> Self::IntoFuture {
237        IncomingFuture(Box::pin(async move {
238            let noq_conn = self.inner.into_future().await?;
239            let conn = conn_from_noq_conn(noq_conn, &self.ep)?.await?;
240            Ok(conn)
241        }))
242    }
243}
244
245/// Error for attempting to retry an [`Incoming`] which already bears a token from a previous retry
246#[stack_error(derive, add_meta, from_sources)]
247#[error("retry() with validated Incoming")]
248pub struct RetryError {
249    err: noq::RetryError,
250    ep: Endpoint,
251}
252
253impl RetryError {
254    /// Get the [`Incoming`]
255    pub fn into_incoming(self) -> Incoming {
256        Incoming {
257            inner: self.err.into_incoming(),
258            ep: self.ep,
259        }
260    }
261}
262
263/// Adaptor to let [`Incoming`] be `await`ed like a [`Connecting`].
264#[derive(derive_more::Debug)]
265#[debug("IncomingFuture")]
266pub struct IncomingFuture(BoxFuture<Result<Connection, ConnectingError>>);
267
268impl Future for IncomingFuture {
269    type Output = Result<Connection, ConnectingError>;
270
271    fn poll(mut self: Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> Poll<Self::Output> {
272        self.0.poll_unpin(cx)
273    }
274}
275
276/// Extracts the ALPN protocol from the peer's handshake data.
277fn alpn_from_noq_conn(conn: &noq::Connection) -> Option<Vec<u8>> {
278    let data = conn.handshake_data()?;
279    match data.downcast::<noq::crypto::rustls::HandshakeData>() {
280        Ok(data) => data.protocol,
281        Err(_) => None,
282    }
283}
284
285async fn alpn_from_noq_connecting(conn: &mut noq::Connecting) -> Result<Vec<u8>, AlpnError> {
286    let data = conn.handshake_data().await?;
287    match data.downcast::<noq::crypto::rustls::HandshakeData>() {
288        Ok(data) => match data.protocol {
289            Some(protocol) => Ok(protocol),
290            None => Err(e!(AlpnError::Unavailable)),
291        },
292        Err(_) => Err(e!(AlpnError::UnknownHandshake)),
293    }
294}
295
296#[stack_error(add_meta, derive, from_sources)]
297#[allow(missing_docs)]
298#[non_exhaustive]
299#[derive(Clone)]
300pub enum AuthenticationError {
301    #[error(transparent)]
302    RemoteId { source: RemoteEndpointIdError },
303    #[error("no ALPN provided")]
304    NoAlpn {},
305}
306
307/// Converts a `noq::Connection` to a `Connection`.
308///
309/// Returns an error if there was a connection error, the handshake data has not completed
310/// or if the remote did not set an ALPN.
311///
312/// Otherwise returns a future that completes once the connection has been registered with the
313/// socket. This future can return an [`RemoteStateActorStoppedError`], which will only be
314/// emitted if the endpoint is closing.
315///
316/// The returned future is `'static`, so it can be stored without being lifetime-bound on `&ep`.
317fn conn_from_noq_conn(
318    conn: noq::Connection,
319    ep: &Endpoint,
320) -> Result<
321    impl Future<Output = Result<Connection, ConnectingError>> + Send + 'static,
322    ConnectingError,
323> {
324    let info = match static_info_from_conn(&conn) {
325        Ok(val) => val,
326        Err(auth_err) => {
327            // If the authentication error raced with a connection error, the connection
328            // error wins.
329            if let Some(conn_err) = conn.close_reason() {
330                return Err(e!(ConnectingError::ConnectionError { source: conn_err }));
331            } else {
332                return Err(e!(ConnectingError::HandshakeFailure { source: auth_err }));
333            }
334        }
335    };
336
337    event!(
338        target: "iroh::_events::conn::connected",
339        tracing::Level::DEBUG,
340        conn_id = conn.stable_id(),
341        side = ?conn.side(),
342        remote_id = %info.endpoint_id.fmt_short(),
343        alpn = %String::from_utf8_lossy(&info.alpn),
344    );
345
346    // Register this connection with the socket.
347    let fut = ep.inner.register_connection(info.endpoint_id, conn.clone());
348
349    // Check hooks
350    let inner = ep.inner.clone();
351    Ok(async move {
352        let paths = fut.await?;
353        let conn = Connection {
354            data: HandshakeCompletedData { info, paths },
355            inner: conn,
356        };
357
358        if let AfterHandshakeOutcome::Reject { error_code, reason } =
359            inner.hooks.after_handshake(&conn).await
360        {
361            conn.close(error_code, &reason);
362            return Err(e!(ConnectingError::LocallyRejected));
363        }
364
365        Ok(conn)
366    })
367}
368
369fn static_info_from_conn(conn: &noq::Connection) -> Result<StaticInfo, AuthenticationError> {
370    let endpoint_id = remote_id_from_noq_conn(conn)?;
371    let alpn = alpn_from_noq_conn(conn).ok_or_else(|| e!(AuthenticationError::NoAlpn))?;
372    Ok(StaticInfo { endpoint_id, alpn })
373}
374
375/// Returns the [`EndpointId`] from the peer's TLS certificate.
376///
377/// The [`PublicKey`] of an endpoint is also known as an [`EndpointId`].  This [`PublicKey`] is
378/// included in the TLS certificate presented during the handshake when connecting.
379/// This function allows you to get the [`EndpointId`] of the remote endpoint of this
380/// connection.
381///
382/// [`PublicKey`]: iroh_base::PublicKey
383fn remote_id_from_noq_conn(conn: &noq::Connection) -> Result<EndpointId, RemoteEndpointIdError> {
384    let data = conn.peer_identity();
385    match data {
386        None => {
387            warn!("no peer certificate found");
388            Err(RemoteEndpointIdError::new())
389        }
390        Some(data) => match data.downcast::<Vec<rustls::pki_types::CertificateDer>>() {
391            Ok(certs) => {
392                if certs.len() != 1 {
393                    warn!(
394                        "expected a single peer certificate, but {} found",
395                        certs.len()
396                    );
397                    return Err(RemoteEndpointIdError::new());
398                }
399
400                let peer_id = EndpointId::from_verifying_key(
401                    VerifyingKey::from_public_key_der(&certs[0])
402                        .map_err(|_| RemoteEndpointIdError::new())?,
403                );
404
405                Ok(peer_id)
406            }
407            Err(err) => {
408                warn!("invalid peer certificate: {:?}", err);
409                Err(RemoteEndpointIdError::new())
410            }
411        },
412    }
413}
414
415/// An outgoing connection in progress.
416///
417/// This future resolves to a [`Connection`] once the handshake completes.
418#[derive(derive_more::Debug)]
419pub struct Connecting {
420    inner: noq::Connecting,
421    /// Future to register the connection with the socket.
422    ///
423    /// This is set and polled after `inner` completes. We are using an option instead of an enum
424    /// because we need infallible access to `inner` in some methods.
425    #[debug("{}", register_with_socket.as_ref().map(|_| "Some(RegisterWithSocketFut)").unwrap_or("None"))]
426    register_with_socket: Option<RegisterWithSocketFut>,
427    ep: Endpoint,
428    /// `Some(remote_id)` if this is an outgoing connection, `None` if this is an incoming conn
429    remote_endpoint_id: EndpointId,
430}
431
432type RegisterWithSocketFut = BoxFuture<Result<Connection, ConnectingError>>;
433
434/// In-progress connection attempt future
435#[derive(derive_more::Debug)]
436pub struct Accepting {
437    inner: noq::Connecting,
438    /// Future to register the connection with the socket.
439    ///
440    /// This is set and polled after `inner` completes. We are using an option instead of an enum
441    /// because we need infallible access to `inner` in some methods.
442    #[debug("{}", register_with_socket.as_ref().map(|_| "Some(RegisterWithSocketFut)").unwrap_or("None"))]
443    register_with_socket: Option<RegisterWithSocketFut>,
444    ep: Endpoint,
445}
446
447#[stack_error(add_meta, derive, from_sources)]
448#[allow(missing_docs)]
449#[non_exhaustive]
450pub enum AlpnError {
451    #[error(transparent)]
452    ConnectionError {
453        #[error(std_err)]
454        source: ConnectionError,
455    },
456    #[error("No ALPN available")]
457    Unavailable,
458    #[error("Unknown handshake type")]
459    UnknownHandshake,
460}
461
462#[stack_error(add_meta, derive, from_sources)]
463#[allow(missing_docs)]
464#[non_exhaustive]
465#[derive(Clone)]
466#[allow(private_interfaces)]
467pub enum ConnectingError {
468    #[error(transparent)]
469    ConnectionError {
470        #[error(std_err)]
471        source: ConnectionError,
472    },
473    #[error("Failure finalizing the handshake")]
474    HandshakeFailure { source: AuthenticationError },
475    #[error("internal consistency error")]
476    InternalConsistencyError {
477        /// Private source type, cannot be created publicly.
478        source: RemoteStateActorStoppedError,
479    },
480    #[error("Connection was rejected locally")]
481    LocallyRejected,
482}
483
484impl Connecting {
485    pub(crate) fn new(
486        inner: noq::Connecting,
487        ep: Endpoint,
488        remote_endpoint_id: EndpointId,
489    ) -> Self {
490        Self {
491            inner,
492            ep,
493            remote_endpoint_id,
494            register_with_socket: None,
495        }
496    }
497
498    /// Converts this [`Connecting`] into a 0-RTT connection at the cost of weakened security.
499    ///
500    /// If 0-RTT can be attempted, returns a [`OutgoingZeroRttConnection`], which represents
501    /// outgoing 0-RTT connection.
502    ///
503    /// If the 0-RTT cannot even be attempted, returns back the same [`Connecting`] without
504    /// changes. You can still `.await` this [`Connecting`] to get a normal [`Connection`].
505    ///
506    /// The [`OutgoingZeroRttConnection`] will attempt to resume a previous TLS session. However,
507    /// **the remote endpoint may actually _reject_ the 0-RTT data--yet still accept
508    /// the connection attempt in general**, once the handshake has completed.
509    ///
510    /// This possibility of whether the 0-RTT data was accepted or rejected is conveyed
511    /// through the [`ZeroRttStatus`] after calling [`OutgoingZeroRttConnection::handshake_completed`].
512    /// When the handshake completes, it returns [`ZeroRttStatus::Accepted`] if the 0-RTT data
513    /// was accepted and [`ZeroRttStatus::Rejected`] if it was rejected. If it was rejected, the
514    /// existence of any streams opened and application data sent prior to the handshake
515    /// completing will not be conveyed to the remote application, and local operations on them
516    /// will return `ZeroRttRejected` errors.
517    ///
518    /// A server may reject 0-RTT data at its discretion, but accepting 0-RTT data requires the
519    /// relevant resumption state to be stored in the server, which servers may limit or lose for
520    /// various reasons including not persisting resumption state across server restarts.
521    ///
522    /// ## Security
523    ///
524    /// This enables transmission of 0-RTT data, which is vulnerable to replay attacks, and
525    /// should therefore never invoke non-idempotent operations.
526    ///
527    /// You can use [`RecvStream::is_0rtt`] to check whether a stream has been opened in 0-RTT
528    /// and thus whether parts of the stream are operating under this reduced security level.
529    ///
530    /// See also documentation for [`Accepting::into_0rtt`].
531    ///
532    /// [`RecvStream::is_0rtt`]: noq::RecvStream::is_0rtt
533    #[allow(clippy::result_large_err)]
534    pub fn into_0rtt(self) -> Result<OutgoingZeroRttConnection, Connecting> {
535        match self.inner.into_0rtt() {
536            Ok((noq_conn, zrtt_accepted)) => {
537                let accepted: BoxFuture<_> = Box::pin({
538                    let noq_conn = noq_conn.clone();
539                    async move {
540                        let accepted = zrtt_accepted.await;
541                        let conn = conn_from_noq_conn(noq_conn, &self.ep)?.await?;
542                        Ok(match accepted {
543                            true => ZeroRttStatus::Accepted(conn),
544                            false => ZeroRttStatus::Rejected(conn),
545                        })
546                    }
547                });
548                let accepted = accepted.shared();
549                Ok(Connection {
550                    inner: noq_conn,
551                    data: OutgoingZeroRttData { accepted },
552                })
553            }
554            Err(inner) => Err(Self { inner, ..self }),
555        }
556    }
557
558    /// Parameters negotiated during the handshake
559    pub async fn handshake_data(&mut self) -> Result<Box<dyn Any>, ConnectionError> {
560        self.inner.handshake_data().await
561    }
562
563    /// Extracts the ALPN protocol from the peer's handshake data.
564    pub async fn alpn(&mut self) -> Result<Vec<u8>, AlpnError> {
565        alpn_from_noq_connecting(&mut self.inner).await
566    }
567
568    /// Returns the [`EndpointId`] of the endpoint that this connection attempt tries to connect to.
569    pub fn remote_id(&self) -> EndpointId {
570        self.remote_endpoint_id
571    }
572}
573
574impl Future for Connecting {
575    type Output = Result<Connection, ConnectingError>;
576
577    fn poll(mut self: Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> Poll<Self::Output> {
578        loop {
579            if let Some(fut) = &mut self.register_with_socket {
580                return fut.poll_unpin(cx).map_err(Into::into);
581            } else {
582                let noq_conn = std::task::ready!(self.inner.poll_unpin(cx)?);
583                let fut = conn_from_noq_conn(noq_conn, &self.ep)?;
584                self.register_with_socket = Some(Box::pin(fut.err_into()));
585            }
586        }
587    }
588}
589
590impl Accepting {
591    pub(crate) fn new(inner: noq::Connecting, ep: Endpoint) -> Self {
592        Self {
593            inner,
594            ep,
595            register_with_socket: None,
596        }
597    }
598
599    /// Converts this [`Accepting`] into a 0-RTT or 0.5-RTT connection at the cost of weakened
600    /// security.
601    ///
602    /// Returns a [`IncomingZeroRttConnection`], which represents an incoming 0-RTT or 0.5-RTT connection.
603    ///
604    /// If the connection was initiated with 0-RTT by the remote endpoint, the local endpoint
605    /// might accept the 0-RTT attempt, allowing the local endpoint to receive application streams
606    /// and data before the handshake finishes.
607    ///
608    /// Otherwise this will enable 0.5-RTT, allowing the [`IncomingZeroRttConnection`] to open streams and send
609    /// data before the handshake finishes.
610    ///
611    /// ## Security
612    ///
613    /// Transmitted 0-RTT data from the client is vulnerable to replay attacks, and should
614    /// therefore never invoke non-idempotent operations.
615    ///
616    /// Transmission of 0.5-RTT data from the server may be sent before TLS client authentication
617    /// has occurred, and should therefore not be used to send data for which client
618    /// authentication is required.
619    ///
620    /// You can use [`RecvStream::is_0rtt`] to check whether a stream has been opened in 0-RTT
621    /// and thus whether parts of the stream are operating under this reduced security level.
622    ///
623    /// See also documentation for [`Connecting::into_0rtt`].
624    ///
625    /// [`RecvStream::is_0rtt`]: crate::endpoint::RecvStream::is_0rtt
626    pub fn into_0rtt(self) -> IncomingZeroRttConnection {
627        let (noq_conn, zrtt_accepted) = self
628            .inner
629            .into_0rtt()
630            .expect("incoming connections can always be converted to 0-RTT");
631
632        let accepted: BoxFuture<_> = Box::pin({
633            let noq_conn = noq_conn.clone();
634            async move {
635                let _ = zrtt_accepted.await;
636                let conn = conn_from_noq_conn(noq_conn, &self.ep)?.await?;
637                Ok(conn)
638            }
639        });
640        let accepted = accepted.shared();
641
642        IncomingZeroRttConnection {
643            inner: noq_conn,
644            data: IncomingZeroRttData { accepted },
645        }
646    }
647
648    /// Returns the remote address of this connection.
649    pub fn remote_addr(&self) -> IncomingAddr {
650        let remote = self.inner.remote_address();
651        self.ep
652            .to_transport_addr(remote)
653            .unwrap_or_else(|| {
654                error!(mapped_addr = ?remote, "Accepting::remote_addr: invalid mapped address");
655                transports::Addr::Ip(remote)
656            })
657            .into()
658    }
659
660    /// Parameters negotiated during the handshake
661    pub async fn handshake_data(&mut self) -> Result<Box<dyn Any>, ConnectionError> {
662        self.inner.handshake_data().await
663    }
664
665    /// Extracts the ALPN protocol from the peer's handshake data.
666    pub async fn alpn(&mut self) -> Result<Vec<u8>, AlpnError> {
667        alpn_from_noq_connecting(&mut self.inner).await
668    }
669}
670
671impl Future for Accepting {
672    type Output = Result<Connection, ConnectingError>;
673
674    fn poll(mut self: Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> Poll<Self::Output> {
675        loop {
676            if let Some(fut) = &mut self.register_with_socket {
677                return fut.poll_unpin(cx).map_err(Into::into);
678            } else {
679                let noq_conn = std::task::ready!(self.inner.poll_unpin(cx)?);
680                match conn_from_noq_conn(noq_conn, &self.ep) {
681                    Err(err) => return Poll::Ready(Err(err)),
682                    Ok(fut) => self.register_with_socket = Some(Box::pin(fut.err_into())),
683                };
684            }
685        }
686    }
687}
688
689/// The client side of a 0-RTT connection.
690///
691/// This is created using [`Connecting::into_0rtt`].
692///
693/// Creating a `OutgoingZeroRttConnection` means that the endpoint is capable
694/// of attempting a 0-RTT connection with the remote. The remote may still
695/// reject the 0-RTT connection. In which case, any data sent before the
696/// handshake has completed may need to be resent.
697///
698/// Look at the [`OutgoingZeroRttConnection::handshake_completed`] method for
699/// more details.
700pub type OutgoingZeroRttConnection = Connection<OutgoingZeroRtt>;
701
702/// Returned from [`OutgoingZeroRttConnection::handshake_completed`].
703#[derive(Debug, Clone)]
704pub enum ZeroRttStatus {
705    /// If the 0-RTT data was accepted, you can continue to use any streams
706    /// that were created before the handshake was completed.
707    Accepted(Connection),
708    /// If the 0-RTT data was rejected, any streams that were created before
709    /// the handshake was completed will error and any data that was
710    /// previously sent on those streams will need to be resent.
711    Rejected(Connection),
712}
713
714/// A QUIC connection on the server-side that can possibly accept 0-RTT data.
715///
716/// It is very similar to a `Connection`, but the `IncomingZeroRttConnection::remote_id`
717/// and `IncomingZeroRttConnection::alpn` may not be set yet, since the handshake has
718/// not necessarily occurred yet.
719///
720/// If the `IncomingZeroRttConnection` has rejected 0-RTT or does not have enough information
721/// to accept 0-RTT, any received 0-RTT packets will simply be dropped before
722/// reaching any receive streams.
723///
724/// Any streams that are created to send or receive data can continue to be used
725/// even after the handshake has completed and we are no longer in a 0-RTT
726/// situation.
727///
728/// Use the [`IncomingZeroRttConnection::handshake_completed`] method to get a [`Connection`] from a
729/// `IncomingZeroRttConnection`. This waits until 0-RTT connection has completed
730/// the handshake and can now confidently derive the ALPN and the
731/// [`EndpointId`] of the remote endpoint.
732pub type IncomingZeroRttConnection = Connection<IncomingZeroRtt>;
733
734/// A QUIC connection.
735///
736/// If all references to a connection (including every clone of the Connection handle,
737/// streams of incoming streams, and the various stream types) have been dropped, then the
738/// connection will be automatically closed with an error_code of 0 and an empty reason. You
739/// can also close the connection explicitly by calling [`Connection::close`].
740///
741/// Closing the connection immediately abandons efforts to deliver data to the peer. Upon
742/// receiving CONNECTION_CLOSE the peer may drop any stream data not yet delivered to the
743/// application. [`Connection::close`] describes in more detail how to gracefully close a
744/// connection without losing application data.
745///
746/// May be cloned to obtain another handle to the same connection.
747#[derive(Debug, Clone)]
748pub struct Connection<State: ConnectionState = HandshakeCompleted> {
749    inner: noq::Connection,
750    /// State-specific information
751    data: State::Data,
752}
753
754#[doc(hidden)]
755#[derive(Debug, Clone)]
756pub struct HandshakeCompletedData {
757    info: StaticInfo,
758    paths: PathStateReceiver,
759}
760
761/// Static info from a completed TLS handshake.
762#[derive(Debug, Clone)]
763struct StaticInfo {
764    endpoint_id: EndpointId,
765    alpn: Vec<u8>,
766}
767
768#[doc(hidden)]
769#[derive(Debug, Clone)]
770pub struct IncomingZeroRttData {
771    accepted: Shared<BoxFuture<Result<Connection, ConnectingError>>>,
772}
773
774#[doc(hidden)]
775#[derive(Debug, Clone)]
776pub struct OutgoingZeroRttData {
777    accepted: Shared<BoxFuture<Result<ZeroRttStatus, ConnectingError>>>,
778}
779
780mod sealed {
781    pub trait Sealed {}
782}
783
784/// Trait to track the state of a [`Connection`] at compile time.
785pub trait ConnectionState: sealed::Sealed {
786    /// State-specific data stored in the [`Connection`].
787    type Data: std::fmt::Debug + Clone;
788}
789
790/// Marker type for a connection that has completed the handshake.
791#[derive(Debug, Clone)]
792pub struct HandshakeCompleted;
793
794/// Marker type for a connection that is in the incoming 0-RTT state.
795#[derive(Debug, Clone)]
796pub struct IncomingZeroRtt;
797
798/// Marker type for a connection that is in the outgoing 0-RTT state.
799#[derive(Debug, Clone)]
800pub struct OutgoingZeroRtt;
801
802impl sealed::Sealed for HandshakeCompleted {}
803impl ConnectionState for HandshakeCompleted {
804    type Data = HandshakeCompletedData;
805}
806impl sealed::Sealed for IncomingZeroRtt {}
807impl ConnectionState for IncomingZeroRtt {
808    type Data = IncomingZeroRttData;
809}
810
811impl sealed::Sealed for OutgoingZeroRtt {}
812impl ConnectionState for OutgoingZeroRtt {
813    type Data = OutgoingZeroRttData;
814}
815
816#[allow(missing_docs)]
817#[stack_error(add_meta, derive)]
818#[error("Protocol error: no remote id available")]
819#[derive(Clone)]
820pub struct RemoteEndpointIdError;
821
822impl<T: ConnectionState> Connection<T> {
823    /// Initiates a new outgoing unidirectional stream.
824    ///
825    /// A unidirectional stream can only transmit data from the endpoint which opens the
826    /// stream, the endpoint accepting the stream can not send any data back on the same
827    /// stream.
828    ///
829    /// # QUIC streams
830    ///
831    /// QUIC can multiplex many streams onto a single connection. Streams can be short or
832    /// long lived and may be opened and closed without incurring any extra cost. The data
833    /// sent in each stream is delivered strictly ordered, yet multiple streams will be
834    /// transmitted interleaved and packet loss on one stream will not delay other
835    /// streams. Thus streams do not suffer head-of-line blocking.
836    ///
837    /// # Opening streams
838    ///
839    /// Both peers of a connection can open streams at any time. Opening a new stream does
840    /// not incur any extra overhead compared to sending data on an existing stream. However
841    /// only once some data has been transmitted on the stream, will the peer become aware
842    /// of the newly opened stream.
843    ///
844    /// # Accepting streams
845    ///
846    /// Each stream needs to be *accepted* by the peer, using either [`Self::accept_uni`] or
847    /// [`Self::accept_bi`] depending on the stream type. Repeated accept call will yield a
848    /// new stream whenever the peer opens a new stream.
849    ///
850    /// Note that opening a stream is not sufficient for the accept call to yield a new
851    /// stream. Data must be sent on a stream before the respective accept call at the peer
852    /// will yield a [`RecvStream`].
853    ///
854    /// # Stream priorities
855    ///
856    /// Streams can have different priorities set using [`SendStream::set_priority`]. Data
857    /// of streams with a higher priority will be transmitted to the peer before data from
858    /// streams with a lower priority.
859    ///
860    /// # Stream limits
861    ///
862    /// The number of streams which can be open concurrently defaults to
863    /// [`QuicTransportConfigBuilder::max_concurrent_uni_streams`] and
864    /// [`QuicTransportConfigBuilder::max_concurrent_bidi_streams`]. While the connection is
865    /// open these limits can be changed using [`Self::set_max_concurrent_uni_streams`] and
866    /// [`Self::set_max_concurrent_bi_streams`].
867    ///
868    /// Each stream has a *receive window* of a maximum number of bytes that may be
869    /// in-flight before the sender is blocked from transmitting more. This is configured in
870    /// [`QuicTransportConfigBuilder::stream_receive_window`]. There is also a
871    /// [`QuicTransportConfigBuilder::receive_window`] which applies to all streams combined
872    /// and can be changed during a connection using [`Self::set_receive_window`].
873    ///
874    /// The protocol limits the total number of streams during the lifetime of a connection
875    /// to 2**62, this limit applies to the sum of uni- and bi-directional streams. For most
876    /// practical purposes this is essentially unlimited.
877    ///
878    /// [`QuicTransportConfigBuilder::max_concurrent_uni_streams`]: super::QuicTransportConfigBuilder::max_concurrent_uni_streams
879    /// [`QuicTransportConfigBuilder::max_concurrent_bidi_streams`]: super::QuicTransportConfigBuilder::max_concurrent_bidi_streams
880    /// [`QuicTransportConfigBuilder::stream_receive_window`]: super::QuicTransportConfigBuilder::stream_receive_window
881    /// [`QuicTransportConfigBuilder::receive_window`]: super::QuicTransportConfigBuilder::receive_window
882    /// [`SendStream::set_priority`]: super::SendStream::set_priority
883    /// [`RecvStream`]: super::RecvStream
884    #[inline]
885    pub fn open_uni(&self) -> OpenUni<'_> {
886        self.inner.open_uni()
887    }
888
889    /// Initiates a new outgoing bidirectional stream.
890    ///
891    /// Bidirectional streams allows both peers to send as well as receive data. They act as
892    /// a pair of related unidirectional streams.
893    ///
894    /// See [`Self::open_uni`] for a detailed description of how streams work.
895    #[inline]
896    pub fn open_bi(&self) -> OpenBi<'_> {
897        self.inner.open_bi()
898    }
899
900    /// Accepts the next incoming uni-directional stream.
901    ///
902    /// See [`Self::open_uni`] for a detailed description of how streams work.
903    #[inline]
904    pub fn accept_uni(&self) -> AcceptUni<'_> {
905        self.inner.accept_uni()
906    }
907
908    /// Accepts the next incoming bidirectional stream.
909    ///
910    /// See [`Self::open_uni`] for a detailed description of how streams work.
911    #[inline]
912    pub fn accept_bi(&self) -> AcceptBi<'_> {
913        self.inner.accept_bi()
914    }
915
916    /// Receives an application datagram.
917    #[inline]
918    pub fn read_datagram(&self) -> ReadDatagram<'_> {
919        self.inner.read_datagram()
920    }
921
922    /// Receives a batch of application datagrams into `out`, in arrival order.
923    ///
924    /// This is the batch analogue of [`read_datagram()`](Self::read_datagram). The returned
925    /// future resolves once at least one datagram is buffered, drains up to `out.len()` of
926    /// them into `out` from the front, and yields the count written. Use this instead of
927    /// `read_datagram()` in a loop when forwarding bursts: a whole batch is taken under a
928    /// single lock hold.
929    #[inline]
930    pub fn read_many_datagrams<'a, 'b>(
931        &'a self,
932        out: &'b mut [Bytes],
933    ) -> ReadManyDatagrams<'a, 'b> {
934        self.inner.read_many_datagrams(out)
935    }
936
937    /// Waits for the connection to be closed for any reason.
938    ///
939    /// Despite the return type's name, closed connections are often not an error condition
940    /// at the application layer. Cases that might be routine include
941    /// [`ConnectionError::LocallyClosed`] and [`ConnectionError::ApplicationClosed`].
942    #[inline]
943    pub async fn closed(&self) -> ConnectionError {
944        self.inner.closed().await
945    }
946
947    /// If the connection is closed, the reason why.
948    ///
949    /// Returns `None` if the connection is still open.
950    #[inline]
951    pub fn close_reason(&self) -> Option<ConnectionError> {
952        self.inner.close_reason()
953    }
954
955    /// Closes the connection immediately.
956    ///
957    /// Pending operations will fail immediately with [`ConnectionError::LocallyClosed`]. No
958    /// more data is sent to the peer and the peer may drop buffered data upon receiving the
959    /// CONNECTION_CLOSE frame.
960    ///
961    /// `error_code` and `reason` are not interpreted, and are provided directly to the
962    /// peer.
963    ///
964    /// `reason` will be truncated to fit in a single packet with overhead; to improve odds
965    /// that it is preserved in full, it should be kept under 1KiB.
966    ///
967    /// # Gracefully closing a connection
968    ///
969    /// Only the peer last receiving application data can be certain that all data is
970    /// delivered. The only reliable action it can then take is to close the connection,
971    /// potentially with a custom error code. The delivery of the final CONNECTION_CLOSE
972    /// frame is very likely if both endpoints stay online long enough, calling
973    /// [`Endpoint::close`] will wait to provide sufficient time. Otherwise, the remote peer
974    /// will time out the connection, provided that the idle timeout is not disabled.
975    ///
976    /// The sending side can not guarantee all stream data is delivered to the remote
977    /// application. It only knows the data is delivered to the QUIC stack of the remote
978    /// endpoint. Once the local side sends a CONNECTION_CLOSE frame in response to calling
979    /// [`close`] the remote endpoint may drop any data it received but is as yet
980    /// undelivered to the application, including data that was acknowledged as received to
981    /// the local endpoint.
982    ///
983    /// [`close`]: Connection::close
984    #[inline]
985    pub fn close(&self, error_code: VarInt, reason: &[u8]) {
986        self.inner.close(error_code, reason)
987    }
988
989    /// Transmits `data` as an unreliable, unordered application datagram.
990    ///
991    /// Application datagrams are a low-level primitive. They may be lost or delivered out
992    /// of order, and `data` must both fit inside a single QUIC packet and be smaller than
993    /// the maximum dictated by the peer.
994    #[inline]
995    pub fn send_datagram(&self, data: Bytes) -> Result<(), SendDatagramError> {
996        self.inner.send_datagram(data)
997    }
998
999    /// Transmits many unreliable, unordered application datagrams in a single call.
1000    ///
1001    /// This is the batch analogue of [`send_datagram()`](Self::send_datagram): it queues the
1002    /// whole batch under one lock hold and wakes the driver once, reducing the per-datagram
1003    /// overhead of calling `send_datagram()` repeatedly. Like `send_datagram()`, older queued
1004    /// datagrams may be dropped to make room.
1005    ///
1006    /// Returns the number of datagrams queued. The batch is rejected with
1007    /// [`SendDatagramError::TooLarge`] if any datagram exceeds the maximum datagram size.
1008    #[inline]
1009    pub fn send_many_datagrams(&self, datagrams: &[Bytes]) -> Result<usize, SendDatagramError> {
1010        self.inner.send_many_datagrams(datagrams)
1011    }
1012
1013    /// Transmits `data` as an unreliable, unordered application datagram
1014    ///
1015    /// Unlike [`send_datagram()`], this method will wait for buffer space during congestion
1016    /// conditions, which effectively prioritizes old datagrams over new datagrams.
1017    ///
1018    /// See [`send_datagram()`] for details.
1019    ///
1020    /// [`send_datagram()`]: Connection::send_datagram
1021    #[inline]
1022    pub fn send_datagram_wait(&self, data: Bytes) -> SendDatagram<'_> {
1023        self.inner.send_datagram_wait(data)
1024    }
1025
1026    /// Computes the maximum size of datagrams that may be passed to [`send_datagram`].
1027    ///
1028    /// Returns `None` if datagrams are unsupported by the peer or disabled locally.
1029    ///
1030    /// This may change over the lifetime of a connection according to variation in the path
1031    /// MTU estimate. The peer can also enforce an arbitrarily small fixed limit, but if the
1032    /// peer's limit is large this is guaranteed to be a little over a kilobyte at minimum.
1033    ///
1034    /// Not necessarily the maximum size of received datagrams.
1035    ///
1036    /// [`send_datagram`]: Self::send_datagram
1037    #[inline]
1038    pub fn max_datagram_size(&self) -> Option<usize> {
1039        self.inner.max_datagram_size()
1040    }
1041
1042    /// Bytes available in the outgoing datagram buffer.
1043    ///
1044    /// When greater than zero, calling [`send_datagram`] with a
1045    /// datagram of at most this size is guaranteed not to cause older datagrams to be
1046    /// dropped.
1047    ///
1048    /// [`send_datagram`]: Self::send_datagram
1049    #[inline]
1050    pub fn datagram_send_buffer_space(&self) -> usize {
1051        self.inner.datagram_send_buffer_space()
1052    }
1053
1054    /// Current best estimate of this connection's latency (round-trip-time).
1055    #[inline]
1056    pub fn rtt(&self, path_id: PathId) -> Option<Duration> {
1057        self.inner.rtt(path_id)
1058    }
1059
1060    /// Returns connection statistics.
1061    #[inline]
1062    pub fn stats(&self) -> ConnectionStats {
1063        self.inner.stats()
1064    }
1065
1066    /// Current state of the congestion control algorithm, for debugging purposes.
1067    #[inline]
1068    pub fn congestion_state(&self, path_id: PathId) -> Option<Box<dyn Controller>> {
1069        self.inner.congestion_state(path_id)
1070    }
1071
1072    /// Parameters negotiated during the handshake.
1073    ///
1074    /// Guaranteed to return `Some` on fully established connections or after
1075    /// [`Connecting::handshake_data()`] succeeds. See that method's documentations for
1076    /// details on the returned value.
1077    ///
1078    /// [`Connection::handshake_data()`]: crate::endpoint::Connecting::handshake_data
1079    #[inline]
1080    pub fn handshake_data(&self) -> Option<Box<dyn Any>> {
1081        self.inner.handshake_data()
1082    }
1083
1084    /// Cryptographic identity of the peer.
1085    ///
1086    /// The dynamic type returned is determined by the configured [`Session`]. For the
1087    /// default `rustls` session, the return value can be [`downcast`] to a
1088    /// <code>Vec<[rustls::pki_types::CertificateDer]></code>
1089    ///
1090    /// [`Session`]: noq_proto::crypto::Session
1091    /// [`downcast`]: Box::downcast
1092    #[inline]
1093    pub fn peer_identity(&self) -> Option<Box<dyn Any>> {
1094        self.inner.peer_identity()
1095    }
1096
1097    /// A stable identifier for this connection.
1098    ///
1099    /// Peer addresses and connection IDs can change, but this value will remain fixed for
1100    /// the lifetime of the connection.
1101    #[inline]
1102    pub fn stable_id(&self) -> usize {
1103        self.inner.stable_id()
1104    }
1105
1106    /// Derives keying material from this connection's TLS session secrets.
1107    ///
1108    /// When both peers call this method with the same `label` and `context`
1109    /// arguments and `output` buffers of equal length, they will get the
1110    /// same sequence of bytes in `output`. These bytes are cryptographically
1111    /// strong and pseudorandom, and are suitable for use as keying material.
1112    ///
1113    /// See [RFC5705](https://tools.ietf.org/html/rfc5705) for more information.
1114    #[inline]
1115    pub fn export_keying_material(
1116        &self,
1117        output: &mut [u8],
1118        label: &[u8],
1119        context: &[u8],
1120    ) -> Result<(), ExportKeyingMaterialError> {
1121        self.inner.export_keying_material(output, label, context)
1122    }
1123
1124    /// Modifies the number of unidirectional streams that may be concurrently opened.
1125    ///
1126    /// No streams may be opened by the peer unless fewer than `count` are already
1127    /// open. Large `count`s increase both minimum and worst-case memory consumption.
1128    #[inline]
1129    pub fn set_max_concurrent_uni_streams(&self, count: VarInt) {
1130        self.inner.set_max_concurrent_uni_streams(count)
1131    }
1132
1133    /// Sets the connection-level flow control receive window.
1134    ///
1135    /// See [`QuicTransportConfigBuilder::receive_window`].
1136    ///
1137    /// [`QuicTransportConfigBuilder::receive_window`]: super::QuicTransportConfigBuilder::receive_window
1138    #[inline]
1139    pub fn set_receive_window(&self, receive_window: VarInt) {
1140        self.inner.set_receive_window(receive_window)
1141    }
1142
1143    /// Modifies the number of bidirectional streams that may be concurrently opened.
1144    ///
1145    /// No streams may be opened by the peer unless fewer than `count` are already
1146    /// open. Large `count`s increase both minimum and worst-case memory consumption.
1147    #[inline]
1148    pub fn set_max_concurrent_bi_streams(&self, count: VarInt) {
1149        self.inner.set_max_concurrent_bi_streams(count)
1150    }
1151}
1152
1153impl Connection<HandshakeCompleted> {
1154    /// Extracts the ALPN protocol from the peer's handshake data.
1155    pub fn alpn(&self) -> &[u8] {
1156        &self.data.info.alpn
1157    }
1158
1159    /// Returns the [`EndpointId`] from the peer's TLS certificate.
1160    ///
1161    /// The [`PublicKey`] of an endpoint is also known as an [`EndpointId`].  This [`PublicKey`] is
1162    /// included in the TLS certificate presented during the handshake when connecting.
1163    /// This function allows you to get the [`EndpointId`] of the remote endpoint of this
1164    /// connection.
1165    ///
1166    /// [`PublicKey`]: iroh_base::PublicKey
1167    pub fn remote_id(&self) -> EndpointId {
1168        self.data.info.endpoint_id
1169    }
1170
1171    /// Returns the currently open network paths for this connection.
1172    ///
1173    /// A connection typically has one path via the relay server and,
1174    /// once holepunching succeeds, a direct path. The returned
1175    /// [`PathList`] is a snapshot taken at call time: it does not
1176    /// reflect later changes, and it does not include paths that have
1177    /// already closed.
1178    ///
1179    /// To observe changes over time, see [`Connection::paths_stream`]
1180    /// for a stream of [`PathList`] snapshots and
1181    /// [`Connection::path_events`] for individual [`PathEvent`]s.
1182    ///
1183    /// [`PathEvent`]: crate::endpoint::PathEvent
1184    pub fn paths(&self) -> PathList<'_> {
1185        self.data.paths.get(&self.inner)
1186    }
1187
1188    /// Returns a stream of [`PathList`] snapshots for this connection.
1189    ///
1190    /// Yields the current snapshot on the first poll, and a fresh
1191    /// snapshot whenever the open paths or the selected path change.
1192    /// Ends when the connection closes.
1193    ///
1194    /// The stream borrows this [`Connection`]. To consume it from a
1195    /// spawned task, move a [`Connection`] clone into the task and
1196    /// call this method inside.
1197    pub fn paths_stream(&self) -> PathListStream<'_> {
1198        self.data.paths.stream(&self.inner)
1199    }
1200
1201    /// Returns a stream of [`PathEvent`]s for this connection.
1202    ///
1203    /// Each event reports one of: a path opened, a path closed (with
1204    /// final per-path statistics), the selected transmission path
1205    /// changed, or the consumer fell behind. The stream ends when the
1206    /// connection closes. It does not borrow this [`Connection`] and
1207    /// may be moved into a spawned task.
1208    ///
1209    /// If the consumer does not poll fast enough, the stream yields a
1210    /// single [`PathEvent::Lagged`]; the current state of the open
1211    /// paths and the selected path remains recoverable via
1212    /// [`Connection::paths`].
1213    ///
1214    /// [`PathEvent`]: crate::endpoint::PathEvent
1215    /// [`PathEvent::Lagged`]: crate::endpoint::PathEvent::Lagged
1216    pub fn path_events(&self) -> PathEventStream {
1217        self.data.paths.events()
1218    }
1219
1220    /// Returns the side of the connection (client or server).
1221    pub fn side(&self) -> Side {
1222        self.inner.side()
1223    }
1224
1225    /// Returns a [`WeakConnectionHandle`] for this connection.
1226    ///
1227    /// A [`WeakConnectionHandle`] does not keep the connection alive. It can be used to
1228    /// wait for the connection to be closed via [`WeakConnectionHandle::closed`] and to
1229    /// attempt to upgrade back to a strong [`Connection`] via
1230    /// [`WeakConnectionHandle::upgrade`].
1231    pub fn weak_handle(&self) -> WeakConnectionHandle {
1232        WeakConnectionHandle {
1233            data: self.data.clone(),
1234            inner: self.inner.weak_handle(),
1235        }
1236    }
1237}
1238
1239impl Connection<IncomingZeroRtt> {
1240    /// Extracts the ALPN protocol from the peer's handshake data.
1241    pub fn alpn(&self) -> Option<Vec<u8>> {
1242        alpn_from_noq_conn(&self.inner)
1243    }
1244
1245    /// Waits until the full handshake occurs and then returns a [`Connection`].
1246    ///
1247    /// This may fail with [`ConnectingError::ConnectionError`], if there was
1248    /// some general failure with the connection, such as a network timeout since
1249    /// we accepted the connection.
1250    ///
1251    /// This may fail with [`ConnectingError::HandshakeFailure`], if the other side
1252    /// doesn't use the right TLS authentication, which usually every iroh endpoint
1253    /// uses and requires.
1254    ///
1255    /// Thus, those errors should only occur if someone connects to you with a
1256    /// modified iroh endpoint or with a plain QUIC client.
1257    pub async fn handshake_completed(&self) -> Result<Connection, ConnectingError> {
1258        self.data.accepted.clone().await
1259    }
1260
1261    /// Returns the [`EndpointId`] from the peer's TLS certificate.
1262    ///
1263    /// The [`PublicKey`] of an endpoint is also known as an [`EndpointId`].  This [`PublicKey`] is
1264    /// included in the TLS certificate presented during the handshake when connecting.
1265    /// This function allows you to get the [`EndpointId`] of the remote endpoint of this
1266    /// connection.
1267    ///
1268    /// [`PublicKey`]: iroh_base::PublicKey
1269    pub fn remote_id(&self) -> Result<EndpointId, RemoteEndpointIdError> {
1270        remote_id_from_noq_conn(&self.inner)
1271    }
1272}
1273
1274impl Connection<OutgoingZeroRtt> {
1275    /// Extracts the ALPN protocol from the peer's handshake data.
1276    pub fn alpn(&self) -> Option<Vec<u8>> {
1277        alpn_from_noq_conn(&self.inner)
1278    }
1279
1280    /// Waits until the full handshake occurs and returns a [`ZeroRttStatus`].
1281    ///
1282    /// If `ZeroRttStatus::Accepted` is returned, then any streams created before
1283    /// the handshake has completed can still be used.
1284    ///
1285    /// If `ZeroRttStatus::Rejected` is returned, then any streams created before
1286    /// the handshake will error and any data sent should be re-sent on a
1287    /// new stream.
1288    ///
1289    /// This may fail with [`ConnectingError::ConnectionError`], if there was
1290    /// some general failure with the connection, such as a network timeout since
1291    /// we initiated the connection.
1292    ///
1293    /// This may fail with [`ConnectingError::HandshakeFailure`], if the other side
1294    /// doesn't use the right TLS authentication, which usually every iroh endpoint
1295    /// uses and requires.
1296    ///
1297    /// Thus, those errors should only occur if someone connects to you with a
1298    /// modified iroh endpoint or with a plain QUIC client.
1299    pub async fn handshake_completed(&self) -> Result<ZeroRttStatus, ConnectingError> {
1300        self.data.accepted.clone().await
1301    }
1302
1303    /// Returns the [`EndpointId`] from the peer's TLS certificate.
1304    ///
1305    /// The [`PublicKey`] of an endpoint is also known as an [`EndpointId`].  This [`PublicKey`] is
1306    /// included in the TLS certificate presented during the handshake when connecting.
1307    /// This function allows you to get the [`EndpointId`] of the remote endpoint of this
1308    /// connection.
1309    ///
1310    /// [`PublicKey`]: iroh_base::PublicKey
1311    pub fn remote_id(&self) -> Result<EndpointId, RemoteEndpointIdError> {
1312        remote_id_from_noq_conn(&self.inner)
1313    }
1314}
1315
1316/// A weak handle to a [`Connection`].
1317///
1318/// A [`WeakConnectionHandle`] does not keep the connection alive: holding one will not
1319/// prevent the connection from being closed when the last [`Connection`] handle is dropped.
1320///
1321/// Use [`upgrade`] to obtain a strong [`Connection`], and [`closed`] to wait for the
1322/// connection to be closed without keeping it alive.
1323///
1324/// [`upgrade`]: WeakConnectionHandle::upgrade
1325/// [`closed`]: WeakConnectionHandle::closed
1326#[derive(Debug, Clone)]
1327pub struct WeakConnectionHandle {
1328    data: HandshakeCompletedData,
1329    inner: NoqWeakConnectionHandle,
1330}
1331
1332impl WeakConnectionHandle {
1333    /// Attempts to upgrade this weak handle to a strong [`Connection`].
1334    ///
1335    /// Returns `None` if the connection has already been dropped.
1336    pub fn upgrade(&self) -> Option<Connection> {
1337        self.inner.upgrade().map(|inner| Connection {
1338            inner,
1339            data: self.data.clone(),
1340        })
1341    }
1342
1343    /// Returns a future that resolves once the connection has been closed.
1344    ///
1345    /// If no strong references to the [`Connection`] exist at the time this is called,
1346    /// the future resolves to `None`. If at least one strong reference still exists at
1347    /// the time of this call, the returned future is guaranteed to receive the close
1348    /// event with the close reason and final connection statistics, even if all strong
1349    /// references are dropped before the future is awaited.
1350    ///
1351    /// The future does not keep the connection alive.
1352    pub fn closed(&self) -> impl Future<Output = Option<Closed>> + Send + 'static {
1353        let registered = self.inner.upgrade().map(|conn| conn.on_closed());
1354        async move {
1355            match registered {
1356                Some(fut) => Some(fut.await),
1357                None => None,
1358            }
1359        }
1360    }
1361}
1362
1363#[cfg(all(test, with_crypto_provider))]
1364mod tests {
1365    use std::time::Duration;
1366
1367    use iroh_base::{EndpointAddr, SecretKey};
1368    use iroh_relay::tls::CaTlsConfig;
1369    use n0_error::{Result, StackResultExt, StdResultExt};
1370    use n0_future::{Stream, StreamExt};
1371    use n0_tracing_test::traced_test;
1372    use rand::{RngExt, SeedableRng};
1373    use tracing::{Instrument, error_span, info, info_span, trace_span};
1374
1375    use super::Endpoint;
1376    use crate::{
1377        RelayMode,
1378        endpoint::{ConnectOptions, Incoming, PathList, ZeroRttStatus, presets},
1379        test_utils::run_relay_server,
1380    };
1381
1382    const TEST_ALPN: &[u8] = b"n0/iroh/test";
1383
1384    async fn spawn_0rtt_server(secret_key: SecretKey, log_span: tracing::Span) -> Result<Endpoint> {
1385        let server = Endpoint::builder(presets::Minimal)
1386            .secret_key(secret_key)
1387            .alpns(vec![TEST_ALPN.to_vec()])
1388            .bind()
1389            .instrument(log_span.clone())
1390            .await?;
1391
1392        async fn handle_incoming(incoming: Incoming) -> Result {
1393            let accepting = incoming
1394                .accept()
1395                .std_context("Failed to accept incoming connection")?;
1396
1397            // accept a possible 0-RTT connection
1398            let zrtt_conn = accepting.into_0rtt();
1399
1400            let (mut send, mut recv) = zrtt_conn
1401                .accept_bi()
1402                .await
1403                .std_context("failed to accept bi stream")?;
1404
1405            let data = recv
1406                .read_to_end(10_000_000)
1407                .await
1408                .std_context("Failed to read data")?;
1409
1410            send.write_all(&data)
1411                .await
1412                .std_context("Failed to write data")?;
1413            send.finish().std_context("Failed to finish send")?;
1414
1415            // Stay alive until the other side closes the connection.
1416            zrtt_conn.closed().await;
1417            Ok(())
1418        }
1419
1420        // Gets aborted via the endpoint closing causing an `Err`
1421        // a simple echo server
1422        tokio::spawn({
1423            let server = server.clone();
1424            async move {
1425                tracing::trace!("Server accept loop started");
1426                while let Some(incoming) = server.accept().await {
1427                    tracing::trace!("Server received incoming connection");
1428                    // Handle connection errors gracefully instead of exiting the task
1429                    if let Err(e) = handle_incoming(incoming).await {
1430                        tracing::warn!("Failure while handling connection: {e:#}");
1431                    }
1432                    tracing::trace!("Connection closed, ready for next");
1433                }
1434                tracing::trace!("Server accept loop exiting");
1435                n0_error::Ok(())
1436            }
1437            .instrument(log_span)
1438        });
1439
1440        Ok(server)
1441    }
1442
1443    async fn connect_client_0rtt_expect_err(
1444        client: &Endpoint,
1445        server_addr: EndpointAddr,
1446    ) -> Result {
1447        let conn = client
1448            .connect_with_opts(server_addr, TEST_ALPN, ConnectOptions::new())
1449            .await?
1450            .into_0rtt()
1451            .expect_err("expected 0-RTT to fail")
1452            .await?;
1453
1454        let (mut send, mut recv) = conn.open_bi().await.anyerr()?;
1455        send.write_all(b"hello").await.anyerr()?;
1456        send.finish().anyerr()?;
1457        let received = recv.read_to_end(1_000).await.anyerr()?;
1458        assert_eq!(&received, b"hello");
1459        conn.close(0u32.into(), b"thx");
1460        Ok(())
1461    }
1462
1463    async fn connect_client_0rtt_expect_ok(
1464        client: &Endpoint,
1465        server_addr: EndpointAddr,
1466        expect_server_accepts: bool,
1467    ) -> Result {
1468        tracing::trace!(?server_addr, "Client connecting with 0-RTT");
1469        let zrtt_conn = client
1470            .connect_with_opts(server_addr, TEST_ALPN, ConnectOptions::new())
1471            .await
1472            .context("connect")?
1473            .into_0rtt()
1474            .ok()
1475            .context("into_0rtt")?;
1476
1477        tracing::trace!("Client established 0-RTT connection");
1478        // This is how we send data in 0-RTT:
1479        let (mut send, mut recv) = zrtt_conn.open_bi().await.anyerr()?;
1480        send.write_all(b"hello").await.anyerr()?;
1481        send.finish().anyerr()?;
1482        tracing::trace!("Client sent 0-RTT data, waiting for server response");
1483        // When this resolves, we've gotten a response from the server about whether the 0-RTT data above was accepted:
1484        let zrtt_res = zrtt_conn.handshake_completed().await;
1485        tracing::trace!(?zrtt_res, "Server responded to 0-RTT");
1486        let zrtt_res = zrtt_res.context("handshake completed")?;
1487        let conn = match zrtt_res {
1488            ZeroRttStatus::Accepted(conn) => {
1489                assert!(expect_server_accepts);
1490                conn
1491            }
1492            ZeroRttStatus::Rejected(conn) => {
1493                assert!(!expect_server_accepts);
1494                // in this case we need to re-send data by re-creating the stream.
1495                let (mut send, r) = conn.open_bi().await.anyerr()?;
1496                send.write_all(b"hello").await.anyerr()?;
1497                send.finish().anyerr()?;
1498                recv = r;
1499                conn
1500            }
1501        };
1502        let received = recv.read_to_end(1_000).await.anyerr()?;
1503        assert_eq!(&received, b"hello");
1504        conn.close(0u32.into(), b"thx");
1505        Ok(())
1506    }
1507
1508    #[tokio::test]
1509    #[traced_test]
1510    async fn test_0rtt() -> Result {
1511        let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(42);
1512        let client = Endpoint::bind(presets::Minimal).await?;
1513        let server =
1514            spawn_0rtt_server(SecretKey::from_bytes(&rng.random()), info_span!("server")).await?;
1515
1516        connect_client_0rtt_expect_err(&client, server.addr()).await?;
1517        // The second 0rtt attempt should work
1518        connect_client_0rtt_expect_ok(&client, server.addr(), true).await?;
1519
1520        client.close().await;
1521        server.close().await;
1522
1523        Ok(())
1524    }
1525
1526    // We have this test, as this would've failed at some point.
1527    // This effectively tests that we correctly categorize the TLS session tickets we
1528    // receive into the respective "bucket" for the recipient.
1529    #[tokio::test]
1530    #[traced_test]
1531    async fn test_0rtt_non_consecutive() -> Result {
1532        let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(42);
1533        let client = Endpoint::bind(presets::Minimal).await?;
1534        let server =
1535            spawn_0rtt_server(SecretKey::from_bytes(&rng.random()), info_span!("server")).await?;
1536
1537        connect_client_0rtt_expect_err(&client, server.addr()).await?;
1538
1539        // connecting with another endpoint should not interfere with our
1540        // TLS session ticket cache for the first endpoint:
1541        let another =
1542            spawn_0rtt_server(SecretKey::from_bytes(&rng.random()), info_span!("another")).await?;
1543        connect_client_0rtt_expect_err(&client, another.addr()).await?;
1544        another.close().await;
1545
1546        connect_client_0rtt_expect_ok(&client, server.addr(), true).await?;
1547
1548        client.close().await;
1549        server.close().await;
1550
1551        Ok(())
1552    }
1553
1554    // Test whether 0-RTT is possible after a restart:
1555    #[tokio::test]
1556    #[traced_test]
1557    async fn test_0rtt_after_server_restart() -> Result {
1558        let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(42);
1559        let client = Endpoint::builder(presets::Minimal)
1560            .bind()
1561            .instrument(info_span!("client"))
1562            .await?;
1563        let server_key = SecretKey::from_bytes(&rng.random());
1564        let server = spawn_0rtt_server(server_key.clone(), info_span!("server-initial")).await?;
1565
1566        connect_client_0rtt_expect_err(&client, server.addr())
1567            .instrument(trace_span!("connect1"))
1568            .await
1569            .context("client connect 1")?;
1570        connect_client_0rtt_expect_ok(&client, server.addr(), true)
1571            .instrument(trace_span!("connect2"))
1572            .await
1573            .context("client connect 2")?;
1574
1575        // adds time to the test, but we need to ensure the server is fully closed before spawning the next one.
1576        server.close().await;
1577
1578        let server = spawn_0rtt_server(server_key, info_span!("server-restart")).await?;
1579
1580        // we expect the client to *believe* it can 0-RTT connect to the server (hence expect_ok),
1581        // but the server will reject the early data because it discarded necessary state
1582        // to decrypt it when restarting.
1583        connect_client_0rtt_expect_ok(&client, server.addr(), false)
1584            .instrument(trace_span!("connect3"))
1585            .await
1586            .context("client connect 3")?;
1587
1588        tokio::join!(client.close(), server.close());
1589        Ok(())
1590    }
1591
1592    #[tokio::test]
1593    #[traced_test]
1594    async fn test_paths_watcher() -> Result {
1595        const ALPN: &[u8] = b"test";
1596        let mut rng = rand_chacha::ChaCha8Rng::seed_from_u64(0u64);
1597        let (relay_map, _relay_url, _guard) = run_relay_server().await?;
1598        let server = Endpoint::builder(presets::Minimal)
1599            .relay_mode(RelayMode::Custom(relay_map.clone()))
1600            .secret_key(SecretKey::from_bytes(&rng.random()))
1601            .ca_tls_config(CaTlsConfig::insecure_skip_verify())
1602            .alpns(vec![ALPN.to_vec()])
1603            .bind()
1604            .await?;
1605
1606        let client = Endpoint::builder(presets::Minimal)
1607            .relay_mode(RelayMode::Custom(relay_map.clone()))
1608            .secret_key(SecretKey::from_bytes(&rng.random()))
1609            .ca_tls_config(CaTlsConfig::insecure_skip_verify())
1610            .bind()
1611            .await?;
1612
1613        server.online().await;
1614        client.online().await;
1615        let server_addr = server.addr();
1616        info!("server addr: {server_addr:?}");
1617
1618        let (conn_client, conn_server) = tokio::join!(
1619            async { client.connect(server_addr, ALPN).await.unwrap() },
1620            async { server.accept().await.unwrap().await.unwrap() }
1621        );
1622        info!("connected");
1623
1624        let mut paths_client = conn_client.paths_stream();
1625        let mut paths_server = conn_server.paths_stream();
1626
1627        /// Advances the path stream until at least one IP and one relay path is available.
1628        ///
1629        /// Panics if the path stream finishes before that happens.
1630        async fn wait_for_paths(mut stream: impl Send + Unpin + Stream<Item = PathList<'_>>) {
1631            loop {
1632                let paths = stream.next().await.expect("paths stream ended");
1633                info!(?paths, "paths");
1634                if paths.len() >= 2
1635                    && paths.iter().any(|p| p.is_relay())
1636                    && paths.iter().any(|p| p.is_ip())
1637                {
1638                    info!("break");
1639                    return;
1640                }
1641            }
1642        }
1643
1644        // Verify that both connections are notified of path changes and get an IP and a relay path.
1645        tokio::join!(
1646            async {
1647                tokio::time::timeout(Duration::from_secs(10), wait_for_paths(&mut paths_server))
1648                    .instrument(error_span!("paths-server"))
1649                    .await
1650                    .unwrap()
1651            },
1652            async {
1653                tokio::time::timeout(Duration::from_secs(10), wait_for_paths(&mut paths_client))
1654                    .instrument(error_span!("paths-client"))
1655                    .await
1656                    .unwrap()
1657            }
1658        );
1659
1660        // Close the client connection.
1661        info!("close client conn");
1662        conn_client.close(0u32.into(), b"");
1663
1664        // Verify that the path watch streams close shortly after the connection is closed
1665        tokio::time::timeout(Duration::from_secs(30), async {
1666            while paths_client.next().await.is_some() {}
1667        })
1668        .await
1669        .expect("client paths watcher did not close within 8s of connection close");
1670        tokio::time::timeout(Duration::from_secs(30), async {
1671            while paths_server.next().await.is_some() {}
1672        })
1673        .await
1674        .expect("server paths watcher did not close within 8s of connection close");
1675
1676        server.close().await;
1677        client.close().await;
1678
1679        Ok(())
1680    }
1681}