use std::fmt;
use std::net::Ipv4Addr;
use std::str::FromStr;
const NAMED_LOOPBACK_HOSTS: [&str; 2] = ["[::1]", "localhost"];
const DEFAULT_HTTP_PORT: u16 = 80;
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct LoopbackUrl {
host: String,
port: u16,
path: String,
}
impl LoopbackUrl {
pub fn host(&self) -> &str {
&self.host
}
pub fn connect_host(&self) -> &str {
if self.host == "localhost" {
"127.0.0.1"
} else {
&self.host
}
}
pub fn port(&self) -> u16 {
self.port
}
pub fn authority(&self) -> String {
format!("{}:{}", self.host, self.port)
}
pub fn path(&self) -> &str {
&self.path
}
pub fn is_origin(&self) -> bool {
self.path.is_empty()
}
pub fn join(&self, path: &str) -> String {
format!("http://{}{path}", self.authority())
}
pub fn to_url_string(&self) -> String {
self.join(&self.path)
}
}
impl fmt::Display for LoopbackUrl {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.to_url_string())
}
}
impl FromStr for LoopbackUrl {
type Err = ParseUrlError;
fn from_str(text: &str) -> Result<Self, Self::Err> {
let rest = text.strip_prefix("http://").ok_or(ParseUrlError::NotHttp)?;
let (authority, path) = match rest.find('/') {
Some(index) => rest.split_at(index),
None => (rest, ""),
};
if authority.contains('@') {
return Err(ParseUrlError::UserInfo);
}
let (host_text, port_text) = split_host_port(authority)?;
if !is_loopback_host(host_text) {
return Err(ParseUrlError::NotLoopback);
}
let port = match port_text {
None => DEFAULT_HTTP_PORT,
Some(digits) => parse_port(digits)?,
};
if !path
.bytes()
.all(|b| b.is_ascii_graphic() && !matches!(b, b'?' | b'#' | b'%'))
{
return Err(ParseUrlError::InvalidPath);
}
let path = if path == "/" { "" } else { path };
Ok(Self {
host: host_text.to_owned(),
port,
path: path.to_owned(),
})
}
}
fn is_loopback_host(text: &str) -> bool {
if NAMED_LOOPBACK_HOSTS.contains(&text) {
return true;
}
text.parse::<Ipv4Addr>()
.is_ok_and(|ip| ip.is_loopback() && ip.to_string() == text)
}
fn split_host_port(authority: &str) -> Result<(&str, Option<&str>), ParseUrlError> {
if authority.starts_with('[') {
let end = authority.find(']').ok_or(ParseUrlError::NotLoopback)?;
let (host, after) = authority.split_at(end + 1);
return match after {
"" => Ok((host, None)),
_ => after
.strip_prefix(':')
.map(|port| (host, Some(port)))
.ok_or(ParseUrlError::InvalidPort),
};
}
Ok(match authority.split_once(':') {
Some((host, port)) => (host, Some(port)),
None => (authority, None),
})
}
fn parse_port(digits: &str) -> Result<u16, ParseUrlError> {
if digits.is_empty() || digits.len() > 5 || !digits.bytes().all(|b| b.is_ascii_digit()) {
return Err(ParseUrlError::InvalidPort);
}
match digits.parse::<u16>() {
Ok(0) | Err(_) => Err(ParseUrlError::InvalidPort),
Ok(port) => Ok(port),
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum ParseUrlError {
#[error("url must start with http:// (the loopback api has no tls)")]
NotHttp,
#[error("url host must be an address in 127.0.0.0/8 (such as 127.0.0.1), [::1] or localhost")]
NotLoopback,
#[error("url port must be a number from 1 to 65535")]
InvalidPort,
#[error("url must not contain user information")]
UserInfo,
#[error("url path must be printable ascii without query, fragment or percent-encoding")]
InvalidPath,
}