Skip to main content

iota_http/
listener.rs

1// Copyright (c) Mysten Labs, Inc.
2// Modifications Copyright (c) 2025 IOTA Stiftung
3// SPDX-License-Identifier: Apache-2.0
4
5use std::{
6    net::{IpAddr, Ipv6Addr},
7    time::Duration,
8};
9
10/// Types that can listen for connections.
11pub trait Listener: Send + 'static {
12    /// The listener's IO type.
13    type Io: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin + Send + 'static;
14
15    /// The listener's address type.
16    // all these bounds are necessary to add this information in a request extension
17    type Addr: Clone + Send + Sync + 'static;
18
19    /// Accept a new incoming connection to this listener.
20    ///
21    /// If the underlying accept call can return an error, this function must
22    /// take care of logging and retrying.
23    fn accept(&mut self) -> impl std::future::Future<Output = (Self::Io, Self::Addr)> + Send;
24
25    /// Returns the local address that this listener is bound to.
26    fn local_addr(&self) -> std::io::Result<Self::Addr>;
27
28    /// Identifies the client at `client`, the remote address of a connection
29    /// this listener accepted. Connections with equal keys count as one client
30    /// under `max_connections_per_client_ip`.
31    fn client_prefix(&self, client: &Self::Addr) -> Vec<u8>;
32}
33
34/// Extensions to [`Listener`].
35pub trait ListenerExt: Listener + Sized {
36    /// Run a mutable closure on every accepted `Io`.
37    ///
38    /// # Example
39    ///
40    /// ```
41    /// use iota_http::ListenerExt;
42    /// use tracing::trace;
43    ///
44    /// # async {
45    /// let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
46    ///     .await
47    ///     .unwrap()
48    ///     .tap_io(|tcp_stream| {
49    ///         if let Err(err) = tcp_stream.set_nodelay(true) {
50    ///             trace!("failed to set TCP_NODELAY on incoming connection: {err:#}");
51    ///         }
52    ///     });
53    /// # };
54    /// ```
55    fn tap_io<F>(self, tap_fn: F) -> TapIo<Self, F>
56    where
57        F: FnMut(&mut Self::Io) + Send + 'static,
58    {
59        TapIo {
60            listener: self,
61            tap_fn,
62        }
63    }
64}
65
66impl<L: Listener> ListenerExt for L {}
67
68impl Listener for tokio::net::TcpListener {
69    type Io = tokio::net::TcpStream;
70    type Addr = std::net::SocketAddr;
71
72    async fn accept(&mut self) -> (Self::Io, Self::Addr) {
73        loop {
74            match Self::accept(self).await {
75                Ok(tup) => return tup,
76                Err(e) => handle_accept_error(e).await,
77            }
78        }
79    }
80
81    #[inline]
82    fn local_addr(&self) -> std::io::Result<Self::Addr> {
83        Self::local_addr(self)
84    }
85
86    fn client_prefix(&self, client: &Self::Addr) -> Vec<u8> {
87        // A bare listener has no settings to take a prefix length from.
88        client_prefix(client.ip(), DEFAULT_IPV6_PREFIX_LEN)
89    }
90}
91
92#[derive(Debug)]
93pub struct TcpListenerWithOptions {
94    inner: tokio::net::TcpListener,
95    keepalive: Option<Duration>,
96    ipv6_prefix_len: u8,
97}
98
99impl TcpListenerWithOptions {
100    pub fn new<A: std::net::ToSocketAddrs>(
101        addr: A,
102        keepalive: Option<Duration>,
103        ipv6_prefix_len: u8,
104    ) -> Result<Self, crate::BoxError> {
105        let std_listener = std::net::TcpListener::bind(addr)?;
106        std_listener.set_nonblocking(true)?;
107        let listener = tokio::net::TcpListener::from_std(std_listener)?;
108
109        Ok(Self::from_listener(listener, keepalive, ipv6_prefix_len))
110    }
111
112    /// Creates a new `TcpIncoming` from an existing `tokio::net::TcpListener`.
113    pub fn from_listener(
114        listener: tokio::net::TcpListener,
115        keepalive: Option<Duration>,
116        ipv6_prefix_len: u8,
117    ) -> Self {
118        Self {
119            inner: listener,
120            keepalive,
121            ipv6_prefix_len,
122        }
123    }
124
125    // Consistent with hyper-0.14, this function does not return an error.
126    fn set_accepted_socket_options(&self, stream: &tokio::net::TcpStream) {
127        if let Err(e) = stream.set_nodelay(true) {
128            tracing::warn!("error trying to set TCP nodelay: {}", e);
129        }
130
131        if let Some(timeout) = self.keepalive {
132            let sock_ref = socket2::SockRef::from(&stream);
133            let sock_keepalive = socket2::TcpKeepalive::new().with_time(timeout);
134
135            if let Err(e) = sock_ref.set_tcp_keepalive(&sock_keepalive) {
136                tracing::warn!("error trying to set TCP keepalive: {}", e);
137            }
138        }
139    }
140}
141
142impl Listener for TcpListenerWithOptions {
143    type Io = tokio::net::TcpStream;
144    type Addr = std::net::SocketAddr;
145
146    async fn accept(&mut self) -> (Self::Io, Self::Addr) {
147        let (io, addr) = Listener::accept(&mut self.inner).await;
148        self.set_accepted_socket_options(&io);
149        (io, addr)
150    }
151
152    #[inline]
153    fn local_addr(&self) -> std::io::Result<Self::Addr> {
154        Listener::local_addr(&self.inner)
155    }
156
157    fn client_prefix(&self, client: &Self::Addr) -> Vec<u8> {
158        client_prefix(client.ip(), self.ipv6_prefix_len)
159    }
160}
161
162// Uncomment once we update tokio to >=1.41.0
163// #[cfg(unix)]
164// impl Listener for tokio::net::UnixListener {
165//     type Io = tokio::net::UnixStream;
166//     type Addr = std::os::unix::net::SocketAddr;
167
168//     async fn accept(&mut self) -> (Self::Io, Self::Addr) {
169//         loop {
170//             match Self::accept(self).await {
171//                 Ok((io, addr)) => return (io, addr.into()),
172//                 Err(e) => handle_accept_error(e).await,
173//             }
174//         }
175//     }
176
177//     #[inline]
178//     fn local_addr(&self) -> std::io::Result<Self::Addr> {
179//         Self::local_addr(self).map(Into::into)
180//     }
181// }
182
183/// Return type of [`ListenerExt::tap_io`].
184///
185/// See that method for details.
186pub struct TapIo<L, F> {
187    listener: L,
188    tap_fn: F,
189}
190
191impl<L, F> std::fmt::Debug for TapIo<L, F>
192where
193    L: Listener + std::fmt::Debug,
194{
195    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
196        f.debug_struct("TapIo")
197            .field("listener", &self.listener)
198            .finish_non_exhaustive()
199    }
200}
201
202impl<L, F> Listener for TapIo<L, F>
203where
204    L: Listener,
205    F: FnMut(&mut L::Io) + Send + 'static,
206{
207    type Io = L::Io;
208    type Addr = L::Addr;
209
210    async fn accept(&mut self) -> (Self::Io, Self::Addr) {
211        let (mut io, addr) = self.listener.accept().await;
212        (self.tap_fn)(&mut io);
213        (io, addr)
214    }
215
216    fn local_addr(&self) -> std::io::Result<Self::Addr> {
217        self.listener.local_addr()
218    }
219
220    fn client_prefix(&self, client: &Self::Addr) -> Vec<u8> {
221        self.listener.client_prefix(client)
222    }
223}
224
225async fn handle_accept_error(e: std::io::Error) {
226    if is_connection_error(&e) {
227        return;
228    }
229
230    // [From `hyper::Server` in 0.14](https://github.com/hyperium/hyper/blob/v0.14.27/src/server/tcp.rs#L186)
231    //
232    // > A possible scenario is that the process has hit the max open files
233    // > allowed, and so trying to accept a new connection will fail with
234    // > `EMFILE`. In some cases, it's preferable to just wait for some time, if
235    // > the application will likely close some files (or connections), and try
236    // > to accept the connection again. If this option is `true`, the error
237    // > will be logged at the `error` level, since it is still a big deal,
238    // > and then the listener will sleep for 1 second.
239    //
240    // hyper allowed customizing this but axum does not.
241    tracing::error!("accept error: {e}");
242    tokio::time::sleep(Duration::from_secs(1)).await;
243}
244
245fn is_connection_error(e: &std::io::Error) -> bool {
246    use std::io::ErrorKind;
247
248    matches!(
249        e.kind(),
250        ErrorKind::ConnectionRefused
251            | ErrorKind::ConnectionAborted
252            | ErrorKind::ConnectionReset
253            | ErrorKind::BrokenPipe
254            | ErrorKind::Interrupted
255            | ErrorKind::WouldBlock
256            | ErrorKind::TimedOut
257    )
258}
259
260/// How many leading bits of an IPv6 address identify its client when no other
261/// length is configured: the size of the network a single site is usually
262/// given.
263pub const DEFAULT_IPV6_PREFIX_LEN: u8 = 64;
264
265/// The shortest IPv6 prefix length accepted. The ranges that
266/// [`ipv6_prefix_len_of`] keeps whole are set by at most the first 32 bits, so
267/// cutting any other address to 32 bits or more never lands it in one.
268pub(crate) const MIN_IPV6_PREFIX_LEN: u8 = 32;
269
270/// The key of the client at `client`. An IPv4 client is its full address. An
271/// IPv6 client is the first `ipv6_prefix_len` bits of its address, with the
272/// rest set to zero: the server cannot see how long a client's own network
273/// prefix is, so it assumes the same length for every IPv6 client. An IPv4
274/// client seen as an IPv4-mapped IPv6 address counts as that IPv4 address.
275/// See [`ipv6_prefix_len_of`] for the IPv6 addresses kept whole.
276///
277/// The key of an IPv4 client is 4 bytes long and that of an IPv6 client 16,
278/// so the two never collide.
279fn client_prefix(client: IpAddr, ipv6_prefix_len: u8) -> Vec<u8> {
280    match client.to_canonical() {
281        IpAddr::V6(address) => {
282            let prefix_len = ipv6_prefix_len_of(address, ipv6_prefix_len);
283            let mask = u128::MAX
284                .checked_shl(128 - u32::from(prefix_len.min(128)))
285                .unwrap_or(0);
286            (u128::from(address) & mask).to_be_bytes().to_vec()
287        }
288        IpAddr::V4(address) => address.octets().to_vec(),
289    }
290}
291
292/// How many leading bits of `address` identify its client: `ipv6_prefix_len`,
293/// or all 128 where unrelated clients share the leading bits. These are
294/// `::/32`, with the unspecified, loopback and IPv4-compatible addresses,
295/// link-local addresses (`fe80::/10`), Teredo addresses (`2001::/32`), and
296/// the NAT64 prefixes in `64:ff9b::/32`, each of whose addresses carries one
297/// IPv4 client.
298fn ipv6_prefix_len_of(address: Ipv6Addr, ipv6_prefix_len: u8) -> u8 {
299    let segments = address.segments();
300    let kept_whole = segments[..2] == [0, 0]
301        || segments[0] & 0xffc0 == 0xfe80
302        || segments[..2] == [0x2001, 0]
303        || segments[..2] == [0x64, 0xff9b];
304    if kept_whole { 128 } else { ipv6_prefix_len }
305}
306
307#[cfg(test)]
308mod tests {
309    use std::net::Ipv4Addr;
310
311    use super::*;
312
313    const CLIENT: IpAddr = IpAddr::V4(Ipv4Addr::new(10, 0, 0, 1));
314
315    fn v6(segments: [u16; 8]) -> IpAddr {
316        IpAddr::V6(Ipv6Addr::from(segments))
317    }
318
319    fn key(segments: [u16; 8]) -> Vec<u8> {
320        Ipv6Addr::from(segments).octets().to_vec()
321    }
322
323    #[test]
324    fn an_ipv6_client_is_its_address_prefix() {
325        let client = v6([0x2001, 0xdb8, 1, 2, 3, 4, 5, 6]);
326        assert_eq!(
327            client_prefix(client, 64),
328            key([0x2001, 0xdb8, 1, 2, 0, 0, 0, 0])
329        );
330        assert_eq!(
331            client_prefix(client, 48),
332            key([0x2001, 0xdb8, 1, 0, 0, 0, 0, 0])
333        );
334        assert_eq!(
335            client_prefix(client, 128),
336            key([0x2001, 0xdb8, 1, 2, 3, 4, 5, 6])
337        );
338    }
339
340    #[test]
341    fn an_ipv4_client_is_its_full_address() {
342        assert_eq!(client_prefix(CLIENT, 64), vec![10, 0, 0, 1]);
343        let IpAddr::V4(address) = CLIENT else {
344            unreachable!()
345        };
346        let mapped = IpAddr::V6(address.to_ipv6_mapped());
347        assert_eq!(client_prefix(mapped, 64), vec![10, 0, 0, 1]);
348    }
349
350    #[test]
351    fn an_ipv4_client_never_shares_a_key_with_an_ipv6_client() {
352        // The IPv4-compatible form of the same address is kept whole, so only
353        // the key's length tells the two apart.
354        let compatible = v6([0, 0, 0, 0, 0, 0, 0x0a00, 0x0001]);
355        assert_ne!(client_prefix(CLIENT, 64), client_prefix(compatible, 64));
356    }
357
358    #[test]
359    fn ipv6_addresses_whose_leading_bits_are_shared_are_kept_whole() {
360        for client in [
361            v6([0, 0, 0, 0, 0, 0, 0, 1]),
362            v6([0, 0, 0, 0, 0, 0, 0x0a00, 0x0001]),
363            v6([0xfe80, 0, 0, 0, 1, 2, 3, 4]),
364            v6([0x2001, 0, 0x4136, 0xe378, 0x8000, 0x63bf, 0x3fff, 0xfdd2]),
365            v6([0x64, 0xff9b, 0, 0, 0, 0, 0x0a00, 0x0001]),
366            v6([0x64, 0xff9b, 1, 0x0a00, 0x0001, 0, 0, 0]),
367        ] {
368            let IpAddr::V6(address) = client else {
369                unreachable!()
370            };
371            assert_eq!(client_prefix(client, 64), address.octets().to_vec());
372        }
373    }
374
375    #[tokio::test]
376    async fn a_tcp_listener_cuts_ipv6_clients_to_its_prefix_length() {
377        let listener = TcpListenerWithOptions::new("127.0.0.1:0", None, 48).unwrap();
378        let client = |segments| std::net::SocketAddr::new(v6(segments), 1);
379
380        assert_eq!(
381            listener.client_prefix(&client([0x2001, 0xdb8, 1, 2, 0, 0, 0, 1])),
382            listener.client_prefix(&client([0x2001, 0xdb8, 1, 3, 0, 0, 0, 1])),
383            "addresses in one /48 must be one client"
384        );
385        assert_ne!(
386            listener.client_prefix(&client([0x2001, 0xdb8, 1, 0, 0, 0, 0, 1])),
387            listener.client_prefix(&client([0x2001, 0xdb8, 2, 0, 0, 0, 0, 1])),
388            "addresses in different /48s must be different clients"
389        );
390    }
391}