#![allow(clippy::unused_self, clippy::unnecessary_wraps)]
use std::ffi::CStr;
use std::io;
use std::mem::{size_of, zeroed};
use std::os::fd::{AsFd, AsRawFd, BorrowedFd, FromRawFd, OwnedFd};
use std::time::{Duration, Instant};
use super::deadline;
use super::unix::{Ready, ifr_name, interface_index, last_error, set_nonblocking, wait};
use crate::bpf::Program;
use crate::bpf_record::{self, Layout};
use crate::config::{Clock, Config, Timestamping};
use crate::packet::{MacAddr, Packet, RxPath, Stats, Timestamp, TimestampSource, TxErrors};
const SIOCADDMULTI: libc::c_ulong = 0x8000_0000
| (((size_of::<libc::ifreq>() as libc::c_ulong) & 0x1fff) << 16)
| ((b'i' as libc::c_ulong) << 8)
| 0x31; #[cfg(target_os = "freebsd")]
const BIOCSDIRECTION: libc::c_ulong = 0x8004_4277;
#[cfg(target_os = "freebsd")]
const BPF_D_IN: libc::c_uint = 0;
#[repr(C)]
#[derive(Clone, Copy, Default)]
struct BpfStat {
recv: libc::c_uint,
drop: libc::c_uint,
}
fn ioctl_int(fd: &OwnedFd, request: libc::c_ulong, value: libc::c_uint, what: &str) -> io::Result<()> {
let mut v = value;
if unsafe { libc::ioctl(fd.as_raw_fd(), request, &raw mut v) } < 0 {
return Err(last_error(what));
}
Ok(())
}
#[derive(Debug)]
pub(crate) struct Inner {
fd: OwnedFd,
name: String,
index: u32,
mac: MacAddr,
timestamping: Timestamping,
nonblocking: bool,
buf: Vec<u8>,
pos: usize,
end: usize,
delivered: u64,
_membership: Option<OwnedFd>,
}
impl Inner {
pub(crate) fn open(cfg: &Config, program: Option<&Program>) -> io::Result<Inner> {
if cfg.tx_time.is_some() {
return Err(io::Error::new(
io::ErrorKind::Unsupported,
"launch-time transmission (SO_TXTIME) is Linux-only",
));
}
let index = interface_index(&cfg.interface)?;
let mac = hardware_address(&cfg.interface)?;
let fd = open_device()?;
let want = cfg.buffer_size.clamp(4096, 1 << 21) as libc::c_uint;
let _ = ioctl_int(&fd, libc::BIOCSBLEN as _, want, "BIOCSBLEN");
let mut ifr: libc::ifreq = unsafe { zeroed() };
ifr.ifr_name = ifr_name(&cfg.interface)?;
if unsafe { libc::ioctl(fd.as_raw_fd(), libc::BIOCSETIF as _, &raw mut ifr) } < 0 {
return Err(last_error(&format!("BIOCSETIF {}", cfg.interface)));
}
ioctl_int(&fd, libc::BIOCIMMEDIATE as _, 1, "BIOCIMMEDIATE")?;
ioctl_int(&fd, libc::BIOCSHDRCMPLT as _, 1, "BIOCSHDRCMPLT")?;
#[cfg(target_os = "macos")]
if !cfg.see_outgoing {
ioctl_int(&fd, libc::BIOCSSEESENT as _, 0, "BIOCSSEESENT")?;
}
#[cfg(target_os = "freebsd")]
if !cfg.see_outgoing {
ioctl_int(&fd, BIOCSDIRECTION, BPF_D_IN, "BIOCSDIRECTION")?;
}
if let Some(p) = program {
let mut insns: Vec<libc::bpf_insn> = p
.instructions()
.iter()
.map(|i| libc::bpf_insn { code: i.code, jt: i.jt, jf: i.jf, k: i.k })
.collect();
let mut prog =
libc::bpf_program { bf_len: insns.len() as libc::c_uint, bf_insns: insns.as_mut_ptr() };
if unsafe { libc::ioctl(fd.as_raw_fd(), libc::BIOCSETF as _, &raw mut prog) } < 0 {
return Err(last_error("BIOCSETF"));
}
}
if cfg.promiscuous || cfg.all_multicast {
if unsafe { libc::ioctl(fd.as_raw_fd(), libc::BIOCPROMISC as _) } < 0 {
return Err(last_error("BIOCPROMISC"));
}
}
let membership =
if cfg.multicast.is_empty() { None } else { Some(join_groups(&cfg.interface, &cfg.multicast)?) };
if cfg.nonblocking {
set_nonblocking(fd.as_fd(), true)?;
}
let mut blen: libc::c_uint = 0;
if unsafe { libc::ioctl(fd.as_raw_fd(), libc::BIOCGBLEN as _, &raw mut blen) } < 0 {
return Err(last_error("BIOCGBLEN"));
}
Ok(Inner {
fd,
name: cfg.interface.clone(),
index,
mac,
timestamping: cfg.timestamping,
nonblocking: cfg.nonblocking,
buf: vec![0u8; blen as usize],
pos: 0,
end: 0,
delivered: 0,
_membership: membership,
})
}
pub(crate) fn interface(&self) -> &str {
&self.name
}
pub(crate) fn index(&self) -> u32 {
self.index
}
pub(crate) fn mac(&self) -> MacAddr {
self.mac
}
pub(crate) fn rx_path(&self) -> RxPath {
RxPath::Bpf
}
pub(crate) fn as_fd(&self) -> BorrowedFd<'_> {
self.fd.as_fd()
}
pub(crate) fn timestamping(&self) -> Timestamping {
if self.timestamping == Timestamping::Off { Timestamping::Off } else { Timestamping::Software }
}
pub(crate) fn recv(&mut self, timeout: Option<Duration>) -> io::Result<Option<Packet<'_>>> {
let timeout = if self.nonblocking { Some(Duration::ZERO) } else { timeout };
let deadline = deadline(timeout);
loop {
if let Some(r) = bpf_record::next(&self.buf[..self.end], &mut self.pos, Layout::native()) {
self.delivered += 1;
let timestamp = (self.timestamping != Timestamping::Off).then(|| Timestamp {
secs: r.secs,
nanos: (r.usecs.clamp(0, 999_999) as u32) * 1000,
source: TimestampSource::Software,
});
return Ok(Some(Packet {
data: &self.buf[r.start..r.start + r.caplen],
original_len: r.datalen,
timestamp,
vlan_restored: false,
}));
}
self.pos = 0;
self.end = 0;
let remaining = deadline.map(|d| d.saturating_duration_since(Instant::now()));
if wait(self.fd.as_fd(), remaining)? == Ready::Timeout {
return Ok(None);
}
let n = unsafe { libc::read(self.fd.as_raw_fd(), self.buf.as_mut_ptr().cast(), self.buf.len()) };
if n < 0 {
let e = io::Error::last_os_error();
match e.kind() {
io::ErrorKind::WouldBlock | io::ErrorKind::Interrupted => continue,
_ => return Err(io::Error::new(e.kind(), format!("interface {}: {e}", self.name))),
}
}
self.end = n as usize;
}
}
pub(crate) fn send(&self, frame: &[u8]) -> io::Result<()> {
let n = unsafe { libc::write(self.fd.as_raw_fd(), frame.as_ptr().cast(), frame.len()) };
if n < 0 {
return Err(last_error("write to BPF"));
}
if n as usize != frame.len() {
return Err(io::Error::new(
io::ErrorKind::WriteZero,
format!("sent {n} of {} octets", frame.len()),
));
}
Ok(())
}
pub(crate) fn send_at(&self, _: &[u8], _: u64) -> io::Result<()> {
Err(io::Error::new(io::ErrorKind::InvalidInput, "send_at needs Config::tx_time, which is Linux-only"))
}
pub(crate) fn send_batch(&mut self, frames: &[&[u8]]) -> io::Result<usize> {
for (k, f) in frames.iter().enumerate() {
if let Err(e) = self.send(f) {
return if k > 0 { Ok(k) } else { Err(e) };
}
}
Ok(frames.len())
}
pub(crate) fn stats(&mut self) -> io::Result<Stats> {
let mut st = BpfStat::default();
if unsafe { libc::ioctl(self.fd.as_raw_fd(), libc::BIOCGSTATS as _, &raw mut st) } < 0 {
return Err(last_error("BIOCGSTATS"));
}
Ok(Stats { received: self.delivered, dropped: u64::from(st.drop) })
}
pub(crate) fn tx_errors(&mut self) -> io::Result<TxErrors> {
Ok(TxErrors::default())
}
pub(crate) fn set_nonblocking(&mut self, on: bool) -> io::Result<()> {
set_nonblocking(self.fd.as_fd(), on)?;
self.nonblocking = on;
Ok(())
}
}
fn open_device() -> io::Result<OwnedFd> {
let open = |path: &CStr| {
let fd = unsafe { libc::open(path.as_ptr(), libc::O_RDWR | libc::O_CLOEXEC) };
if fd < 0 {
Err(io::Error::last_os_error())
} else {
Ok(unsafe { OwnedFd::from_raw_fd(fd) })
}
};
match open(c"/dev/bpf") {
Ok(fd) => return Ok(fd),
Err(e) if e.kind() == io::ErrorKind::PermissionDenied => return Err(permission()),
Err(_) => {}
}
for n in 0..256 {
let path = std::ffi::CString::new(format!("/dev/bpf{n}")).map_err(io::Error::other)?;
match open(&path) {
Ok(fd) => return Ok(fd),
Err(e) if e.raw_os_error() == Some(libc::EBUSY) => {}
Err(e) if e.kind() == io::ErrorKind::PermissionDenied => return Err(permission()),
Err(e) if e.kind() == io::ErrorKind::NotFound => break,
Err(e) => return Err(io::Error::new(e.kind(), format!("open /dev/bpf{n}: {e}"))),
}
}
Err(io::Error::new(io::ErrorKind::NotFound, "no free BPF device"))
}
fn permission() -> io::Error {
io::Error::new(
io::ErrorKind::PermissionDenied,
"opening a BPF device needs read and write access to /dev/bpf* (run as root, or grant the group, e.g. Wireshark's ChmodBPF)",
)
}
fn hardware_address(name: &str) -> io::Result<MacAddr> {
let mut list: *mut libc::ifaddrs = std::ptr::null_mut();
if unsafe { libc::getifaddrs(&raw mut list) } < 0 {
return Err(last_error("getifaddrs"));
}
let mut found = None;
let mut cur = list;
while !cur.is_null() {
let ifa = unsafe { &*cur };
let this = unsafe { CStr::from_ptr(ifa.ifa_name) };
if this.to_bytes() == name.as_bytes() && !ifa.ifa_addr.is_null() {
let family = i32::from(unsafe { (*ifa.ifa_addr).sa_family });
if family == libc::AF_LINK {
let base = ifa.ifa_addr.cast::<u8>().cast_const();
let (len, nlen, alen) = unsafe {
let dl = ifa.ifa_addr.cast::<libc::sockaddr_dl>();
(usize::from((*dl).sdl_len), usize::from((*dl).sdl_nlen), (*dl).sdl_alen)
};
let at = std::mem::offset_of!(libc::sockaddr_dl, sdl_data) + nlen;
if alen == 6 && at + 6 <= len {
let mut mac = [0u8; 6];
unsafe { std::ptr::copy_nonoverlapping(base.add(at), mac.as_mut_ptr(), 6) };
found = Some(MacAddr(mac));
}
}
}
cur = ifa.ifa_next;
}
unsafe { libc::freeifaddrs(list) };
Ok(found.unwrap_or_default())
}
fn join_groups(name: &str, groups: &[MacAddr]) -> io::Result<OwnedFd> {
let raw = unsafe { libc::socket(libc::AF_INET, libc::SOCK_DGRAM | libc_cloexec(), 0) };
if raw < 0 {
return Err(last_error("socket for multicast membership"));
}
let fd = unsafe { OwnedFd::from_raw_fd(raw) };
set_cloexec(&fd)?;
for g in groups {
let mut ifr: libc::ifreq = unsafe { zeroed() };
ifr.ifr_name = ifr_name(name)?;
let sa = unsafe { &mut ifr.ifr_ifru.ifru_addr };
sa.sa_family = libc::AF_UNSPEC as libc::sa_family_t;
sa.sa_len = size_of::<libc::sockaddr>() as u8;
for (o, b) in sa.sa_data.iter_mut().zip(g.0) {
*o = b as libc::c_char;
}
if unsafe { libc::ioctl(fd.as_raw_fd(), SIOCADDMULTI as _, &raw mut ifr) } < 0 {
return Err(last_error(&format!("SIOCADDMULTI {g} on {name}")));
}
}
Ok(fd)
}
#[cfg(target_os = "macos")]
fn libc_cloexec() -> libc::c_int {
0
}
#[cfg(not(target_os = "macos"))]
fn libc_cloexec() -> libc::c_int {
libc::SOCK_CLOEXEC
}
fn set_cloexec(fd: &OwnedFd) -> io::Result<()> {
if unsafe { libc::fcntl(fd.as_raw_fd(), libc::F_SETFD, libc::FD_CLOEXEC) } < 0 {
return Err(last_error("fcntl(F_SETFD)"));
}
Ok(())
}
pub(crate) fn clock_now(clock: Clock) -> io::Result<Duration> {
let id = match clock {
Clock::Tai => return Err(io::Error::new(io::ErrorKind::Unsupported, "CLOCK_TAI is Linux-only")),
Clock::Monotonic => libc::CLOCK_MONOTONIC,
Clock::Realtime => libc::CLOCK_REALTIME,
};
let mut ts: libc::timespec = unsafe { zeroed() };
if unsafe { libc::clock_gettime(id, &raw mut ts) } < 0 {
return Err(last_error("clock_gettime"));
}
Ok(Duration::new(ts.tv_sec as u64, ts.tv_nsec as u32))
}
pub(crate) fn drop_capabilities() -> io::Result<()> {
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn locally_defined_ioctls_match_the_headers() {
assert_eq!(SIOCADDMULTI, 0x8020_6931);
#[cfg(target_os = "freebsd")]
assert_eq!(BIOCSDIRECTION, 0x8004_4277);
}
}