Cotton code
62 lines · 2.5 KB · RustRaw
//! Which addresses are a HOME NETWORK's — one predicate, held in one place.//!//! The three IPv4 ranges RFC 1918 reserves for private use (`10/8`,//! `172.16/12`, `192.168/16`) are the ones a Mac and a phone can be on//! together with no internet in between. Two sides ask the question://!//! - the Mac, choosing which of its interfaces to hand a phone//!   (`cotton-ffi — shell::lan`);//! - the phone, deciding whether a plain-http address it was given is one it//!   may sign to at all.//!//! They must agree, or a Mac recommends an address the phone then refuses, so//! the predicate lives HERE rather than beside either of them. It is pure text//! in and a decision out: it parses the four octets itself rather than taking//! an `Ipv4Addr`, because both callers hold a string the OS or a person gave//! them, and "not an address at all" is one of the answers./// One of the three private IPv4 ranges — `10.x.x.x`, `172.16…31.x.x`,/// `192.168.x.x` — and nothing else.////// Anything that is not four decimal octets is `false`, including an IPv6/// address, a host name and `999.1.1.1`. Loopback is deliberately NOT private/// here: `127.0.0.1` is this machine talking to itself, which is a different/// decision each caller makes for itself.pub fn is_private_ipv4(address: &str) -> bool {    let parts: Vec<&str> = address.split('.').collect();    if parts.len() != 4 {        return false;    }    let mut octets = [0u16; 4];    for (slot, part) in octets.iter_mut().zip(parts) {        match part.parse::<u16>() {            Ok(value) if value <= 255 => *slot = value,            _ => return false,        }    }    octets[0] == 10        || (octets[0] == 172 && (16..=31).contains(&octets[1]))        || (octets[0] == 192 && octets[1] == 168)}/// A tailnet's IPv4 — Tailscale's `100.64.0.0/10` (the carrier-grade NAT/// range, which Tailscale hands its devices out of) — and nothing else.////// Kept apart from [`is_private_ipv4`] on purpose: that one decides which/// address a Mac calls its LAN and which a phone dials across the room, and a/// tailnet address is neither — it is a way of its own, tried after the room/// and before the relay, and only for a household with a Tailscale/// connection.pub fn is_tailnet_ipv4(address: &str) -> bool {    match address.parse::<std::net::Ipv4Addr>() {        Ok(ip) => {            let [a, b, ..] = ip.octets();            a == 100 && (64..128).contains(&b)        }        Err(_) => false,    }}#[cfg(test)]#[path = "net_tests.rs"]mod tests;