use std::io;
use crate::Socket;
use crate::bpf::Program;
use crate::packet::MacAddr;
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub enum Filter {
#[default]
All,
EtherTypes(Vec<u16>),
Bpf(Program),
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct RingConfig {
pub block_size: u32,
pub block_count: u32,
pub frame_size: u32,
pub retire_ms: u32,
}
impl Default for RingConfig {
fn default() -> RingConfig {
RingConfig { block_size: 1 << 16, block_count: 64, frame_size: 2048, retire_ms: 1 }
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum RxMode {
#[default]
Auto,
Ring(RingConfig),
Plain,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Timestamping {
Off,
#[default]
Software,
Hardware,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Clock {
Tai,
Monotonic,
Realtime,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct TxTime {
pub clock: Clock,
pub deadline: bool,
pub report_errors: bool,
}
impl Default for TxTime {
fn default() -> TxTime {
TxTime { clock: Clock::Tai, deadline: false, report_errors: true }
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[allow(clippy::struct_excessive_bools)] pub struct Config {
pub(crate) interface: String,
pub(crate) filter: Filter,
pub(crate) multicast: Vec<MacAddr>,
pub(crate) all_multicast: bool,
pub(crate) promiscuous: bool,
pub(crate) rx: RxMode,
pub(crate) timestamping: Timestamping,
pub(crate) priority: Option<u32>,
pub(crate) tx_time: Option<TxTime>,
pub(crate) qdisc_bypass: bool,
pub(crate) nonblocking: bool,
pub(crate) restore_vlan: bool,
pub(crate) see_outgoing: bool,
pub(crate) buffer_size: usize,
}
impl Config {
pub fn new(interface: impl Into<String>) -> Config {
Config {
interface: interface.into(),
filter: Filter::All,
multicast: Vec::new(),
all_multicast: false,
promiscuous: false,
rx: RxMode::Auto,
timestamping: Timestamping::Software,
priority: None,
tx_time: None,
qdisc_bypass: false,
nonblocking: false,
restore_vlan: true,
see_outgoing: false,
buffer_size: 1 << 20,
}
}
#[must_use]
pub fn ethertypes(mut self, types: &[u16]) -> Config {
self.filter = Filter::EtherTypes(types.to_vec());
self
}
#[must_use]
pub fn filter(mut self, filter: Filter) -> Config {
self.filter = filter;
self
}
#[must_use]
pub fn join(mut self, group: MacAddr) -> Config {
if !self.multicast.contains(&group) {
self.multicast.push(group);
}
self
}
#[must_use]
pub fn all_multicast(mut self, on: bool) -> Config {
self.all_multicast = on;
self
}
#[must_use]
pub fn promiscuous(mut self, on: bool) -> Config {
self.promiscuous = on;
self
}
#[must_use]
pub fn rx_mode(mut self, mode: RxMode) -> Config {
self.rx = mode;
self
}
#[must_use]
pub fn timestamping(mut self, t: Timestamping) -> Config {
self.timestamping = t;
self
}
#[must_use]
pub fn priority(mut self, priority: u32) -> Config {
self.priority = Some(priority);
self
}
#[must_use]
pub fn tx_time(mut self, t: TxTime) -> Config {
self.tx_time = Some(t);
self
}
#[must_use]
pub fn qdisc_bypass(mut self, on: bool) -> Config {
self.qdisc_bypass = on;
self
}
#[must_use]
pub fn nonblocking(mut self, on: bool) -> Config {
self.nonblocking = on;
self
}
#[must_use]
pub fn restore_vlan(mut self, on: bool) -> Config {
self.restore_vlan = on;
self
}
#[must_use]
pub fn see_outgoing(mut self, on: bool) -> Config {
self.see_outgoing = on;
self
}
#[must_use]
pub fn buffer_size(mut self, octets: usize) -> Config {
self.buffer_size = octets.max(4096);
self
}
pub fn interface(&self) -> &str {
&self.interface
}
pub fn open(&self) -> io::Result<Socket> {
Socket::open(self)
}
pub(crate) fn program(&self) -> io::Result<Option<Program>> {
match &self.filter {
Filter::All => Ok(None),
Filter::EtherTypes(types) => Program::ethertypes(types).map(Some),
Filter::Bpf(p) => Ok(Some(p.clone())),
}
}
pub(crate) fn validate(&self) -> io::Result<()> {
if self.interface.is_empty() || self.interface.len() >= 16 || self.interface.contains('\0') {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
format!("{:?} is not an interface name (1 to 15 octets, no NUL)", self.interface),
));
}
if let Some(m) = self.multicast.iter().find(|m| !m.is_multicast()) {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
format!("{m} is not a multicast address"),
));
}
if let RxMode::Ring(r) = self.rx
&& (r.block_count == 0
|| !r.block_size.is_power_of_two()
|| r.frame_size < 128
|| r.frame_size > r.block_size
|| (r.block_size / r.frame_size).checked_mul(r.block_count).is_none()
|| (r.block_size as usize).checked_mul(r.block_count as usize).is_none())
{
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
format!("ring geometry {r:?} is not usable"),
));
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_configuration_is_checked_before_any_system_call() {
assert!(Config::new("").validate().is_err());
assert!(Config::new("a-name-that-is-too-long").validate().is_err());
assert!(Config::new("eth0").join(MacAddr([0, 1, 2, 3, 4, 5])).validate().is_err(), "unicast group");
assert!(Config::new("eth0").join(MacAddr([1, 0x80, 0xc2, 0, 0, 0xe])).validate().is_ok());
let ring = RingConfig { block_size: 1000, ..RingConfig::default() };
assert!(Config::new("eth0").rx_mode(RxMode::Ring(ring)).validate().is_err());
let huge = RingConfig { block_size: 1 << 31, frame_size: 128, block_count: u32::MAX, retire_ms: 1 };
assert!(Config::new("eth0").rx_mode(RxMode::Ring(huge)).validate().is_err());
let none = RingConfig { block_count: 0, ..RingConfig::default() };
assert!(Config::new("eth0").rx_mode(RxMode::Ring(none)).validate().is_err());
assert!(Config::new("eth0").ethertypes(&[]).program().is_err());
assert!(Config::new("eth0").ethertypes(&[0x88cc]).program().expect("program").is_some());
}
#[test]
fn joining_a_group_twice_joins_it_once() {
let g = MacAddr([1, 0x80, 0xc2, 0, 0, 0xe]);
assert_eq!(Config::new("eth0").join(g).join(g).multicast, vec![g]);
}
}