use std::net::IpAddr;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::thread::{self, JoinHandle};
use pcap::{Active, Capture, Device};
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;
pub type CaptureStream = mpsc::UnboundedReceiver<(Vec<u8>, IpAddr)>;
pub struct CaptureGuard {
stop: Arc<AtomicBool>,
handles: Vec<JoinHandle<()>>,
}
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(test)]
pub fn noop() -> Self {
Self {
stop: Arc::new(AtomicBool::new(true)),
handles: Vec::new(),
}
}
}
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();
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();
handles.push(
thread::Builder::new()
.name(format!("capture-{name}"))
.spawn(move || reader_loop(capture, link, tx, stop))
.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 }))
}
fn open(name: &str, filter: &str) -> anyhow::Result<(Capture<Active>, LinkType)> {
let device = Device::from(name);
let mut capture = Capture::from_device(device)?
.immediate_mode(true)
.snaplen(SNAP_LEN)
.timeout(READ_TIMEOUT_MS)
.open()?;
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<(Vec<u8>, IpAddr)>,
stop: Arc<AtomicBool>,
) {
while !stop.load(Ordering::Relaxed) {
match capture.next_packet() {
Ok(packet) => {
if let Some((source, segment)) = frame::parse_captured_segment(link, packet.data)
&& tx.send((segment.to_vec(), source)).is_err()
{
break;
}
}
Err(pcap::Error::TimeoutExpired) => continue,
Err(pcap::Error::NoMorePackets) => break,
Err(e) => {
error!("Capture read error: {e}");
break;
}
}
}
}