1use std::net::{IpAddr, Ipv6Addr, SocketAddr};
10
11#[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 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#[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 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
83fn 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
96fn embedded_ipv4(ip: Ipv6Addr) -> Option<std::net::Ipv4Addr> {
98 let [a, b, c, d, e, f, _, _] = ip.segments();
99 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 #[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 #[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 #[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}