iroh/socket/mapped_addrs.rs
1//! The various mapped addresses we use.
2
3//! We use non-IP transports to carry datagrams. Yet Noq needs to address those
4//! transports using IPv6 addresses. These defines mappings of several IPv6 Unique Local
5//! Address ranges we use to keep track of the various "fake" address types we use.
6
7use std::{
8 fmt,
9 hash::Hash,
10 net::{IpAddr, Ipv6Addr, SocketAddr, SocketAddrV6},
11 sync::Arc,
12};
13
14use n0_error::{e, stack_error};
15use rand::Rng;
16use rustc_hash::FxHashMap;
17use tracing::trace;
18
19/// The Prefix/L of all Unique Local Addresses.
20const ADDR_PREFIXL: u8 = 0xfd;
21
22/// The Global ID used in n0's Unique Local Addresses.
23const ADDR_GLOBAL_ID: [u8; 5] = [0x15, 0x07, 0x0a, 0x51, 0x0b];
24
25/// The Subnet ID for [`RelayMappedAddr]: fd15:70a:510b:1::/64.
26const RELAY_MAPPED_SUBNET: [u8; 2] = [0x00, 0x01];
27
28/// The Subnet ID for [`CustomMappedAddr`]: fd15:70a:510b:3::/64.
29const CUSTOM_MAPPED_SUBNET: [u8; 2] = [0x00, 0x03];
30
31/// The Subnet ID for [`EndpointIdMappedAddr`]: fd15:70a:510b::/64.
32const ENDPOINT_ID_SUBNET: [u8; 2] = [0x00, 0x00];
33
34/// A default fake addr, using the maximum addr that the internal fake addrs could be using.
35pub(crate) const DEFAULT_FAKE_ADDR: SocketAddrV6 = SocketAddrV6::new(
36 Ipv6Addr::new(
37 u16::from_be_bytes([ADDR_PREFIXL, 21]),
38 u16::from_be_bytes([7, 10]),
39 u16::from_be_bytes([81, 11]),
40 u16::from_be_bytes([0, 0]),
41 u16::MAX,
42 u16::MAX,
43 u16::MAX,
44 u16::MAX,
45 ),
46 MAPPED_PORT,
47 0,
48 0,
49);
50
51/// The dummy port used for all mapped addresses.
52///
53/// We map each entity, usually an [`crate::EndpointId`], to an IPv6 address. But socket addresses
54/// involve ports, so we use a dummy fixed port when creating socket addresses.
55const MAPPED_PORT: u16 = 12345;
56
57/// Generic mapped address.
58///
59/// Allows implementing [`AddrMap`].
60pub(crate) trait MappedAddr {
61 /// Generates a new mapped address in the IPv6 Unique Local Address space.
62 ///
63 /// The host bits are random so a remote peer cannot guess one of our live mapped
64 /// addresses (uniqueness is ensured by [`AddrMap::get`]).
65 fn generate() -> Self;
66
67 /// Returns a consistent [`SocketAddr`] for the mapped addr.
68 ///
69 /// This socket address does not have a routable IP address. It uses a fake but
70 /// consistent port number, since the port does not play a role in the addressing. This
71 /// socket address is only to be used to pass into Noq.
72 fn private_socket_addr(&self) -> SocketAddr;
73}
74
75/// An enum encompassing all the mapped and unmapped addresses.
76///
77/// This is essentially a slightly-stronger typed version of the IPv6 mapped addresses that
78/// we use on the Noq side. It categorises the addressed in what kind of mapped or
79/// unmapped addresses they are.
80///
81/// It does not guarantee that a mapped address exists in the mapping. Or that a particular
82/// address is even supported on this platform. Hence no wasm exceptions here.
83#[derive(Clone, Debug)]
84pub(crate) enum MultipathMappedAddr {
85 /// An address for a [`crate::EndpointId`], via one or more paths.
86 Mixed(EndpointIdMappedAddr),
87 /// An address for a particular [`crate::EndpointId`] via a particular relay.
88 Relay(RelayMappedAddr),
89 /// An IP based transport address.
90 Ip(SocketAddr),
91 /// Custom transport address.
92 Custom(CustomMappedAddr),
93}
94
95impl From<SocketAddr> for MultipathMappedAddr {
96 fn from(value: SocketAddr) -> Self {
97 match value.ip() {
98 IpAddr::V4(_) => Self::Ip(value),
99 IpAddr::V6(addr) => {
100 if let Ok(addr) = EndpointIdMappedAddr::try_from(addr) {
101 return Self::Mixed(addr);
102 }
103 if let Ok(addr) = RelayMappedAddr::try_from(addr) {
104 return Self::Relay(addr);
105 }
106 if let Ok(addr) = CustomMappedAddr::try_from(addr) {
107 return Self::Custom(addr);
108 }
109 Self::Ip(value)
110 }
111 }
112 }
113}
114
115/// An address used to address a endpoint on any or all paths.
116///
117/// This is only used for initially connecting to a remote endpoint. We instruct Noq to
118/// send to this address, and duplicate all packets for this address to send on all paths we
119/// might want to send the initial on:
120///
121/// - If this the first connection to the remote endpoint we don't know which path will work
122/// and send to all of them.
123///
124/// - If there already is an active connection to this endpoint we now which path to use.
125///
126/// It is but a newtype around an IPv6 Unique Local Addr. And in our QUIC-facing socket
127/// APIs like [`noq::AsyncUdpSocket`] it comes in as the inner [`Ipv6Addr`], in those
128/// interfaces we have to be careful to do the conversion to this type.
129#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
130pub(crate) struct EndpointIdMappedAddr(Ipv6Addr);
131
132impl MappedAddr for EndpointIdMappedAddr {
133 /// Generates a globally unique fake UDP address.
134 ///
135 /// This generates and IPv6 Unique Local Address according to RFC 4193.
136 fn generate() -> Self {
137 let mut addr = [0u8; 16];
138 addr[0] = ADDR_PREFIXL;
139 addr[1..6].copy_from_slice(&ADDR_GLOBAL_ID);
140 addr[6..8].copy_from_slice(&ENDPOINT_ID_SUBNET);
141 rand::rng().fill_bytes(&mut addr[8..16]);
142
143 Self(Ipv6Addr::from(addr))
144 }
145
146 /// Returns a consistent [`SocketAddr`] for the [`EndpointIdMappedAddr`].
147 ///
148 /// This socket address does not have a routable IP address and port.
149 ///
150 /// This uses a made-up port number, since the port does not play a role in the
151 /// addressing. This socket address is only to be used to pass into Noq.
152 fn private_socket_addr(&self) -> SocketAddr {
153 SocketAddr::new(IpAddr::from(self.0), MAPPED_PORT)
154 }
155}
156
157impl std::fmt::Display for EndpointIdMappedAddr {
158 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
159 write!(f, "EndpointIdMappedAddr({})", self.0)
160 }
161}
162
163impl TryFrom<Ipv6Addr> for EndpointIdMappedAddr {
164 type Error = EndpointIdMappedAddrError;
165
166 fn try_from(value: Ipv6Addr) -> Result<Self, Self::Error> {
167 let octets = value.octets();
168 if octets[0] == ADDR_PREFIXL
169 && octets[1..6] == ADDR_GLOBAL_ID
170 && octets[6..8] == ENDPOINT_ID_SUBNET
171 {
172 return Ok(Self(value));
173 }
174 Err(e!(EndpointIdMappedAddrError))
175 }
176}
177
178/// Can occur when converting a [`SocketAddr`] to an [`EndpointIdMappedAddr`]
179#[stack_error(derive, add_meta)]
180#[error("Failed to convert")]
181pub(crate) struct EndpointIdMappedAddrError;
182
183/// An Ipv6 ULA address, identifying a relay path for a [`crate::EndpointId`].
184///
185/// Since iroh endpoint are reachable via a relay server we have a network path indicated by
186/// the `(EndpointId, RelayUrl)`. However Noq can only handle socket addresses, so we use
187/// IPv6 addresses in a private IPv6 Unique Local Address range, which map to a unique
188/// `(EndointId, RelayUrl)` pair.
189#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, Ord, PartialOrd)]
190pub(crate) struct RelayMappedAddr(Ipv6Addr);
191
192impl MappedAddr for RelayMappedAddr {
193 /// Generates a globally unique fake UDP address.
194 ///
195 /// This generates a new IPv6 address in the Unique Local Address range (RFC 4193)
196 /// which is recognised by iroh as an IP mapped address.
197 fn generate() -> Self {
198 let mut addr = [0u8; 16];
199 addr[0] = ADDR_PREFIXL;
200 addr[1..6].copy_from_slice(&ADDR_GLOBAL_ID);
201 addr[6..8].copy_from_slice(&RELAY_MAPPED_SUBNET);
202 rand::rng().fill_bytes(&mut addr[8..16]);
203
204 Self(Ipv6Addr::from(addr))
205 }
206
207 /// Returns a consistent [`SocketAddr`] for the [`RelayMappedAddr`].
208 ///
209 /// This socket address does not have a routable IP address and port.
210 ///
211 /// This uses a made-up port number, since the port does not play a role in the
212 /// addressing. This socket address is only to be used to pass into Noq.
213 fn private_socket_addr(&self) -> SocketAddr {
214 SocketAddr::new(IpAddr::from(self.0), MAPPED_PORT)
215 }
216}
217
218impl TryFrom<Ipv6Addr> for RelayMappedAddr {
219 type Error = RelayMappedAddrError;
220
221 fn try_from(value: Ipv6Addr) -> std::result::Result<Self, Self::Error> {
222 let octets = value.octets();
223 if octets[0] == ADDR_PREFIXL
224 && octets[1..6] == ADDR_GLOBAL_ID
225 && octets[6..8] == RELAY_MAPPED_SUBNET
226 {
227 return Ok(Self(value));
228 }
229 Err(e!(RelayMappedAddrError))
230 }
231}
232
233/// Can occur when converting a [`SocketAddr`] to an [`RelayMappedAddr`]
234#[stack_error(derive, add_meta)]
235#[error("Failed to convert")]
236pub(crate) struct RelayMappedAddrError;
237
238impl std::fmt::Display for RelayMappedAddr {
239 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
240 write!(f, "RelayMappedAddr({})", self.0)
241 }
242}
243
244/// An Ipv6 ULA address, identifying a custom transport path.
245///
246/// Custom transports allow user-defined transport mechanisms. However Noq can only handle
247/// socket addresses, so we use IPv6 addresses in a private IPv6 Unique Local Address range,
248/// which map to a unique [`iroh_base::CustomAddr`].
249#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, Ord, PartialOrd)]
250pub(crate) struct CustomMappedAddr(Ipv6Addr);
251
252impl MappedAddr for CustomMappedAddr {
253 /// Generates a globally unique fake UDP address.
254 ///
255 /// This generates a new IPv6 address in the Unique Local Address range (RFC 4193)
256 /// which is recognised by iroh as an IP mapped address.
257 fn generate() -> Self {
258 let mut addr = [0u8; 16];
259 addr[0] = ADDR_PREFIXL;
260 addr[1..6].copy_from_slice(&ADDR_GLOBAL_ID);
261 addr[6..8].copy_from_slice(&CUSTOM_MAPPED_SUBNET);
262 rand::rng().fill_bytes(&mut addr[8..16]);
263
264 Self(Ipv6Addr::from(addr))
265 }
266
267 /// Returns a consistent [`SocketAddr`] for the [`CustomMappedAddr`].
268 ///
269 /// This socket address does not have a routable IP address and port.
270 ///
271 /// This uses a made-up port number, since the port does not play a role in the
272 /// addressing. This socket address is only to be used to pass into Noq.
273 fn private_socket_addr(&self) -> SocketAddr {
274 SocketAddr::new(IpAddr::from(self.0), MAPPED_PORT)
275 }
276}
277
278impl TryFrom<IpAddr> for CustomMappedAddr {
279 type Error = CustomMappedAddrError;
280
281 fn try_from(value: IpAddr) -> std::result::Result<Self, Self::Error> {
282 match value {
283 IpAddr::V4(_) => Err(e!(CustomMappedAddrError)),
284 IpAddr::V6(addr) => addr.try_into(),
285 }
286 }
287}
288
289impl TryFrom<Ipv6Addr> for CustomMappedAddr {
290 type Error = CustomMappedAddrError;
291
292 fn try_from(value: Ipv6Addr) -> std::result::Result<Self, Self::Error> {
293 let octets = value.octets();
294 if octets[0] == ADDR_PREFIXL
295 && octets[1..6] == ADDR_GLOBAL_ID
296 && octets[6..8] == CUSTOM_MAPPED_SUBNET
297 {
298 return Ok(Self(value));
299 }
300 Err(e!(CustomMappedAddrError))
301 }
302}
303
304/// Can occur when converting a [`SocketAddr`] to a [`CustomMappedAddr`]
305#[stack_error(derive, add_meta)]
306#[error("Failed to convert")]
307pub(crate) struct CustomMappedAddrError;
308
309impl std::fmt::Display for CustomMappedAddr {
310 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
311 write!(f, "CustomMappedAddr({})", self.0)
312 }
313}
314
315/// A bi-directional map between a key and a [`MappedAddr`].
316#[derive(Debug, Clone)]
317pub(super) struct AddrMap<K, V> {
318 inner: Arc<std::sync::Mutex<AddrMapInner<K, V>>>,
319}
320
321// Manual impl because derive ends up requiring T: Default.
322impl<K, V> Default for AddrMap<K, V> {
323 fn default() -> Self {
324 Self {
325 inner: Default::default(),
326 }
327 }
328}
329
330impl<K, V> AddrMap<K, V>
331where
332 K: Eq + Hash + Clone + fmt::Debug,
333 V: MappedAddr + Eq + Hash + Copy + fmt::Debug,
334{
335 /// Returns the [`MappedAddr`], generating one if needed.
336 pub(super) fn get(&self, key: &K) -> V {
337 let mut inner = self.inner.lock().expect("poisoned");
338 match inner.addrs.get(key) {
339 Some(addr) => *addr,
340 None => {
341 let addr = loop {
342 let candidate = V::generate();
343 if !inner.lookup.contains_key(&candidate) {
344 break candidate;
345 }
346 };
347 inner.addrs.insert(key.clone(), addr);
348 inner.lookup.insert(addr, key.clone());
349 trace!(?addr, ?key, "generated new addr");
350 addr
351 }
352 }
353 }
354
355 /// Performs the reverse lookup.
356 pub(super) fn lookup(&self, addr: &V) -> Option<K> {
357 let inner = self.inner.lock().expect("poisoned");
358 inner.lookup.get(addr).cloned()
359 }
360}
361
362#[derive(Debug)]
363struct AddrMapInner<K, V> {
364 addrs: FxHashMap<K, V>,
365 lookup: FxHashMap<V, K>,
366}
367
368// Manual impl because derive ends up requiring T: Default.
369impl<K, V> Default for AddrMapInner<K, V> {
370 fn default() -> Self {
371 Self {
372 addrs: Default::default(),
373 lookup: Default::default(),
374 }
375 }
376}