iroh/endpoint/
hooks.rs

1use std::pin::Pin;
2
3use iroh_base::EndpointAddr;
4
5use crate::endpoint::{connection::Connection, quic::VarInt};
6
7type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
8
9/// Outcome of [`EndpointHooks::before_connect`]
10#[derive(Debug)]
11pub enum BeforeConnectOutcome {
12    /// Accept the connect attempt.
13    Accept,
14    /// Reject the connect attempt.
15    Reject,
16}
17
18/// Outcome of [`EndpointHooks::after_handshake`]
19#[derive(Debug)]
20pub enum AfterHandshakeOutcome {
21    /// Accept the connection.
22    Accept,
23    /// Reject and close the connection.
24    ///
25    /// See [`Connection::close`] for details on `error_code` and `reason`.
26    ///
27    /// [`Connection::close`]: crate::endpoint::Connection::close
28    Reject {
29        /// Error code to send with the connection close frame.
30        error_code: VarInt,
31        /// Close reason to send with the connection close frame.
32        reason: Vec<u8>,
33    },
34}
35
36impl AfterHandshakeOutcome {
37    /// Returns [`Self::Accept`].
38    pub fn accept() -> Self {
39        Self::Accept
40    }
41
42    /// Returns [`Self::Reject`].
43    pub fn reject(&self, error_code: VarInt, reason: &[u8]) -> Self {
44        Self::Reject {
45            error_code,
46            reason: reason.to_vec(),
47        }
48    }
49}
50
51/// EndpointHooks intercept the connection establishment process of an [`Endpoint`].
52///
53/// Use [`Builder::hooks`] to install hooks onto an endpoint.
54///
55/// For each hook, all installed hooks are invoked in the order they were installed on
56/// the endpoint builder. If a hook returns `Accept`, processing continues with the next
57/// hook. If a hook returns `Reject`, processing is aborted and further hooks
58/// are not invoked for this hook point.
59///
60/// ## Notes to implementers
61///
62/// As hooks are stored on the endpoint, you must make sure to never store an [`Endpoint`]
63/// on the hook struct itself, as this would create reference counting loop and cause the
64/// endpoint to never be dropped, leaking memory.
65///
66/// [`Endpoint`]: crate::Endpoint
67/// [`Builder::hooks`]: crate::endpoint::Builder::hooks
68pub trait EndpointHooks: std::fmt::Debug + Send + Sync {
69    /// Intercept outgoing connections before they are started.
70    ///
71    /// This is called whenever a new outgoing connection is initiated via [`Endpoint::connect`]
72    /// or [`Endpoint::connect_with_opts`].
73    ///
74    /// If any hook returns [`BeforeConnectOutcome::Reject`], the connection attempt is aborted
75    /// before any packets are sent to the remote.
76    ///
77    /// [`Endpoint::connect`]: crate::Endpoint::connect
78    /// [`Endpoint::connect_with_opts`]: crate::Endpoint::connect_with_opts
79    fn before_connect<'a>(
80        &'a self,
81        _remote_addr: &'a EndpointAddr,
82        _alpn: &'a [u8],
83    ) -> impl Future<Output = BeforeConnectOutcome> + Send + 'a {
84        async { BeforeConnectOutcome::Accept }
85    }
86
87    /// Intercept both incoming and outgoing connections once the TLS handshake has completed.
88    ///
89    /// At this point in time, we know the remote's endpoint id and ALPN. If any hook returns
90    /// [`AfterHandshakeOutcome::Reject`], the connection is closed with the provided error code
91    /// and reason.
92    ///
93    /// The hook receives the [`Connection`] by reference so that implementations can read any
94    /// information they need synchronously. Do not clone the [`Connection`] out of the hook:
95    /// holding a strong [`Connection`] handle keeps the connection alive and disables
96    /// close-on-drop, which the primary use sites of the connection might rely on. If you need to
97    /// keep a reference for later (for example to wait for the connection to close, or to
98    /// look up the connection in a map), call [`Connection::weak_handle`] and store the
99    /// resulting [`WeakConnectionHandle`] instead.
100    ///
101    /// [`WeakConnectionHandle`]: crate::endpoint::WeakConnectionHandle
102    fn after_handshake<'a>(
103        &'a self,
104        _conn: &'a Connection,
105    ) -> impl Future<Output = AfterHandshakeOutcome> + Send + 'a {
106        async { AfterHandshakeOutcome::accept() }
107    }
108}
109
110pub(crate) trait DynEndpointHooks: std::fmt::Debug + Send + Sync {
111    fn before_connect<'a>(
112        &'a self,
113        remote_addr: &'a EndpointAddr,
114        alpn: &'a [u8],
115    ) -> BoxFuture<'a, BeforeConnectOutcome>;
116    fn after_handshake<'a>(&'a self, conn: &'a Connection) -> BoxFuture<'a, AfterHandshakeOutcome>;
117}
118
119impl<T: EndpointHooks> DynEndpointHooks for T {
120    fn before_connect<'a>(
121        &'a self,
122        remote_addr: &'a EndpointAddr,
123        alpn: &'a [u8],
124    ) -> BoxFuture<'a, BeforeConnectOutcome> {
125        Box::pin(EndpointHooks::before_connect(self, remote_addr, alpn))
126    }
127
128    fn after_handshake<'a>(&'a self, conn: &'a Connection) -> BoxFuture<'a, AfterHandshakeOutcome> {
129        Box::pin(EndpointHooks::after_handshake(self, conn))
130    }
131}
132
133#[derive(Debug, Default)]
134pub(crate) struct EndpointHooksList {
135    inner: Vec<Box<dyn DynEndpointHooks>>,
136}
137
138impl EndpointHooksList {
139    pub(super) fn push(&mut self, hook: impl EndpointHooks + 'static) {
140        let hook: Box<dyn DynEndpointHooks> = Box::new(hook);
141        self.inner.push(hook);
142    }
143
144    pub(super) async fn before_connect(
145        &self,
146        remote_addr: &EndpointAddr,
147        alpn: &[u8],
148    ) -> BeforeConnectOutcome {
149        for hook in self.inner.iter() {
150            match hook.before_connect(remote_addr, alpn).await {
151                BeforeConnectOutcome::Accept => continue,
152                reject @ BeforeConnectOutcome::Reject => {
153                    return reject;
154                }
155            }
156        }
157        BeforeConnectOutcome::Accept
158    }
159
160    pub(super) async fn after_handshake(&self, conn: &Connection) -> AfterHandshakeOutcome {
161        for hook in self.inner.iter() {
162            match hook.after_handshake(conn).await {
163                AfterHandshakeOutcome::Accept => continue,
164                reject @ AfterHandshakeOutcome::Reject { .. } => {
165                    return reject;
166                }
167            }
168        }
169        AfterHandshakeOutcome::Accept
170    }
171}