#![deny(unsafe_op_in_unsafe_fn)]
pub mod bpf;
#[cfg(any(target_os = "macos", target_os = "freebsd", test, fuzzing))]
mod bpf_record;
mod config;
pub mod frame;
#[cfg(any(target_os = "linux", test))]
mod hwtstamp;
mod packet;
#[cfg(any(target_os = "linux", test, fuzzing))]
mod ring;
mod sys;
pub mod threat_model;
#[cfg(any(target_os = "linux", test, fuzzing))]
mod vlan;
use std::io;
use std::time::Duration;
pub use config::{Clock, Config, Filter, RingConfig, RxMode, Timestamping, TxTime};
pub use frame::{Frame, FrameBuilder, TagKind, VlanTag};
pub use packet::{MacAddr, Packet, RxPath, Stats, Timestamp, TimestampSource, TxErrors};
#[derive(Debug)]
pub struct Socket {
inner: sys::Inner,
}
impl Socket {
pub fn open(config: &Config) -> io::Result<Socket> {
config.validate()?;
let program = config.program()?;
Ok(Socket { inner: sys::Inner::open(config, program.as_ref())? })
}
pub fn interface(&self) -> &str {
self.inner.interface()
}
pub fn index(&self) -> u32 {
self.inner.index()
}
pub fn mac_address(&self) -> MacAddr {
self.inner.mac()
}
pub fn rx_path(&self) -> RxPath {
self.inner.rx_path()
}
pub fn recv(&mut self, timeout: Option<Duration>) -> io::Result<Option<Packet<'_>>> {
self.inner.recv(timeout)
}
pub fn try_recv(&mut self) -> io::Result<Option<Packet<'_>>> {
self.inner.recv(Some(Duration::ZERO))
}
pub fn send(&self, frame: &[u8]) -> io::Result<()> {
check_frame(frame)?;
self.inner.send(frame)
}
pub fn send_at(&self, frame: &[u8], launch_ns: u64) -> io::Result<()> {
check_frame(frame)?;
self.inner.send_at(frame, launch_ns)
}
pub fn send_batch(&mut self, frames: &[&[u8]]) -> io::Result<usize> {
for f in frames {
check_frame(f)?;
}
self.inner.send_batch(frames)
}
pub fn stats(&mut self) -> io::Result<Stats> {
self.inner.stats()
}
pub fn tx_errors(&mut self) -> io::Result<TxErrors> {
self.inner.tx_errors()
}
pub fn timestamping(&self) -> Timestamping {
self.inner.timestamping()
}
pub fn set_nonblocking(&mut self, on: bool) -> io::Result<()> {
self.inner.set_nonblocking(on)
}
}
#[cfg(unix)]
impl std::os::fd::AsFd for Socket {
fn as_fd(&self) -> std::os::fd::BorrowedFd<'_> {
self.inner.as_fd()
}
}
#[cfg(unix)]
impl std::os::fd::AsRawFd for Socket {
fn as_raw_fd(&self) -> std::os::fd::RawFd {
self.inner.as_fd().as_raw_fd()
}
}
pub fn drop_capabilities() -> io::Result<()> {
sys::drop_capabilities()
}
pub fn clock_now(clock: Clock) -> io::Result<Duration> {
sys::clock_now(clock)
}
fn check_frame(frame: &[u8]) -> io::Result<()> {
if frame.len() < 14 {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
format!("a frame of {} octets has no Ethernet header", frame.len()),
));
}
Ok(())
}
#[cfg(fuzzing)]
#[doc(hidden)]
pub mod fuzzing {
pub fn ring_walk(block: &mut [u8]) {
let Some(mut cur) = crate::ring::Cursor::start(block) else { return };
let mut found = Vec::new();
while let Some((at, meta)) = cur.next(block) {
assert!(at + meta.mac + meta.snaplen <= block.len());
found.push((at + meta.mac, meta.snaplen, meta.stripped_vlan()));
}
for (start, len, tag) in found {
if let (Some((tpid, tci)), Some(lo)) = (tag, start.checked_sub(4))
&& let Some(region) = block.get_mut(lo..start + len)
{
let _ = crate::vlan::reinsert(region, 4, len, tpid, tci);
}
}
}
pub fn bpf_records(buf: &[u8]) {
for layout in [crate::bpf_record::Layout::MACOS, crate::bpf_record::Layout::FREEBSD_LP64] {
let mut pos = 0;
while let Some(r) = crate::bpf_record::next(buf, &mut pos, layout) {
assert!(r.start + r.caplen <= buf.len());
}
}
}
pub fn vlan_reinsert(buf: &mut [u8], start: usize, len: usize, tpid: u16, tci: u16) {
let before = buf.to_vec();
match crate::vlan::reinsert(buf, start, len, tpid, tci) {
Some((s, l)) => assert!(s + l <= buf.len()),
None => assert_eq!(buf, &before[..], "a refused re-insertion leaves the buffer alone"),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
#[cfg_attr(miri, ignore)] fn opening_a_missing_interface_or_on_an_unsupported_platform_fails_cleanly() {
let e = Socket::open(&Config::new("no-such-if0")).expect_err("no interface");
assert!(
matches!(
e.kind(),
io::ErrorKind::NotFound | io::ErrorKind::PermissionDenied | io::ErrorKind::Unsupported
),
"{e:?}"
);
}
#[cfg(target_os = "macos")]
#[test]
#[cfg_attr(miri, ignore)] fn the_loopback_interface_opens_or_says_what_access_is_missing() {
match Socket::open(&Config::new("lo0")) {
Ok(s) => assert_eq!(s.rx_path(), RxPath::Bpf),
Err(e) => {
assert_eq!(e.kind(), io::ErrorKind::PermissionDenied, "{e}");
assert!(e.to_string().contains("/dev/bpf"), "{e}");
}
}
}
#[test]
fn the_default_configuration_is_neither_promiscuous_nor_all_multicast() {
let c = Config::new("eth0");
assert!(!c.promiscuous && !c.all_multicast);
}
#[test]
fn a_frame_without_a_header_is_refused_before_any_system_call() {
assert_eq!(check_frame(&[0; 13]).expect_err("short").kind(), io::ErrorKind::InvalidInput);
assert!(check_frame(&[0; 14]).is_ok());
}
}