use tr064::{Client, ClientBuilder, Fingerprint, Url};
use crate::config::Profile;
pub const DEFAULT_HOST: &str = "fritz.box";
pub const HTTPS_PORT: u16 = 49443;
pub const HTTP_PORT: u16 = 49000;
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error("{host} is not a valid host: {reason}")]
InvalidHost {
host: String,
reason: &'static str,
},
#[error("no certificate is trusted for {0}, run `fritz tls trust`")]
NotTrusted(Url),
#[error("{0} is not a SHA-256 fingerprint of 64 hex digits")]
InvalidFingerprint(String),
#[error("no user is set for {0}, pass --user or run `fritz config init --user <name>`")]
NoUsername(Url),
}
pub fn parse_host(host: &str) -> Result<Url, Error> {
let invalid = |reason| Error::InvalidHost {
host: host.to_owned(),
reason,
};
let url = if host.contains("://") {
let url = Url::parse(host).map_err(|_| invalid("not an address"))?;
if !matches!(url.scheme(), "http" | "https") {
return Err(invalid("the scheme is neither http nor https"));
}
url
} else {
let mut url =
Url::parse(&format!("https://{host}")).map_err(|_| invalid("not a host name"))?;
let port = url.port().unwrap_or(HTTPS_PORT);
let _ = url.set_port(Some(port));
url
};
if url.path() != "/" || url.query().is_some() || url.fragment().is_some() {
return Err(invalid("the address has a path"));
}
Ok(url)
}
#[derive(Debug, Default, Clone)]
pub struct Overrides {
pub host: Option<String>,
pub username: Option<String>,
pub fingerprint: Option<String>,
}
impl Overrides {
pub fn fingerprint(&self) -> Result<Option<Fingerprint>, Error> {
self.fingerprint
.as_deref()
.map(|f| {
f.parse()
.map_err(|_| Error::InvalidFingerprint(f.to_owned()))
})
.transpose()
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Target {
pub url: Url,
pub username: Option<String>,
pub fingerprint: Option<Fingerprint>,
}
impl Target {
pub fn resolve(profile: Option<&Profile>, overrides: &Overrides) -> Result<Self, Error> {
let host = overrides
.host
.as_deref()
.or(profile.map(|p| p.host.as_str()))
.unwrap_or(DEFAULT_HOST);
let url = parse_host(host)?;
let trusted = profile
.filter(|p| parse_host(&p.host).is_ok_and(|own| own == url))
.and_then(|p| p.fingerprint);
Ok(Self {
username: overrides
.username
.clone()
.or_else(|| profile.and_then(|p| p.username.clone())),
fingerprint: overrides.fingerprint()?.or(trusted),
url,
})
}
pub fn username(&self) -> Result<&str, Error> {
self.username
.as_deref()
.ok_or_else(|| Error::NoUsername(self.url.clone()))
}
pub fn account(&self) -> Result<String, Error> {
Ok(format!(
"{}@{}",
self.username()?,
self.url.host_str().unwrap_or_default()
))
}
#[must_use]
pub fn web(&self) -> Self {
let mut url = self.url.clone();
let port = match (url.scheme(), url.port()) {
("https", Some(HTTPS_PORT)) | ("http", Some(HTTP_PORT)) => None,
(_, port) => port,
};
let _ = url.set_port(port);
Self {
url,
..self.clone()
}
}
pub fn client(&self) -> Result<ClientBuilder, Error> {
let builder = Client::builder(self.url.clone());
match (self.url.scheme(), self.fingerprint) {
("https", Some(fingerprint)) => Ok(builder.pin(fingerprint)),
("https", None) => Err(Error::NotTrusted(self.url.clone())),
_ => Ok(builder),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn fingerprint(byte: u8) -> Fingerprint {
Fingerprint::of(&[byte])
}
#[test]
fn parses_hosts() {
for (host, url) in [
("fritz.box", "https://fritz.box:49443/"),
("192.168.178.1:8443", "https://192.168.178.1:8443/"),
("[fd00::1]", "https://[fd00::1]:49443/"),
("http://fritz.box:49000", "http://fritz.box:49000/"),
("https://fritz.box", "https://fritz.box/"),
] {
assert_eq!(parse_host(host).unwrap().as_str(), url, "{host}");
}
}
#[test]
fn rejects_invalid_hosts() {
for (host, reason) in [
("ftp://fritz.box", "the scheme is neither http nor https"),
("http://", "not an address"),
("fritz box", "not a host name"),
("fritz.box/path", "the address has a path"),
("https://fritz.box/?query", "the address has a path"),
("fritz.box#top", "the address has a path"),
] {
let error = parse_host(host).unwrap_err();
assert_eq!(
error.to_string(),
format!("{host} is not a valid host: {reason}")
);
}
}
#[test]
fn defaults_to_fritz_box() {
let target = Target::resolve(None, &Overrides::default()).unwrap();
assert_eq!(target.url.as_str(), "https://fritz.box:49443/");
assert_eq!(target.username, None);
assert_eq!(target.fingerprint, None);
assert_eq!(
target.username().unwrap_err().to_string(),
"no user is set for https://fritz.box:49443/, pass --user or run `fritz config init --user <name>`"
);
assert!(target.account().is_err());
assert_eq!(
target.client().unwrap_err().to_string(),
"no certificate is trusted for https://fritz.box:49443/, run `fritz tls trust`"
);
}
#[test]
fn takes_the_profile() {
let profile = Profile {
host: "192.168.178.1".to_owned(),
username: Some("agent".to_owned()),
fingerprint: Some(fingerprint(1)),
};
let target = Target::resolve(Some(&profile), &Overrides::default()).unwrap();
assert_eq!(target.url.as_str(), "https://192.168.178.1:49443/");
assert_eq!(target.account().unwrap(), "agent@192.168.178.1");
assert_eq!(target.fingerprint, Some(fingerprint(1)));
assert!(target.client().unwrap().build().is_ok());
let overrides = Overrides {
host: Some("https://192.168.178.1:49443".to_owned()),
..Overrides::default()
};
let target = Target::resolve(Some(&profile), &overrides).unwrap();
assert_eq!(target.fingerprint, Some(fingerprint(1)));
}
#[test]
fn prefers_the_overrides() {
let profile = Profile {
host: "192.168.178.1".to_owned(),
username: Some("agent".to_owned()),
fingerprint: Some(fingerprint(1)),
};
let overrides = Overrides {
host: Some("lab.example:8443".to_owned()),
username: Some("admin".to_owned()),
fingerprint: None,
};
let target = Target::resolve(Some(&profile), &overrides).unwrap();
assert_eq!(target.url.as_str(), "https://lab.example:8443/");
assert_eq!(target.account().unwrap(), "admin@lab.example");
assert_eq!(target.fingerprint, None);
let overrides = Overrides {
fingerprint: Some(fingerprint(2).to_string()),
..overrides
};
let target = Target::resolve(Some(&profile), &overrides).unwrap();
assert_eq!(target.fingerprint, Some(fingerprint(2)));
let overrides = Overrides {
fingerprint: Some("se://docker/mcp/fritz.fingerprint".to_owned()),
..overrides
};
assert_eq!(
Target::resolve(Some(&profile), &overrides)
.unwrap_err()
.to_string(),
"se://docker/mcp/fritz.fingerprint is not a SHA-256 fingerprint of 64 hex digits"
);
}
#[test]
fn ignores_the_certificate_for_http() {
let overrides = Overrides {
host: Some("http://127.0.0.1:49000".to_owned()),
fingerprint: Some(fingerprint(1).to_string()),
..Overrides::default()
};
let target = Target::resolve(None, &overrides).unwrap();
assert!(target.client().unwrap().build().is_ok());
}
#[test]
fn derives_the_web_interface() {
for (host, web) in [
("fritz.box", "https://fritz.box/"),
("http://fritz.box:49000", "http://fritz.box/"),
("fritz.box:8443", "https://fritz.box:8443/"),
("http://127.0.0.1:49443", "http://127.0.0.1:49443/"),
("https://fritz.box", "https://fritz.box/"),
] {
let overrides = Overrides {
host: Some(host.to_owned()),
username: Some("agent".to_owned()),
fingerprint: Some(fingerprint(1).to_string()),
};
let target = Target::resolve(None, &overrides).unwrap();
let expected = Target {
url: Url::parse(web).unwrap(),
..target.clone()
};
assert_eq!(target.web(), expected, "{host}");
}
}
#[test]
fn reports_an_invalid_profile_host() {
let profile = Profile {
host: "fritz box".to_owned(),
..Profile::default()
};
assert!(Target::resolve(Some(&profile), &Overrides::default()).is_err());
}
}