Skip to main content

syncspin_core/
endpoint.rs

1//! The two rules `connection.md` puts on an advertised endpoint, shared by both roles.
2//!
3//! A peer that discovers a record over mDNS SHOULD only connect to an address that is not a
4//! loopback or unspecified one, and only when the advertised `path` matches the `path-absolute` rule
5//! of RFC 3986. The client dials servers and the server dials clients under the same rule, so the
6//! rule lives here and not in either crate. Both functions are pure string checks: no socket, no
7//! resolver.
8
9use std::net::{IpAddr, Ipv6Addr, SocketAddr};
10
11/// Whether `path` matches the `path-absolute` rule of RFC 3986, section 3.3.
12///
13/// That is a `/`, then optionally a non-empty first segment and further `/`-separated segments,
14/// each made of unreserved characters, percent-encoded octets, sub-delimiters, `:` and `@`. A
15/// query, a fragment, a space or a control character is not part of it.
16#[must_use]
17pub fn is_path_absolute(path: &str) -> bool {
18    let Some(rest) = path.strip_prefix('/') else {
19        return false;
20    };
21    if rest.starts_with('/') {
22        return false;
23    }
24    let mut bytes = rest.bytes();
25    while let Some(byte) = bytes.next() {
26        match byte {
27            b'/' | b':' | b'@' | b'-' | b'.' | b'_' | b'~' | b'!' | b'$' | b'&' | b'\'' | b'('
28            | b')' | b'*' | b'+' | b',' | b';' | b'=' => {}
29            b'%' => {
30                // A percent-encoded octet is exactly two hex digits; the iterator consumes them.
31                let (Some(high), Some(low)) = (bytes.next(), bytes.next()) else {
32                    return false;
33                };
34                if !(high.is_ascii_hexdigit() && low.is_ascii_hexdigit()) {
35                    return false;
36                }
37            }
38            byte if byte.is_ascii_alphanumeric() => {}
39            _ => return false,
40        }
41    }
42    true
43}
44
45/// Whether `address` is one a peer must not dial: a loopback or unspecified address, or a host
46/// name that is a loopback by rule.
47///
48/// An IP literal, with or without a port, is judged by its address. An IPv6 address that embeds an
49/// IPv4 one - mapped (`::ffff:a.b.c.d`), compatible (`::a.b.c.d`) or NAT64 (`64:ff9b::a.b.c.d`) -
50/// is judged by the address it embeds. Any other text is a host name: it is local when it is
51/// `localhost`, `localhost.localdomain` or a name under `.localhost` (RFC 6761), or when its last
52/// label is a legacy numeric IPv4 spelling such as `127.1` or `0x7f.1`, which a resolver turns into
53/// an address. A real host name never ends in an all-digit label or in `0x` followed by hex digits.
54#[must_use]
55pub fn is_local_address(address: &str) -> bool {
56    if let Ok(socket) = address.parse::<SocketAddr>() {
57        return is_local_ip(socket.ip());
58    }
59    let bare = address
60        .strip_prefix('[')
61        .and_then(|rest| rest.strip_suffix(']'))
62        .unwrap_or(address);
63    if let Ok(ip) = bare.parse::<IpAddr>() {
64        return is_local_ip(ip);
65    }
66    // `host:port`; a bare host has no port to strip, and an IPv6 literal was handled above.
67    let host = address
68        .rsplit_once(':')
69        .filter(|(_, port)| !port.is_empty() && port.bytes().all(|byte| byte.is_ascii_digit()))
70        .map_or(address, |(host, _)| host)
71        .trim_end_matches('.')
72        .to_ascii_lowercase();
73    let last_label = host.rsplit('.').next().unwrap_or("");
74    host == "localhost"
75        || host == "localhost.localdomain"
76        || host.ends_with(".localhost")
77        || last_label
78            .strip_prefix("0x")
79            .is_some_and(|hex| !hex.is_empty() && hex.bytes().all(|byte| byte.is_ascii_hexdigit()))
80        || (!last_label.is_empty() && last_label.bytes().all(|byte| byte.is_ascii_digit()))
81}
82
83/// Whether `ip` is loopback or unspecified, looking through an embedded IPv4 address.
84fn is_local_ip(ip: IpAddr) -> bool {
85    match ip {
86        IpAddr::V4(ip) => ip.is_loopback() || ip.is_unspecified(),
87        IpAddr::V6(ip) => {
88            ip.is_loopback()
89                || ip.is_unspecified()
90                || embedded_ipv4(ip)
91                    .is_some_and(|inner| inner.is_loopback() || inner.is_unspecified())
92        }
93    }
94}
95
96/// The IPv4 address an IPv6 one embeds, for the mapped, compatible and NAT64 forms.
97fn embedded_ipv4(ip: Ipv6Addr) -> Option<std::net::Ipv4Addr> {
98    let [a, b, c, d, e, f, _, _] = ip.segments();
99    // The last four octets, taken as they are: no shift or mask for a mutant to hide in.
100    let [.., o1, o2, o3, o4] = ip.octets();
101    let inner = std::net::Ipv4Addr::new(o1, o2, o3, o4);
102    let mapped = [a, b, c, d, e] == [0, 0, 0, 0, 0] && f == 0xffff;
103    let compatible = [a, b, c, d, e, f] == [0; 6];
104    let nat64 = [a, b, c, d, e, f] == [0x64, 0xff9b, 0, 0, 0, 0];
105    (mapped || compatible || nat64).then_some(inner)
106}
107
108#[cfg(test)]
109mod tests {
110    use super::*;
111
112    /// The path rule accepts what RFC 3986 calls `path-absolute` and nothing else.
113    #[test]
114    fn a_path_must_be_path_absolute() {
115        for path in [
116            "/",
117            "/sendspin",
118            "/a/b",
119            "/a%20b",
120            "/%41",
121            "/a%41",
122            "/ab%41",
123            "/a:b@c",
124            "/~x_y-z.w",
125            "/a/",
126            "/a;b=c",
127        ] {
128            assert!(is_path_absolute(path), "{path:?}");
129        }
130        for path in [
131            "", "sendspin", "//a", "/a?b", "/a#b", "/a b", "/a%zz", "/a%2G", "/a%", "/é",
132        ] {
133            assert!(!is_path_absolute(path), "{path:?}");
134        }
135    }
136
137    /// The embedded address is taken whole: an extraction that kept only one byte would still
138    /// pass the local-address tests, because loopback depends on the first octet alone.
139    #[test]
140    fn an_embedded_ipv4_is_extracted_whole() {
141        let parse = |address: &str| address.parse::<Ipv6Addr>().expect("the address parses");
142        for address in ["::ffff:192.0.2.1", "::c000:201", "64:ff9b::c000:201"] {
143            assert_eq!(
144                embedded_ipv4(parse(address)),
145                Some(std::net::Ipv4Addr::new(192, 0, 2, 1)),
146                "{address}"
147            );
148        }
149        assert_eq!(embedded_ipv4(parse("2001:db8::1")), None);
150    }
151
152    #[test]
153    fn local_addresses_are_refused_in_every_spelling() {
154        for address in [
155            "127.0.0.1:8927",
156            "127.0.0.1",
157            "[::1]:8927",
158            "::1",
159            "[::1]",
160            "0.0.0.0:8927",
161            "[::]:8927",
162            "[::ffff:127.0.0.1]:8927",
163            "[::ffff:0.0.0.0]:8927",
164            "[::7f00:1]:8927",
165            "[64:ff9b::7f00:1]:8927",
166            "localhost:8927",
167            "LOCALHOST.:8927",
168            "kitchen.localhost:8927",
169            "localhost.localdomain:8927",
170            "127.1:8927",
171            "0x7f.1:8927",
172            "0x7f000001:8927",
173            "2130706433:8927",
174        ] {
175            assert!(is_local_address(address), "{address}");
176        }
177    }
178
179    /// A host name or address that merely looks like a loopback one is not refused.
180    #[test]
181    fn ordinary_addresses_are_kept() {
182        for address in [
183            "speaker.local:8927",
184            "my-host2:8927",
185            "a.localhosting.example:8927",
186            "host.0xfoo:8927",
187            "host.0x:8927",
188            "192.0.2.1:8927",
189            "192.0.2.1",
190            "192.0.2.1:abc",
191            "[1:2:3:4:5:ffff:7f00:1]:8927",
192            "[::1:7f00:1]:8927",
193            "[2001:db8::1]:8927",
194            "[fe80::1%eth0]:8927",
195            "[64:ff9b::c000:201]:8927",
196            "[::c000:201]:8927",
197        ] {
198            assert!(!is_local_address(address), "{address}");
199        }
200    }
201}