use std::collections::BTreeMap;
use super::ExecError;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Origin {
Agent,
Operator,
}
pub const DEFAULT_MAX_REDIRECTS: u8 = 10;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HttpRequest {
pub method: String,
pub url: String,
pub headers: BTreeMap<String, String>,
pub body: Option<Vec<u8>>,
pub max_bytes: Option<u64>,
pub max_redirects: u8,
pub public_only: bool,
pub internal_target: bool,
}
impl HttpRequest {
pub fn new(method: impl Into<String>, url: impl Into<String>) -> Self {
Self {
method: method.into(),
url: url.into(),
headers: BTreeMap::new(),
body: None,
max_bytes: None,
max_redirects: DEFAULT_MAX_REDIRECTS,
public_only: false,
internal_target: false,
}
}
pub fn public_only(mut self) -> Self {
self.public_only = true;
self
}
pub fn public_only_but_target(mut self) -> Self {
self.public_only = true;
self.internal_target = true;
self
}
pub fn get(url: impl Into<String>) -> Self {
Self::new("GET", url)
}
pub fn post(url: impl Into<String>) -> Self {
Self::new("POST", url)
}
pub fn header(mut self, k: impl Into<String>, v: impl Into<String>) -> Self {
self.headers.insert(k.into(), v.into());
self
}
pub fn body(mut self, body: impl Into<Vec<u8>>) -> Self {
self.body = Some(body.into());
self
}
pub fn max_bytes(mut self, n: u64) -> Self {
self.max_bytes = Some(n);
self
}
pub fn max_redirects(mut self, n: u8) -> Self {
self.max_redirects = n;
self
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HttpResponse {
pub status: u16,
pub headers: BTreeMap<String, String>,
pub body: Vec<u8>,
}
impl HttpResponse {
pub fn body_text(&self) -> String {
String::from_utf8_lossy(&self.body).into_owned()
}
}
pub struct HttpStream {
pub status: u16,
pub headers: BTreeMap<String, String>,
pub body: futures::stream::BoxStream<'static, Result<Vec<u8>, ExecError>>,
}
#[async_trait::async_trait]
pub trait Network: Send + Sync {
async fn send(&self, req: HttpRequest, origin: Origin) -> Result<HttpResponse, ExecError>;
async fn open(&self, req: HttpRequest, origin: Origin) -> Result<HttpStream, ExecError> {
let r = self.send(req, origin).await?;
Ok(HttpStream {
status: r.status,
headers: r.headers,
body: Box::pin(futures::stream::once(async move { Ok(r.body) })),
})
}
fn permits(&self, host: &str, origin: Origin) -> bool;
}
pub fn domains_name_host(domains: &[String], host: &str) -> bool {
let host = domain_key(host);
domains.iter().any(|d| {
let d = domain_key(d);
!d.is_empty() && (host == d || host.ends_with(&format!(".{d}")))
})
}
pub fn domain_key(entry: &str) -> String {
let bare = entry
.trim()
.trim_start_matches('[')
.trim_end_matches(']')
.trim_end_matches('.');
match bare.parse::<std::net::IpAddr>() {
Ok(ip) => ip.to_string(),
Err(_) => bare.to_ascii_lowercase(),
}
}
pub fn names_loopback(entry: &str) -> bool {
let key = domain_key(entry);
key == "localhost"
|| key
.parse::<std::net::IpAddr>()
.is_ok_and(|ip| ip.is_loopback())
}
pub fn is_internal_address(ip: std::net::IpAddr) -> bool {
match ip {
std::net::IpAddr::V4(v4) => internal_v4(v4),
std::net::IpAddr::V6(v6) => internal_v6(v6),
}
}
fn internal_v4(ip: std::net::Ipv4Addr) -> bool {
let [a, b, c, _] = ip.octets();
a == 0
|| ip.is_loopback()
|| ip.is_private()
|| ip.is_link_local()
|| (a == 100 && (64..128).contains(&b))
|| (a == 192 && b == 0 && c == 0)
|| (a == 198 && (b == 18 || b == 19))
|| ip.is_multicast()
|| a >= 240
}
fn internal_v6(ip: std::net::Ipv6Addr) -> bool {
let first = ip.segments()[0];
ip.is_unspecified()
|| ip.is_loopback()
|| (first & 0xfe00) == 0xfc00
|| (first & 0xffc0) == 0xfe80
|| (first & 0xffc0) == 0xfec0
|| ip.is_multicast()
|| matches!(ip.segments(), [0x64, 0xff9b, 1, ..])
|| carried_v4(ip).is_some_and(internal_v4)
}
pub fn carried_v4(ip: std::net::Ipv6Addr) -> Option<std::net::Ipv4Addr> {
if let Some(v4) = ip.to_ipv4_mapped() {
return Some(v4);
}
let from = |hi: u16, lo: u16| {
let [a, b] = hi.to_be_bytes();
let [c, d] = lo.to_be_bytes();
std::net::Ipv4Addr::new(a, b, c, d)
};
match ip.segments() {
[0, 0, 0, 0, 0, 0, hi, lo] => Some(from(hi, lo)),
[0, 0, 0, 0, 0xffff, 0, hi, lo] => Some(from(hi, lo)),
[0x64, 0xff9b, 0, 0, 0, 0, hi, lo] => Some(from(hi, lo)),
[0x64, 0xff9b, 1, _, _, _, hi, lo] => Some(from(hi, lo)),
[0x2002, hi, lo, ..] => Some(from(hi, lo)),
[0x2001, 0, _, _, _, _, hi, lo] => Some(from(!hi, !lo)),
_ => None,
}
}
#[cfg(test)]
mod tests {
use super::{is_internal_address, names_loopback};
#[test]
fn localhost_and_the_loopback_addresses_name_the_loopback() {
for entry in [
"localhost",
"LOCALHOST.",
"127.0.0.1",
"127.1.2.3",
"::1",
"[::1]",
] {
assert!(names_loopback(entry), "{entry}");
}
for entry in ["example.com", "localhost.example.com", "10.0.0.1", "*", ""] {
assert!(!names_loopback(entry), "{entry}");
}
}
#[test]
fn every_spelling_of_this_machine_and_the_networks_behind_it_is_internal() {
for ip in [
"0.0.0.0",
"0.1.2.3",
"127.0.0.1",
"127.255.0.9",
"10.0.0.5",
"172.16.0.1",
"172.31.255.255",
"192.168.1.1",
"169.254.169.254",
"100.64.0.1",
"100.127.255.255",
"192.0.0.8",
"198.18.0.1",
"224.0.0.1",
"240.0.0.1",
"255.255.255.255",
"::",
"::1",
"::ffff:127.0.0.1",
"::ffff:10.0.0.1",
"::ffff:169.254.169.254",
"::127.0.0.1",
"64:ff9b::7f00:1",
"2002:7f00:1::",
"2002:c0a8:101::1",
"::ffff:0:7f00:1",
"::ffff:0:a00:1",
"64:ff9b:1::a9fe:a9fe",
"64:ff9b:1:2::808:808",
"2001:0:4136:e378:8000:63bf:80ff:fffe",
"2001:0:4136:e378:8000:63bf:f5ff:fffe",
"fc00::1",
"fd12:3456::1",
"fe80::1",
"febf::1",
"fec0::1",
"ff02::1",
] {
assert!(is_internal_address(ip.parse().expect("an address")), "{ip}");
}
}
#[test]
fn the_public_internet_is_not() {
for ip in [
"8.8.8.8",
"1.1.1.1",
"100.63.255.255",
"100.128.0.1",
"172.15.255.255",
"172.32.0.1",
"93.184.216.34",
"2001:4860:4860::8888",
"2606:4700::1111",
"::ffff:8.8.8.8",
"64:ff9b::808:808",
"2002:808:808::1",
"::ffff:0:808:808",
"2001:0:4136:e378:8000:63bf:f7f7:f7f7",
] {
assert!(
!is_internal_address(ip.parse().expect("an address")),
"{ip}"
);
}
}
}