use std::fmt;
const MAX_NAME_CHARS: usize = 255;
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum NameKind {
Host,
NetbiosHost,
Domain,
NetbiosDomain,
Forest,
}
impl NameKind {
pub const ALL: &'static [Self] = &[
Self::Host,
Self::NetbiosHost,
Self::Domain,
Self::NetbiosDomain,
Self::Forest,
];
pub const fn label(self) -> &'static str {
match self {
Self::Host => "host",
Self::NetbiosHost => "NetBIOS host",
Self::Domain => "domain",
Self::NetbiosDomain => "NetBIOS domain",
Self::Forest => "forest",
}
}
}
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum NameSource {
Ntlm,
Ldap,
Kerberos,
Smb,
Netbios,
L2tp,
}
impl NameSource {
pub const ALL: &'static [Self] = &[
Self::Ntlm,
Self::Ldap,
Self::Kerberos,
Self::Smb,
Self::Netbios,
Self::L2tp,
];
pub const fn label(self) -> &'static str {
match self {
Self::Ntlm => "NTLM",
Self::Ldap => "LDAP",
Self::Kerberos => "Kerberos",
Self::Smb => "SMB",
Self::Netbios => "NetBIOS",
Self::L2tp => "L2TP",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct HostName {
kind: NameKind,
source: NameSource,
name: String,
}
impl HostName {
#[must_use]
pub fn new(kind: NameKind, source: NameSource, name: &str) -> Option<Self> {
let name = name.trim();
let valid = !name.is_empty()
&& name.chars().count() <= MAX_NAME_CHARS
&& !name.chars().any(char::is_control);
valid.then(|| Self {
kind,
source,
name: name.to_owned(),
})
}
pub fn kind(&self) -> NameKind {
self.kind
}
pub fn source(&self) -> NameSource {
self.source
}
pub fn name(&self) -> &str {
&self.name
}
}
impl fmt::Display for HostName {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"{} ({}, {})",
self.name,
self.kind.label(),
self.source.label()
)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_name_is_kept_as_the_host_stated_it() {
let name = HostName::new(NameKind::Domain, NameSource::Ntlm, " corp.example ")
.expect("an ordinary domain name");
assert_eq!(name.name(), "corp.example");
assert_eq!(name.to_string(), "corp.example (domain, NTLM)");
}
#[test]
fn a_field_that_names_nothing_is_refused() {
for refused in ["", " ", "dc01\ncorp", "dc01\0", &"a".repeat(256)] {
assert_eq!(
HostName::new(NameKind::Host, NameSource::Ldap, refused),
None,
"{refused:?}"
);
}
assert!(HostName::new(NameKind::Host, NameSource::Ldap, &"a".repeat(255)).is_some());
}
#[test]
fn names_order_by_what_they_name_before_who_said_them() {
let forest = HostName::new(NameKind::Forest, NameSource::Ntlm, "corp.example").unwrap();
let host = HostName::new(NameKind::Host, NameSource::Ldap, "dc01.corp.example").unwrap();
assert!(host < forest);
}
}