use crate::model::mac::{self, MacAddr};
use std::{collections::BTreeMap, sync::Arc, time::SystemTime};
pub const MAX_MACS_PER_HOST: usize = 64;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HardwareInfo {
macs: BTreeMap<MacAddr, SystemTime>,
vendor: Option<Arc<str>>,
product: Option<Arc<str>>,
family: Option<Arc<str>>,
cpe23: Option<Arc<str>>,
model: Option<Arc<str>>,
version: Option<Arc<str>>,
serial_number: Option<Arc<str>>,
}
#[derive(Debug, Clone, Copy, Default)]
pub struct HardwareDescription<'a> {
pub vendor: Option<&'a str>,
pub product: Option<&'a str>,
pub family: Option<&'a str>,
pub cpe23: Option<&'a str>,
pub model: Option<&'a str>,
pub version: Option<&'a str>,
pub serial_number: Option<&'a str>,
}
impl HardwareInfo {
pub fn new(mac: MacAddr) -> Self {
let mut macs = BTreeMap::new();
macs.insert(mac, SystemTime::now());
Self {
macs,
vendor: mac::vendor(&mac).map(Arc::from),
product: None,
family: None,
cpe23: None,
model: None,
version: None,
serial_number: None,
}
}
pub fn described(described: HardwareDescription<'_>) -> Option<Self> {
let built = Self {
macs: BTreeMap::new(),
vendor: described.vendor.map(Arc::from),
product: described.product.map(Arc::from),
family: described.family.map(Arc::from),
cpe23: described.cpe23.map(Arc::from),
model: described.model.map(Arc::from),
version: described.version.map(Arc::from),
serial_number: described.serial_number.map(Arc::from),
};
built.names_something().then_some(built)
}
fn names_something(&self) -> bool {
self.vendor.is_some()
|| self.product.is_some()
|| self.family.is_some()
|| self.cpe23.is_some()
|| self.model.is_some()
|| self.version.is_some()
|| self.serial_number.is_some()
}
pub fn product(&self) -> Option<&str> {
self.product.as_deref()
}
pub fn family(&self) -> Option<&str> {
self.family.as_deref()
}
pub fn cpe23(&self) -> Option<&str> {
self.cpe23.as_deref()
}
pub fn model(&self) -> Option<&str> {
self.model.as_deref()
}
pub fn hardware_version(&self) -> Option<&str> {
self.version.as_deref()
}
pub fn serial_number(&self) -> Option<&str> {
self.serial_number.as_deref()
}
pub fn add_mac(&mut self, mac: MacAddr) {
self.record_mac_seen_at(mac, SystemTime::now());
}
pub fn record_mac_seen_at(&mut self, mac: MacAddr, at: SystemTime) {
let is_new = self.macs.insert(mac, at).is_none();
if is_new {
self.evict_oldest_past_the_bound();
if self.vendor.is_none() {
self.vendor = mac::vendor(&mac).map(Arc::from);
}
}
}
fn evict_oldest_past_the_bound(&mut self) {
while self.macs.len() > MAX_MACS_PER_HOST {
let Some(oldest) = self
.macs
.iter()
.min_by_key(|(mac, seen)| (*seen, *mac))
.map(|(mac, _)| *mac)
else {
return;
};
self.macs.remove(&oldest);
}
}
pub fn vendor(&self) -> Option<&str> {
self.vendor.as_deref()
}
pub(crate) fn registered_vendor(&self) -> Option<String> {
let mut newest_first: Vec<(&MacAddr, &SystemTime)> = self.macs.iter().collect();
newest_first.sort_by(|a, b| b.1.cmp(a.1));
newest_first
.into_iter()
.find_map(|(address, _)| mac::vendor(address))
}
#[inline]
pub fn macs(&self) -> &BTreeMap<MacAddr, SystemTime> {
&self.macs
}
pub fn most_recent_mac(&self) -> Option<MacAddr> {
self.macs
.iter()
.max_by_key(|&(_, time)| time)
.map(|(mac, _)| *mac)
}
pub fn prune_stale_macs(&mut self, cutoff: SystemTime) {
self.macs.retain(|_, last_seen| *last_seen >= cutoff);
}
pub fn merge(&mut self, other: HardwareInfo) {
let describes_a_box = other.names_more_than_a_vendor();
for (mac, time) in other.macs {
self.macs
.entry(mac)
.and_modify(|t| {
if time > *t {
*t = time;
}
})
.or_insert(time);
}
self.evict_oldest_past_the_bound();
if self.vendor.is_none() || (other.vendor.is_some() && describes_a_box) {
self.vendor = other.vendor.or_else(|| self.vendor.take());
}
self.product = self.product.take().or(other.product);
self.family = self.family.take().or(other.family);
self.cpe23 = self.cpe23.take().or(other.cpe23);
self.model = self.model.take().or(other.model);
self.version = self.version.take().or(other.version);
self.serial_number = self.serial_number.take().or(other.serial_number);
}
fn names_more_than_a_vendor(&self) -> bool {
self.product.is_some()
|| self.family.is_some()
|| self.cpe23.is_some()
|| self.model.is_some()
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::time::Duration;
#[test]
fn a_sighting_records_the_address_and_resolves_its_vendor() {
let mac = MacAddr::new(0x00, 0x0C, 0x29, 0xAB, 0xCD, 0xEF);
let hw = HardwareInfo::new(mac);
assert!(hw.vendor().is_some(), "a registered OUI");
assert!(hw.macs().contains_key(&mac));
}
#[test]
fn the_most_recent_sighting_is_the_newest_one_not_the_last_inserted() {
let newest = MacAddr::new(0x02, 0, 0, 0, 0, 0x01);
let older = MacAddr::new(0x02, 0xff, 0, 0, 0, 0xff);
let mut hw = HardwareInfo::new(older);
hw.macs
.insert(newest, SystemTime::now() + Duration::from_secs(60));
assert_eq!(hw.most_recent_mac(), Some(newest));
}
#[test]
fn a_flood_of_addresses_is_held_to_the_bound_and_keeps_the_newest() {
let start = SystemTime::now();
let mut hw = HardwareInfo::new(MacAddr::new(0x02, 0, 0, 0, 0, 0));
let sightings = u32::try_from(MAX_MACS_PER_HOST).expect("a small bound") * 4;
for i in 0..sightings {
let b = i.to_be_bytes();
hw.record_mac_seen_at(
MacAddr::new(0x02, b[0], b[1], b[2], b[3], 0xff),
start + Duration::from_secs(u64::from(i) + 1),
);
}
assert_eq!(hw.macs().len(), MAX_MACS_PER_HOST);
let last = sightings - 1;
let b = last.to_be_bytes();
let newest = MacAddr::new(0x02, b[0], b[1], b[2], b[3], 0xff);
assert_eq!(hw.most_recent_mac(), Some(newest), "the newest survives");
assert!(
!hw.macs().contains_key(&MacAddr::new(0x02, 0, 0, 0, 0, 0)),
"and the first sighting is what made room"
);
}
#[test]
fn merging_two_records_holds_their_union_to_the_bound() {
let start = SystemTime::now();
let fill = |first: u8| {
let mut hw = HardwareInfo::new(MacAddr::new(0x02, first, 0, 0, 0, 0));
for i in 0..u8::try_from(MAX_MACS_PER_HOST).expect("a small bound") {
hw.record_mac_seen_at(
MacAddr::new(0x02, first, 0, 0, 0, i),
start + Duration::from_secs(u64::from(i) + 1),
);
}
hw
};
let mut a = fill(0xaa);
let b = fill(0xbb);
assert_eq!(a.macs().len(), MAX_MACS_PER_HOST);
assert_eq!(b.macs().len(), MAX_MACS_PER_HOST);
a.merge(b);
assert_eq!(a.macs().len(), MAX_MACS_PER_HOST);
}
#[test]
fn a_record_with_no_addresses_left_names_none() {
let hw = HardwareInfo {
macs: BTreeMap::new(),
vendor: None,
product: None,
family: None,
cpe23: None,
model: None,
version: None,
serial_number: None,
};
assert_eq!(hw.most_recent_mac(), None);
}
#[test]
fn pruning_forgets_the_addresses_not_seen_since_the_cutoff() {
let recent = MacAddr::new(1, 1, 1, 1, 1, 1);
let stale = MacAddr::new(2, 2, 2, 2, 2, 2);
let mut hw = HardwareInfo::new(recent);
hw.macs
.insert(stale, SystemTime::now() - Duration::from_secs(3600));
hw.prune_stale_macs(SystemTime::now() - Duration::from_secs(1800));
assert_eq!(hw.macs().len(), 1);
assert!(hw.macs().contains_key(&recent));
}
#[test]
fn hardware_a_service_described_needs_no_address() {
let described = HardwareInfo::described(HardwareDescription {
vendor: Some("Merit LILIN"),
product: Some("PDR M800"),
cpe23: Some("cpe:/h:merit_lilin:pdr_m800"),
..HardwareDescription::default()
})
.expect("it names something");
assert_eq!(described.vendor(), Some("Merit LILIN"));
assert_eq!(described.product(), Some("PDR M800"));
assert_eq!(described.most_recent_mac(), None);
}
#[test]
fn a_description_naming_nothing_is_not_recorded() {
assert!(HardwareInfo::described(HardwareDescription::default()).is_none());
}
#[test]
fn a_stated_vendor_outranks_one_read_from_an_address() {
let mut known = HardwareInfo::new(MacAddr::new(0x00, 0x1b, 0x21, 0x11, 0x22, 0x33));
let described = HardwareInfo::described(HardwareDescription {
vendor: Some("Check Point"),
product: Some("Firewall-1"),
..HardwareDescription::default()
})
.expect("it names something");
known.merge(described);
assert_eq!(known.vendor(), Some("Check Point"));
assert_eq!(known.product(), Some("Firewall-1"));
assert_eq!(
known.macs().len(),
1,
"merging a description must not lose the address"
);
}
#[test]
fn a_bare_stated_vendor_does_not_displace_the_registered_one() {
let mut known = HardwareInfo::new(MacAddr::new(0x00, 0x1b, 0x21, 0x11, 0x22, 0x33));
let before = known.vendor().map(str::to_string);
let thin = HardwareInfo::described(HardwareDescription {
vendor: Some("Unhelpful"),
..HardwareDescription::default()
})
.expect("it names something");
known.merge(thin);
assert_eq!(known.vendor().map(str::to_string), before);
}
}