rtci-ice 0.2.1

Sans-I/O ICE agent (RFC 8445) with trickle ICE, ICE-TCP and consent freshness, for WebRTC
Documentation
//! The two cases in which `QueryAndGather` may leave a host address unwrapped, each its own
//! opt-in setting, off by default (draft-ietf-mmusic-mdns-ice-candidates-03).
//!
//! Section 3.1.1, step 1: "Check whether this IP address satisfies the ICE agent's policy
//! regarding whether an address is safe to expose (typically, following the advice from
//! Section 3.1.2.2 below). If so, expose the candidate and abort this process."
//!
//! 1. **An address known to be public** ([`AgentConfig::multicast_dns_expose_known_public_addresses`]).
//!    Section 3.1.2.2: "If the STUN response returns the same value as the local IP address,
//!    this indicates the address is in fact public, although processing will continue as
//!    described below. [...] Because a new candidate is always generated by the STUN query,
//!    the ICE agent SHOULD initially provide mDNS-wrapped candidates to the application and
//!    then follow with server-reflexive candidates once they are obtained, unless it has a
//!    priori knowledge that a given address is public and does not require mDNS wrapping. To
//!    that end, once an address has been identified as public, the ICE agent MAY cache this
//!    information and skip mDNS protection for that address in future ICE gathering phases.
//!    Note that if the set of STUN servers changes, any cached information SHOULD be
//!    discarded, as the new set may return different results."
//! 2. **An RFC 4941 temporary IPv6 address** ([`AgentConfig::multicast_dns_expose_temporary_ipv6_addresses`]).
//!    Section 3.1.2.3: "the [RFC4941] IPv6 addresses recommended for WebRTC have inherent
//!    privacy protections, namely a short lifetime and the lack of any stateful information.
//!    Accordingly, implementations MAY choose to not conceal [RFC4941] addresses with mDNS
//!    names as a tradeoff for improved peer-to-peer connectivity."
//!
//! Neither ever unwraps an address that [`is_global_unicast`] refuses (private, loopback,
//! link-local, unique-local, shared CGNAT space, documentation, ...), whatever the STUN server
//! answered or the application marked.
//!
//! [`AgentConfig::multicast_dns_expose_known_public_addresses`]: crate::agent::agent_config::AgentConfig::multicast_dns_expose_known_public_addresses
//! [`AgentConfig::multicast_dns_expose_temporary_ipv6_addresses`]: crate::agent::agent_config::AgentConfig::multicast_dns_expose_temporary_ipv6_addresses

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

/// Whether `ip` is a globally reachable unicast address: the only kind of address the two
/// exposure settings may ever leave unwrapped. A hard check of the engine, applied whatever a
/// STUN server answered or the application marked.
///
/// IPv4: every address except `0.0.0.0/8`, `10.0.0.0/8`, `100.64.0.0/10` (shared CGNAT
/// space, RFC 6598), `127.0.0.0/8`, `169.254.0.0/16`, `172.16.0.0/12`, `192.0.0.0/24`,
/// `192.0.2.0/24`, `192.88.99.0/24`, `192.168.0.0/16`, `198.18.0.0/15`, `198.51.100.0/24`,
/// `203.0.113.0/24`, `224.0.0.0/4` and `240.0.0.0/4` (the IANA IPv4 special-purpose
/// registry's entries that are not globally reachable, and multicast).
///
/// IPv6: only global unicast space, `2000::/3`, and in it not `2001::/23` (IETF protocol
/// assignments, Teredo among them), `2001:db8::/32` and `3fff::/20` (documentation), nor
/// `2002::/16` (6to4, which carries an IPv4 address). Everything outside `2000::/3` is
/// refused: loopback, unspecified, IPv4-mapped and -translated (NAT64, which section 3.1.2.2
/// names as private IPv6 that looks public), unique-local `fc00::/7`, link-local
/// `fe80::/10`, site-local, multicast. Stricter than the registry where an address could
/// still embed a private one; stricter only ever hides more.
pub fn is_global_unicast(ip: IpAddr) -> bool {
    match ip {
        IpAddr::V4(v4) => is_global_v4(v4),
        IpAddr::V6(v6) => is_global_v6(v6),
    }
}

fn is_global_v4(ip: Ipv4Addr) -> bool {
    let o = ip.octets();
    let in_net = |net: [u8; 4], len: u32| {
        let mask = if len == 0 { 0 } else { u32::MAX << (32 - len) };
        u32::from_be_bytes(o) & mask == u32::from_be_bytes(net) & mask
    };
    const NOT_GLOBAL: [([u8; 4], u32); 15] = [
        ([0, 0, 0, 0], 8),
        ([10, 0, 0, 0], 8),
        ([100, 64, 0, 0], 10),
        ([127, 0, 0, 0], 8),
        ([169, 254, 0, 0], 16),
        ([172, 16, 0, 0], 12),
        ([192, 0, 0, 0], 24),
        ([192, 0, 2, 0], 24),
        ([192, 88, 99, 0], 24),
        ([192, 168, 0, 0], 16),
        ([198, 18, 0, 0], 15),
        ([198, 51, 100, 0], 24),
        ([203, 0, 113, 0], 24),
        ([224, 0, 0, 0], 4),
        ([240, 0, 0, 0], 4),
    ];
    !NOT_GLOBAL.iter().any(|(net, len)| in_net(*net, *len))
}

fn is_global_v6(ip: Ipv6Addr) -> bool {
    let s = ip.segments();
    let global_unicast = s[0] & 0xe000 == 0x2000;
    let ietf_protocol = s[0] == 0x2001 && s[1] < 0x0200;
    let documentation = (s[0] == 0x2001 && s[1] == 0x0db8) || s[0] & 0xfff0 == 0x3ff0;
    let six_to_four = s[0] == 0x2002;
    global_unicast && !ietf_protocol && !documentation && !six_to_four
}

/// Setting 1's cache: the local addresses a server-reflexive candidate showed to be public,
/// each with the ICE generation of the gathering that showed it. Per agent (the engine keeps
/// no process-wide state). An address shown public in generation `g` is unwrapped in
/// generation `g + 1` only: "future ICE gathering phases", never the gathering that showed
/// it (its mDNS candidate has been provided already), and each restart takes only what the
/// gathering just before it found again, so an address that is no longer seen public is
/// wrapped again from the next restart on. Emptied when the set of STUN / TURN servers
/// changes (section 3.1.2.2, SHOULD).
#[derive(Debug, Clone, Default)]
pub(crate) struct KnownPublicAddresses {
    entries: Vec<(IpAddr, u64)>,
}

impl KnownPublicAddresses {
    /// `ip` was shown public by the gathering of `generation`.
    pub(crate) fn record(&mut self, ip: IpAddr, generation: u64) {
        match self.entries.iter_mut().find(|(i, _)| *i == ip) {
            Some((_, g)) => *g = (*g).max(generation),
            None => self.entries.push((ip, generation)),
        }
    }

    /// Whether a host candidate on `ip` of `generation` may go out unwrapped: the gathering of
    /// the generation just before showed it public.
    pub(crate) fn exposes(&self, ip: IpAddr, generation: u64) -> bool {
        self.entries
            .iter()
            .any(|(i, g)| *i == ip && g.checked_add(1) == Some(generation))
    }

    /// A new generation `generation` is applied: what earlier gatherings than the one just
    /// before found is dropped.
    pub(crate) fn restarted(&mut self, generation: u64) {
        self.entries
            .retain(|(_, g)| g.saturating_add(1) >= generation);
    }

    /// The set of servers changed: nothing is known any more.
    pub(crate) fn clear(&mut self) {
        self.entries.clear();
    }

    pub(crate) fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }
}