1use std::{
6 net::{IpAddr, Ipv6Addr},
7 time::Duration,
8};
9
10pub trait Listener: Send + 'static {
12 type Io: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin + Send + 'static;
14
15 type Addr: Clone + Send + Sync + 'static;
18
19 fn accept(&mut self) -> impl std::future::Future<Output = (Self::Io, Self::Addr)> + Send;
24
25 fn local_addr(&self) -> std::io::Result<Self::Addr>;
27
28 fn client_prefix(&self, client: &Self::Addr) -> Vec<u8>;
32}
33
34pub trait ListenerExt: Listener + Sized {
36 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 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 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 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
162pub 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 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
260pub const DEFAULT_IPV6_PREFIX_LEN: u8 = 64;
264
265pub(crate) const MIN_IPV6_PREFIX_LEN: u8 = 32;
269
270fn 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
292fn 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 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}