use std::net::IpAddr;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::thread::{self, JoinHandle};
use pcap::{Active, Capture, Device};
use pnet::packet::ip::IpNextHeaderProtocol;
#[cfg(not(windows))]
use std::os::unix::io::AsRawFd;
use tokio::sync::mpsc;
use crate::network::frame::{self, LinkType};
use crate::{error, info, warn};
const SNAP_LEN: i32 = 65_535;
const READ_TIMEOUT_MS: i32 = 100;
const STATS_EVERY_FRAMES: u32 = 128;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CapturedSegment {
pub source: IpAddr,
pub protocol: IpNextHeaderProtocol,
pub bytes: Vec<u8>,
}
pub type CaptureStream = mpsc::UnboundedReceiver<CapturedSegment>;
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct CaptureCounts {
pub received: u64,
pub dropped: u64,
pub if_dropped: u64,
}
impl std::ops::Add for CaptureCounts {
type Output = Self;
fn add(self, other: Self) -> Self {
Self {
received: self.received + other.received,
dropped: self.dropped + other.dropped,
if_dropped: self.if_dropped + other.if_dropped,
}
}
}
#[derive(Debug, Default)]
struct CaptureStats {
received: AtomicU64,
dropped: AtomicU64,
if_dropped: AtomicU64,
}
impl CaptureStats {
fn store(&self, stat: &pcap::Stat) {
self.received.store(stat.received as u64, Ordering::Relaxed);
self.dropped.store(stat.dropped as u64, Ordering::Relaxed);
self.if_dropped
.store(stat.if_dropped as u64, Ordering::Relaxed);
}
fn snapshot(&self) -> CaptureCounts {
CaptureCounts {
received: self.received.load(Ordering::Relaxed),
dropped: self.dropped.load(Ordering::Relaxed),
if_dropped: self.if_dropped.load(Ordering::Relaxed),
}
}
}
pub struct CaptureGuard {
stop: Arc<AtomicBool>,
handles: Vec<JoinHandle<()>>,
stats: Vec<Arc<CaptureStats>>,
}
impl Drop for CaptureGuard {
fn drop(&mut self) {
self.stop.store(true, Ordering::Relaxed);
for handle in self.handles.drain(..) {
let _ = handle.join();
}
}
}
impl CaptureGuard {
#[cfg(any(test, feature = "test-support"))]
pub(crate) fn noop() -> Self {
Self {
stop: Arc::new(AtomicBool::new(true)),
handles: Vec::new(),
stats: Vec::new(),
}
}
pub fn counts(&self) -> Option<CaptureCounts> {
if self.stats.is_empty() {
return None;
}
Some(
self.stats
.iter()
.map(|stats| stats.snapshot())
.fold(CaptureCounts::default(), |total, counts| total + counts),
)
}
}
pub fn start(interfaces: &[String], filter: &str) -> anyhow::Result<(CaptureStream, CaptureGuard)> {
let (tx, rx) = mpsc::unbounded_channel();
let stop = Arc::new(AtomicBool::new(false));
let mut handles = Vec::new();
let mut stats = Vec::new();
for name in interfaces {
match open(name, filter) {
Ok((capture, link)) => {
info!(
verbosity = 1,
"Capturing on {name} (link type {link:?}) with filter: {filter}"
);
let tx = tx.clone();
let stop = stop.clone();
let counters = Arc::new(CaptureStats::default());
stats.push(counters.clone());
let name = name.clone();
handles.push(
thread::Builder::new()
.name(format!("capture-{name}"))
.spawn(move || reader_loop(capture, link, tx, stop, &name, &counters))
.expect("spawning capture thread"),
);
}
Err(e) => warn!("Skipping capture on {name}: {e}"),
}
}
if handles.is_empty() {
anyhow::bail!("no interface could be captured for replies");
}
Ok((
rx,
CaptureGuard {
stop,
handles,
stats,
},
))
}
fn open(name: &str, filter: &str) -> anyhow::Result<(Capture<Active>, LinkType)> {
let device = Device::from(name);
let capture = Capture::from_device(device)?
.immediate_mode(true)
.snaplen(SNAP_LEN)
.timeout(READ_TIMEOUT_MS)
.open()?;
#[cfg(not(windows))]
let capture = capture.setnonblock()?;
let mut capture = capture;
let link = LinkType::from_dlt(capture.get_datalink().0);
if let LinkType::Unsupported(dlt) = link {
anyhow::bail!("unsupported data-link type {dlt}");
}
capture
.filter(filter, true)
.map_err(|e| anyhow::anyhow!("compiling BPF filter `{filter}`: {e}"))?;
Ok((capture, link))
}
fn reader_loop(
mut capture: Capture<Active>,
link: LinkType,
tx: mpsc::UnboundedSender<CapturedSegment>,
stop: Arc<AtomicBool>,
name: &str,
counters: &CaptureStats,
) {
#[cfg(not(windows))]
let fd = capture.as_raw_fd();
let mut since_refresh: u32 = 0;
while !stop.load(Ordering::Relaxed) {
let mut read_frame = false;
match capture.next_packet() {
Ok(packet) => {
read_frame = true;
if let Some(parsed) = frame::parse_captured_segment(link, packet.data)
&& tx
.send(CapturedSegment {
source: parsed.source,
protocol: parsed.protocol,
bytes: parsed.payload.to_vec(),
})
.is_err()
{
break;
}
}
Err(pcap::Error::TimeoutExpired) => {}
Err(pcap::Error::NoMorePackets) => break,
Err(e) => {
error!("Capture read error: {e}");
break;
}
}
since_refresh += u32::from(read_frame);
if since_refresh >= STATS_EVERY_FRAMES {
refresh(&mut capture, counters);
since_refresh = 0;
}
if !read_frame {
refresh(&mut capture, counters);
since_refresh = 0;
#[cfg(not(windows))]
wait_readable(fd);
}
}
refresh(&mut capture, counters);
let counts = counters.snapshot();
if counts.dropped > 0 || counts.if_dropped > 0 {
info!(
verbosity = 1,
"Capture on {name} lost frames: {} dropped, {} dropped by the interface, of {} received",
counts.dropped,
counts.if_dropped,
counts.received
);
}
}
fn refresh(capture: &mut Capture<Active>, counters: &CaptureStats) {
if let Ok(stat) = capture.stats() {
counters.store(&stat);
}
}
#[cfg(not(windows))]
fn wait_readable(fd: std::os::unix::io::RawFd) {
let mut poll_fd = libc::pollfd {
fd,
events: libc::POLLIN,
revents: 0,
};
unsafe { libc::poll(&mut poll_fd, 1, READ_TIMEOUT_MS) };
}
#[cfg(test)]
mod tests {
use super::*;
fn guard_over(stats: Vec<Arc<CaptureStats>>) -> CaptureGuard {
CaptureGuard {
stop: Arc::new(AtomicBool::new(true)),
handles: Vec::new(),
stats,
}
}
fn stats_of(received: u32, dropped: u32, if_dropped: u32) -> Arc<CaptureStats> {
let stats = Arc::new(CaptureStats::default());
stats.store(&pcap::Stat {
received,
dropped,
if_dropped,
});
stats
}
#[test]
fn counts_are_summed_across_every_live_capture() {
let guard = guard_over(vec![stats_of(100, 3, 1), stats_of(40, 0, 0)]);
assert_eq!(
guard.counts(),
Some(CaptureCounts {
received: 140,
dropped: 3,
if_dropped: 1,
})
);
}
#[test]
fn a_guard_over_no_capture_reports_nothing_rather_than_zero() {
assert_eq!(CaptureGuard::noop().counts(), None);
assert_eq!(guard_over(Vec::new()).counts(), None);
}
#[test]
fn a_refresh_replaces_the_previous_reading_rather_than_adding_to_it() {
let stats = CaptureStats::default();
stats.store(&pcap::Stat {
received: 500,
dropped: 4,
if_dropped: 0,
});
stats.store(&pcap::Stat {
received: 900,
dropped: 9,
if_dropped: 0,
});
assert_eq!(
stats.snapshot(),
CaptureCounts {
received: 900,
dropped: 9,
if_dropped: 0,
}
);
}
}