use std::collections::HashMap;
use std::net::IpAddr;
#[derive(Debug, Default)]
pub(crate) struct HostsTable {
by_name: HashMap<String, Vec<IpAddr>>,
by_address: HashMap<IpAddr, String>,
}
#[derive(Debug, PartialEq, Eq)]
pub(crate) struct HostsAnswer {
pub(crate) addresses: Vec<IpAddr>,
pub(crate) shadowed: Vec<IpAddr>,
}
impl HostsTable {
pub(crate) fn read_system() -> Self {
match std::fs::read_to_string(hosts_path()) {
Ok(text) => Self::parse(&text),
Err(e) => {
crate::info!(verbosity = 1, "hosts file not read ({e})");
Self::default()
}
}
}
pub(crate) fn parse(text: &str) -> Self {
let mut table = Self::default();
for line in text.lines() {
let line = line.split_once('#').map_or(line, |(kept, _)| kept);
let mut fields = line.split_whitespace().peekable();
let Some(Ok(address)) = fields.next().map(str::parse::<IpAddr>) else {
continue;
};
if let Some(canonical) = fields.peek() {
table
.by_address
.entry(address)
.or_insert_with(|| canonical.trim_end_matches('.').to_owned());
}
for name in fields {
let listed = table.by_name.entry(fold(name)).or_default();
if !listed.contains(&address) {
listed.push(address);
}
}
}
table
}
pub(crate) fn lookup(&self, name: &str) -> Option<HostsAnswer> {
let listed = self.by_name.get(&fold(name))?;
let mut answer = HostsAnswer {
addresses: Vec::new(),
shadowed: Vec::new(),
};
for &address in listed {
let answered = answer
.addresses
.iter()
.any(|kept| kept.is_ipv4() == address.is_ipv4());
if answered {
answer.shadowed.push(address);
} else {
answer.addresses.push(address);
}
}
Some(answer)
}
pub(crate) fn name_of(&self, address: IpAddr) -> Option<&str> {
self.by_address.get(&address).map(String::as_str)
}
}
fn fold(name: &str) -> String {
name.trim_end_matches('.').to_ascii_lowercase()
}
#[cfg(unix)]
fn hosts_path() -> std::path::PathBuf {
std::path::PathBuf::from("/etc/hosts")
}
#[cfg(windows)]
fn hosts_path() -> std::path::PathBuf {
let root = std::env::var_os("SystemRoot").unwrap_or_else(|| "C:\\Windows".into());
std::path::Path::new(&root).join("System32\\drivers\\etc\\hosts")
}
#[cfg(test)]
mod tests {
use super::*;
fn ip(s: &str) -> IpAddr {
s.parse().expect("a test address parses")
}
#[test]
fn every_name_on_a_line_answers_in_any_case() {
let table = HostsTable::parse(
"# a comment line\n\
198.51.100.7\tforest.corp.local corp.local # the lab's domain controller\n\
\n\
not-an-address ignored.example\n\
fe80::1%lo0 zoned.example\n",
);
for name in ["forest.corp.local", "CORP.LOCAL", "corp.local."] {
assert_eq!(
table.lookup(name).map(|a| a.addresses),
Some(vec![ip("198.51.100.7")]),
"{name}"
);
}
assert_eq!(table.lookup("ignored.example"), None);
assert_eq!(table.lookup("zoned.example"), None);
assert_eq!(table.lookup("a.comment"), None);
}
#[test]
fn a_later_line_for_a_name_is_shadowed_by_the_first_in_its_family() {
let table = HostsTable::parse(
"198.51.100.23 box.example\n\
2001:db8::23 box.example\n\
198.51.100.99 box.example\n\
198.51.100.23 box.example\n",
);
assert_eq!(
table.lookup("box.example"),
Some(HostsAnswer {
addresses: vec![ip("198.51.100.23"), ip("2001:db8::23")],
shadowed: vec![ip("198.51.100.99")],
}),
"one address per family, and the repeat of the first is no conflict"
);
}
#[test]
fn an_address_is_named_by_the_first_line_listing_it() {
let table = HostsTable::parse(
"198.51.100.23 old-box.example old-box\n\
198.51.100.23 new-box.example\n\
2001:db8::23 Box6.Example.\n",
);
assert_eq!(table.name_of(ip("198.51.100.23")), Some("old-box.example"));
assert_eq!(table.name_of(ip("2001:db8::23")), Some("Box6.Example"));
assert_eq!(table.name_of(ip("198.51.100.24")), None);
}
}