use crate::core::{AsxError, ErrorCode, ErrorContext, Result};
pub(crate) fn is_private_ip(addr: std::net::IpAddr) -> bool {
match addr.to_canonical() {
std::net::IpAddr::V4(ip) => is_private_ipv4(ip),
std::net::IpAddr::V6(ip) => is_private_ipv6(ip),
}
}
fn is_private_ipv4(ip: std::net::Ipv4Addr) -> bool {
let [a, b, ..] = ip.octets();
ip.is_loopback() || ip.is_private() || ip.is_link_local() || ip.is_broadcast() || ip.is_documentation() || ip.is_multicast() || a == 0 || (a == 100 && (64..=127).contains(&b)) || (a == 192 && b == 0) || (a == 198 && (b == 18 || b == 19)) || a >= 240 }
fn is_private_ipv6(ip: std::net::Ipv6Addr) -> bool {
let seg = ip.segments();
let low32 = std::net::Ipv4Addr::new(
(seg[6] >> 8) as u8,
seg[6] as u8,
(seg[7] >> 8) as u8,
seg[7] as u8,
);
let nat64_wkp = seg[0] == 0x0064 && seg[1] == 0xff9b && seg[2..6] == [0, 0, 0, 0];
let nat64_local = seg[0] == 0x0064 && seg[1] == 0xff9b && seg[2] == 0x0001;
let ipv4_compatible = seg[0..6] == [0, 0, 0, 0, 0, 0];
if nat64_wkp || nat64_local || ipv4_compatible {
return is_private_ipv4(low32);
}
if seg[0] == 0x2002 {
let embedded = std::net::Ipv4Addr::new(
(seg[1] >> 8) as u8,
seg[1] as u8,
(seg[2] >> 8) as u8,
seg[2] as u8,
);
return is_private_ipv4(embedded);
}
ip.is_loopback()
|| ip.is_unspecified()
|| ip.is_multicast()
|| (seg[0] & 0xfe00) == 0xfc00
|| (seg[0] & 0xffc0) == 0xfe80
|| (seg[0] == 0x2001 && seg[1] == 0x0000)
|| (seg[0] == 0x2001 && seg[1] == 0x0db8)
|| seg[0..4] == [0x0100, 0, 0, 0]
}
pub(crate) fn is_private_host(host: &str) -> bool {
if host.eq_ignore_ascii_case("localhost") {
return true;
}
let h_lower = host.to_ascii_lowercase();
let h_bare = h_lower.trim_start_matches('[').trim_end_matches(']');
if let Ok(ip) = h_bare.parse::<std::net::IpAddr>() {
return is_private_ip(ip);
}
false
}
pub(crate) async fn read_body_capped(
response: http::Response<hyper::body::Incoming>,
cap: usize,
stage: &'static str,
) -> Result<bytes::Bytes> {
use http_body_util::BodyExt;
let too_large = |size: String| {
AsxError::new(
ErrorCode::PayloadTooLarge,
format!("response body {size} exceeds the {cap} byte limit"),
ErrorContext::new(stage),
)
};
let declared = response
.headers()
.get(http::header::CONTENT_LENGTH)
.and_then(|v| v.to_str().ok())
.and_then(|v| v.trim().parse::<u64>().ok());
if let Some(declared) = declared
&& declared > cap as u64
{
return Err(too_large(format!("of {declared} bytes (Content-Length)")));
}
let mut incoming = response.into_body();
let mut body = bytes::BytesMut::new();
while let Some(frame) = incoming.frame().await {
let frame = frame.map_err(|err| {
AsxError::new(
ErrorCode::TransportFailure,
format!("failed to read response body: {err}"),
ErrorContext::new(stage),
)
})?;
let Ok(chunk) = frame.into_data() else {
continue; };
if body.len().saturating_add(chunk.len()) > cap {
return Err(too_large(format!(
"of more than {} bytes",
body.len().saturating_add(chunk.len())
)));
}
body.extend_from_slice(&chunk);
}
Ok(body.freeze())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn private_and_reserved_ranges_are_private() {
for addr in [
"127.0.0.1",
"127.1.2.3",
"10.0.0.1",
"172.16.0.1",
"172.31.255.255",
"192.168.1.100",
"169.254.1.1",
"169.254.169.254",
"0.0.0.0",
"100.64.0.1",
"203.0.113.9",
"::1",
"fc00::1",
"fd12:3456:789a::1",
"fe80::1",
"::ffff:127.0.0.1",
"::ffff:169.254.169.254",
"::ffff:10.0.0.1",
] {
let ip: std::net::IpAddr = addr.parse().expect(addr);
assert!(is_private_ip(ip), "{addr} must be private");
}
for host in ["localhost", "LOCALHOST", "[::1]", "127.0.0.1"] {
assert!(is_private_host(host), "{host}");
}
assert!(!is_private_host("example.org"));
}
#[test]
fn transition_benchmark_and_documentation_ranges_are_private() {
let private = [
"64:ff9b::10.0.0.1", "64:ff9b:1::a00:1", "2002:0a00:0001::1", "::10.0.0.1", "2001:0::1", "198.18.0.1", "2001:db8::1", "100::1", ];
for addr in private {
let ip: std::net::IpAddr = addr.parse().expect(addr);
assert!(is_private_ip(ip), "{addr} must be private");
}
let public = [
"64:ff9b::8.8.8.8",
"2002:0808:0808::1",
"8.8.8.8",
"2606:4700::1111",
];
for addr in public {
let ip: std::net::IpAddr = addr.parse().expect(addr);
assert!(!is_private_ip(ip), "{addr} must stay public");
}
}
}