rtci-shared 0.5.0

Shared types of a sans-I/O WebRTC stack: marshalling traits, transport context, replay detection, the stream transport interface
Documentation
//! NAT64 for the Happy Eyeballs engine on an IPv6-only network (RFC 8305 section 7, RFC 8445
//! section 5.1.1.2): the prefix the network's NAT64 uses is discovered with RFC 7050 (the
//! AAAA records of [`IPV4ONLY_ARPA`], which a DNS64 resolver synthesizes from its well-known
//! IPv4 addresses), and IPv4 addresses are written into IPv6 ones with that prefix as RFC 6052
//! section 2.2 has it.

use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr};

/// RFC 7050 section 2: the well-known name whose AAAA records a DNS64 resolver synthesizes.
pub const IPV4ONLY_ARPA: &str = "ipv4only.arpa";

/// RFC 7050 section 2.2: the well-known IPv4 addresses of [`IPV4ONLY_ARPA`].
pub const WELL_KNOWN_IPV4: [Ipv4Addr; 2] =
    [Ipv4Addr::new(192, 0, 0, 170), Ipv4Addr::new(192, 0, 0, 171)];

/// RFC 6052 section 2.2: the prefix lengths an IPv4-embedded IPv6 address may have.
pub const PREFIX_LENGTHS: [u8; 6] = [96, 64, 56, 48, 40, 32];

/// A NAT64 prefix (RFC 6052 section 2.2): its first `len` bits are the network's.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Nat64Prefix {
    /// The prefix, the bits past `len` zero.
    pub prefix: Ipv6Addr,
    /// 32, 40, 48, 56, 64 or 96.
    pub len: u8,
}

/// The byte positions of the 32 IPv4 bits in an IPv4-embedded IPv6 address of a prefix of
/// `len` bits (RFC 6052 section 2.2, figure 1): bits 64 to 71 (byte 8, "u") are skipped and
/// left zero.
fn ipv4_positions(len: u8) -> Option<[usize; 4]> {
    Some(match len {
        32 => [4, 5, 6, 7],
        40 => [5, 6, 7, 9],
        48 => [6, 7, 9, 10],
        56 => [7, 9, 10, 11],
        64 => [9, 10, 11, 12],
        96 => [12, 13, 14, 15],
        _ => return None,
    })
}

impl Nat64Prefix {
    /// The prefix of length `len` of `addr` (bits past it cleared); `None` for a length
    /// RFC 6052 does not allow.
    pub fn new(addr: Ipv6Addr, len: u8) -> Option<Self> {
        ipv4_positions(len)?;
        let bits = u128::from(addr);
        let mask = if len == 0 {
            0
        } else {
            u128::MAX << (128 - u32::from(len))
        };
        Some(Self {
            prefix: Ipv6Addr::from(bits & mask),
            len,
        })
    }

    /// RFC 6052 section 2.2: `v4` embedded under this prefix, the "u" octet (bits 64 to 71)
    /// and the suffix zero.
    pub fn synthesize(&self, v4: Ipv4Addr) -> Ipv6Addr {
        let mut octets = self.prefix.octets();
        // Bits from the prefix length on are the IPv4 address's, the u octet's and the
        // suffix's: start them from zero.
        for (i, o) in octets.iter_mut().enumerate() {
            if i * 8 >= usize::from(self.len) {
                *o = 0;
            }
        }
        let positions = ipv4_positions(self.len).unwrap_or([12, 13, 14, 15]);
        for (p, b) in positions.iter().zip(v4.octets()) {
            octets[*p] = b;
        }
        Ipv6Addr::from(octets)
    }

    /// The IPv4 address `addr` embeds under this prefix, if `addr` has the prefix.
    pub fn extract(&self, addr: Ipv6Addr) -> Option<Ipv4Addr> {
        if Self::new(addr, self.len)? != *self {
            return None;
        }
        let o = addr.octets();
        let p = ipv4_positions(self.len)?;
        Some(Ipv4Addr::new(o[p[0]], o[p[1]], o[p[2]], o[p[3]]))
    }
}

/// RFC 7050 section 3: the NAT64 prefixes the AAAA answers for [`IPV4ONLY_ARPA`] show. Each
/// IPv6 address is searched for one of the [`WELL_KNOWN_IPV4`] addresses at each prefix
/// length (longest first); an address that holds none is not a synthesized one and is
/// ignored. Duplicates are dropped; the order of the answers is kept.
pub fn discover_prefixes(answers: &[IpAddr]) -> Vec<Nat64Prefix> {
    let mut out: Vec<Nat64Prefix> = vec![];
    for answer in answers {
        let IpAddr::V6(v6) = answer else {
            continue;
        };
        let found = PREFIX_LENGTHS.iter().find_map(|&len| {
            let prefix = Nat64Prefix::new(*v6, len)?;
            let embedded = prefix.extract(*v6)?;
            (WELL_KNOWN_IPV4.contains(&embedded) && prefix.synthesize(embedded) == *v6)
                .then_some(prefix)
        });
        if let Some(prefix) = found
            && !out.contains(&prefix)
        {
            out.push(prefix);
        }
    }
    out
}

/// RFC 8305 section 7.1: the IPv6 addresses synthesized for the IPv4 ones among `addresses`
/// with each of `prefixes`, with their ports. "The synthesized addresses are then inserted
/// into the list of addresses as if they were results from DNS queries".
pub fn synthesize_all(addresses: &[SocketAddr], prefixes: &[Nat64Prefix]) -> Vec<SocketAddr> {
    let mut out = vec![];
    for a in addresses {
        let IpAddr::V4(v4) = a.ip() else {
            continue;
        };
        for p in prefixes {
            let s = SocketAddr::new(IpAddr::V6(p.synthesize(v4)), a.port());
            if !out.contains(&s) {
                out.push(s);
            }
        }
    }
    out
}

#[cfg(test)]
mod tests {
    use super::*;

    fn v6(s: &str) -> Ipv6Addr {
        s.parse().unwrap()
    }

    /// RFC 6052 section 2.4, table 1: 192.0.2.33 under 2001:db8:100::/40 and the other
    /// lengths of the table's example prefixes, and under the well-known prefix 64:ff9b::/96.
    #[test]
    fn synthesis_follows_rfc_6052_table_1() {
        let v4 = Ipv4Addr::new(192, 0, 2, 33);
        let cases = [
            ("2001:db8::", 32, "2001:db8:c000:221::"),
            ("2001:db8:100::", 40, "2001:db8:1c0:2:21::"),
            ("2001:db8:122::", 48, "2001:db8:122:c000:2:2100::"),
            ("2001:db8:122:300::", 56, "2001:db8:122:3c0:0:221::"),
            ("2001:db8:122:344::", 64, "2001:db8:122:344:c0:2:2100:0"),
            ("2001:db8:122:344::", 96, "2001:db8:122:344::c000:221"),
            ("64:ff9b::", 96, "64:ff9b::c000:221"),
        ];
        for (prefix, len, want) in cases {
            let p = Nat64Prefix::new(v6(prefix), len).unwrap();
            assert_eq!(p.synthesize(v4), v6(want), "/{len}");
            assert_eq!(p.extract(v6(want)), Some(v4), "/{len}");
        }
        assert!(Nat64Prefix::new(v6("64:ff9b::"), 80).is_none());
        assert_eq!(
            Nat64Prefix::new(v6("64:ff9b::"), 96)
                .unwrap()
                .extract(v6("2001:db8::c000:221")),
            None,
            "another prefix"
        );
    }

    /// RFC 7050 section 3: the prefix is found from the synthesized AAAA records of
    /// ipv4only.arpa, at whichever length holds a well-known address; an answer that holds
    /// none is ignored.
    #[test]
    fn prefixes_are_discovered_from_the_well_known_addresses() {
        let answers: Vec<IpAddr> = vec![
            "64:ff9b::c000:aa".parse().unwrap(),
            "64:ff9b::c000:ab".parse().unwrap(),
            "2001:db8:122:3c0:0:aa::".parse().unwrap(),
            "2001:db8::1".parse().unwrap(),
            "192.0.0.170".parse().unwrap(),
        ];
        let found = discover_prefixes(&answers);
        assert_eq!(
            found,
            vec![
                Nat64Prefix::new(v6("64:ff9b::"), 96).unwrap(),
                Nat64Prefix::new(v6("2001:db8:122:300::"), 56).unwrap(),
            ]
        );
        assert!(discover_prefixes(&["2001:db8::1".parse().unwrap()]).is_empty());
        let synthesized = synthesize_all(
            &[
                "192.0.2.10:3478".parse().unwrap(),
                "[2001:db8::9]:3478".parse().unwrap(),
            ],
            &found[..1],
        );
        assert_eq!(
            synthesized,
            vec!["[64:ff9b::c000:20a]:3478".parse().unwrap()]
        );
    }
}