use std::{collections::BTreeSet, fs::read_to_string, io::ErrorKind, path::Path};
use anyhow::{Context as _, Result, bail};
use serde::Deserialize;
use toml::{Table, Value};
pub(crate) const HOST_OPTIONS: &[&str] = &[
"server_port",
"private_key_path",
"public_key_path",
"max_reconnect_backoff_secs",
"predict",
"nat_warmup",
"nat_warmup_count",
"min_protocol_version",
"ssh",
"ssh_command",
"mps_command",
"diff_mode",
"transport",
"legacy_passthrough",
"probe_terminal_colors",
"preferred_algorithms",
"send_env",
"send_path",
"escape_key",
];
#[derive(Clone, Debug, Default, PartialEq)]
pub(crate) struct HostSettings {
pub(crate) overlay: Table,
pub(crate) hostname: Option<String>,
pub(crate) user: Option<String>,
pub(crate) matched: Vec<String>,
}
impl HostSettings {
pub(crate) fn keys(&self) -> BTreeSet<String> {
let mut keys = BTreeSet::new();
for (key, value) in &self.overlay {
let _ = keys.insert(key.clone());
if let Value::Table(sub) = value {
for sub_key in sub.keys() {
let _ = keys.insert(format!("{key}.{sub_key}"));
}
}
}
for (key, set) in [("hostname", &self.hostname), ("user", &self.user)] {
if set.is_some() {
let _ = keys.insert(key.to_string());
}
}
keys
}
}
#[derive(Deserialize)]
#[serde(untagged)]
enum Patterns {
One(String),
Many(Vec<String>),
}
impl Patterns {
fn into_list(self) -> Vec<String> {
let parts = match self {
Patterns::One(s) => vec![s],
Patterns::Many(v) => v,
};
parts
.iter()
.flat_map(|s| s.split(|c: char| c.is_whitespace() || c == ','))
.filter(|p| !p.is_empty())
.map(str::to_owned)
.collect()
}
}
#[derive(Deserialize)]
struct Block {
#[serde(rename = "match")]
patterns: Patterns,
hostname: Option<String>,
user: Option<String>,
#[serde(flatten)]
options: Table,
}
#[derive(Deserialize)]
struct HostsFile {
#[serde(default)]
hosts: Vec<Block>,
}
pub(crate) fn host_settings_from_file(path: &Path, host: &str) -> Result<HostSettings> {
let text = match read_to_string(path) {
Ok(text) => text,
Err(e) if e.kind() == ErrorKind::NotFound => return Ok(HostSettings::default()),
Err(e) => return Err(e).with_context(|| format!("reading {}", path.display())),
};
host_settings(&text, host).with_context(|| format!("in {}", path.display()))
}
pub(crate) fn host_settings(toml_text: &str, host: &str) -> Result<HostSettings> {
let file: HostsFile = toml::from_str(toml_text).context("invalid [[hosts]] block")?;
let mut settings = HostSettings::default();
for (index, block) in file.hosts.into_iter().enumerate() {
let number = index + 1;
let patterns = block.patterns.into_list();
if patterns.is_empty() {
bail!("[[hosts]] block {number} has an empty `match`");
}
let spec = patterns.join(" ");
if let Some(key) = block
.options
.keys()
.find(|key| !HOST_OPTIONS.contains(&key.as_str()))
{
bail!(
"[[hosts]] block {number} (match = \"{spec}\"): unknown option '{key}'; \
a host block can set hostname, user, {}",
HOST_OPTIONS.join(", ")
);
}
if !matches_host(&patterns, host) {
continue;
}
settings.matched.push(spec);
if settings.hostname.is_none() {
settings.hostname = block.hostname;
}
if settings.user.is_none() {
settings.user = block.user;
}
for (key, value) in block.options {
let _ = settings.overlay.entry(key).or_insert(value);
}
}
Ok(settings)
}
fn matches_host(patterns: &[String], host: &str) -> bool {
let host = host.to_ascii_lowercase();
let mut matched = false;
for pattern in patterns {
let pattern = pattern.to_ascii_lowercase();
if let Some(negated) = pattern.strip_prefix('!') {
if glob_match(negated, &host) {
return false;
}
} else if glob_match(&pattern, &host) {
matched = true;
}
}
matched
}
fn glob_match(pattern: &str, text: &str) -> bool {
let pattern: Vec<char> = pattern.chars().collect();
let text: Vec<char> = text.chars().collect();
let (mut p, mut t) = (0, 0);
let mut star: Option<(usize, usize)> = None;
while t < text.len() {
if p < pattern.len() && (pattern[p] == '?' || pattern[p] == text[t]) {
p += 1;
t += 1;
} else if p < pattern.len() && pattern[p] == '*' {
star = Some((p, t));
p += 1;
} else if let Some((star_p, star_t)) = star {
p = star_p + 1;
t = star_t + 1;
star = Some((star_p, star_t + 1));
} else {
return false;
}
}
pattern[p..].iter().all(|&c| c == '*')
}
pub(crate) fn destination_host(destination: &str) -> &str {
let host_part = destination
.split_once('@')
.map_or(destination, |(_, host)| host);
if let Some(rest) = host_part.strip_prefix('[') {
return rest.split_once(']').map_or(rest, |(host, _)| host);
}
match host_part.split_once(':') {
Some((host, port)) if !port.contains(':') => host,
_ => host_part,
}
}
pub(crate) fn apply_host_aliases(
destination: &str,
hostname: Option<&str>,
user: Option<&str>,
) -> String {
let (typed_user, host_part) = destination
.split_once('@')
.map_or((None, destination), |(user, host)| (Some(user), host));
let host_part = match hostname {
Some(hostname) => {
let port = port_suffix(host_part);
if hostname.contains(':') && !hostname.starts_with('[') {
format!("[{hostname}]{port}")
} else {
format!("{hostname}{port}")
}
}
None => host_part.to_string(),
};
match typed_user.or(user) {
Some(user) => format!("{user}@{host_part}"),
None => host_part,
}
}
fn port_suffix(host_part: &str) -> &str {
if host_part.starts_with('[') {
return host_part.split_once(']').map_or("", |(_, rest)| rest);
}
match host_part.find(':') {
Some(i) if host_part.matches(':').count() == 1 => &host_part[i..],
_ => "",
}
}
#[cfg(test)]
mod tests {
use toml::Value;
use super::{
HOST_OPTIONS, HostSettings, apply_host_aliases, destination_host, glob_match,
host_settings, matches_host,
};
const SAMPLE: &str = r#"
server_port = 40404
transport = "udp"
[[hosts]]
match = "box"
hostname = "box.internal.example.com"
user = "me"
transport = "tcp"
[[hosts]]
match = ["*.example.com", "!secret.example.com"]
escape_key = "ctrl-a"
transport = "udp"
[[hosts]]
match = "*"
escape_key = "ctrl-]"
server_port = 40500
[hosts.preferred_algorithms]
kex = ["ml-kem-768-sha256"]
"#;
#[test]
fn globs() {
assert!(glob_match("*", ""));
assert!(glob_match("*", "anything"));
assert!(glob_match("box", "box"));
assert!(!glob_match("box", "box2"));
assert!(glob_match("box?", "box2"));
assert!(!glob_match("box?", "box"));
assert!(glob_match("*.example.com", "a.b.example.com"));
assert!(!glob_match("*.example.com", "example.com"));
assert!(glob_match("10.0.*.?", "10.0.0.3"));
assert!(glob_match("a*b*c", "aXXbYYc"));
assert!(!glob_match("a*b*c", "aXXbYY"));
}
#[test]
fn negation_and_case() {
let patterns = vec![
"*.Example.com".to_string(),
"!secret.example.com".to_string(),
];
assert!(matches_host(&patterns, "web.EXAMPLE.com"));
assert!(!matches_host(&patterns, "secret.example.com"));
assert!(!matches_host(&["!foo".to_string()], "bar"));
}
#[test]
fn first_block_to_set_an_option_wins() -> anyhow::Result<()> {
let s = host_settings(SAMPLE, "box")?;
assert_eq!(s.matched, vec!["box", "*"]);
assert_eq!(s.hostname.as_deref(), Some("box.internal.example.com"));
assert_eq!(s.user.as_deref(), Some("me"));
assert_eq!(s.overlay.get("transport"), Some(&Value::from("tcp")));
assert_eq!(s.overlay.get("escape_key"), Some(&Value::from("ctrl-]")));
assert_eq!(s.overlay.get("server_port"), Some(&Value::from(40500)));
assert!(s.keys().contains("preferred_algorithms.kex"));
assert!(s.keys().contains("hostname"));
Ok(())
}
#[test]
fn later_blocks_fill_in_and_excluded_hosts_skip() -> anyhow::Result<()> {
let web = host_settings(SAMPLE, "web.example.com")?;
assert_eq!(web.matched, vec!["*.example.com !secret.example.com", "*"]);
assert_eq!(web.overlay.get("escape_key"), Some(&Value::from("ctrl-a")));
assert_eq!(web.hostname, None);
let secret = host_settings(SAMPLE, "secret.example.com")?;
assert_eq!(secret.matched, vec!["*"]);
assert_eq!(
secret.overlay.get("escape_key"),
Some(&Value::from("ctrl-]"))
);
Ok(())
}
#[test]
fn no_blocks_or_no_match_is_empty() -> anyhow::Result<()> {
assert_eq!(
host_settings("server_port = 1\n", "box")?,
HostSettings::default()
);
let s = host_settings("[[hosts]]\nmatch = \"a b,c\"\ntransport = \"tcp\"\n", "d")?;
assert!(s.matched.is_empty() && s.overlay.is_empty());
let s = host_settings("[[hosts]]\nmatch = \"a b,c\"\ntransport = \"tcp\"\n", "c")?;
assert_eq!(s.matched, vec!["a b c"]);
Ok(())
}
#[test]
fn unknown_options_and_empty_match_are_errors() {
let typo = "[[hosts]]\nmatch = \"other\"\ntransprot = \"tcp\"\n";
let err = format!("{:#}", host_settings(typo, "box").unwrap_err());
assert!(err.contains("unknown option 'transprot'"), "{err}");
assert!(err.contains("match = \"other\""), "{err}");
let tracing = "[[hosts]]\nmatch = \"box\"\n[hosts.tracing]\n";
assert!(host_settings(tracing, "box").is_err());
let empty = "[[hosts]]\nmatch = \" , \"\n";
let err = format!("{:#}", host_settings(empty, "box").unwrap_err());
assert!(err.contains("empty `match`"), "{err}");
let no_match = "[[hosts]]\ntransport = \"tcp\"\n";
assert!(host_settings(no_match, "box").is_err());
}
#[test]
fn every_host_option_is_a_config_field() -> anyhow::Result<()> {
use crate::config::Config;
let defaults = toml::to_string(&Config::default())?;
let defaults: toml::Table = toml::from_str(&defaults)?;
for option in HOST_OPTIONS {
let optional = [
"private_key_path",
"public_key_path",
"min_protocol_version",
]
.contains(option);
assert!(
defaults.contains_key(*option) || optional,
"{option} is not a Config field"
);
}
Ok(())
}
#[test]
fn destination_hosts() {
assert_eq!(destination_host("box"), "box");
assert_eq!(destination_host("me@box"), "box");
assert_eq!(destination_host("me@box:2222"), "box");
assert_eq!(destination_host("[::1]:40404"), "::1");
assert_eq!(destination_host("me@[fe80::1]"), "fe80::1");
assert_eq!(destination_host("10.0.0.3:40405"), "10.0.0.3");
}
#[test]
fn aliases() {
let h = Some("box.internal");
assert_eq!(apply_host_aliases("box", h, Some("me")), "me@box.internal");
assert_eq!(
apply_host_aliases("you@box", h, Some("me")),
"you@box.internal"
);
assert_eq!(apply_host_aliases("box:2222", h, None), "box.internal:2222");
assert_eq!(apply_host_aliases("[::1]:9", h, None), "box.internal:9");
assert_eq!(
apply_host_aliases("box", Some("fe80::1"), None),
"[fe80::1]"
);
assert_eq!(
apply_host_aliases("box:7", Some("fe80::1"), None),
"[fe80::1]:7"
);
assert_eq!(apply_host_aliases("me@box:1", None, None), "me@box:1");
assert_eq!(apply_host_aliases("box", None, Some("me")), "me@box");
}
}