iroh/
protocol.rs

1//! Tools for spawning an accept loop that routes incoming requests to the right protocol.
2//!
3//! ## Example
4//!
5//! ```no_run
6//! # #[cfg(with_crypto_provider)]
7//! # use iroh::{
8//! #     endpoint::{BindError, presets},
9//! #     protocol::Router,
10//! #     Endpoint,
11//! # };
12//! # use iroh::{
13//! #     endpoint::Connection,
14//! #     protocol::{AcceptError, ProtocolHandler},
15//! # };
16//! #
17//! # #[cfg(with_crypto_provider)]
18//! # async fn test_compile() -> Result<(), BindError> {
19//! let endpoint = Endpoint::bind(presets::N0).await?;
20//!
21//! let router = Router::builder(endpoint).accept(b"/my/alpn", Echo).spawn();
22//! # Ok(())
23//! # }
24//!
25//! // The protocol definition:
26//! #[derive(Debug, Clone)]
27//! struct Echo;
28//!
29//! impl ProtocolHandler for Echo {
30//!     async fn accept(&self, connection: Connection) -> Result<(), AcceptError> {
31//!         let (mut send, mut recv) = connection.accept_bi().await?;
32//!
33//!         // Echo any bytes received back directly.
34//!         let bytes_sent = tokio::io::copy(&mut recv, &mut send).await?;
35//!
36//!         send.finish()?;
37//!         connection.closed().await;
38//!
39//!         Ok(())
40//!     }
41//! }
42//! ```
43use std::{
44    collections::HashMap,
45    future::Future,
46    pin::Pin,
47    sync::{Arc, Mutex},
48};
49
50use n0_error::{AnyError, e, stack_error};
51use n0_future::{
52    join_all,
53    task::{self, AbortOnDropHandle, JoinSet},
54};
55use tokio_util::sync::CancellationToken;
56use tracing::{Instrument, debug, error, field::Empty, info_span, trace, warn};
57
58use crate::{
59    Endpoint,
60    endpoint::{Accepting, Connection, RemoteEndpointIdError, quic},
61};
62
63/// The built router.
64///
65/// Construct this using [`Router::builder`].
66///
67/// When dropped, this will abort listening the tasks, so make sure to store it.
68///
69/// Even with this abort-on-drop behaviour, it's recommended to call and await
70/// [`Router::shutdown`] before ending the process.
71///
72/// As an example for graceful shutdown, e.g. for tests or CLI tools,
73/// wait for [`tokio::signal::ctrl_c()`]:
74///
75/// ```no_run
76/// # #[cfg(with_crypto_provider)]
77/// # {
78/// # use std::sync::Arc;
79/// # use n0_error::StdResultExt;
80/// # use iroh::{endpoint::{Connecting, presets}, protocol::{ProtocolHandler, Router}, Endpoint, EndpointAddr};
81/// #
82/// # async fn test_compile() -> n0_error::Result<()> {
83/// let endpoint = Endpoint::bind(presets::N0).await?;
84///
85/// let router = Router::builder(endpoint)
86///     // .accept(&ALPN, <something>)
87///     .spawn();
88///
89/// // wait until the user wants to
90/// tokio::signal::ctrl_c().await.std_context("ctrl+c")?;
91/// router.shutdown().await.std_context("shutdown")?;
92/// # Ok(())
93/// # }
94/// # }
95/// ```
96#[derive(Clone, Debug)]
97pub struct Router {
98    endpoint: Endpoint,
99    // `Router` needs to be `Clone + Send`, and we need to `task.await` in its `shutdown()` impl.
100    task: Arc<Mutex<Option<AbortOnDropHandle<()>>>>,
101    cancel_token: CancellationToken,
102}
103
104/// Builder for creating a [`Router`] for accepting protocols.
105#[derive(derive_more::Debug)]
106pub struct RouterBuilder {
107    endpoint: Endpoint,
108    protocols: ProtocolMap,
109    #[debug(skip)]
110    incoming_filter: Option<IncomingFilter>,
111}
112
113#[allow(missing_docs)]
114#[stack_error(derive, add_meta, from_sources, std_sources)]
115#[non_exhaustive]
116pub enum AcceptError {
117    #[error(transparent)]
118    Connecting {
119        source: crate::endpoint::ConnectingError,
120    },
121    #[error(transparent)]
122    Connection {
123        source: crate::endpoint::ConnectionError,
124    },
125    #[error(transparent)]
126    MissingRemoteEndpointId { source: RemoteEndpointIdError },
127    #[error("Not allowed.")]
128    NotAllowed {},
129    #[error(transparent)]
130    User { source: AnyError },
131}
132
133impl AcceptError {
134    /// Creates a new user error from an arbitrary error type.
135    // TODO(Frando): Rename to `from_std`
136    #[track_caller]
137    pub fn from_err<T: std::error::Error + Send + Sync + 'static>(value: T) -> Self {
138        e!(AcceptError::User {
139            source: AnyError::from_std(value)
140        })
141    }
142
143    /// Creates a new user error from an arbitrary boxed error.
144    #[track_caller]
145    pub fn from_boxed(value: Box<dyn std::error::Error + Send + Sync>) -> Self {
146        e!(AcceptError::User {
147            source: AnyError::from_std_box(value)
148        })
149    }
150}
151
152impl From<std::io::Error> for AcceptError {
153    fn from(err: std::io::Error) -> Self {
154        Self::from_err(err)
155    }
156}
157
158impl From<quic::ClosedStream> for AcceptError {
159    fn from(err: quic::ClosedStream) -> Self {
160        Self::from_err(err)
161    }
162}
163
164/// Verdict from a [`IncomingFilter`] for an incoming connection.
165///
166/// The filter can accept the connection, send a retry token to validate
167/// the source address, actively refuse the connection, or silently drop it.
168#[derive(Debug, Clone, Copy, PartialEq, Eq)]
169#[non_exhaustive]
170pub enum IncomingFilterOutcome {
171    /// Accept the connection.
172    Accept,
173    /// Tell the remote to retry with a token (a QUIC `RETRY` packet).
174    ///
175    /// What this does depends on the connection type:
176    ///
177    /// - **Direct (UDP) connections**: this is QUIC source address
178    ///   validation. If the socket address was spoofed, the retry token is
179    ///   sent to the spoofed address, so we never hear from the attacker
180    ///   again. If the address was real, the client repeats the connection
181    ///   attempt with the token, and the next [`Incoming`] for that flow has
182    ///   [`Incoming::remote_addr_validated`] set to `true`. The token is
183    ///   bound to the source address.
184    ///
185    /// - **Relay connections**: there is no source address to validate
186    ///   (the relay already vouches for the packet origin), so the
187    ///   "validation" itself has no security meaning. However, the retry
188    ///   still imposes a real cost on the client: an extra round trip
189    ///   through the relay plus the work of sending a fresh ClientHello
190    ///   with the token. This filters out adversarial clients that
191    ///   don't bother to handle retry tokens, and adds latency before
192    ///   we get to the more expensive part of the handshake. The next
193    ///   [`Incoming`] for that flow will also have
194    ///   [`Incoming::remote_addr_validated`] set to `true`, but again,
195    ///   that just means the client cooperated with the retry.
196    ///
197    /// In short: for direct connections, `Retry` is address validation;
198    /// for relay connections, it is a cost-imposition mechanism.
199    ///
200    /// [`Incoming`]: crate::endpoint::Incoming
201    /// [`Incoming::remote_addr_validated`]: crate::endpoint::Incoming::remote_addr_validated
202    Retry,
203    /// Actively refuse the connection. The remote will receive a
204    /// CONNECTION_REFUSED error immediately.
205    Reject,
206    /// Ignore the connection entirely. The remote gets no response and will
207    /// eventually time out.
208    Ignore,
209}
210
211/// Filter predicate used for early filtering of incoming connections before the handshake completes.
212///
213/// See [`RouterBuilder::incoming_filter`] for more details.
214pub type IncomingFilter =
215    Arc<dyn Fn(&crate::endpoint::Incoming) -> IncomingFilterOutcome + Send + Sync + 'static>;
216
217/// Handler for incoming connections.
218///
219/// A router accepts connections for arbitrary ALPN protocols.
220///
221/// With this trait, you can handle incoming connections for any protocol.
222///
223/// Implement this trait on a struct that should handle incoming connections.
224/// The protocol handler must then be registered on the endpoint for an ALPN protocol with
225/// [`crate::protocol::RouterBuilder::accept`].
226///
227/// See the [module documentation](crate::protocol) for an example.
228pub trait ProtocolHandler: Send + Sync + std::fmt::Debug + 'static {
229    /// Optional interception point to handle the `Accepting` state.
230    ///
231    /// Can be implemented as `async fn on_accepting(&self, accepting: Accepting) -> Result<Connection>`.
232    ///
233    /// Typically, this method is used as an early interception point to accept
234    /// or reject a connection.
235    ///
236    /// However, this method can also be used to implement the accept side of a
237    /// 0-RTT connection.
238    ///
239    /// ## 0-RTT
240    ///
241    /// `ProtocolHandler::on_accepting` allows you to take over the connection
242    /// state machine early in the handshake processes, by calling [`Accepting::into_0rtt`].
243    ///
244    /// When working with 0-RTT, you may want to implement all of your protocol
245    /// logic in `on_accepting`. This is fine because `on_accepting` can handle
246    /// long-running processes. In this case, the [`ProtocolHandler::accept`] method
247    /// can simply return `Ok(())`.
248    fn on_accepting(
249        &self,
250        accepting: Accepting,
251    ) -> impl Future<Output = Result<Connection, AcceptError>> + Send {
252        async move {
253            let conn = accepting.await?;
254            Ok(conn)
255        }
256    }
257
258    /// Handle an incoming connection.
259    ///
260    /// Can be implemented as `async fn accept(&self, connection: Connection) -> Result<()>`.
261    ///
262    /// The returned future runs on a freshly spawned tokio task so it can be long-running. Once
263    /// `accept()` returns, the connection is dropped. This means that it will be closed
264    /// if there are no other clones of the connection.  If there is a protocol error, you
265    /// can use [`Connection::close`] to send an error code to the remote peer. Returning
266    /// an `Err<AcceptError>` will also drop the connection and log a warning, but no
267    /// dedicated error code will be sent to the peer, so it's recommended to explicitly
268    /// close the connection within your accept handler.
269    ///
270    /// When [`Router::shutdown`] is called, no further connections will be accepted, and
271    /// the futures returned by [`Self::accept`] will be aborted after the future returned
272    /// from [`ProtocolHandler::shutdown`] completes.
273    fn accept(
274        &self,
275        connection: Connection,
276    ) -> impl Future<Output = Result<(), AcceptError>> + Send;
277
278    /// Called when the router shuts down.
279    ///
280    /// Can be implemented as `async fn shutdown(&self)`.
281    ///
282    /// This is called from [`Router::shutdown`]. The returned future is awaited before
283    /// the router closes the endpoint.
284    fn shutdown(&self) -> impl Future<Output = ()> + Send {
285        async move {}
286    }
287}
288
289impl<T: ProtocolHandler> ProtocolHandler for Arc<T> {
290    async fn on_accepting(&self, accepting: Accepting) -> Result<Connection, AcceptError> {
291        self.as_ref().on_accepting(accepting).await
292    }
293
294    async fn accept(&self, conn: Connection) -> Result<(), AcceptError> {
295        self.as_ref().accept(conn).await
296    }
297
298    async fn shutdown(&self) {
299        self.as_ref().shutdown().await
300    }
301}
302
303impl<T: ProtocolHandler> ProtocolHandler for Box<T> {
304    async fn on_accepting(&self, accepting: Accepting) -> Result<Connection, AcceptError> {
305        self.as_ref().on_accepting(accepting).await
306    }
307
308    async fn accept(&self, conn: Connection) -> Result<(), AcceptError> {
309        self.as_ref().accept(conn).await
310    }
311
312    async fn shutdown(&self) {
313        self.as_ref().shutdown().await
314    }
315}
316
317impl<T: ProtocolHandler> From<T> for Box<dyn DynProtocolHandler> {
318    fn from(value: T) -> Self {
319        Box::new(value)
320    }
321}
322
323/// A dyn-compatible version of [`ProtocolHandler`] that returns boxed futures.
324///
325/// Any type that implements [`ProtocolHandler`] automatically also implements [`DynProtocolHandler`].
326/// There is a also [`From`] impl to turn any type that implements [`ProtocolHandler`] into a
327/// `Box<dyn DynProtocolHandler>`.
328//
329// We are not using [`n0_future::boxed::BoxFuture] because we don't need a `'static` bound
330// on these futures.
331pub trait DynProtocolHandler: Send + Sync + std::fmt::Debug + 'static {
332    /// See [`ProtocolHandler::on_accepting`].
333    fn on_accepting(
334        &self,
335        accepting: Accepting,
336    ) -> Pin<Box<dyn Future<Output = Result<Connection, AcceptError>> + Send + '_>> {
337        Box::pin(async move {
338            let conn = accepting.await?;
339            Ok(conn)
340        })
341    }
342
343    /// See [`ProtocolHandler::accept`].
344    fn accept(
345        &self,
346        connection: Connection,
347    ) -> Pin<Box<dyn Future<Output = Result<(), AcceptError>> + Send + '_>>;
348
349    /// See [`ProtocolHandler::shutdown`].
350    fn shutdown(&self) -> Pin<Box<dyn Future<Output = ()> + Send + '_>> {
351        Box::pin(async move {})
352    }
353}
354
355impl<P: ProtocolHandler> DynProtocolHandler for P {
356    fn accept(
357        &self,
358        connection: Connection,
359    ) -> Pin<Box<dyn Future<Output = Result<(), AcceptError>> + Send + '_>> {
360        Box::pin(<Self as ProtocolHandler>::accept(self, connection))
361    }
362
363    fn on_accepting(
364        &self,
365        accepting: Accepting,
366    ) -> Pin<Box<dyn Future<Output = Result<Connection, AcceptError>> + Send + '_>> {
367        Box::pin(<Self as ProtocolHandler>::on_accepting(self, accepting))
368    }
369
370    fn shutdown(&self) -> Pin<Box<dyn Future<Output = ()> + Send + '_>> {
371        Box::pin(<Self as ProtocolHandler>::shutdown(self))
372    }
373}
374
375/// A typed map of protocol handlers, mapping them from ALPNs.
376#[derive(Debug, Default)]
377pub(crate) struct ProtocolMap {
378    /// List of ALPNs in insertion order.
379    alpns: Vec<Vec<u8>>,
380    /// Map of protocol handlers by ALPN.
381    map: HashMap<Vec<u8>, Box<dyn DynProtocolHandler>>,
382}
383
384impl ProtocolMap {
385    /// Returns the registered protocol handler for an ALPN as a [`Arc<dyn ProtocolHandler>`].
386    pub(crate) fn get(&self, alpn: &[u8]) -> Option<&dyn DynProtocolHandler> {
387        self.map.get(alpn).map(|p| &**p)
388    }
389
390    /// Inserts a protocol handler.
391    pub(crate) fn insert(&mut self, alpn: Vec<u8>, handler: Box<dyn DynProtocolHandler>) {
392        self.alpns.push(alpn.clone());
393        self.map.insert(alpn, handler);
394    }
395
396    /// Returns an iterator of all registered ALPN protocol identifiers.
397    pub(crate) fn alpns(&self) -> impl Iterator<Item = &Vec<u8>> {
398        self.alpns.iter()
399    }
400
401    /// Shuts down all protocol handlers.
402    ///
403    /// Calls and awaits [`ProtocolHandler::shutdown`] for all registered handlers concurrently.
404    pub(crate) async fn shutdown(&self) {
405        let handlers = self.map.values().map(|p| p.shutdown());
406        join_all(handlers).await;
407    }
408}
409
410impl Router {
411    /// Creates a new [`Router`] using given [`Endpoint`].
412    pub fn builder(endpoint: Endpoint) -> RouterBuilder {
413        RouterBuilder::new(endpoint)
414    }
415
416    /// Returns the [`Endpoint`] stored in this router.
417    pub fn endpoint(&self) -> &Endpoint {
418        &self.endpoint
419    }
420
421    /// Checks if the router is already shutdown.
422    pub fn is_shutdown(&self) -> bool {
423        self.cancel_token.is_cancelled()
424    }
425
426    /// Shuts down the accept loop cleanly.
427    ///
428    /// When this function returns, all [`ProtocolHandler`]s will be shutdown and
429    /// `Endpoint::close` will have been called.
430    ///
431    /// If already shutdown, it returns `Ok`.
432    ///
433    /// If some [`ProtocolHandler`] panicked in the accept loop, this will propagate
434    /// that panic into the result here.
435    pub async fn shutdown(&self) -> Result<(), n0_future::task::JoinError> {
436        if self.is_shutdown() {
437            return Ok(());
438        }
439
440        // Trigger shutdown of the main run task by activating the cancel token.
441        self.cancel_token.cancel();
442
443        // Wait for the main task to terminate.
444
445        // MutexGuard is not held across await point
446        let task = self.task.lock().expect("poisoned").take();
447        if let Some(task) = task {
448            task.await?;
449        }
450
451        Ok(())
452    }
453}
454
455impl RouterBuilder {
456    /// Creates a new router builder using given [`Endpoint`].
457    pub fn new(endpoint: Endpoint) -> Self {
458        Self {
459            endpoint,
460            protocols: ProtocolMap::default(),
461            incoming_filter: None,
462        }
463    }
464
465    /// Sets a filter that decides whether to accept an incoming connection before the
466    /// TLS handshake completes.
467    ///
468    /// The filter is called with the raw [`Incoming`] for each connection attempt
469    /// and returns an [`IncomingFilterOutcome`] that determines what happens next.
470    ///
471    /// Implementers have full access to the [`Incoming`] and can use any of its
472    /// methods (including [`Incoming::decrypt`]) to make their decision. Note that
473    /// `decrypt()` is relatively expensive, so filters should reject based on
474    /// cheaper signals (e.g. remote address) first.
475    ///
476    /// [`Incoming`]: crate::endpoint::Incoming
477    /// [`Incoming::decrypt`]: crate::endpoint::Incoming::decrypt
478    pub fn incoming_filter(mut self, filter: IncomingFilter) -> Self {
479        self.incoming_filter = Some(filter);
480        self
481    }
482
483    /// Configures the router to accept the [`ProtocolHandler`] when receiving a connection
484    /// with this `alpn`.
485    ///
486    /// `handler` can either be a type that implements [`ProtocolHandler`] or a
487    /// [`Box<dyn DynProtocolHandler>`].
488    ///
489    /// The protocols registered on the router are passed to [`Endpoint::set_alpns`] in the order
490    /// of the calls to [`Self::accept`]. Ordering matters for protocol negotiation. When an incoming
491    /// connection offers multiple ALPNs, the first matching ALPN will be chosen. This means that
492    /// your preferred protocol should be registered first on the router builder.
493    ///
494    /// [`Box<dyn DynProtocolHandler>`]: DynProtocolHandler
495    pub fn accept(
496        mut self,
497        alpn: impl AsRef<[u8]>,
498        handler: impl Into<Box<dyn DynProtocolHandler>>,
499    ) -> Self {
500        self.protocols
501            .insert(alpn.as_ref().to_vec(), handler.into());
502        self
503    }
504
505    /// Returns the [`Endpoint`] stored in this builder.
506    pub fn endpoint(&self) -> &Endpoint {
507        &self.endpoint
508    }
509
510    /// Spawns an accept loop and returns a handle to it encapsulated as the [`Router`].
511    #[must_use = "Router aborts when dropped, use Router::shutdown to shut the router down cleanly"]
512    pub fn spawn(self) -> Router {
513        // Update the endpoint with our alpns.
514        let alpns = self
515            .protocols
516            .alpns()
517            .map(|alpn| alpn.to_vec())
518            .collect::<Vec<_>>();
519
520        let protocols = Arc::new(self.protocols);
521        let incoming_filter = self.incoming_filter;
522        self.endpoint.set_alpns(alpns);
523
524        let mut join_set = JoinSet::new();
525        let endpoint = self.endpoint.clone();
526
527        // Our own shutdown works with a cancellation token.
528        let cancel = CancellationToken::new();
529        let cancel_token = cancel.clone();
530
531        let run_loop_fut = async move {
532            // Make sure to cancel the token, if this future ever exits.
533            let _cancel_guard = cancel_token.clone().drop_guard();
534            // We create a separate cancellation token to stop any `ProtocolHandler::accept` futures
535            // that are still running after `ProtocolHandler::shutdown` was called.
536            let handler_cancel_token = CancellationToken::new();
537
538            loop {
539                tokio::select! {
540                    biased;
541                    _ = cancel_token.cancelled() => {
542                        break;
543                    },
544                    // handle task terminations and quit on panics.
545                    Some(res) = join_set.join_next() => {
546                        match res {
547                            Err(outer) => {
548                                if outer.is_panic() {
549                                    error!("Task panicked: {outer:?}");
550                                    break;
551                                } else if outer.is_cancelled() {
552                                    trace!("Task cancelled: {outer:?}");
553                                } else {
554                                    error!("Task failed: {outer:?}");
555                                    break;
556                                }
557                            }
558                            Ok(Some(())) => {
559                                trace!("Task finished");
560                            }
561                            Ok(None) => {
562                                trace!("Task cancelled");
563                            }
564                        }
565                    },
566
567                    // handle incoming p2p connections.
568                    incoming = endpoint.accept() => {
569                        let Some(incoming) = incoming else {
570                            break; // Endpoint is closed.
571                        };
572
573                        if let Some(filter) = &incoming_filter {
574                            match filter(&incoming) {
575                                IncomingFilterOutcome::Accept => {}
576                                IncomingFilterOutcome::Retry => {
577                                    if incoming.remote_addr_validated() {
578                                        debug!(
579                                            "filter returned Retry for an already validated connection",
580                                        );
581                                    }
582                                    if let Err(err) = incoming.retry() {
583                                        err.into_incoming().refuse();
584                                    }
585                                    continue;
586                                }
587                                IncomingFilterOutcome::Reject => {
588                                    incoming.refuse();
589                                    continue;
590                                }
591                                IncomingFilterOutcome::Ignore => {
592                                    incoming.ignore();
593                                    continue;
594                                }
595                            }
596                        }
597
598                        let protocols = protocols.clone();
599                        let token = handler_cancel_token.child_token();
600                        let span = info_span!("router.accept", me=%endpoint.id().fmt_short(), remote=Empty, alpn=Empty);
601                        join_set.spawn(async move {
602                            token.run_until_cancelled(handle_connection(incoming, protocols)).await
603                        }.instrument(span));
604                    },
605                }
606            }
607
608            // We first shutdown the protocol handlers to give them a chance to close connections gracefully.
609            protocols.shutdown().await;
610            // We now cancel the remaining `ProtocolHandler::accept` futures.
611            handler_cancel_token.cancel();
612            // Now we close the endpoint. This will force-close all connections that are not yet closed.
613            endpoint.close().await;
614            // Finally, we abort the remaining accept tasks. This should be a noop because we already cancelled
615            // the futures above.
616            tracing::debug!("Shutting down remaining tasks");
617            join_set.abort_all();
618            while let Some(res) = join_set.join_next().await {
619                match res {
620                    Err(err) if err.is_panic() => error!("Task panicked: {err:?}"),
621                    _ => {}
622                }
623            }
624        };
625        let task = task::spawn(run_loop_fut.instrument(tracing::Span::current()));
626        let task = AbortOnDropHandle::new(task);
627
628        Router {
629            endpoint: self.endpoint,
630            task: Arc::new(Mutex::new(Some(task))),
631            cancel_token: cancel,
632        }
633    }
634}
635
636async fn handle_connection(incoming: crate::endpoint::Incoming, protocols: Arc<ProtocolMap>) {
637    let mut accepting = match incoming.accept() {
638        Ok(conn) => conn,
639        Err(err) => {
640            warn!("Ignoring connection: accepting failed: {err:#}");
641            return;
642        }
643    };
644    let alpn = match accepting.alpn().await {
645        Ok(alpn) => alpn,
646        Err(err) => {
647            warn!("Ignoring connection: invalid handshake: {err:#}");
648            return;
649        }
650    };
651    tracing::Span::current().record("alpn", String::from_utf8_lossy(&alpn).to_string());
652
653    let Some(handler) = protocols.get(&alpn) else {
654        warn!("Ignoring connection: unsupported ALPN protocol");
655        return;
656    };
657    match handler.on_accepting(accepting).await {
658        Ok(connection) => {
659            tracing::Span::current().record(
660                "remote",
661                tracing::field::display(connection.remote_id().fmt_short()),
662            );
663
664            if let Err(err) = handler.accept(connection).await {
665                warn!("Handling incoming connection ended with error: {err}");
666            }
667        }
668        Err(err) => {
669            warn!("Accepting incoming connection ended with error: {err}");
670        }
671    }
672}
673
674#[cfg(all(test, with_crypto_provider))]
675mod tests {
676    use std::{sync::Mutex, time::Duration};
677
678    use n0_error::{Result, StdResultExt};
679    use n0_tracing_test::traced_test;
680
681    use super::*;
682    use crate::endpoint::{
683        ApplicationClose, BeforeConnectOutcome, ConnectError, ConnectOptions, ConnectWithOptsError,
684        ConnectionError, EndpointHooks, presets,
685    };
686
687    #[tokio::test]
688    async fn test_shutdown() -> Result {
689        let endpoint = Endpoint::bind(presets::Minimal).await?;
690        let router = Router::builder(endpoint.clone()).spawn();
691
692        assert!(!router.is_shutdown());
693        assert!(!endpoint.is_closed());
694
695        router.shutdown().await.anyerr()?;
696
697        assert!(router.is_shutdown());
698        assert!(endpoint.is_closed());
699
700        Ok(())
701    }
702
703    // The protocol definition:
704    #[derive(Debug, Clone)]
705    struct Echo;
706
707    const ECHO_ALPN: &[u8] = b"/iroh/echo/1";
708
709    impl ProtocolHandler for Echo {
710        async fn accept(&self, connection: Connection) -> Result<(), AcceptError> {
711            println!("accepting echo");
712            let (mut send, mut recv) = connection.accept_bi().await?;
713
714            // Echo any bytes received back directly.
715            let _bytes_sent = tokio::io::copy(&mut recv, &mut send).await?;
716
717            send.finish()?;
718            connection.closed().await;
719
720            Ok(())
721        }
722    }
723
724    #[tokio::test]
725    async fn test_limiter_hook() -> Result {
726        // tracing_subscriber::fmt::try_init().ok();
727        #[derive(Debug, Default)]
728        struct LimitHook;
729        impl EndpointHooks for LimitHook {
730            async fn before_connect<'a>(
731                &'a self,
732                _remote_addr: &'a iroh_base::EndpointAddr,
733                alpn: &'a [u8],
734            ) -> BeforeConnectOutcome {
735                assert_eq!(alpn, ECHO_ALPN);
736
737                // deny all access
738                BeforeConnectOutcome::Reject
739            }
740        }
741
742        let e1 = Endpoint::bind(presets::Minimal).await?;
743
744        let r1 = Router::builder(e1.clone()).accept(ECHO_ALPN, Echo).spawn();
745
746        let addr1 = r1.endpoint().addr();
747        dbg!(&addr1);
748        let e2 = Endpoint::builder(presets::Minimal)
749            .hooks(LimitHook)
750            .bind()
751            .await?;
752
753        println!("connecting");
754        let conn_err = e2.connect(addr1, ECHO_ALPN).await.unwrap_err();
755
756        assert!(matches!(
757            conn_err,
758            ConnectError::Connect {
759                source: ConnectWithOptsError::LocallyRejected { .. },
760                ..
761            }
762        ));
763
764        r1.shutdown().await.anyerr()?;
765        e2.close().await;
766
767        Ok(())
768    }
769
770    /// Test that `Accepting::remote_addr()` is consistent with `Incoming::remote_addr()`.
771    #[tokio::test]
772    #[traced_test]
773    async fn test_accepting_remote_addr() -> Result {
774        use crate::endpoint::{IncomingAddr, presets};
775
776        let e1 = Endpoint::builder(presets::Minimal)
777            .alpns(vec![ECHO_ALPN.to_vec()])
778            .bind()
779            .await?;
780        let addr1 = e1.addr();
781
782        let e2 = Endpoint::bind(presets::Minimal).await?;
783
784        // Spawn the client connect so it runs concurrently with accept.
785        let connect_task = tokio::spawn({
786            let addr1 = addr1.clone();
787            let e2 = e2.clone();
788            async move { e2.connect(addr1, ECHO_ALPN).await }
789        });
790
791        let incoming = e1.accept().await.expect("accept");
792        let incoming_addr = incoming.remote_addr();
793        assert!(matches!(incoming_addr, IncomingAddr::Ip(_)));
794
795        let accepting = incoming.accept().anyerr()?;
796        assert_eq!(incoming_addr, accepting.remote_addr());
797
798        // Clean up.
799        drop(accepting);
800        drop(connect_task);
801        e1.close().await;
802        e2.close().await;
803        Ok(())
804    }
805
806    mod incoming_filter {
807        use std::{
808            sync::{
809                Arc,
810                atomic::{AtomicBool, Ordering::Relaxed},
811            },
812            time::Duration,
813        };
814
815        use n0_error::{Result, StdResultExt};
816        use n0_tracing_test::traced_test;
817
818        use crate::{
819            Endpoint, EndpointAddr,
820            endpoint::presets,
821            protocol::{
822                IncomingFilterOutcome, Router,
823                tests::{ECHO_ALPN, Echo},
824            },
825        };
826
827        /// Two direct endpoints with a filtered router on the first.
828        ///
829        /// Binds to IPv4 loopback only so retry-token validation works on
830        /// multi-homed CI hosts (tokens are tied to the source address).
831        async fn direct_pair<F>(filter: F) -> Result<(Router, Endpoint, EndpointAddr)>
832        where
833            F: Fn(&crate::endpoint::Incoming) -> IncomingFilterOutcome + Send + Sync + 'static,
834        {
835            let e1 = Endpoint::builder(presets::Minimal)
836                .clear_ip_transports()
837                .bind_addr((std::net::Ipv4Addr::LOCALHOST, 0))
838                .anyerr()?
839                .bind()
840                .await?;
841            let r1 = Router::builder(e1.clone())
842                .incoming_filter(Arc::new(filter))
843                .accept(ECHO_ALPN, Echo)
844                .spawn();
845            let addr = r1.endpoint().addr();
846            let e2 = Endpoint::builder(presets::Minimal)
847                .clear_ip_transports()
848                .bind_addr((std::net::Ipv4Addr::LOCALHOST, 0))
849                .anyerr()?
850                .bind()
851                .await?;
852            Ok((r1, e2, addr))
853        }
854
855        /// Two relay-only endpoints with a filtered router on the first.
856        async fn relay_pair<F>(
857            filter: F,
858        ) -> Result<(Router, Endpoint, EndpointAddr, impl std::any::Any)>
859        where
860            F: Fn(&crate::endpoint::Incoming) -> IncomingFilterOutcome + Send + Sync + 'static,
861        {
862            let (_relay_map, relay_url, guard) =
863                crate::test_utils::run_relay_server().await.anyerr()?;
864            let relay_mode = crate::RelayMode::Custom(crate::RelayMap::from(relay_url.clone()));
865
866            let e1 = Endpoint::builder(presets::Minimal)
867                .relay_mode(relay_mode.clone())
868                .ca_tls_config(crate::tls::CaTlsConfig::insecure_skip_verify())
869                .bind()
870                .await?;
871            let r1 = Router::builder(e1.clone())
872                .incoming_filter(Arc::new(filter))
873                .accept(ECHO_ALPN, Echo)
874                .spawn();
875            let addr = EndpointAddr::new(e1.id()).with_relay_url(relay_url);
876            let e2 = Endpoint::builder(presets::Minimal)
877                .relay_mode(relay_mode)
878                .ca_tls_config(crate::tls::CaTlsConfig::insecure_skip_verify())
879                .bind()
880                .await?;
881            Ok((r1, e2, addr, guard))
882        }
883
884        #[tokio::test]
885        #[traced_test]
886        async fn addr_retry() -> Result {
887            let (r1, e2, addr) = direct_pair(|incoming| {
888                if !incoming.remote_addr_validated() {
889                    IncomingFilterOutcome::Retry
890                } else {
891                    IncomingFilterOutcome::Accept
892                }
893            })
894            .await?;
895            // Server sends retry (unvalidated), then accepts once validated.
896            assert!(e2.connect(addr, ECHO_ALPN).await.is_ok());
897            r1.shutdown().await.anyerr()?;
898            e2.close().await;
899            Ok(())
900        }
901
902        #[tokio::test]
903        #[traced_test]
904        async fn addr_reject() -> Result {
905            let (r1, e2, addr) = direct_pair(|_| IncomingFilterOutcome::Reject).await?;
906            assert!(e2.connect(addr, ECHO_ALPN).await.is_err());
907            r1.shutdown().await.anyerr()?;
908            e2.close().await;
909            Ok(())
910        }
911
912        #[tokio::test]
913        #[traced_test]
914        async fn addr_ignore() -> Result {
915            let (r1, e2, addr) = direct_pair(|_| IncomingFilterOutcome::Ignore).await?;
916            // No response at all — connect times out.
917            let result =
918                tokio::time::timeout(Duration::from_millis(500), e2.connect(addr, ECHO_ALPN)).await;
919            assert!(result.is_err(), "expected timeout");
920            r1.shutdown().await.anyerr()?;
921            e2.close().await;
922            Ok(())
923        }
924
925        #[tokio::test]
926        #[traced_test]
927        async fn relay_reject() -> Result {
928            let (r1, e2, addr, _guard) = relay_pair(|_| IncomingFilterOutcome::Reject).await?;
929            assert!(e2.connect(addr, ECHO_ALPN).await.is_err());
930            r1.shutdown().await.anyerr()?;
931            e2.close().await;
932            Ok(())
933        }
934
935        #[tokio::test]
936        #[traced_test]
937        async fn relay_ignore() -> Result {
938            let (r1, e2, addr, _guard) = relay_pair(|_| IncomingFilterOutcome::Ignore).await?;
939            let result =
940                tokio::time::timeout(Duration::from_millis(500), e2.connect(addr, ECHO_ALPN)).await;
941            assert!(result.is_err(), "expected timeout");
942            r1.shutdown().await.anyerr()?;
943            e2.close().await;
944            Ok(())
945        }
946
947        /// Verify that returning `Retry` for a direct connection causes the
948        /// remote to retry with a token, after which `validated` is true.
949        #[tokio::test]
950        #[traced_test]
951        async fn addr_retry_then_validated() -> Result {
952            let saw_validated = Arc::<AtomicBool>::default();
953            let saw_unvalidated = Arc::<AtomicBool>::default();
954            let (sv, su) = (saw_validated.clone(), saw_unvalidated.clone());
955
956            let (r1, e2, addr) = direct_pair(move |incoming| {
957                if incoming.remote_addr_validated() {
958                    sv.store(true, Relaxed);
959                    IncomingFilterOutcome::Accept
960                } else {
961                    su.store(true, Relaxed);
962                    IncomingFilterOutcome::Retry
963                }
964            })
965            .await?;
966
967            // The connection should now succeed: first attempt returns Retry,
968            // the client retries with the token, the second attempt is
969            // validated and accepted.
970            let _conn = e2.connect(addr, ECHO_ALPN).await?;
971
972            assert!(saw_unvalidated.load(Relaxed));
973            assert!(saw_validated.load(Relaxed));
974
975            r1.shutdown().await.anyerr()?;
976            e2.close().await;
977            Ok(())
978        }
979
980        /// Verify that returning `Retry` for a relay connection also causes
981        /// the remote to retry with a token. The "validation" has no
982        /// security meaning over a relay, but it does impose a round-trip
983        /// cost on the client.
984        #[tokio::test]
985        #[traced_test]
986        async fn relay_retry_then_validated() -> Result {
987            let saw_validated = Arc::<AtomicBool>::default();
988            let saw_unvalidated = Arc::<AtomicBool>::default();
989            let (sv, su) = (saw_validated.clone(), saw_unvalidated.clone());
990
991            let (r1, e2, addr, _guard) = relay_pair(move |incoming| {
992                if incoming.remote_addr_validated() {
993                    sv.store(true, Relaxed);
994                    IncomingFilterOutcome::Accept
995                } else {
996                    su.store(true, Relaxed);
997                    IncomingFilterOutcome::Retry
998                }
999            })
1000            .await?;
1001
1002            let _conn = e2.connect(addr, ECHO_ALPN).await?;
1003
1004            assert!(
1005                saw_unvalidated.load(Relaxed),
1006                "expected unvalidated incoming"
1007            );
1008            assert!(
1009                saw_validated.load(Relaxed),
1010                "expected validated incoming after retry"
1011            );
1012
1013            r1.shutdown().await.anyerr()?;
1014            e2.close().await;
1015            Ok(())
1016        }
1017    }
1018
1019    #[tokio::test]
1020    async fn test_graceful_shutdown() -> Result {
1021        #[derive(Debug, Clone, Default)]
1022        struct TestProtocol {
1023            connections: Arc<Mutex<Vec<Connection>>>,
1024        }
1025
1026        const TEST_ALPN: &[u8] = b"/iroh/test/1";
1027
1028        impl ProtocolHandler for TestProtocol {
1029            async fn accept(&self, connection: Connection) -> Result<(), AcceptError> {
1030                self.connections.lock().expect("poisoned").push(connection);
1031                Ok(())
1032            }
1033
1034            async fn shutdown(&self) {
1035                tokio::time::sleep(Duration::from_millis(100)).await;
1036                let mut connections = self.connections.lock().expect("poisoned");
1037                for conn in connections.drain(..) {
1038                    conn.close(42u32.into(), b"shutdown");
1039                }
1040            }
1041        }
1042
1043        eprintln!("creating ep1");
1044        let endpoint = Endpoint::bind(presets::Minimal).await?;
1045        let router = Router::builder(endpoint)
1046            .accept(TEST_ALPN, TestProtocol::default())
1047            .spawn();
1048        eprintln!("waiting for endpoint addr");
1049        let addr = router.endpoint().addr();
1050
1051        eprintln!("creating ep2");
1052        let endpoint2 = Endpoint::bind(presets::Minimal).await?;
1053        eprintln!("connecting to {addr:?}");
1054        let conn = endpoint2.connect(addr, TEST_ALPN).await?;
1055
1056        eprintln!("starting shutdown");
1057        router.shutdown().await.anyerr()?;
1058
1059        eprintln!("waiting for closed conn");
1060        let reason = conn.closed().await;
1061        assert_eq!(
1062            reason,
1063            ConnectionError::ApplicationClosed(ApplicationClose {
1064                error_code: 42u32.into(),
1065                reason: b"shutdown".to_vec().into()
1066            })
1067        );
1068        Ok(())
1069    }
1070
1071    #[tokio::test]
1072    async fn protocol_negotiation() -> n0_error::Result<()> {
1073        // We define two ALPNs.
1074        const ALPN_1: &[u8] = b"myproto/1";
1075        const ALPN_2: &[u8] = b"myproto/2";
1076
1077        #[derive(Debug, Clone)]
1078        struct Handler1;
1079
1080        #[derive(Debug, Clone)]
1081        struct Handler2;
1082
1083        impl ProtocolHandler for Handler1 {
1084            async fn accept(&self, _connection: Connection) -> Result<(), AcceptError> {
1085                Ok(())
1086            }
1087        }
1088
1089        impl ProtocolHandler for Handler2 {
1090            async fn accept(&self, _connection: Connection) -> Result<(), AcceptError> {
1091                Ok(())
1092            }
1093        }
1094
1095        let server = Endpoint::bind(presets::N0).await?;
1096        let server_addr = server.addr();
1097
1098        let router = Router::builder(server)
1099            // Ordering is preferred-first.
1100            .accept(ALPN_2, Handler2)
1101            .accept(ALPN_1, Handler1)
1102            .spawn();
1103
1104        let client = Endpoint::bind(presets::N0).await?;
1105
1106        // We expect ALPN_2 to be negotiated.
1107        let conn = client
1108            .connect_with_opts(
1109                server_addr.clone(),
1110                ALPN_1,
1111                ConnectOptions::new().with_additional_alpns(vec![ALPN_2.to_vec()]),
1112            )
1113            .await?
1114            .await?;
1115        assert_eq!(conn.alpn(), ALPN_2);
1116
1117        // Ordering is server-side, so this must yield ALPN_2 as well.
1118        let conn = client
1119            .connect_with_opts(
1120                server_addr,
1121                ALPN_2,
1122                ConnectOptions::new().with_additional_alpns(vec![ALPN_1.to_vec()]),
1123            )
1124            .await?
1125            .await?;
1126        assert_eq!(conn.alpn(), ALPN_2);
1127
1128        client.close().await;
1129        router.shutdown().await.unwrap();
1130        Ok(())
1131    }
1132}