iroh/socket/transports/
ip.rs

1use std::{
2    io,
3    net::{IpAddr, SocketAddr, SocketAddrV4, SocketAddrV6},
4    num::NonZeroUsize,
5    pin::Pin,
6    sync::Arc,
7    task::{Context, Poll},
8};
9
10use ipnet::{Ipv4Net, Ipv6Net};
11use n0_watcher::Watchable;
12use netwatch::{UdpSender, UdpSocket};
13use pin_project::pin_project;
14use tracing::{debug, info, trace};
15
16use super::{RecvInfo, Transmit};
17use crate::metrics::{EndpointMetrics, SocketMetrics};
18
19#[derive(Debug)]
20pub(crate) struct IpTransport {
21    config: Config,
22    socket: Arc<UdpSocket>,
23    local_addr: Watchable<SocketAddr>,
24    metrics: Arc<SocketMetrics>,
25}
26
27impl std::fmt::Display for IpTransport {
28    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
29        let version = if self.config.is_ipv4() { "v4" } else { "v6" };
30        write!(f, "IpTransport({version})")
31    }
32}
33
34/// IP transport configuration
35#[derive(Debug, Copy, Clone, PartialEq, Eq)]
36pub(crate) enum Config {
37    /// General IPv4 binding
38    V4 {
39        /// The IP address to bind on
40        ip_net: Ipv4Net,
41        /// The port to bind on
42        port: u16,
43        /// Is binding mandatory?
44        is_required: bool,
45        /// Is this a default route?
46        is_default: bool,
47    },
48    /// General IPv6 binding
49    V6 {
50        /// The IP address to bind on
51        ip_net: Ipv6Net,
52        /// The scope id.
53        scope_id: u32,
54        /// The port to bind on
55        port: u16,
56        /// Is binding mandatory?
57        is_required: bool,
58        /// Is this a default route?
59        is_default: bool,
60    },
61}
62
63impl Config {
64    /// Is this a v4 config.
65    pub(crate) fn is_ipv4(&self) -> bool {
66        matches!(self,  | Self::V4 { .. })
67    }
68
69    /// Is this a v6 config.
70    pub(crate) fn is_ipv6(&self) -> bool {
71        matches!(self, | Self::V6 { .. })
72    }
73
74    /// Returns the prefix len for the address.
75    pub(crate) fn prefix_len(&self) -> u8 {
76        match self {
77            Self::V4 { ip_net, .. } => ip_net.prefix_len(),
78            Self::V6 { ip_net, .. } => ip_net.prefix_len(),
79        }
80    }
81
82    /// Is this a default config?
83    pub(crate) fn is_default(&self) -> bool {
84        match self {
85            Self::V4 { is_default, .. } => *is_default,
86            Self::V6 { is_default, .. } => *is_default,
87        }
88    }
89
90    /// Is this required to bind.
91    pub(crate) fn is_required(&self) -> bool {
92        match self {
93            Self::V4 { is_required, .. } => *is_required,
94            Self::V6 { is_required, .. } => *is_required,
95        }
96    }
97
98    pub(crate) fn is_valid_default_addr(&self, src: Option<IpAddr>, dst: SocketAddr) -> bool {
99        match src {
100            Some(src) => match (self, src) {
101                (Self::V4 { is_default, .. }, IpAddr::V4(_)) => *is_default,
102                (Self::V6 { is_default, .. }, IpAddr::V6(_)) => *is_default,
103                _ => false,
104            },
105            None => match (self, dst) {
106                (Self::V4 { is_default, .. }, SocketAddr::V4(_)) => *is_default,
107                (Self::V6 { is_default, .. }, SocketAddr::V6(_)) => *is_default,
108                _ => false,
109            },
110        }
111    }
112
113    /// Does this configuration match to send to the given `src` and `dst` address.
114    pub(crate) fn is_valid_send_addr(&self, src: Option<IpAddr>, dst: SocketAddr) -> bool {
115        match src {
116            Some(src) => match (self, src) {
117                (Self::V4 { ip_net, .. }, IpAddr::V4(src)) => {
118                    ip_net.addr().is_unspecified() || ip_net.addr() == src
119                }
120                (Self::V6 { ip_net, .. }, IpAddr::V6(src)) => {
121                    ip_net.addr().is_unspecified() || ip_net.addr() == src
122                }
123                _ => false,
124            },
125            None => {
126                match (self, dst) {
127                    (Self::V4 { ip_net, .. }, SocketAddr::V4(dst_v4)) => {
128                        ip_net.contains(dst_v4.ip())
129                    }
130                    (
131                        Self::V6 {
132                            ip_net, scope_id, ..
133                        },
134                        SocketAddr::V6(dst_v6),
135                    ) => {
136                        if ip_net.contains(dst_v6.ip()) {
137                            return true;
138                        }
139                        if dst_v6.ip().is_unicast_link_local() {
140                            // If we have a link local interface, use the scope id
141                            if *scope_id == dst_v6.scope_id() {
142                                return true;
143                            }
144                        }
145                        false
146                    }
147                    _ => false,
148                }
149            }
150        }
151    }
152}
153
154impl From<Config> for SocketAddr {
155    fn from(value: Config) -> Self {
156        match value {
157            Config::V4 { ip_net, port, .. } => {
158                SocketAddr::V4(SocketAddrV4::new(ip_net.addr(), port))
159            }
160            Config::V6 {
161                ip_net,
162                scope_id,
163                port,
164                ..
165            } => SocketAddr::V6(SocketAddrV6::new(ip_net.addr(), port, 0, scope_id)),
166        }
167    }
168}
169
170impl IpTransport {
171    pub(crate) fn bind(config: Config, metrics: Arc<SocketMetrics>) -> io::Result<Self> {
172        let addr: SocketAddr = config.into();
173        debug!(?addr, "binding");
174        let socket = netwatch::UdpSocket::bind_full(addr).inspect_err(|err| {
175            debug!(%addr, "failed to bind: {err:#}");
176        })?;
177        let local_addr = socket.local_addr()?;
178        debug!(%addr, %local_addr, "successfully bound");
179        // Currently gets updated on manual rebind
180        // TODO: update when UdpSocket under the hood rebinds automatically
181        let local_addr = Watchable::new(local_addr);
182
183        Ok(Self {
184            config,
185            socket: Arc::new(socket),
186            local_addr,
187            metrics,
188        })
189    }
190
191    /// NOTE: Receiving on a closed socket will return [`Poll::Pending`] indefinitely.
192    pub(super) fn poll_recv(
193        &mut self,
194        cx: &mut Context,
195        bufs: &mut [io::IoSliceMut<'_>],
196        metas: &mut [noq_udp::RecvMeta],
197        recv_infos: &mut [RecvInfo],
198    ) -> Poll<io::Result<usize>> {
199        assert_eq!(bufs.len(), metas.len(), "non matching bufs & metas");
200        assert_eq!(
201            bufs.len(),
202            recv_infos.len(),
203            "non matching bufs & recv_infos"
204        );
205        match self.socket.poll_recv_noq(cx, bufs, metas) {
206            Poll::Pending => Poll::Pending,
207            Poll::Ready(Ok(n)) => {
208                for i in 0..n {
209                    let meta = &mut metas[i];
210                    let recv_info = &mut recv_infos[i];
211                    if meta.addr.is_ipv4() {
212                        // The AsyncUdpSocket is an AF_INET6 socket and needs to show this
213                        // as coming from an IPv4-mapped IPv6 addresses, since Noq will
214                        // use those when sending on an INET6 socket.
215                        let v6_ip = match meta.addr.ip() {
216                            IpAddr::V4(ipv4_addr) => ipv4_addr.to_ipv6_mapped(),
217                            IpAddr::V6(ipv6_addr) => ipv6_addr,
218                        };
219                        meta.addr = SocketAddr::new(v6_ip.into(), meta.addr.port());
220                    }
221                    // The transport addresses are internal to iroh and we always want those
222                    // to remain the canonical address.
223                    *recv_info = RecvInfo::from_addr(
224                        SocketAddr::new(meta.addr.ip().to_canonical(), meta.addr.port()).into(),
225                    );
226                }
227                Poll::Ready(Ok(n))
228            }
229            Poll::Ready(Err(err)) => Poll::Ready(Err(err)),
230        }
231    }
232
233    pub(super) fn local_addr_watch(&self) -> n0_watcher::Direct<SocketAddr> {
234        self.local_addr.watch()
235    }
236
237    pub(super) fn max_transmit_segments(&self) -> NonZeroUsize {
238        self.socket.max_gso_segments()
239    }
240
241    pub(super) fn max_receive_segments(&self) -> NonZeroUsize {
242        self.socket.gro_segments()
243    }
244
245    pub(super) fn may_fragment(&self) -> bool {
246        self.socket.may_fragment()
247    }
248
249    pub(crate) fn bind_addr(&self) -> SocketAddr {
250        self.config.into()
251    }
252
253    pub(super) fn create_network_change_sender(&self) -> IpNetworkChangeSender {
254        IpNetworkChangeSender {
255            socket: self.socket.clone(),
256            local_addr: self.local_addr.clone(),
257        }
258    }
259
260    pub(super) fn create_sender(&self) -> IpSender {
261        let sender = self.socket.clone().create_sender();
262        IpSender {
263            config: self.config,
264            sender,
265            metrics: self.metrics.clone(),
266        }
267    }
268}
269
270#[derive(Debug)]
271pub(super) struct IpNetworkChangeSender {
272    socket: Arc<UdpSocket>,
273    local_addr: Watchable<SocketAddr>,
274}
275
276impl IpNetworkChangeSender {
277    pub(super) fn rebind(&self) -> io::Result<()> {
278        let old_addr = self.local_addr.get();
279        self.socket.rebind()?;
280        let addr = self.socket.local_addr()?;
281        self.local_addr.set(addr).ok();
282        trace!("rebound from {} to {}", old_addr, addr);
283
284        Ok(())
285    }
286
287    pub(super) fn on_network_change(&self, _info: &crate::socket::Report) {
288        // Nothing to do for now
289    }
290}
291
292#[derive(Debug, Clone)]
293#[pin_project]
294pub(super) struct IpSender {
295    config: Config,
296    #[pin]
297    sender: UdpSender,
298    metrics: Arc<SocketMetrics>,
299}
300
301impl IpSender {
302    pub(super) fn is_valid_send_addr(&self, src: Option<IpAddr>, dst: &SocketAddr) -> bool {
303        self.config.is_valid_send_addr(src, *dst)
304    }
305
306    pub(super) fn is_valid_default_addr(&self, src: Option<IpAddr>, dst: &SocketAddr) -> bool {
307        self.config.is_valid_default_addr(src, *dst)
308    }
309
310    /// Creates a canonical socket address.
311    ///
312    /// We may be asked to send IPv4-mapped IPv6 addresses.  But our sockets are configured
313    /// to only send their actual family.  So we need to map those back to the canonical
314    /// addresses.
315    #[inline]
316    fn canonical_addr(addr: SocketAddr) -> SocketAddr {
317        SocketAddr::new(addr.ip().to_canonical(), addr.port())
318    }
319
320    pub(super) fn poll_send(
321        mut self: Pin<&mut Self>,
322        cx: &mut std::task::Context,
323        dst: SocketAddr,
324        src: Option<IpAddr>,
325        transmit: &Transmit<'_>,
326    ) -> Poll<io::Result<()>> {
327        let total_bytes = transmit.contents.len() as u64;
328        let res = Pin::new(&mut self.sender).poll_send(
329            &noq_udp::Transmit {
330                destination: Self::canonical_addr(dst),
331                ecn: transmit.ecn,
332                contents: transmit.contents,
333                segment_size: transmit.segment_size,
334                src_ip: src,
335            },
336            cx,
337        );
338
339        match res {
340            Poll::Ready(Ok(res)) => {
341                match dst {
342                    SocketAddr::V4(_) => {
343                        self.metrics.send_ipv4.inc_by(total_bytes);
344                    }
345                    SocketAddr::V6(_) => {
346                        self.metrics.send_ipv6.inc_by(total_bytes);
347                    }
348                }
349                Poll::Ready(Ok(res))
350            }
351            Poll::Ready(Err(err)) => Poll::Ready(Err(err)),
352            Poll::Pending => Poll::Pending,
353        }
354    }
355}
356
357#[derive(Debug, Clone)]
358pub(super) struct IpTransportsSender {
359    /// Stored sorted by prefix len
360    v4: Vec<IpSender>,
361    default_v4_index: Option<usize>,
362    /// Stored sorted by prefix len
363    v6: Vec<IpSender>,
364    default_v6_index: Option<usize>,
365}
366
367impl IpTransportsSender {
368    pub(super) fn v4_iter_mut(&mut self) -> impl Iterator<Item = &mut IpSender> {
369        self.v4.iter_mut()
370    }
371
372    pub(super) fn v4_default_mut(&mut self) -> Option<&mut IpSender> {
373        if let Some(i) = self.default_v4_index {
374            return Some(&mut self.v4[i]);
375        }
376        None
377    }
378
379    pub(super) fn v6_iter_mut(&mut self) -> impl Iterator<Item = &mut IpSender> {
380        self.v6.iter_mut()
381    }
382
383    pub(super) fn v6_default_mut(&mut self) -> Option<&mut IpSender> {
384        if let Some(i) = self.default_v6_index {
385            return Some(&mut self.v6[i]);
386        }
387        None
388    }
389}
390
391#[derive(Debug)]
392pub(super) struct IpTransports {
393    v4: Vec<IpTransport>,
394    default_v4_index: Option<usize>,
395    v6: Vec<IpTransport>,
396    default_v6_index: Option<usize>,
397}
398
399impl IpTransports {
400    pub(super) fn create_sender(&self) -> IpTransportsSender {
401        let ip_v4 = self.v4.iter().map(|t| t.create_sender()).collect();
402        let ip_v6 = self.v6.iter().map(|t| t.create_sender()).collect();
403
404        IpTransportsSender {
405            v4: ip_v4,
406            default_v4_index: self.default_v4_index,
407            v6: ip_v6,
408            default_v6_index: self.default_v6_index,
409        }
410    }
411
412    pub(super) fn iter(&self) -> impl Iterator<Item = &IpTransport> {
413        self.v4.iter().chain(self.v6.iter())
414    }
415
416    pub(super) fn bind(
417        configs: impl Iterator<Item = Config>,
418        metrics: &EndpointMetrics,
419    ) -> io::Result<Self> {
420        let mut has_v4_default = false;
421        let mut ip_v4 = Vec::new();
422
423        let mut has_v6_default = false;
424        let mut ip_v6 = Vec::new();
425
426        for config in configs {
427            match IpTransport::bind(config, metrics.socket.clone()) {
428                Ok(transport) => {
429                    if config.is_ipv4() {
430                        if config.is_default() {
431                            if has_v4_default {
432                                return Err(io::Error::other(
433                                    "can only have a single IPv4 default transport",
434                                ));
435                            }
436                            has_v4_default = true;
437                        }
438                        ip_v4.push(transport);
439                    } else if config.is_ipv6() {
440                        if config.is_default() {
441                            if has_v6_default {
442                                return Err(io::Error::other(
443                                    "can only have a single IPv6 default transport",
444                                ));
445                            }
446                            has_v6_default = true;
447                        }
448                        ip_v6.push(transport);
449                    }
450                }
451                Err(err) => {
452                    if config.is_required() {
453                        return Err(err);
454                    }
455                    info!("ignoring non required bind failure: {:?}", err);
456                }
457            }
458        }
459
460        // Sort in descending order by prefix len
461        ip_v4.sort_by_key(|i| std::cmp::Reverse(i.config.prefix_len()));
462        ip_v6.sort_by_key(|i| std::cmp::Reverse(i.config.prefix_len()));
463
464        let default_v4_index = ip_v4.iter().position(|i| i.config.is_default());
465        let default_v6_index = ip_v6.iter().position(|i| i.config.is_default());
466
467        Ok(Self {
468            v4: ip_v4,
469            default_v4_index,
470            v6: ip_v6,
471            default_v6_index,
472        })
473    }
474
475    pub(super) fn iter_mut(&mut self) -> impl Iterator<Item = &mut IpTransport> {
476        self.v4.iter_mut().chain(self.v6.iter_mut())
477    }
478}
479
480#[cfg(test)]
481mod tests {
482    use super::*;
483
484    #[tokio::test]
485    async fn test_bind_sorting() -> n0_error::Result {
486        let has_ipv6 = tokio::net::UdpSocket::bind("[::1]:0").await.is_ok();
487        eprintln!("testing with ipv6? {has_ipv6}");
488
489        let metrics = EndpointMetrics::default();
490        let config = vec![
491            Config::V4 {
492                ip_net: Ipv4Net::new("127.0.0.1".parse().unwrap(), 8).unwrap(),
493                port: 2222,
494                is_required: true,
495                is_default: false,
496            },
497            Config::V4 {
498                ip_net: Ipv4Net::new("127.0.0.1".parse().unwrap(), 24).unwrap(),
499                port: 1111,
500                is_required: true,
501                is_default: true,
502            },
503            Config::V4 {
504                ip_net: Ipv4Net::new("127.0.0.1".parse().unwrap(), 0).unwrap(),
505                port: 9999,
506                is_required: true,
507                is_default: false,
508            },
509            Config::V6 {
510                ip_net: Ipv6Net::new("::1".parse().unwrap(), 4).unwrap(),
511                port: 2228,
512                scope_id: 0,
513                is_required: has_ipv6,
514                is_default: false,
515            },
516            Config::V6 {
517                ip_net: Ipv6Net::new("::1".parse().unwrap(), 2).unwrap(),
518                port: 9998,
519                scope_id: 0,
520                is_required: has_ipv6,
521                is_default: true,
522            },
523            Config::V6 {
524                ip_net: Ipv6Net::new("::1".parse().unwrap(), 32).unwrap(),
525                port: 1118,
526                scope_id: 0,
527                is_required: has_ipv6,
528                is_default: false,
529            },
530        ];
531
532        let transports = IpTransports::bind(config.into_iter(), &metrics)?;
533        assert_eq!(transports.v4[0].config.prefix_len(), 24);
534        assert_eq!(transports.v4[1].config.prefix_len(), 8);
535        assert_eq!(transports.v4[2].config.prefix_len(), 0);
536
537        assert_eq!(transports.default_v4_index, Some(0));
538
539        if has_ipv6 {
540            assert_eq!(transports.v6[0].config.prefix_len(), 32);
541            assert_eq!(transports.v6[1].config.prefix_len(), 4);
542            assert_eq!(transports.v6[2].config.prefix_len(), 2);
543
544            assert_eq!(transports.default_v6_index, Some(2));
545        }
546        Ok(())
547    }
548}