use std::net::Ipv4Addr;
use crate::finding::{Finding, Severity};
const T24_EVIDENCE: &str = "the NIC device plugin's env contract \
(RUSTERON_DPDK_{SENDER,RECEIVER}_{PCI,IPV4_CIDR,GATEWAY}); not measured here";
const SENDER: [&str; 3] = [
"RUSTERON_DPDK_SENDER_PCI",
"RUSTERON_DPDK_SENDER_IPV4_CIDR",
"RUSTERON_DPDK_SENDER_GATEWAY",
];
const PCI_BAD: &str = "is not a PCI address dddd:bb:dd.d or a DPDK device name";
const CIDR_BAD: &str = "is not an IPv4 cidr a.b.c.d/len with a prefix of 0 to 32";
const GATEWAY_BAD: &str = "is not an IPv4 address";
#[must_use]
pub fn t24_dpdk_nic_pair(on_dpdk: bool, env: impl Fn(&str) -> Option<String>) -> Finding {
let id = "T24";
let sev = Severity::Warn;
if !on_dpdk {
return Finding::ok(
id,
sev,
T24_EVIDENCE,
"this process is not on a DPDK port, so the NIC pair does not apply here".to_owned(),
);
}
let pair = match DpdkNicPair::from_env(env) {
Ok(Some(pair)) => pair,
Ok(None) => {
return Finding::ok(
id,
sev,
T24_EVIDENCE,
format!(
"{} are unset: the device plugin has not granted a pair, so nothing here \
guesses an address, a gateway or a PCI device",
SENDER.join(", ")
),
);
}
Err(problems) => {
return Finding::found(
id,
sev,
T24_EVIDENCE,
format!(
"the NIC pair is not usable: {problems}. Effect: no copy line can be built \
from it. Fix: set every empty key and correct every bad one from the pair \
the device plugin granted; this check copies nothing, binds no NIC and \
sets no AERON_DIR"
),
);
}
};
Finding::found(
id,
Severity::Info,
T24_EVIDENCE,
format!(
"the NIC pair is set; the two shortest lines built from it (copied, not guessed): \
{}; {}. This check copies nothing, binds no NIC and sets no AERON_DIR",
pair.addr_gateway_line(),
pair.port_ip_eal_line()
),
)
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DpdkNicPair {
pub pci: String,
pub addr: Ipv4Addr,
pub prefix_len: u8,
pub gateway: Ipv4Addr,
}
impl DpdkNicPair {
pub const ENV: [&'static str; 3] = SENDER;
pub fn from_env(env: impl Fn(&str) -> Option<String>) -> Result<Option<Self>, String> {
let raw: [Option<String>; 3] = SENDER.map(|name| env(name).map(|v| v.trim().to_owned()));
if raw.iter().all(Option::is_none) {
return Ok(None);
}
let mut problems: Vec<String> = Vec::new();
for (i, name) in SENDER.iter().enumerate() {
match raw[i].as_deref() {
None | Some("") => problems.push(format!("{name} is still empty")),
Some(value) => {
let why = match i {
0 => pci_why(value),
1 => cidr_why(value),
_ => address_why(value),
};
if let Some(why) = why {
problems.push(format!("{name}={value} {why}"));
}
}
}
}
if !problems.is_empty() {
return Err(problems.join("; "));
}
let [Some(pci), Some(cidr), Some(gateway)] = raw else {
return Err("the NIC pair is incomplete".to_owned());
};
let (addr, prefix) = cidr.split_once('/').unwrap_or((cidr.as_str(), ""));
match (addr.parse(), prefix.parse(), gateway.parse()) {
(Ok(addr), Ok(prefix_len), Ok(gateway)) => Ok(Some(Self {
pci,
addr,
prefix_len,
gateway,
})),
_ => Err(format!("{} {CIDR_BAD}", SENDER[1])),
}
}
#[must_use]
pub fn is_pci_address(&self) -> bool {
self.pci.contains(':')
}
#[must_use]
pub fn eal_args(&self) -> [String; 2] {
if self.is_pci_address() {
["-a".to_owned(), self.pci.clone()]
} else {
["--vdev".to_owned(), self.pci.clone()]
}
}
#[must_use]
pub fn addr_gateway_line(&self) -> String {
let prefix = if self.prefix_len == 24 {
String::new()
} else {
format!(",prefix_len={}", self.prefix_len)
};
format!(
"addr={},gateway={},port={}{prefix}",
self.addr, self.gateway, self.pci
)
}
#[must_use]
pub fn port_ip_eal_line(&self) -> String {
format!(
"port={},ip={}/{},eal={}",
self.pci,
self.addr,
self.prefix_len,
self.eal_args().join(" ")
)
}
}
fn pci_why(value: &str) -> Option<&'static str> {
if value.split_whitespace().count() != 1 || value.contains(',') || value.contains('=') {
return Some(PCI_BAD);
}
if !value.contains(':') {
return None;
}
let fields: Vec<&str> = value.split([':', '.']).collect();
let bdf = match fields.as_slice() {
[domain, bus, dev, func] => {
is_hex(domain, 1, 4) && is_hex(bus, 2, 2) && is_hex(dev, 2, 2) && is_func(func)
}
[bus, dev, func] => is_hex(bus, 2, 2) && is_hex(dev, 2, 2) && is_func(func),
_ => false,
};
if bdf { None } else { Some(PCI_BAD) }
}
fn cidr_why(value: &str) -> Option<&'static str> {
let Some((addr, prefix)) = value.split_once('/') else {
return Some(CIDR_BAD);
};
if addr.parse::<Ipv4Addr>().is_err() {
return Some(CIDR_BAD);
}
match prefix.parse::<u8>() {
Ok(len) if len <= 32 => None,
_ => Some(CIDR_BAD),
}
}
fn address_why(value: &str) -> Option<&'static str> {
if value.parse::<Ipv4Addr>().is_ok() {
None
} else {
Some(GATEWAY_BAD)
}
}
fn is_hex(field: &str, min: usize, max: usize) -> bool {
field.len() >= min && field.len() <= max && field.chars().all(|c| c.is_ascii_hexdigit())
}
fn is_func(field: &str) -> bool {
field.len() == 1 && field.chars().all(|c| c.is_ascii_hexdigit()) && field <= "7"
}