Skip to main content

netstack3_base/socket/
address.rs

1// Copyright 2022 The Fuchsia Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5//! A collection of types that represent the various parts of socket addresses.
6
7use core::fmt::{self, Debug, Display, Formatter};
8use core::marker::PhantomData;
9use core::num::NonZeroU16;
10use core::ops::Deref;
11
12use derivative::Derivative;
13use net_types::ip::{
14    GenericOverIp, Ip, IpAddress, Ipv4, Ipv4Addr, Ipv4SourceAddr, Ipv6Addr, Ipv6SourceAddr,
15};
16use net_types::{
17    MulticastAddr, NonMappedAddr, ScopeableAddress, SpecifiedAddr, UnicastAddr, Witness, ZonedAddr,
18};
19
20use crate::socket::base::{
21    AddrVec, DualStackIpExt, EitherStack, SocketIpAddrExt as _, SocketIpExt, SocketMapAddrSpec,
22};
23
24/// A [`ZonedAddr`] whose address is `Zoned` iff a zone is required.
25///
26/// Any address whose scope can have a zone, will be the `Zoned` variant. The
27/// one exception is the loopback address, which is represented as `Unzoned`.
28/// This is because the loopback address is allowed to have, but does not
29/// require having, a zone.
30///
31/// # Type Parameters
32///
33/// A: The base [`IpAddress`] type.
34/// W: The [`Witness`] types of the `A`.
35/// Z: The zone of `A`.
36#[derive(Copy, Clone, Eq, Hash, PartialEq)]
37pub struct StrictlyZonedAddr<A, W, Z> {
38    addr: ZonedAddr<W, Z>,
39    marker: PhantomData<A>,
40}
41
42impl<A: Debug, W: Debug, Z: Debug> Debug for StrictlyZonedAddr<A, W, Z> {
43    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
44        let StrictlyZonedAddr { addr, marker: PhantomData } = self;
45        write!(f, "{:?}", addr)
46    }
47}
48
49impl<A: IpAddress, W: Witness<A> + ScopeableAddress + Copy, Z> StrictlyZonedAddr<A, W, Z> {
50    /// Convert self into the inner [`ZonedAddr`]
51    pub fn into_inner(self) -> ZonedAddr<W, Z> {
52        let StrictlyZonedAddr { addr, marker: PhantomData } = self;
53        addr
54    }
55
56    /// Convert self into the inner [`ZonedAddr`] while discarding the witness.
57    pub fn into_inner_without_witness(self) -> ZonedAddr<A, Z> {
58        self.into_inner().map_addr(|addr| addr.into_addr())
59    }
60
61    /// Creates from a specified IP address and an optional zone.
62    ///
63    /// If `addr` requires a zone, then `get_zone` will be called to provide
64    /// the zone.
65    ///
66    /// # Panics
67    /// This method panics if the `addr` wants a zone and `get_zone` will panic
68    /// when called.
69    pub fn new_with_zone(addr: W, get_zone: impl FnOnce() -> Z) -> Self {
70        if let Some(addr_and_zone) = addr.try_into_null_zoned() {
71            StrictlyZonedAddr {
72                addr: ZonedAddr::Zoned(addr_and_zone.map_zone(move |()| get_zone())),
73                marker: PhantomData,
74            }
75        } else {
76            StrictlyZonedAddr { addr: ZonedAddr::Unzoned(addr), marker: PhantomData }
77        }
78    }
79
80    #[cfg(feature = "testutils")]
81    /// Creates the unzoned variant, or panics if the addr's scope needs a zone.
82    pub fn new_unzoned_or_panic(addr: W) -> Self {
83        Self::new_with_zone(addr, || panic!("addr unexpectedly required a zone."))
84    }
85}
86
87impl<A: IpAddress, W: Witness<A>, Z> Deref for StrictlyZonedAddr<A, W, Z> {
88    type Target = ZonedAddr<W, Z>;
89    fn deref(&self) -> &Self::Target {
90        let StrictlyZonedAddr { addr, marker: PhantomData } = self;
91        addr
92    }
93}
94
95/// An IP address that witnesses all required properties of a socket address.
96///
97/// Requires `SpecifiedAddr` because most contexts do not permit unspecified
98/// addresses; those that do can hold a `Option<SocketIpAddr>`.
99///
100/// Requires `NonMappedAddr` because mapped addresses (i.e. ipv4-mapped-ipv6
101/// addresses) are converted from their original IP version to their target IP
102/// version when entering the stack.
103#[derive(Copy, Clone, Eq, GenericOverIp, Hash, PartialEq)]
104#[generic_over_ip(A, IpAddress)]
105pub struct SocketIpAddr<A: IpAddress>(NonMappedAddr<SpecifiedAddr<A>>);
106
107impl<A: IpAddress> Display for SocketIpAddr<A> {
108    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
109        let Self(addr) = self;
110        write!(f, "{}", addr)
111    }
112}
113
114impl<A: IpAddress> Debug for SocketIpAddr<A> {
115    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
116        let Self(addr) = self;
117        write!(f, "{:?}", addr)
118    }
119}
120
121impl<A: IpAddress> SocketIpAddr<A> {
122    /// Constructs a [`SocketIpAddr`] if the address is compliant, else `None`.
123    pub fn new(addr: A) -> Option<SocketIpAddr<A>> {
124        Some(SocketIpAddr(NonMappedAddr::new(SpecifiedAddr::new(addr)?)?))
125    }
126
127    /// Constructs a [`SocketIpAddr`] from the inner witness.
128    pub fn new_from_witness(addr: NonMappedAddr<SpecifiedAddr<A>>) -> Self {
129        Self(addr)
130    }
131
132    /// Constructs a [`SocketIpAddr`] without verify the address's properties.
133    ///
134    ///
135    /// # Safety
136    ///
137    /// Callers must ensure that the addr is both a [`SpecifiedAddr`] and
138    /// a [`NonMappedAddr`].
139    pub const unsafe fn new_unchecked(addr: A) -> SocketIpAddr<A> {
140        // SAFETY: delegated to caller.
141        let non_mapped =
142            unsafe { NonMappedAddr::new_unchecked(SpecifiedAddr::new_unchecked(addr)) };
143        SocketIpAddr(non_mapped)
144    }
145
146    /// Like [`SocketIpAddr::new_unchecked`], but the address is specified.
147    ///
148    /// # Safety
149    ///
150    /// Callers must ensure that the addr is a [`NonMappedAddr`].
151    pub const unsafe fn new_from_specified_unchecked(addr: SpecifiedAddr<A>) -> SocketIpAddr<A> {
152        // SAFETY: delegated to caller.
153        let non_mapped = unsafe { NonMappedAddr::new_unchecked(addr) };
154        SocketIpAddr(non_mapped)
155    }
156
157    /// Returns the inner address, dropping all witnesses.
158    pub fn addr(self) -> A {
159        let SocketIpAddr(addr) = self;
160        **addr
161    }
162
163    /// Returns the inner address, including all witness types.
164    pub fn into_inner(self) -> NonMappedAddr<SpecifiedAddr<A>> {
165        let SocketIpAddr(addr) = self;
166        addr
167    }
168
169    /// Constructs a [`SocketIpAddr`] from the given multicast address.
170    pub fn new_from_multicast(addr: MulticastAddr<A>) -> SocketIpAddr<A> {
171        let addr: MulticastAddr<NonMappedAddr<_>> = addr.non_mapped().transpose();
172        let addr: NonMappedAddr<SpecifiedAddr<_>> = addr.into_specified().transpose();
173        SocketIpAddr(addr)
174    }
175}
176
177impl SocketIpAddr<Ipv4Addr> {
178    /// Constructs a [`SocketIpAddr`] from a given specified IPv4 address.
179    pub fn new_ipv4_specified(addr: SpecifiedAddr<Ipv4Addr>) -> Self {
180        addr.try_into().unwrap_or_else(|AddrIsMappedError {}| {
181            unreachable!("IPv4 addresses must be non-mapped")
182        })
183    }
184
185    /// Constructs a [`SocketIpAddr`] from the given [`Ipv4SourceAddr`].
186    ///
187    /// Returns `None` if the given address is unspecified.
188    pub fn new_from_ipv4_source(addr: Ipv4SourceAddr) -> Option<Self> {
189        match addr {
190            Ipv4SourceAddr::Unspecified => None,
191            Ipv4SourceAddr::Specified(addr) => Some(SocketIpAddr::new_ipv4_specified(addr.get())),
192        }
193    }
194}
195
196impl SocketIpAddr<Ipv6Addr> {
197    /// Constructs a [`SocketIpAddr`] from the given [`Ipv6DeviceAddr`].
198    pub fn new_from_ipv6_non_mapped_unicast(addr: NonMappedAddr<UnicastAddr<Ipv6Addr>>) -> Self {
199        let addr: UnicastAddr<NonMappedAddr<_>> = addr.transpose();
200        let addr: NonMappedAddr<SpecifiedAddr<_>> = addr.into_specified().transpose();
201        SocketIpAddr(addr)
202    }
203
204    /// Optionally constructs a [`SocketIpAddr`] from the given
205    /// [`Ipv6SourceAddr`], returning `None` if the given addr is `Unspecified`.
206    pub fn new_from_ipv6_source(addr: Ipv6SourceAddr) -> Option<Self> {
207        match addr {
208            Ipv6SourceAddr::Unspecified => None,
209            Ipv6SourceAddr::Unicast(addr) => {
210                Some(SocketIpAddr::new_from_ipv6_non_mapped_unicast(addr))
211            }
212        }
213    }
214}
215
216impl<A: IpAddress> From<SocketIpAddr<A>> for SpecifiedAddr<A> {
217    fn from(addr: SocketIpAddr<A>) -> Self {
218        let SocketIpAddr(addr) = addr;
219        *addr
220    }
221}
222
223impl<A: IpAddress> AsRef<SpecifiedAddr<A>> for SocketIpAddr<A> {
224    fn as_ref(&self) -> &SpecifiedAddr<A> {
225        let SocketIpAddr(addr) = self;
226        addr.as_ref()
227    }
228}
229
230/// The addr could not be converted to a `NonMappedAddr`.
231///
232/// Perhaps the address was an ipv4-mapped-ipv6 addresses.
233#[derive(Debug)]
234pub struct AddrIsMappedError {}
235
236impl<A: IpAddress> TryFrom<SpecifiedAddr<A>> for SocketIpAddr<A> {
237    type Error = AddrIsMappedError;
238    fn try_from(addr: SpecifiedAddr<A>) -> Result<Self, Self::Error> {
239        NonMappedAddr::new(addr).map(SocketIpAddr).ok_or(AddrIsMappedError {})
240    }
241}
242
243/// Allows [`SocketIpAddr`] to be used inside of a [`ZonedAddr`].
244impl<A: IpAddress> ScopeableAddress for SocketIpAddr<A> {
245    type Scope = A::Scope;
246    fn scope(&self) -> Self::Scope {
247        let SocketIpAddr(addr) = self;
248        addr.scope()
249    }
250}
251
252/// The IP address and identifier (port) of a listening socket.
253#[derive(Copy, Clone, Debug, Eq, GenericOverIp, Hash, PartialEq)]
254#[generic_over_ip(A, IpAddress)]
255pub struct ListenerIpAddr<A: IpAddress, LI> {
256    /// The specific address being listened on, or `None` for all addresses.
257    pub addr: Option<SocketIpAddr<A>>,
258    /// The local identifier (i.e. port for TCP/UDP).
259    pub identifier: LI,
260}
261
262impl<A: IpAddress, LI: Into<NonZeroU16>> Into<(Option<SpecifiedAddr<A>>, NonZeroU16)>
263    for ListenerIpAddr<A, LI>
264{
265    fn into(self) -> (Option<SpecifiedAddr<A>>, NonZeroU16) {
266        let Self { addr, identifier } = self;
267        (addr.map(Into::into), identifier.into())
268    }
269}
270
271/// The address of a listening socket.
272#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq, GenericOverIp)]
273#[generic_over_ip(A, GenericOverIp)]
274pub struct ListenerAddr<A, D> {
275    /// The IP address of the listening socket.
276    pub ip: A,
277    /// The bound device of the listening socket.
278    pub device: Option<D>,
279}
280
281impl<A, D> AsRef<Option<D>> for ListenerAddr<A, D> {
282    fn as_ref(&self) -> &Option<D> {
283        &self.device
284    }
285}
286
287impl<TA, OA, D> AsRef<Option<D>> for EitherStack<ListenerAddr<TA, D>, ListenerAddr<OA, D>> {
288    fn as_ref(&self) -> &Option<D> {
289        match self {
290            EitherStack::ThisStack(l) => &l.device,
291            EitherStack::OtherStack(l) => &l.device,
292        }
293    }
294}
295
296/// The IP addresses and identifiers (ports) of a connected socket.
297#[derive(Copy, Clone, Debug, Eq, GenericOverIp, Hash, PartialEq)]
298#[generic_over_ip(A, IpAddress)]
299pub struct ConnIpAddrInner<A, LI, RI> {
300    /// The local address, port tuple.
301    pub local: (A, LI),
302    /// The remote address, port tuple.
303    pub remote: (A, RI),
304}
305
306/// The IP addresses and identifiers (ports) of a connected socket.
307pub type ConnIpAddr<A, LI, RI> = ConnIpAddrInner<SocketIpAddr<A>, LI, RI>;
308/// The IP addresses (mapped if dual-stack) and identifiers (ports) of a connected socket.
309pub type ConnInfoAddr<A, RI> = ConnIpAddrInner<SpecifiedAddr<A>, NonZeroU16, RI>;
310
311impl<A: IpAddress, LI: Into<NonZeroU16>, RI> From<ConnIpAddr<A, LI, RI>> for ConnInfoAddr<A, RI> {
312    fn from(
313        ConnIpAddr { local: (local_ip, local_identifier), remote: (remote_ip, remote_identifier) }: ConnIpAddr<A, LI, RI>,
314    ) -> Self {
315        Self {
316            local: (local_ip.into(), local_identifier.into()),
317            remote: (remote_ip.into(), remote_identifier),
318        }
319    }
320}
321
322/// The address of a connected socket.
323#[derive(Copy, Clone, Debug, Eq, GenericOverIp, Hash, PartialEq)]
324#[generic_over_ip()]
325pub struct ConnAddr<A, D> {
326    /// The IP address for the connected socket.
327    pub ip: A,
328    /// The bound device for the connected socket.
329    pub device: Option<D>,
330}
331
332/// The IP address and identifier (port) of a dual-stack listening socket.
333#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq)]
334pub enum DualStackListenerIpAddr<A: IpAddress, LI: Into<NonZeroU16>>
335where
336    A::Version: DualStackIpExt,
337{
338    /// The socket is bound to this stack.
339    ThisStack(ListenerIpAddr<A, LI>),
340    /// The socket is bound to the other stack.
341    OtherStack(ListenerIpAddr<<<A::Version as DualStackIpExt>::OtherVersion as Ip>::Addr, LI>),
342    /// The socket is dual-stack enabled and bound to the IPv6 any address.
343    BothStacks(LI),
344}
345
346impl<A: IpAddress, NewIp: DualStackIpExt, LI: Into<NonZeroU16>> GenericOverIp<NewIp>
347    for DualStackListenerIpAddr<A, LI>
348where
349    A::Version: DualStackIpExt,
350{
351    type Type = DualStackListenerIpAddr<NewIp::Addr, LI>;
352}
353
354impl<LI: Into<NonZeroU16>> Into<(Option<SpecifiedAddr<Ipv6Addr>>, NonZeroU16)>
355    for DualStackListenerIpAddr<Ipv6Addr, LI>
356{
357    fn into(self) -> (Option<SpecifiedAddr<Ipv6Addr>>, NonZeroU16) {
358        match self {
359            Self::ThisStack(listener_ip_addr) => listener_ip_addr.into(),
360            Self::OtherStack(ListenerIpAddr { addr, identifier }) => (
361                Some(addr.map_or(Ipv4::UNSPECIFIED_ADDRESS, SocketIpAddr::addr).to_ipv6_mapped()),
362                identifier.into(),
363            ),
364            Self::BothStacks(identifier) => (None, identifier.into()),
365        }
366    }
367}
368
369/// The IP address and identifiers (ports) of a dual-stack connected socket.
370#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq)]
371#[allow(missing_docs)]
372pub enum DualStackConnIpAddr<A: IpAddress, LI, RI>
373where
374    A::Version: DualStackIpExt,
375{
376    ThisStack(ConnIpAddr<A, LI, RI>),
377    OtherStack(ConnIpAddr<<<A::Version as DualStackIpExt>::OtherVersion as Ip>::Addr, LI, RI>),
378}
379
380impl<A: IpAddress, NewIp: DualStackIpExt, LI, RI> GenericOverIp<NewIp>
381    for DualStackConnIpAddr<A, LI, RI>
382where
383    A::Version: DualStackIpExt,
384{
385    type Type = DualStackConnIpAddr<NewIp::Addr, LI, RI>;
386}
387
388impl<LI: Into<NonZeroU16>, RI> From<DualStackConnIpAddr<Ipv6Addr, LI, RI>>
389    for ConnInfoAddr<Ipv6Addr, RI>
390{
391    fn from(addr: DualStackConnIpAddr<Ipv6Addr, LI, RI>) -> Self {
392        match addr {
393            DualStackConnIpAddr::ThisStack(conn_ip_addr) => conn_ip_addr.into(),
394            DualStackConnIpAddr::OtherStack(ConnIpAddr {
395                local: (local_ip, local_identifier),
396                remote: (remote_ip, remote_identifier),
397            }) => ConnInfoAddr {
398                local: (local_ip.addr().to_ipv6_mapped(), local_identifier.into()),
399                remote: (remote_ip.addr().to_ipv6_mapped(), remote_identifier),
400            },
401        }
402    }
403}
404
405impl<I: Ip, A: SocketMapAddrSpec> From<ListenerIpAddr<I::Addr, A::LocalIdentifier>>
406    for IpAddrVec<I, A>
407{
408    fn from(listener: ListenerIpAddr<I::Addr, A::LocalIdentifier>) -> Self {
409        IpAddrVec::Listener(listener)
410    }
411}
412
413impl<I: Ip, A: SocketMapAddrSpec> From<ConnIpAddr<I::Addr, A::LocalIdentifier, A::RemoteIdentifier>>
414    for IpAddrVec<I, A>
415{
416    fn from(conn: ConnIpAddr<I::Addr, A::LocalIdentifier, A::RemoteIdentifier>) -> Self {
417        IpAddrVec::Connected(conn)
418    }
419}
420
421impl<I: Ip, D, A: SocketMapAddrSpec>
422    From<ListenerAddr<ListenerIpAddr<I::Addr, A::LocalIdentifier>, D>> for AddrVec<I, D, A>
423{
424    fn from(listener: ListenerAddr<ListenerIpAddr<I::Addr, A::LocalIdentifier>, D>) -> Self {
425        AddrVec::Listen(listener)
426    }
427}
428
429impl<I: Ip, D, A: SocketMapAddrSpec>
430    From<ConnAddr<ConnIpAddr<I::Addr, A::LocalIdentifier, A::RemoteIdentifier>, D>>
431    for AddrVec<I, D, A>
432{
433    fn from(
434        conn: ConnAddr<ConnIpAddr<I::Addr, A::LocalIdentifier, A::RemoteIdentifier>, D>,
435    ) -> Self {
436        AddrVec::Conn(conn)
437    }
438}
439
440/// An address vector containing the portions of a socket address that are
441/// visible in an IP packet.
442#[derive(Derivative)]
443#[derivative(
444    Debug(bound = ""),
445    Clone(bound = ""),
446    Eq(bound = ""),
447    PartialEq(bound = ""),
448    Hash(bound = "")
449)]
450#[allow(missing_docs)]
451pub enum IpAddrVec<I: Ip, A: SocketMapAddrSpec> {
452    Listener(ListenerIpAddr<I::Addr, A::LocalIdentifier>),
453    Connected(ConnIpAddr<I::Addr, A::LocalIdentifier, A::RemoteIdentifier>),
454}
455
456impl<I: Ip, A: SocketMapAddrSpec> IpAddrVec<I, A> {
457    fn with_device<D>(self, device: Option<D>) -> AddrVec<I, D, A> {
458        match self {
459            IpAddrVec::Listener(ip) => AddrVec::Listen(ListenerAddr { ip, device }),
460            IpAddrVec::Connected(ip) => AddrVec::Conn(ConnAddr { ip, device }),
461        }
462    }
463
464    /// Creates a new listener address vector.
465    pub fn new_listener(ip: SocketIpAddr<I::Addr>, identifier: A::LocalIdentifier) -> Self {
466        IpAddrVec::Listener(ListenerIpAddr { addr: Some(ip), identifier })
467    }
468}
469
470impl<I: Ip, A: SocketMapAddrSpec> IpAddrVec<I, A> {
471    /// Returns the next smallest address vector that would receive all the same
472    /// packets as this one.
473    ///
474    /// Address vectors are ordered by their shadowing relationship, such that
475    /// a "smaller" vector shadows a "larger" one. This function returns the
476    /// smallest of the set of shadows of `self`.
477    fn widen(self) -> Option<Self> {
478        match self {
479            IpAddrVec::Listener(ListenerIpAddr { addr: None, identifier }) => {
480                let _: A::LocalIdentifier = identifier;
481                None
482            }
483            IpAddrVec::Connected(ConnIpAddr { local: (local_ip, local_identifier), remote }) => {
484                let _: (SocketIpAddr<I::Addr>, A::RemoteIdentifier) = remote;
485                Some(ListenerIpAddr { addr: Some(local_ip), identifier: local_identifier })
486            }
487            IpAddrVec::Listener(ListenerIpAddr { addr: Some(addr), identifier }) => {
488                let _: SocketIpAddr<I::Addr> = addr;
489                Some(ListenerIpAddr { addr: None, identifier })
490            }
491        }
492        .map(IpAddrVec::Listener)
493    }
494}
495
496pub(crate) enum AddrVecIterInner<I: Ip, D, A: SocketMapAddrSpec> {
497    WithDevice { device: D, emitted_device: bool, addr: IpAddrVec<I, A> },
498    NoDevice { addr: IpAddrVec<I, A> },
499    Done,
500}
501
502impl<I: Ip, D: Clone, A: SocketMapAddrSpec> Iterator for AddrVecIterInner<I, D, A> {
503    type Item = AddrVec<I, D, A>;
504
505    fn next(&mut self) -> Option<Self::Item> {
506        match self {
507            Self::Done => None,
508            Self::WithDevice { device, emitted_device, addr } => {
509                if !*emitted_device {
510                    *emitted_device = true;
511                    Some(addr.clone().with_device(Some(device.clone())))
512                } else {
513                    let r = addr.clone().with_device(None);
514                    if let Some(next) = addr.clone().widen() {
515                        *addr = next;
516                        *emitted_device = false;
517                    } else {
518                        *self = Self::Done;
519                    }
520                    Some(r)
521                }
522            }
523            Self::NoDevice { addr } => {
524                let r = addr.clone().with_device(None);
525                if let Some(next) = addr.clone().widen() {
526                    *addr = next;
527                } else {
528                    *self = Self::Done
529                }
530                Some(r)
531            }
532        }
533    }
534}
535
536/// An iterator over socket addresses.
537///
538/// The generated address vectors are ordered according to the following
539/// rules (ordered by precedence):
540///   - a connected address is preferred over a listening address,
541///   - a listening address for a specific IP address is preferred over one
542///     for all addresses,
543///   - an address with a specific device is preferred over one for all
544///     devices.
545///
546/// The first yielded address is always the one provided via
547/// [`AddrVecIter::with_device`] or [`AddrVecIter::without_device`].
548pub struct AddrVecIter<I: Ip, D, A: SocketMapAddrSpec>(AddrVecIterInner<I, D, A>);
549
550impl<I: Ip, D, A: SocketMapAddrSpec> AddrVecIter<I, D, A> {
551    /// Constructs an [`AddrVecIter`] with `addr` and a specified `device`.
552    pub fn with_device(addr: IpAddrVec<I, A>, device: D) -> Self {
553        Self(AddrVecIterInner::WithDevice { device, emitted_device: false, addr })
554    }
555
556    /// Constructs an [`AddrVecIter`] with `addr` without a specified device.
557    pub fn without_device(addr: IpAddrVec<I, A>) -> Self {
558        Self(AddrVecIterInner::NoDevice { addr })
559    }
560}
561
562impl<I: Ip, D: Clone, A: SocketMapAddrSpec> Iterator for AddrVecIter<I, D, A> {
563    type Item = AddrVec<I, D, A>;
564
565    fn next(&mut self) -> Option<Self::Item> {
566        let Self(it) = self;
567        it.next()
568    }
569}
570
571#[derive(GenericOverIp)]
572#[generic_over_ip(I, Ip)]
573enum TryUnmapResult<I: DualStackIpExt, D> {
574    /// The address does not have an un-mapped representation.
575    ///
576    /// This spits back the input address unmodified.
577    CannotBeUnmapped(ZonedAddr<SocketIpAddr<I::Addr>, D>),
578    /// The address in the other stack that corresponds to the input.
579    ///
580    /// Since [`SocketIpAddr`] is guaranteed to hold a specified address,
581    /// this must hold an `Option<SocketIpAddr>`. Since `::FFFF:0.0.0.0` is
582    /// a legal IPv4-mapped IPv6 address, this allows us to represent it as the
583    /// unspecified IPv4 address.
584    Mapped(Option<ZonedAddr<SocketIpAddr<<I::OtherVersion as Ip>::Addr>, D>>),
585}
586
587/// Try to convert a specified address into the address that maps to it from
588/// the other stack.
589///
590/// This is an IP-generic function that tries to invert the
591/// IPv4-to-IPv4-mapped-IPv6 conversion that is performed by
592/// [`Ipv4Addr::to_ipv6_mapped`].
593///
594/// The only inputs that will produce [`TryUnmapResult::Mapped`] are
595/// IPv4-mapped IPv6 addresses. All other inputs will produce
596/// [`TryUnmapResult::CannotBeUnmapped`].
597fn try_unmap<A: IpAddress, D>(addr: ZonedAddr<SpecifiedAddr<A>, D>) -> TryUnmapResult<A::Version, D>
598where
599    A::Version: DualStackIpExt,
600{
601    <A::Version as Ip>::map_ip(
602        addr,
603        |v4| {
604            let addr = SocketIpAddr::new_ipv4_specified(v4.addr());
605            TryUnmapResult::CannotBeUnmapped(ZonedAddr::Unzoned(addr))
606        },
607        |v6| match v6.addr().to_ipv4_mapped() {
608            Some(v4) => {
609                let addr = SpecifiedAddr::new(v4).map(SocketIpAddr::new_ipv4_specified);
610                TryUnmapResult::Mapped(addr.map(ZonedAddr::Unzoned))
611            }
612            None => {
613                let (addr, zone) = v6.into_addr_zone();
614                let addr: SocketIpAddr<_> =
615                    addr.try_into().unwrap_or_else(|AddrIsMappedError {}| {
616                        unreachable!(
617                            "addr cannot be mapped because `to_ipv4_mapped` returned `None`"
618                        )
619                    });
620                TryUnmapResult::CannotBeUnmapped(ZonedAddr::new(addr, zone).unwrap_or_else(|| {
621                    unreachable!("addr should still be scopeable after wrapping in `SocketIpAddr`")
622                }))
623            }
624        },
625    )
626}
627
628/// Provides a specified IP address to use in-place of an unspecified
629/// remote.
630///
631/// Concretely, this method is called during `connect()` and `send_to()`
632/// socket operations to transform an unspecified remote IP address to the
633/// loopback address. This ensures conformance with Linux and BSD.
634fn specify_unspecified_remote<I: SocketIpExt, A: From<SocketIpAddr<I::Addr>>, Z>(
635    addr: Option<ZonedAddr<A, Z>>,
636) -> ZonedAddr<A, Z> {
637    addr.unwrap_or_else(|| ZonedAddr::Unzoned(I::LOOPBACK_ADDRESS_AS_SOCKET_IP_ADDR.into()))
638}
639
640/// A remote IP address that's either in the current stack or the other stack.
641#[allow(missing_docs)]
642pub enum DualStackRemoteIp<I: DualStackIpExt, D> {
643    ThisStack(ZonedAddr<SocketIpAddr<I::Addr>, D>),
644    OtherStack(ZonedAddr<SocketIpAddr<<I::OtherVersion as Ip>::Addr>, D>),
645}
646
647impl<I: SocketIpExt + DualStackIpExt<OtherVersion: SocketIpExt>, D> DualStackRemoteIp<I, D> {
648    /// Returns the [`DualStackRemoteIp`] for the given `remote_ip``.
649    ///
650    /// An IPv4-mapped-IPv6 address will be unmapped to the inner IPv4 address,
651    /// and an unspecified address will be populated with
652    /// [`specify_unspecified_remote`].
653    pub fn new(remote_ip: Option<ZonedAddr<SpecifiedAddr<I::Addr>, D>>) -> Self {
654        let remote_ip = specify_unspecified_remote::<I, _, _>(remote_ip);
655        match try_unmap(remote_ip) {
656            TryUnmapResult::CannotBeUnmapped(remote_ip) => Self::ThisStack(remote_ip),
657            TryUnmapResult::Mapped(remote_ip) => {
658                // NB: Even though we ensured the address was specified above by
659                // calling `specify_unspecified_remote`, it's possible that
660                // unmapping the address made it unspecified (e.g. `::FFFF:0.0.0.0`
661                // is a specified IPv6 addr but an unspecified IPv4 addr). Call
662                // `specify_unspecified_remote` again to ensure the unmapped address
663                // is specified.
664                let remote_ip = specify_unspecified_remote::<I::OtherVersion, _, _>(remote_ip);
665                Self::OtherStack(remote_ip)
666            }
667        }
668    }
669}
670
671/// A local IP address that's either in the current stack or the other stack.
672#[allow(missing_docs)]
673pub enum DualStackLocalIp<I: DualStackIpExt, D> {
674    ThisStack(ZonedAddr<SocketIpAddr<I::Addr>, D>),
675    OtherStack(Option<ZonedAddr<SocketIpAddr<<I::OtherVersion as Ip>::Addr>, D>>),
676}
677
678impl<I: SocketIpExt + DualStackIpExt<OtherVersion: SocketIpExt>, D> DualStackLocalIp<I, D> {
679    /// Returns the [`DualStackLocalIp`] for the given `local_ip``.
680    ///
681    /// If `local_ip` is the unspecified address for the other stack, returns
682    /// `Self::OtherStack(None)`.
683    pub fn new(local_ip: ZonedAddr<SpecifiedAddr<I::Addr>, D>) -> Self {
684        match try_unmap(local_ip) {
685            TryUnmapResult::CannotBeUnmapped(local_ip) => Self::ThisStack(local_ip),
686            TryUnmapResult::Mapped(local_ip) => Self::OtherStack(local_ip),
687        }
688    }
689}