use crate::model::host::OsEvidence;
use crate::model::host::OsSource;
pub const CONFIDENCE: f32 = 0.35;
const DEFAULT_NAMES: &[(Pattern, &str)] = &[
(
generated("desktop-", Token::Random { min: 7, max: 7 }),
"Windows",
),
(
generated("laptop-", Token::Random { min: 7, max: 7 }),
"Windows",
),
(
generated("win-", Token::Random { min: 8, max: 15 }),
"Windows",
),
(model("windows-phone"), "Windows"),
(model("macbook-pro"), "macOS"),
(model("macbook-air"), "macOS"),
(model("macbook"), "macOS"),
(model("imac-pro"), "macOS"),
(model("imac"), "macOS"),
(model("mac-studio"), "macOS"),
(model("mac-mini"), "macOS"),
(model("mac-pro"), "macOS"),
(model("iphone"), "iOS"),
(model("ipad"), "iPadOS"),
(model("appletv"), "tvOS"),
(model("apple-tv"), "tvOS"),
(model("homepod"), "audioOS"),
(model("apple-watch"), "watchOS"),
(model("applewatch"), "watchOS"),
(generated("android-", Token::Hex { len: 16 }), "Linux"),
(generated("android_", Token::Hex { len: 16 }), "Linux"),
(model("googlecast"), "Linux"),
(model("google-home"), "Linux"),
(model("nest-hub"), "Linux"),
(model("nest-mini"), "Linux"),
(model("firetv"), "Linux"),
(model("raspberrypi"), "Linux"),
(model("beaglebone"), "Linux"),
(model("tegra-ubuntu"), "Linux"),
(model("jetson"), "Linux"),
(model("steamdeck"), "Linux"),
(generated("sonos-", Token::Hex { len: 12 }), "Linux"),
(model("lgwebostv"), "webOS"),
(model("webostv"), "webOS"),
(model("samsung-tizen"), "Tizen"),
(model("openwrt"), "Linux"),
(model("dd-wrt"), "Linux"),
(model("pfsense"), "FreeBSD"),
(model("opnsense"), "FreeBSD"),
(model("truenas"), "FreeBSD"),
(model("freenas"), "FreeBSD"),
(model("freebsd"), "FreeBSD"),
(model("openbsd"), "OpenBSD"),
(model("netbsd"), "NetBSD"),
];
#[cfg(test)]
const WITHDRAWN: &[&str] = &[
"sm-",
"galaxy-",
"amazon-",
"echo-",
"roku",
"roku-",
"chromebook-",
"chromeos-",
];
#[derive(Debug, Clone, Copy)]
enum Token {
Random { min: usize, max: usize },
Hex { len: usize },
}
impl Token {
fn matches(self, tail: &str) -> bool {
match self {
Token::Random { min, max } => {
(min..=max).contains(&tail.len())
&& tail.bytes().all(|b| b.is_ascii_alphanumeric())
&& tail.bytes().any(|b| b.is_ascii_digit())
}
Token::Hex { len } => tail.len() == len && tail.bytes().all(|b| b.is_ascii_hexdigit()),
}
}
}
#[derive(Debug, Clone, Copy)]
enum Pattern {
Model(&'static str),
Generated(&'static str, Token),
}
const fn model(text: &'static str) -> Pattern {
Pattern::Model(text)
}
const fn generated(text: &'static str, token: Token) -> Pattern {
Pattern::Generated(text, token)
}
impl Pattern {
fn matches(self, hostname: &str) -> bool {
match self {
Pattern::Model(text) => match hostname.strip_prefix(text) {
Some("") | Some("-") => true,
Some(rest) => match rest.strip_prefix('-') {
Some(digits) => {
!digits.is_empty()
&& digits.len() <= 2
&& digits.bytes().all(|b| b.is_ascii_digit())
}
None => false,
},
None => false,
},
Pattern::Generated(text, token) => hostname
.strip_prefix(text)
.is_some_and(|tail| token.matches(tail)),
}
}
}
pub fn evidence_from(hostname: Option<&str>) -> Option<OsEvidence> {
let hostname = hostname?;
let trimmed = hostname.strip_suffix(".local").unwrap_or(hostname);
let trimmed = trimmed.strip_suffix('.').unwrap_or(trimmed);
let lowered = trimmed.to_ascii_lowercase();
let (_, family) = DEFAULT_NAMES
.iter()
.find(|(pattern, _)| pattern.matches(&lowered))?;
Some(OsEvidence {
source: OsSource::Hostname,
family: Some((*family).to_string()),
device: None,
vendor: None,
product: None,
version: None,
kernel: None,
arch: None,
cpe: None,
confidence: CONFIDENCE,
evidence: format!("hostname {hostname}"),
})
}
#[cfg(test)]
mod tests {
use super::*;
fn family_of(hostname: Option<&str>) -> Option<String> {
evidence_from(hostname).and_then(|evidence| evidence.family)
}
#[test]
fn a_windows_default_name_says_windows() {
assert_eq!(
family_of(Some("DESKTOP-FKV0V2O")),
Some("Windows".to_string())
);
assert_eq!(
family_of(Some("desktop-0000000")),
Some("Windows".to_string())
);
}
#[test]
fn an_apple_device_name_names_its_platform() {
let cases = [
("MacBook-Pro", "macOS"),
("MacBook-Pro.local", "macOS"),
("MacBook-Air-3", "macOS"),
("Mac-mini", "macOS"),
("Mac-Pro", "macOS"),
("IMac", "macOS"),
("iPhone-2", "iOS"),
("IPad", "iPadOS"),
("AppleTV-6", "tvOS"),
];
for (name, family) in cases {
assert_eq!(family_of(Some(name)), Some(family.to_string()), "{name}");
}
}
#[test]
fn a_persons_own_name_says_nothing() {
for name in [
"web01",
"linux-server",
"mail",
"NAS",
"eriks-macbook",
"macbook-of-erik",
"macbook-12345678",
"the-ipad",
] {
assert_eq!(family_of(Some(name)), None, "{name}");
}
}
#[test]
fn a_hostname_alone_never_reaches_the_reporting_floor() {
let evidence = evidence_from(Some("DESKTOP-FKV0V2O")).expect("a default name matches");
assert!(
(evidence.confidence * 100.0)
< f32::from(super::super::verdict::MIN_REPORTABLE_ACCURACY),
"a lone hostname must stay below the floor that reports anything"
);
}
#[test]
fn additional_oem_defaults_resolve_correctly() {
let cases = [
("LAPTOP-G384HJ2", "Windows"),
("WIN-89KLP0M9", "Windows"),
("MacBook-Air", "macOS"),
("Mac-Studio-1", "macOS"),
("HomePod-2", "audioOS"),
("Apple-Watch-3", "watchOS"),
("steamdeck", "Linux"),
("openwrt.local", "Linux"),
("pfsense", "FreeBSD"),
("opnsense.local", "FreeBSD"),
("lgwebostv", "webOS"),
("lgwebostv-2", "webOS"),
];
for (name, family) in cases {
assert_eq!(
family_of(Some(name)),
Some(family.to_string()),
"failed on {name}"
);
}
}
#[test]
fn a_name_a_person_typed_does_not_wear_a_generated_prefix() {
for name in [
"desktop-erik",
"desktop-manager",
"laptop-of-erik",
"win-file-server",
"sm-prod-db01",
"echo-service",
"amazon-connector",
"rokuro-pc",
"jetsonville-nas",
"galaxy-cluster-01",
"android-build-agent",
"sonos-living-room",
] {
assert_eq!(family_of(Some(name)), None, "`{name}` is somebody's name");
}
}
#[test]
fn a_generated_tail_is_still_recognised() {
let cases = [
("DESKTOP-FKV0V2O", "Windows"),
("LAPTOP-G384HJ2", "Windows"),
("WIN-K3JD8FH2LQ0", "Windows"),
("android-a1b2c3d4e5f60718", "Linux"),
("Sonos-949F3EC5D2E0", "Linux"),
];
for (name, family) in cases {
assert_eq!(family_of(Some(name)), Some(family.to_string()), "{name}");
}
}
#[test]
fn a_withdrawn_convention_matches_nothing() {
for prefix in WITHDRAWN {
for tail in ["", "-01", "server", "a1b2c3d", "0123456789abcdef"] {
let name = format!("{prefix}{tail}");
assert_eq!(
family_of(Some(&name)),
None,
"`{name}` is back in the table"
);
}
}
}
#[test]
fn a_mistaken_hostname_would_have_cost_a_correct_reading() {
use crate::model::host::OsSource;
let stack = crate::model::host::OsEvidence {
source: OsSource::TcpStack,
family: Some("Linux".to_string()),
device: None,
vendor: None,
product: None,
version: None,
kernel: None,
arch: None,
cpe: None,
confidence: 0.65,
evidence: "a stack reading".to_string(),
};
let alone = super::super::resolve(vec![stack.clone()]).expect("names the host");
assert_eq!(alone.accuracy, 65);
let mistaken = crate::model::host::OsEvidence {
source: OsSource::Hostname,
family: Some("Windows".to_string()),
confidence: CONFIDENCE,
evidence: "hostname suggests Windows".to_string(),
..stack.clone()
};
let contested = super::super::resolve(vec![stack, mistaken]).expect("still resolves");
assert!(
contested.accuracy < alone.accuracy - 20,
"a dissenting vote costs the leader real accuracy: {} against {}",
contested.accuracy,
alone.accuracy
);
assert_eq!(family_of(Some("desktop-erik")), None);
}
}