#![allow(clippy::doc_markdown)]
mod filter;
use alloc::string::String;
use alloc::vec::Vec;
use std::time::Duration;
pub use rawether::{RingConfig, RxMode as Receive, RxPath, TxErrors as LaunchErrors};
use crate::common::{Error, Instant, MacAddr, Result, monotonic_now};
pub const ETHERTYPE_GOOSE: u16 = 0x88B8;
pub const ETHERTYPE_SV: u16 = 0x88BA;
pub const GOOSE_MULTICAST_PREFIX: [u8; 4] = [0x01, 0x0C, 0xCD, 0x01];
pub const SV_MULTICAST_PREFIX: [u8; 4] = [0x01, 0x0C, 0xCD, 0x04];
pub const DEFAULT_PRIORITY: u32 = 4;
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct LinkOptions {
ethertypes: Vec<u16>,
join: Vec<MacAddr>,
prefixes: Vec<[u8; 4]>,
promiscuous: bool,
priority: Option<u32>,
launch_time: bool,
hardware_timestamps: bool,
receive: Receive,
}
impl LinkOptions {
fn with(ethertypes: &[u16], prefixes: &[[u8; 4]]) -> LinkOptions {
LinkOptions {
ethertypes: ethertypes.to_vec(),
join: Vec::new(),
prefixes: prefixes.to_vec(),
promiscuous: false,
priority: Some(DEFAULT_PRIORITY),
launch_time: false,
hardware_timestamps: false,
receive: Receive::Auto,
}
}
pub fn goose() -> LinkOptions {
LinkOptions::with(&[ETHERTYPE_GOOSE], &[GOOSE_MULTICAST_PREFIX])
}
pub fn sv() -> LinkOptions {
LinkOptions::with(&[ETHERTYPE_SV], &[SV_MULTICAST_PREFIX])
}
pub fn process_bus() -> LinkOptions {
LinkOptions::with(&[ETHERTYPE_GOOSE, ETHERTYPE_SV], &[GOOSE_MULTICAST_PREFIX, SV_MULTICAST_PREFIX])
}
#[must_use]
pub fn join(mut self, group: MacAddr) -> LinkOptions {
if !self.join.contains(&group) {
self.join.push(group);
}
self
}
#[must_use]
pub fn promiscuous(mut self, on: bool) -> LinkOptions {
self.promiscuous = on;
self
}
#[must_use]
pub fn priority(mut self, priority: Option<u32>) -> LinkOptions {
self.priority = priority;
self
}
#[must_use]
pub fn launch_time(mut self, on: bool) -> LinkOptions {
self.launch_time = on;
self
}
#[must_use]
pub fn hardware_timestamps(mut self, on: bool) -> LinkOptions {
self.hardware_timestamps = on;
self
}
#[must_use]
pub fn receive(mut self, receive: Receive) -> LinkOptions {
self.receive = receive;
self
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct WireTime {
pub secs: i64,
pub nanos: u32,
pub hardware: bool,
}
#[derive(Debug)]
pub struct Received<'a> {
pub frame: &'a [u8],
pub at: Instant,
pub wire_time: Option<WireTime>,
pub truncated: bool,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct LinkStats {
pub received: u64,
pub dropped: u64,
}
#[derive(Debug)]
pub struct Link {
sock: rawether::Socket,
mac: MacAddr,
tai_offset: Option<i128>,
}
fn io(e: &std::io::Error) -> Error {
Error::Io(alloc::format!("{e}"))
}
impl Link {
pub fn open(iface: &str, options: &LinkOptions) -> Result<Link> {
let destinations = if options.join.is_empty() {
filter::Destinations::Prefixes(options.prefixes.clone())
} else {
filter::Destinations::Exactly(options.join.clone())
};
let program = filter::program(&options.ethertypes, &destinations)?;
let mut cfg = rawether::Config::new(iface)
.filter(rawether::Filter::Bpf(program))
.rx_mode(options.receive)
.promiscuous(options.promiscuous)
.timestamping(if options.hardware_timestamps { rawether::Timestamping::Hardware } else { rawether::Timestamping::Software });
if options.join.is_empty() {
cfg = cfg.all_multicast(true);
}
for g in &options.join {
cfg = cfg.join(rawether::MacAddr(g.0));
}
if let Some(p) = options.priority {
cfg = cfg.priority(p);
}
if options.launch_time {
cfg = cfg.tx_time(rawether::TxTime { clock: rawether::Clock::Tai, deadline: false, report_errors: true });
}
let sock = cfg.open().map_err(|e| io(&e))?;
let mac = MacAddr(sock.mac_address().0);
let tai_offset = if options.launch_time {
let tai = rawether::clock_now(rawether::Clock::Tai).map_err(|e| io(&e))?;
let mono = monotonic_now();
Some(tai.as_nanos() as i128 - i128::from(mono.0))
} else {
None
};
Ok(Link { sock, mac, tai_offset })
}
pub fn from_env(var: &str, options: &LinkOptions) -> Result<Option<Link>> {
match std::env::var(var) {
Ok(iface) if !iface.is_empty() => Link::open(&iface, options).map(Some),
_ => Ok(None),
}
}
pub fn mac(&self) -> MacAddr {
self.mac
}
pub fn interface(&self) -> &str {
self.sock.interface()
}
pub fn receive_path(&self) -> RxPath {
self.sock.rx_path()
}
pub fn send(&self, frame: &[u8]) -> Result<()> {
self.sock.send(frame).map_err(|e| io(&e))
}
pub fn send_at(&self, frame: &[u8], due: Instant) -> Result<()> {
let offset = self.tai_offset.ok_or_else(|| Error::Io(String::from("send_at needs LinkOptions::launch_time")))?;
let tai = (i128::from(due.0) + offset).max(0) as u64;
self.sock.send_at(frame, tai).map_err(|e| io(&e))
}
pub fn send_batch(&mut self, frames: &[&[u8]]) -> Result<usize> {
self.sock.send_batch(frames).map_err(|e| io(&e))
}
pub fn recv(&mut self, timeout: Option<Duration>) -> Result<Option<Received<'_>>> {
let Some(p) = self.sock.recv(timeout).map_err(|e| io(&e))? else { return Ok(None) };
let at = monotonic_now();
let wire_time = p.timestamp().map(|t| WireTime { secs: t.secs, nanos: t.nanos, hardware: t.source == rawether::TimestampSource::Hardware });
Ok(Some(Received { frame: p.data(), at, wire_time, truncated: p.is_truncated() }))
}
pub fn stats(&mut self) -> Result<LinkStats> {
let s = self.sock.stats().map_err(|e| io(&e))?;
Ok(LinkStats { received: s.received, dropped: s.dropped })
}
pub fn launch_errors(&mut self) -> Result<LaunchErrors> {
self.sock.tx_errors().map_err(|e| io(&e))
}
}
#[cfg(unix)]
impl std::os::fd::AsFd for Link {
fn as_fd(&self) -> std::os::fd::BorrowedFd<'_> {
self.sock.as_fd()
}
}
pub fn drop_capabilities() -> Result<()> {
rawether::drop_capabilities().map_err(|e| io(&e))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_presets_are_not_promiscuous() {
for o in [LinkOptions::goose(), LinkOptions::sv(), LinkOptions::process_bus()] {
assert!(!o.promiscuous && o.join.is_empty() && !o.prefixes.is_empty(), "{o:?}");
}
assert!(LinkOptions::goose().promiscuous(true).promiscuous);
assert_eq!(LinkOptions::goose().prefixes, [GOOSE_MULTICAST_PREFIX]);
assert_eq!(LinkOptions::sv().prefixes, [SV_MULTICAST_PREFIX]);
}
}