use std::fmt;
use crate::finding::Finding;
pub const HOST_CHECKS_ENV: &str = "ERGON_HOST_CHECKS";
pub const SILENCE: &str = "(ERGON_HOST_CHECKS=off silences host-check warnings)";
const SUBSYSTEM_CHECKS: [&str; 23] = [
"T3", "T4", "T5", "T6", "T11", "T13", "T14", "T15", "T16", "T17", "T18", "T19", "T20", "T21",
"T25", "K6", "K7", "N1", "N2", "N3", "N4", "N5", "M4",
];
#[must_use]
pub fn unknown_stops_require(id: &str) -> bool {
!SUBSYSTEM_CHECKS.contains(&id)
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Default)]
pub enum HostCheckPolicy {
Off,
#[default]
On,
Require,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum HostCheckError {
Invalid {
value: String,
},
Warnings {
count: usize,
ids: String,
},
}
impl fmt::Display for HostCheckError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Invalid { value } => write!(
f,
"{HOST_CHECKS_ENV}={value}: set {HOST_CHECKS_ENV} to off, on or require (off prints \
no host-check warning line; require refuses to start on a warning, or on a check \
that could not be proven)"
),
Self::Warnings { count, ids } => write!(
f,
"{HOST_CHECKS_ENV}=require and {count} host check(s) warned or could not be \
proven ({ids}), printed above: fix them, or set {HOST_CHECKS_ENV}=off to start \
anyway"
),
}
}
}
impl std::error::Error for HostCheckError {}
impl HostCheckPolicy {
pub fn parse(value: &str) -> Result<Self, HostCheckError> {
match value.trim().to_ascii_lowercase().as_str() {
"off" => Ok(Self::Off),
"on" | "warn" => Ok(Self::On),
"require" => Ok(Self::Require),
_ => Err(HostCheckError::Invalid {
value: value.to_owned(),
}),
}
}
pub fn from_var(value: Option<&str>) -> Result<Self, HostCheckError> {
value.map_or(Ok(Self::On), Self::parse)
}
pub fn from_env() -> Result<Self, HostCheckError> {
match std::env::var(HOST_CHECKS_ENV) {
Ok(v) => Self::from_var(Some(&v)),
Err(std::env::VarError::NotPresent) => Self::from_var(None),
Err(std::env::VarError::NotUnicode(_)) => Err(HostCheckError::Invalid {
value: "not valid Unicode".to_owned(),
}),
}
}
#[must_use]
pub fn warn_lines(&self, prefix: &str, findings: &[Finding]) -> Vec<String> {
if *self == Self::Off {
return Vec::new();
}
findings
.iter()
.filter_map(|f| warn_line(prefix, f))
.collect()
}
#[must_use]
pub fn lines(&self, prefix: &str, findings: &[Finding]) -> Vec<String> {
findings
.iter()
.filter(|f| *self != Self::Off || !f.is_warning())
.filter_map(|f| host_check_line(prefix, f))
.collect()
}
#[must_use]
pub fn refusal(&self, findings: &[Finding]) -> Option<HostCheckError> {
if *self != Self::Require {
return None;
}
let mut ids: Vec<&str> = Vec::new();
let mut count = 0;
for f in findings
.iter()
.filter(|f| f.is_warning() || (f.is_unknown() && unknown_stops_require(f.id)))
{
count += 1;
let id = f.id;
if !ids.contains(&id) {
ids.push(id);
}
}
if count == 0 {
None
} else {
Some(HostCheckError::Warnings {
count,
ids: ids.join(", "),
})
}
}
}
#[must_use]
pub fn warn_line(prefix: &str, f: &Finding) -> Option<String> {
if f.is_warning() {
Some(format!("{prefix} warning: {f} {SILENCE}"))
} else {
None
}
}
#[must_use]
pub fn host_check_line(prefix: &str, f: &Finding) -> Option<String> {
if f.is_warning() {
warn_line(prefix, f)
} else if f.is_unknown() || f.is_finding() {
Some(format!("{prefix} info: {f}"))
} else {
None
}
}