use std::fmt;
use std::net::Ipv6Addr;
use std::str::FromStr;
use crate::error::CliError;
use crate::url::LoopbackUrl;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Scheme {
Http,
Https,
}
impl Scheme {
pub fn as_str(self) -> &'static str {
match self {
Self::Http => "http",
Self::Https => "https",
}
}
fn default_port(self) -> u16 {
match self {
Self::Http => 80,
Self::Https => 443,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CanonicalOrigin {
scheme: Scheme,
host: String,
port: Option<u16>,
}
impl CanonicalOrigin {
pub fn scheme(&self) -> Scheme {
self.scheme
}
pub fn host(&self) -> &str {
&self.host
}
pub fn port(&self) -> u16 {
self.port.unwrap_or_else(|| self.scheme.default_port())
}
pub fn authority(&self) -> String {
match self.port {
Some(port) => format!("{}:{port}", self.host),
None => self.host.clone(),
}
}
pub fn as_str(&self) -> String {
format!("{}://{}", self.scheme.as_str(), self.authority())
}
pub fn url(&self, path: &str) -> String {
format!("{}{path}", self.as_str())
}
}
impl fmt::Display for CanonicalOrigin {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.as_str())
}
}
impl FromStr for CanonicalOrigin {
type Err = ParseOriginError;
fn from_str(text: &str) -> Result<Self, Self::Err> {
let (scheme, rest) = if let Some(rest) = text.strip_prefix("https://") {
(Scheme::Https, rest)
} else if let Some(rest) = text.strip_prefix("http://") {
(Scheme::Http, rest)
} else {
return Err(ParseOriginError::Scheme);
};
let authority = rest.strip_suffix('/').unwrap_or(rest);
if authority.contains(['/', '?', '#']) {
return Err(ParseOriginError::NotAnOrigin);
}
if authority.contains('@') {
return Err(ParseOriginError::UserInfo);
}
let (host, port_text) = if let Some(inner) = authority.strip_prefix('[') {
let (literal, after) = inner.split_once(']').ok_or(ParseOriginError::Host)?;
let canonical = literal
.parse::<Ipv6Addr>()
.is_ok_and(|addr| addr.to_string() == literal);
if !canonical {
return Err(ParseOriginError::Host);
}
let port = match after {
"" => None,
other => Some(other.strip_prefix(':').ok_or(ParseOriginError::Port)?),
};
(format!("[{literal}]"), port)
} else {
let (host, port) = match authority.split_once(':') {
Some((host, port)) => (host, Some(port)),
None => (authority, None),
};
if !is_dns_host(host) {
return Err(ParseOriginError::Host);
}
(host.to_owned(), port)
};
let port = match port_text {
None => None,
Some(digits) => {
let valid = !digits.is_empty()
&& digits.len() <= 5
&& digits.bytes().all(|b| b.is_ascii_digit())
&& !digits.starts_with('0');
let port = digits
.parse::<u16>()
.ok()
.filter(|_| valid)
.ok_or(ParseOriginError::Port)?;
if port == scheme.default_port() {
return Err(ParseOriginError::DefaultPort);
}
Some(port)
}
};
Ok(Self { scheme, host, port })
}
}
fn is_dns_host(host: &str) -> bool {
!host.is_empty()
&& host.len() <= 253
&& host.split('.').all(|label| {
!label.is_empty()
&& label.len() <= 63
&& !label.starts_with('-')
&& !label.ends_with('-')
&& label
.bytes()
.all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
})
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum ParseOriginError {
#[error("origin must start with https:// or http://")]
Scheme,
#[error("origin must have no path, query or fragment")]
NotAnOrigin,
#[error("origin must not contain user information")]
UserInfo,
#[error("origin host must be a lowercase name or address (ipv6 in brackets, rfc 5952 form)")]
Host,
#[error("origin port must be a number from 1 to 65535")]
Port,
#[error("origin must omit the scheme's default port")]
DefaultPort,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct GateTarget {
origin: CanonicalOrigin,
connect: LoopbackUrl,
}
impl GateTarget {
pub fn new(origin: CanonicalOrigin, connect: Option<ConnectAddress>) -> Result<Self, CliError> {
let connect = match connect {
Some(address) => address.0,
None => match origin.scheme() {
Scheme::Https => {
return Err(CliError::Usage(format!(
"{origin} is an https:// origin and this client has no TLS transport yet: \
the remote transport arrives with the public origin. Reach the gate on \
this machine with --connect <host:port>"
)))
}
Scheme::Http => format!("http://{}:{}", origin.host(), origin.port())
.parse::<LoopbackUrl>()
.map_err(|_| {
CliError::Usage(format!(
"{origin} is not a loopback address; pass --connect <host:port> with \
a loopback address to reach the gate"
))
})?,
},
};
Ok(Self { origin, connect })
}
pub fn origin(&self) -> &CanonicalOrigin {
&self.origin
}
pub fn connect(&self) -> &LoopbackUrl {
&self.connect
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ConnectAddress(LoopbackUrl);
impl ConnectAddress {
pub fn authority(&self) -> String {
self.0.authority()
}
}
impl fmt::Display for ConnectAddress {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0.authority())
}
}
impl FromStr for ConnectAddress {
type Err = ParseConnectError;
fn from_str(text: &str) -> Result<Self, Self::Err> {
if text.contains('/') {
return Err(ParseConnectError);
}
let url: LoopbackUrl = format!("http://{text}")
.parse()
.map_err(|_| ParseConnectError)?;
if url.authority() != text {
return Err(ParseConnectError);
}
Ok(Self(url))
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
#[error(
"connect address must be <host>:<port> with a host in 127.0.0.0/8 (such as 127.0.0.1), [::1] or localhost"
)]
#[non_exhaustive]
pub struct ParseConnectError;
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn origins_keep_one_spelling() {
for (text, canonical, authority) in [
("https://a.example", "https://a.example", "a.example"),
("https://a.example/", "https://a.example", "a.example"),
(
"https://a.example:8443",
"https://a.example:8443",
"a.example:8443",
),
(
"http://127.0.0.1:7461",
"http://127.0.0.1:7461",
"127.0.0.1:7461",
),
("https://[::1]:9", "https://[::1]:9", "[::1]:9"),
] {
let origin: CanonicalOrigin = text.parse().expect(text);
assert_eq!(origin.as_str(), canonical, "{text}");
assert_eq!(origin.authority(), authority, "{text}");
}
for bad in [
"ftp://a.example",
"https://A.example",
"https://a.example:443",
"http://a.example:80",
"https://a.example:0",
"https://a.example:08443",
"https://a.example/x",
"https://a.example?x",
"https://u@a.example",
"https://[0:0::1]",
"https://a..example",
"https://",
] {
assert!(bad.parse::<CanonicalOrigin>().is_err(), "{bad}");
}
}
#[test]
fn https_without_connect_is_refused_and_http_needs_loopback() {
let https: CanonicalOrigin = "https://a.example".parse().expect("origin");
let err = GateTarget::new(https, None).expect_err("refused");
assert!(
err.to_string()
.contains("remote transport arrives with the public origin"),
"{err}"
);
let far: CanonicalOrigin = "http://a.example:7461".parse().expect("origin");
assert!(GateTarget::new(far, None).is_err());
let near: CanonicalOrigin = "http://localhost:7461".parse().expect("origin");
let target = GateTarget::new(near, None).expect("loopback");
assert_eq!(target.connect().connect_host(), "127.0.0.1");
}
}