use std::net::IpAddr;
use std::ops::ControlFlow;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::thread::{self, JoinHandle};
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use pcap::{Active, Capture};
use pnet_packet::ip::IpNextHeaderProtocol;
#[cfg(not(windows))]
use std::os::unix::io::AsRawFd;
use tokio::sync::mpsc;
use crate::logging::error;
use crate::model::capture::{CaptureCounts, IpObservation};
use crate::model::ip::scoped::Zone;
use crate::protocols::ethernet::VLAN_TAG_LEN;
use crate::protocols::sizes::{ETH_HDR_LEN, IP_V6_HDR_LEN};
use crate::transport::frame::{self, LinkType};
use crate::{counted, info, warn};
use pnet_base::MacAddr;
pub const REPLY_SNAP_LEN: u32 = 65_535;
pub const MIN_SNAP_LEN: u32 =
(ETH_HDR_LEN + 2 * VLAN_TAG_LEN + IP_V6_HDR_LEN + TCP_MAX_HDR_LEN) as u32;
const TCP_MAX_HDR_LEN: usize = 60;
const _: () = assert!(
MIN_SNAP_LEN as usize >= ETH_HDR_LEN + 2 * VLAN_TAG_LEN + IP_V6_HDR_LEN + TCP_MAX_HDR_LEN,
"the snapshot floor is below a header stack this crate parses"
);
const _: () = assert!(
REPLY_SNAP_LEN > MIN_SNAP_LEN,
"the snapshot length a scanner takes unchanged is below the floor"
);
const _: () = assert!(
frame::SLL_HDR_LEN <= ETH_HDR_LEN + 2 * VLAN_TAG_LEN
&& frame::SLL2_HDR_LEN <= ETH_HDR_LEN + 2 * VLAN_TAG_LEN,
"a cooked link header is deeper than the one the snapshot floor was sized for"
);
#[must_use]
#[derive(Debug, Clone)]
pub struct CaptureOptions {
filter: CaptureFilter,
snaplen: u32,
promiscuous: bool,
buffer_bytes: Option<u32>,
}
impl CaptureOptions {
pub fn for_replies(filter: impl Into<CaptureFilter>) -> Self {
Self {
filter: filter.into(),
snaplen: REPLY_SNAP_LEN,
promiscuous: false,
buffer_bytes: None,
}
}
pub fn for_link_traffic(filter: impl Into<CaptureFilter>) -> Self {
Self {
promiscuous: true,
..Self::for_replies(filter)
}
}
pub fn with_snaplen(mut self, bytes: u32) -> Self {
self.snaplen = bytes.max(MIN_SNAP_LEN);
self
}
pub fn with_promiscuous(mut self, promiscuous: bool) -> Self {
self.promiscuous = promiscuous;
self
}
pub fn with_buffer_bytes(mut self, bytes: u32) -> Self {
self.buffer_bytes = Some(bytes);
self
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CaptureFilter {
shape: FilterShape,
}
#[derive(Debug, Clone, PartialEq, Eq)]
enum FilterShape {
Expression(String),
AnyOf(Vec<String>),
}
impl CaptureFilter {
pub fn expression(expression: impl Into<String>) -> Self {
Self {
shape: FilterShape::Expression(expression.into()),
}
}
pub fn any_of<I, S>(clauses: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<String>,
{
Self {
shape: FilterShape::AnyOf(clauses.into_iter().map(Into::into).collect()),
}
}
pub(crate) fn for_link<T: pcap::Activated + ?Sized>(
&self,
capture: &Capture<T>,
) -> Result<(String, Vec<String>), CaptureError> {
let clauses = match &self.shape {
FilterShape::Expression(expression) => return Ok((expression.clone(), Vec::new())),
FilterShape::AnyOf(clauses) => clauses,
};
let mut kept = Vec::new();
let mut left_out = Vec::new();
let mut refused = None;
for clause in clauses {
match capture.compile(clause, true) {
Ok(_) => kept.push(clause.as_str()),
Err(source) => {
if let Err(malformed) = compiles_for_ethernet(clause) {
return Err(CaptureError::Filter {
filter: clause.clone(),
source: malformed,
});
}
left_out.push(clause.clone());
refused = Some(source);
}
}
}
match refused {
Some(source) if kept.is_empty() => Err(CaptureError::Filter {
filter: self.to_string(),
source,
}),
_ => Ok((kept.join(" or "), left_out)),
}
}
}
fn compiles_for_ethernet(clause: &str) -> Result<(), pcap::Error> {
Capture::dead(pcap::Linktype::ETHERNET)?.compile(clause, true)?;
Ok(())
}
impl std::fmt::Display for CaptureFilter {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.shape {
FilterShape::Expression(expression) => f.write_str(expression),
FilterShape::AnyOf(clauses) => f.write_str(&clauses.join(" or ")),
}
}
}
impl From<String> for CaptureFilter {
fn from(expression: String) -> Self {
Self::expression(expression)
}
}
impl From<&str> for CaptureFilter {
fn from(expression: &str) -> Self {
Self::expression(expression)
}
}
const READ_TIMEOUT_MS: i32 = 100;
const STATS_EVERY_FRAMES: u32 = 128;
const QUEUE_FULL_PAUSE: Duration = Duration::from_millis(1);
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CapturedSegment {
pub source: IpAddr,
pub destination: Option<IpAddr>,
pub protocol: IpNextHeaderProtocol,
pub bytes: Vec<u8>,
pub observation: Option<IpObservation>,
pub source_mac: Option<MacAddr>,
pub received_at: Instant,
}
impl CapturedSegment {
pub fn synthetic(source: IpAddr, protocol: IpNextHeaderProtocol, bytes: Vec<u8>) -> Self {
Self {
source,
destination: None,
protocol,
bytes,
observation: None,
received_at: Instant::now(),
source_mac: None,
}
}
}
pub type CaptureStream = mpsc::Receiver<CapturedSegment>;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CapturedFrame {
pub zone: Zone,
pub link: LinkType,
pub bytes: Vec<u8>,
pub observed_at: SystemTime,
}
pub type FrameStream = mpsc::Receiver<CapturedFrame>;
#[derive(Debug, Default)]
struct CaptureStats {
received: AtomicU64,
dropped: AtomicU64,
if_dropped: AtomicU64,
stopped_early: AtomicBool,
}
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),
stopped_early: u64::from(self.stopped_early.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);
let handles = std::mem::take(&mut self.handles);
let wait = move || {
for handle in handles {
let _ = handle.join();
}
};
match tokio::runtime::Handle::try_current().map(|handle| handle.runtime_flavor()) {
Ok(tokio::runtime::RuntimeFlavor::MultiThread) => tokio::task::block_in_place(wait),
_ => wait(),
}
}
}
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(),
}
}
#[cfg(test)]
pub(crate) fn stopped_early() -> Self {
let counters = CaptureStats::default();
counters.stopped_early.store(true, Ordering::Relaxed);
Self {
stop: Arc::new(AtomicBool::new(true)),
handles: Vec::new(),
stats: vec![Arc::new(counters)],
}
}
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),
)
}
}
#[non_exhaustive]
#[derive(Debug, thiserror::Error)]
pub enum CaptureError {
#[error(
"no link could be captured on, so nothing could be heard: {}",
refusals_reason(refused)
)]
NoInterface {
refused: Vec<(String, CaptureError)>,
},
#[error(
"captured {} but could not start a reader for any of them: {source}",
crate::logging::counted(*opened as u128, "link", "links")
)]
NoReader {
opened: usize,
#[source]
source: std::io::Error,
},
#[error("{interface} carries data-link type {dlt}, which nothing here parses")]
UnsupportedLinkType {
interface: String,
dlt: i32,
},
#[error("the filter `{filter}` would not compile: {}", library_message(.source))]
Filter {
filter: String,
#[source]
source: pcap::Error,
},
#[error("{interface} could not be opened: {}", library_message(.source))]
Open {
interface: String,
#[source]
source: pcap::Error,
},
#[error(
"{interface} could not be opened without privileges this process lacks: {}",
library_message(.source)
)]
Denied {
interface: String,
#[source]
source: pcap::Error,
},
}
impl CaptureError {
pub fn is_denied(&self) -> bool {
match self {
Self::Denied { .. } => true,
Self::NoInterface { refused } => {
!refused.is_empty() && refused.iter().all(|(_, error)| error.is_denied())
}
_ => false,
}
}
pub(crate) fn reason(&self) -> String {
match self {
Self::NoInterface { refused } => match refused.as_slice() {
[(_, only)] => only.reason(),
several => refusals_reason(several),
},
Self::Open { source, .. } => library_message(source).into_owned(),
Self::Denied { source, .. } => format!(
"this process lacks the privileges to capture on it: {}",
library_message(source)
),
Self::UnsupportedLinkType { dlt, .. } => {
format!("it carries data-link type {dlt}, which nothing here parses")
}
other => other.to_string(),
}
}
}
fn refusals_reason(refused: &[(String, CaptureError)]) -> String {
if refused.is_empty() {
return "there was no link to capture on".to_owned();
}
if refused.iter().all(|(_, error)| error.is_denied()) {
return "this process may not capture (opening a capture needs root)".to_owned();
}
refused
.iter()
.map(|(link, error)| format!("{link}: {}", error.reason()))
.collect::<Vec<_>>()
.join("; ")
}
fn library_message(error: &pcap::Error) -> std::borrow::Cow<'_, str> {
match error {
pcap::Error::PcapError(message) => message.into(),
other => other.to_string().into(),
}
}
pub fn segments(
links: &[Zone],
options: &CaptureOptions,
queue_depth: usize,
) -> Result<(CaptureStream, CaptureGuard), CaptureError> {
let (tx, rx) = mpsc::channel(queue_depth);
let guard = spawn_captures(links, options, move |_zone, link, stop| {
let tx = tx.clone();
move |packet: &pcap::Packet<'_>| {
let Some((parsed, source_mac)) = frame::parse_captured(link, packet.data) else {
return ControlFlow::Continue(());
};
let mut segment = CapturedSegment {
source: parsed.source,
destination: Some(parsed.destination),
protocol: parsed.protocol,
bytes: parsed.payload.to_vec(),
observation: Some(parsed.observation),
source_mac,
received_at: Instant::now(),
};
loop {
match tx.try_send(segment) {
Ok(()) => return ControlFlow::Continue(()),
Err(mpsc::error::TrySendError::Closed(_)) => return ControlFlow::Break(()),
Err(mpsc::error::TrySendError::Full(returned)) => {
if stop.load(Ordering::Relaxed) {
return ControlFlow::Break(());
}
segment = returned;
thread::sleep(QUEUE_FULL_PAUSE);
}
}
}
}
})?;
Ok((rx, guard))
}
pub fn frames(
links: &[Zone],
options: &CaptureOptions,
queue_depth: usize,
) -> Result<(FrameStream, CaptureGuard), CaptureError> {
let (tx, rx) = mpsc::channel(queue_depth);
let guard = spawn_captures(links, options, move |zone, link, stop| {
let tx = tx.clone();
let zone = zone.clone();
move |packet: &pcap::Packet<'_>| {
let mut frame = CapturedFrame {
zone: zone.clone(),
link,
bytes: packet.data.to_vec(),
observed_at: timestamp_of(packet),
};
loop {
match tx.try_send(frame) {
Ok(()) => return ControlFlow::Continue(()),
Err(mpsc::error::TrySendError::Closed(_)) => return ControlFlow::Break(()),
Err(mpsc::error::TrySendError::Full(returned)) => {
if stop.load(Ordering::Relaxed) {
return ControlFlow::Break(());
}
frame = returned;
thread::sleep(QUEUE_FULL_PAUSE);
}
}
}
}
})?;
Ok((rx, guard))
}
fn spawn_captures<D>(
links: &[Zone],
options: &CaptureOptions,
mut deliver_for: impl FnMut(&Zone, LinkType, Arc<AtomicBool>) -> D,
) -> Result<CaptureGuard, CaptureError>
where
D: FnMut(&pcap::Packet<'_>) -> ControlFlow<()> + Send + 'static,
{
let stop = Arc::new(AtomicBool::new(false));
let mut handles = Vec::new();
let mut stats = Vec::new();
let mut opened = 0usize;
let mut unstarted: Option<std::io::Error> = None;
let mut unheard: Vec<(&Zone, CaptureError)> = Vec::new();
for zone in links {
let name = zone.name();
match open(name, options) {
Ok(Opened {
capture,
link,
warning,
left_out,
}) => {
match warning {
Some(warning) => info!(
verbosity = 3,
"capturing on {name} (link type {link:?}), which libpcap \
opened with a warning: {warning}"
),
None => info!(verbosity = 3, "capturing on {name} (link type {link:?})"),
}
if !left_out.is_empty() {
info!(
verbosity = 3,
"capturing on {name} without the filter clauses it cannot express: {}",
left_out.join(" or ")
);
}
opened += 1;
let stop = stop.clone();
let deliver = deliver_for(zone, link, stop.clone());
let counters = Arc::new(CaptureStats::default());
stats.push(counters.clone());
let name = name.to_owned();
match spawn_reader(&name.clone(), counters, move |counters| {
reader_loop(capture, &stop, &name, counters, deliver)
}) {
Ok(handle) => handles.push(handle),
Err(e) => {
warn!("no reader thread for {}: {e}", zone.name());
stats.pop();
unstarted = Some(e);
}
}
}
Err(e) => unheard.push((zone, e)),
}
}
if !unheard.is_empty() {
tell_unheard(&unheard, opened == 0);
}
if handles.is_empty() {
return Err(match unstarted {
Some(source) => CaptureError::NoReader { opened, source },
None => CaptureError::NoInterface {
refused: unheard
.into_iter()
.map(|(zone, error)| (zone.name().to_owned(), error))
.collect(),
},
});
}
info!(
verbosity = 3,
"capturing on {} with filter: {}",
counted(opened as u128, "interface", "interfaces"),
options.filter,
);
Ok(CaptureGuard {
stop,
handles,
stats,
})
}
fn tell_unheard(unheard: &[(&Zone, CaptureError)], every_link_failed: bool) {
let links = crate::system::interface::interfaces();
let mut told = TOLD
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
for (zone, error) in unheard {
let link = links.iter().find(|link| link.zone() == **zone);
let loudness = loudness(
every_link_failed,
link.is_some_and(|link| link.carries_default_route()),
);
if !told.first_time(zone.name(), loudness) {
continue;
}
let known_as = link.map_or(zone.name(), |link| link.display_name());
let reason = error.reason();
match loudness {
Loudness::Aloud => warn!("no capture on {known_as}: {reason}"),
Loudness::Quiet if known_as == zone.name() => {
warn!(verbosity = 1, "no capture on {known_as}: {reason}");
}
Loudness::Quiet => {
warn!(
verbosity = 1,
"no capture on {known_as} ({}): {reason}",
zone.name()
);
}
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
enum Loudness {
Quiet,
Aloud,
}
fn loudness(every_link_failed: bool, carries_default_route: bool) -> Loudness {
if carries_default_route && !every_link_failed {
Loudness::Aloud
} else {
Loudness::Quiet
}
}
struct Told(std::collections::BTreeMap<String, Loudness>);
impl Told {
const fn new() -> Self {
Self(std::collections::BTreeMap::new())
}
fn first_time(&mut self, link: &str, loudness: Loudness) -> bool {
match self.0.get(link) {
Some(&said) if said >= loudness => false,
_ => {
self.0.insert(link.to_owned(), loudness);
true
}
}
}
}
static TOLD: std::sync::Mutex<Told> = std::sync::Mutex::new(Told::new());
fn spawn_reader(
name: &str,
counters: Arc<CaptureStats>,
read: impl FnOnce(&CaptureStats) + Send + 'static,
) -> std::io::Result<JoinHandle<()>> {
let link = name.to_owned();
thread::Builder::new()
.name(format!("capture-{name}"))
.spawn(move || {
let _mark = DeafOnUnwind {
counters: &counters,
link: &link,
};
read(&counters);
})
}
struct DeafOnUnwind<'a> {
counters: &'a CaptureStats,
link: &'a str,
}
impl Drop for DeafOnUnwind<'_> {
fn drop(&mut self) {
if thread::panicking() {
self.counters.stopped_early.store(true, Ordering::Relaxed);
error!(
"the capture on {} failed and will hear nothing further; replies \
arriving on this link are lost from here on",
self.link
);
}
}
}
fn timestamp_of(packet: &pcap::Packet<'_>) -> SystemTime {
let seconds = u64::try_from(packet.header.ts.tv_sec).unwrap_or(0);
let micros = u32::try_from(packet.header.ts.tv_usec).unwrap_or(0);
UNIX_EPOCH + Duration::new(seconds, micros.saturating_mul(1_000))
}
fn device_name(name: &str) -> String {
#[cfg(windows)]
{
npcap_device_name(name)
}
#[cfg(not(windows))]
{
name.to_owned()
}
}
#[cfg_attr(not(windows), allow(dead_code))]
fn npcap_device_name(name: &str) -> String {
if name.starts_with('{') {
format!("\\Device\\NPF_{name}")
} else {
name.to_owned()
}
}
struct Opened {
capture: Capture<Active>,
link: LinkType,
warning: Option<String>,
left_out: Vec<String>,
}
fn open(name: &str, options: &CaptureOptions) -> Result<Opened, CaptureError> {
let (capture, warning) = libpcap::activate(
name,
&libpcap::Setup {
snaplen: saturating_i32(options.snaplen),
promiscuous: options.promiscuous,
timeout_ms: READ_TIMEOUT_MS,
immediate: true,
buffer_bytes: options.buffer_bytes.map(saturating_i32),
},
)?;
#[cfg(not(windows))]
let capture = capture.setnonblock().map_err(|source| CaptureError::Open {
interface: name.to_owned(),
source,
})?;
let mut capture = capture;
let link = LinkType::from_dlt(capture.get_datalink().0);
if let LinkType::Unsupported(dlt) = link {
return Err(CaptureError::UnsupportedLinkType {
interface: name.to_owned(),
dlt,
});
}
let (filter, left_out) = options.filter.for_link(&capture)?;
capture
.filter(&filter, true)
.map_err(|source| CaptureError::Filter { filter, source })?;
Ok(Opened {
capture,
link,
warning,
left_out,
})
}
fn saturating_i32(bytes: u32) -> i32 {
i32::try_from(bytes).unwrap_or(i32::MAX)
}
fn reader_loop(
mut capture: Capture<Active>,
stop: &AtomicBool,
name: &str,
counters: &CaptureStats,
mut deliver: impl FnMut(&pcap::Packet<'_>) -> ControlFlow<()>,
) {
#[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 deliver(&packet).is_break() {
break;
}
}
Err(pcap::Error::TimeoutExpired) => {}
Err(e) => {
if ends_the_link(&e) {
counters.stopped_early.store(true, Ordering::Relaxed);
error!(
"capture on {name} stopped and will hear nothing further \
({e}); replies arriving on this link are lost from here on"
);
}
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, READ_TIMEOUT_MS);
}
}
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 ends_the_link(error: &pcap::Error) -> bool {
!matches!(
error,
pcap::Error::NoMorePackets | pcap::Error::TimeoutExpired
)
}
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, timeout_ms: i32) {
let mut poll_fd = libc::pollfd {
fd,
events: libc::POLLIN,
revents: 0,
};
unsafe { libc::poll(&mut poll_fd, 1, timeout_ms) };
}
pub struct FrameSender {
capture: Capture<Active>,
}
impl FrameSender {
pub fn open(link: &str) -> Result<Self, CaptureError> {
let (mut capture, _) = libpcap::activate(
link,
&libpcap::Setup {
snaplen: 1,
promiscuous: false,
timeout_ms: 1,
immediate: false,
buffer_bytes: None,
},
)?;
capture
.filter("less 0", true)
.map_err(|source| CaptureError::Open {
interface: link.to_owned(),
source,
})?;
Ok(Self { capture })
}
}
impl FrameSink for FrameSender {
fn send_frame(&mut self, frame: &[u8]) -> Result<(), String> {
self.capture.sendpacket(frame).map_err(|e| e.to_string())
}
}
pub trait FrameSink: Send {
fn send_frame(&mut self, frame: &[u8]) -> Result<(), String>;
}
pub struct FrameChannel {
capture: Capture<Active>,
#[cfg(not(windows))]
wait_ms: i32,
frame: Vec<u8>,
}
impl FrameChannel {
pub fn open(
link: &str,
filter: &str,
read_timeout: std::time::Duration,
) -> Result<Self, CaptureError> {
let wait_ms = i32::try_from(read_timeout.as_millis()).unwrap_or(i32::MAX);
let (capture, _) = libpcap::activate(
link,
&libpcap::Setup {
snaplen: saturating_i32(REPLY_SNAP_LEN),
promiscuous: false,
timeout_ms: wait_ms,
immediate: true,
buffer_bytes: None,
},
)?;
#[cfg(not(windows))]
let capture = capture.setnonblock().map_err(|source| CaptureError::Open {
interface: link.to_owned(),
source,
})?;
let mut capture = capture;
capture
.filter(filter, true)
.map_err(|source| CaptureError::Filter {
filter: filter.to_owned(),
source,
})?;
Ok(Self {
capture,
#[cfg(not(windows))]
wait_ms,
frame: Vec::new(),
})
}
pub fn next_frame(&mut self) -> Option<&[u8]> {
if self.read_one() {
return Some(&self.frame);
}
#[cfg(not(windows))]
{
wait_readable(self.capture.as_raw_fd(), self.wait_ms);
if self.read_one() {
return Some(&self.frame);
}
}
None
}
fn read_one(&mut self) -> bool {
match self.capture.next_packet() {
Ok(packet) => {
self.frame.clear();
self.frame.extend_from_slice(packet.data);
true
}
Err(_) => false,
}
}
}
impl FrameSink for FrameChannel {
fn send_frame(&mut self, frame: &[u8]) -> Result<(), String> {
self.capture.sendpacket(frame).map_err(|e| e.to_string())
}
}
mod libpcap {
use std::ffi::{CStr, CString, c_char, c_int};
use std::marker::{PhantomData, PhantomPinned};
use std::ptr::NonNull;
use pcap::{Active, Capture};
use super::{CaptureError, device_name};
#[repr(C)]
struct Handle {
_opaque: [u8; 0],
_unmovable: PhantomData<(*mut u8, PhantomPinned)>,
}
const ERRBUF_SIZE: usize = 256;
const PCAP_WARNING: c_int = 1;
const PCAP_WARNING_PROMISC_NOTSUP: c_int = 2;
const PCAP_WARNING_TSTAMP_TYPE_NOTSUP: c_int = 3;
pub(super) const PCAP_ERROR_NO_SUCH_DEVICE: c_int = -5;
pub(super) const PCAP_ERROR_PERM_DENIED: c_int = -8;
const PCAP_ERROR_IFACE_NOT_UP: c_int = -9;
pub(super) const PCAP_ERROR_PROMISC_PERM_DENIED: c_int = -11;
unsafe extern "C" {
fn pcap_create(source: *const c_char, errbuf: *mut c_char) -> *mut Handle;
fn pcap_set_snaplen(handle: *mut Handle, snaplen: c_int) -> c_int;
fn pcap_set_promisc(handle: *mut Handle, promisc: c_int) -> c_int;
fn pcap_set_timeout(handle: *mut Handle, to_ms: c_int) -> c_int;
fn pcap_set_immediate_mode(handle: *mut Handle, immediate: c_int) -> c_int;
fn pcap_set_buffer_size(handle: *mut Handle, buffer_size: c_int) -> c_int;
fn pcap_activate(handle: *mut Handle) -> c_int;
fn pcap_geterr(handle: *mut Handle) -> *mut c_char;
}
pub(super) struct Setup {
pub(super) snaplen: c_int,
pub(super) promiscuous: bool,
pub(super) timeout_ms: c_int,
pub(super) immediate: bool,
pub(super) buffer_bytes: Option<c_int>,
}
pub(super) fn activate(
link: &str,
setup: &Setup,
) -> Result<(Capture<Active>, Option<String>), CaptureError> {
let device = CString::new(device_name(link)).map_err(|_| CaptureError::Open {
interface: link.to_owned(),
source: pcap::Error::InvalidInputString,
})?;
let mut errbuf = [0 as c_char; ERRBUF_SIZE];
let created = unsafe { pcap_create(device.as_ptr(), errbuf.as_mut_ptr()) };
let Some(created) = NonNull::new(created) else {
let message = unsafe { CStr::from_ptr(errbuf.as_ptr()) };
return Err(CaptureError::Open {
interface: link.to_owned(),
source: pcap::Error::PcapError(message.to_string_lossy().into_owned()),
});
};
let capture: Capture<Active> = Capture::from(created.cast());
let handle = capture.as_ptr().cast::<Handle>();
unsafe {
pcap_set_snaplen(handle, setup.snaplen);
pcap_set_promisc(handle, c_int::from(setup.promiscuous));
pcap_set_timeout(handle, setup.timeout_ms);
pcap_set_immediate_mode(handle, c_int::from(setup.immediate));
if let Some(bytes) = setup.buffer_bytes {
pcap_set_buffer_size(handle, bytes);
}
}
let status = unsafe { pcap_activate(handle) };
let message = || status_message(handle, status);
match status {
0 => Ok((capture, None)),
warning if warning > 0 => Ok((capture, Some(message()))),
failure => Err(refusal(link, failure, message())),
}
}
pub(super) fn refusal(link: &str, status: c_int, message: String) -> CaptureError {
let source = pcap::Error::PcapError(message);
match status {
PCAP_ERROR_PERM_DENIED | PCAP_ERROR_PROMISC_PERM_DENIED => CaptureError::Denied {
interface: link.to_owned(),
source,
},
_ => CaptureError::Open {
interface: link.to_owned(),
source,
},
}
}
fn status_message(handle: *mut Handle, status: c_int) -> String {
let said = unsafe { CStr::from_ptr(pcap_geterr(handle)) }
.to_string_lossy()
.into_owned();
if !said.is_empty() {
return said;
}
match status {
PCAP_WARNING => "a generic warning".to_owned(),
PCAP_WARNING_PROMISC_NOTSUP => {
"this device does not support promiscuous mode".to_owned()
}
PCAP_WARNING_TSTAMP_TYPE_NOTSUP => {
"this device does not support the requested timestamp type".to_owned()
}
PCAP_ERROR_NO_SUCH_DEVICE => "no such device exists".to_owned(),
PCAP_ERROR_PERM_DENIED => "permission denied".to_owned(),
PCAP_ERROR_IFACE_NOT_UP => "the interface is not up".to_owned(),
PCAP_ERROR_PROMISC_PERM_DENIED => {
"permission denied to put it in promiscuous mode".to_owned()
}
other => format!("activation failed with status {other}"),
}
}
}
#[cfg(test)]
mod tests {
#[test]
fn a_refused_open_names_the_adapter_once_and_quotes_the_library() {
let guid = "{4D36E972-E325-11CE-BFC1-08002BE10318}";
let message = "Error opening adapter: Network interface was not found.";
let refused = CaptureError::Open {
interface: guid.to_owned(),
source: pcap::Error::PcapError(message.to_owned()),
};
assert_eq!(
refused.to_string(),
format!("{guid} could not be opened: {message}")
);
assert_eq!(refused.reason(), message, "the reason leaves the name out");
}
#[test]
fn only_a_refusal_libpcap_reports_as_denied_is_blamed_on_privilege() {
for status in [
libpcap::PCAP_ERROR_PERM_DENIED,
libpcap::PCAP_ERROR_PROMISC_PERM_DENIED,
] {
let refused =
libpcap::refusal("eth0", status, "socket: Operation not permitted".into());
assert!(refused.is_denied(), "status {status}");
assert!(refused.to_string().contains("privileges"), "{refused}");
}
for status in [libpcap::PCAP_ERROR_NO_SUCH_DEVICE, -1] {
let refused = libpcap::refusal("eth0", status, "no such device".into());
assert!(!refused.is_denied(), "status {status}");
assert!(!refused.to_string().contains("privilege"), "{refused}");
}
}
#[test]
fn a_capture_no_link_would_take_says_why_each_refused() {
let denied = |link: &str| CaptureError::Denied {
interface: link.to_owned(),
source: pcap::Error::PcapError("Operation not permitted".into()),
};
let filter = CaptureError::Filter {
filter: "ether dst 02:00:00:00:00:01".into(),
source: pcap::Error::PcapError(
"ethernet addresses supported only on ethernet/FDDI/token ring".into(),
),
};
let unprivileged = CaptureError::NoInterface {
refused: vec![
("eth0".into(), denied("eth0")),
("wg0".into(), denied("wg0")),
],
};
assert!(unprivileged.is_denied());
assert_eq!(
unprivileged.to_string(),
"no link could be captured on, so nothing could be heard: this process may \
not capture (opening a capture needs root)"
);
let root = CaptureError::NoInterface {
refused: vec![("wg0".into(), filter)],
};
assert!(!root.is_denied());
let said = root.to_string();
assert!(said.contains("wg0: the filter"), "{said}");
assert!(said.contains("ethernet addresses"), "{said}");
assert!(
!said.contains("root") && !said.contains("privilege"),
"{said}"
);
let mixed = CaptureError::NoInterface {
refused: vec![
("eth0".into(), denied("eth0")),
(
"gre1".into(),
CaptureError::UnsupportedLinkType {
interface: "gre1".into(),
dlt: 778,
},
),
],
};
assert!(
!mixed.is_denied(),
"privilege would not have made gre1 parseable"
);
let said = mixed.to_string();
assert!(
said.contains("eth0: this process lacks the privileges"),
"{said}"
);
assert!(
said.contains("gre1: it carries data-link type 778"),
"{said}"
);
}
#[test]
fn a_capture_that_could_not_open_blames_privilege_only_when_it_was_denied() {
let link = Zone::unresolved("zondnone0");
let refused = frames(
std::slice::from_ref(&link),
&CaptureOptions::for_replies("tcp"),
1,
)
.err()
.expect("no such link can be captured on");
let said = refused.to_string();
assert_eq!(said.contains("needs root"), refused.is_denied(), "{said}");
if !refused.is_denied() {
assert!(said.contains("zondnone0"), "{said}");
assert!(!said.contains("privilege"), "{said}");
}
}
fn link_of(dlt: i32) -> Capture<pcap::Dead> {
Capture::dead(pcap::Linktype(dlt)).expect("a dead capture")
}
const RAW: i32 = 12;
#[test]
fn alternatives_are_narrowed_to_what_a_link_can_express() {
let filter = CaptureFilter::any_of(["(ether dst 01:00:0c:cc:cc:cc)", "(tcp)"]);
let (expression, left_out) = filter.for_link(&link_of(RAW)).expect("tcp compiles");
assert_eq!(expression, "(tcp)");
assert_eq!(left_out, ["(ether dst 01:00:0c:cc:cc:cc)"]);
let (expression, left_out) = filter
.for_link(&link_of(1))
.expect("Ethernet expresses both");
assert_eq!(expression, "(ether dst 01:00:0c:cc:cc:cc) or (tcp)");
assert!(left_out.is_empty());
}
#[test]
fn a_clause_no_link_can_express_is_refused_rather_than_left_out() {
let filter = CaptureFilter::any_of(["(tcp)", "(ether dts 01:00:0c:cc:cc:cc)"]);
for dlt in [RAW, 1] {
match filter.for_link(&link_of(dlt)) {
Err(CaptureError::Filter { filter, .. }) => {
assert_eq!(filter, "(ether dts 01:00:0c:cc:cc:cc)");
}
other => panic!("a malformed clause was accepted on {dlt}: {other:?}"),
}
}
}
#[test]
fn a_link_that_can_express_no_alternative_is_refused() {
let filter =
CaptureFilter::any_of(["(ether dst 01:00:0c:cc:cc:cc)", "(ether proto 0x88cc)"]);
match filter.for_link(&link_of(RAW)) {
Err(CaptureError::Filter { filter: named, .. }) => {
assert_eq!(named, filter.to_string());
}
other => panic!("a filter admitting nothing was accepted: {other:?}"),
}
}
#[test]
fn an_expression_is_never_narrowed() {
let written = "tcp and ether src 02:00:00:00:00:01";
let (expression, left_out) = CaptureFilter::from(written)
.for_link(&link_of(RAW))
.expect("an expression is handed on as written");
assert_eq!(expression, written);
assert!(left_out.is_empty());
assert!(
link_of(RAW).compile(&expression, true).is_err(),
"and the link then refuses it whole"
);
}
#[test]
fn a_frame_channel_bounds_its_wait_itself_rather_than_trusting_libpcap() {
let Some(loopback) = crate::system::interface::interfaces()
.into_iter()
.find(|link| link.is_loopback())
else {
return;
};
let timeout = Duration::from_millis(50);
let mut channel = match FrameChannel::open(loopback.name(), "less 0", timeout) {
Ok(channel) => channel,
Err(refused) if refused.is_denied() => return,
Err(refused) => panic!("the loopback would not open: {refused}"),
};
#[cfg(not(windows))]
assert!(
channel.capture.is_nonblock(),
"a blocking read is bounded by nothing on Linux"
);
let started = Instant::now();
assert_eq!(channel.next_frame(), None, "`less 0` admits nothing");
let waited = started.elapsed();
assert!(
waited >= timeout / 2 && waited < Duration::from_secs(1),
"a {timeout:?} wait took {waited:?}"
);
}
#[test]
fn a_failed_link_is_told_aloud_only_when_answers_depend_on_it() {
assert_eq!(loudness(false, false), Loudness::Quiet, "a spare adapter");
assert_eq!(
loudness(false, true),
Loudness::Aloud,
"the link off-segment targets answer through"
);
assert_eq!(
loudness(true, false),
Loudness::Quiet,
"no link heard at all, which the error says"
);
assert_eq!(
loudness(true, true),
Loudness::Quiet,
"nor the default route's, when the error names it too"
);
}
#[test]
fn a_failed_link_is_told_about_once_unless_it_comes_to_matter_more() {
let mut told = Told::new();
let guid = "{4D36E972-E325-11CE-BFC1-08002BE10318}";
assert!(told.first_time(guid, Loudness::Quiet));
assert!(
!told.first_time(guid, Loudness::Quiet),
"a second transport"
);
assert!(told.first_time(guid, Loudness::Aloud), "now it matters");
assert!(!told.first_time(guid, Loudness::Aloud));
assert!(
!told.first_time(guid, Loudness::Quiet),
"said louder already"
);
assert!(told.first_time("eth1", Loudness::Quiet), "another link");
}
#[test]
fn an_adapter_guid_is_named_the_way_npcap_names_it() {
let guid = "{4D36E972-E325-11CE-BFC1-08002BE10318}";
assert_eq!(npcap_device_name(guid), format!("\\Device\\NPF_{guid}"));
assert_eq!(
npcap_device_name(&format!("\\Device\\NPF_{guid}")),
format!("\\Device\\NPF_{guid}"),
"a name already in Npcap's form is left alone"
);
assert_eq!(npcap_device_name("en0"), "en0");
}
#[test]
fn a_segment_is_stamped_before_it_is_queued() {
use std::net::Ipv4Addr;
use pnet_packet::ip::IpNextHeaderProtocols;
let before = Instant::now();
let segment = CapturedSegment::synthetic(
IpAddr::V4(Ipv4Addr::LOCALHOST),
IpNextHeaderProtocols::Tcp,
vec![0; 20],
);
let after = Instant::now();
assert!(segment.received_at >= before && segment.received_at <= after);
}
use super::*;
#[test]
fn a_snapshot_length_too_short_to_read_a_reply_is_raised_to_one_that_can() {
for asked in [0, 1, MIN_SNAP_LEN - 1] {
let options = CaptureOptions::for_replies("tcp").with_snaplen(asked);
assert_eq!(
options.snaplen, MIN_SNAP_LEN,
"a snapshot length of {asked} reached libpcap"
);
}
for asked in [MIN_SNAP_LEN, MIN_SNAP_LEN + 1, REPLY_SNAP_LEN] {
assert_eq!(
CaptureOptions::for_replies("tcp")
.with_snaplen(asked)
.snaplen,
asked
);
}
}
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,
stopped_early: 0,
})
);
}
#[test]
fn a_capture_that_ran_out_of_packets_did_not_lose_its_link() {
assert!(!ends_the_link(&pcap::Error::NoMorePackets));
assert!(!ends_the_link(&pcap::Error::TimeoutExpired));
for failure in [
pcap::Error::PcapError("the device went away".to_string()),
pcap::Error::InvalidString,
pcap::Error::IoError(std::io::ErrorKind::PermissionDenied),
] {
assert!(
ends_the_link(&failure),
"{failure:?} left the link readable"
);
}
}
#[test]
fn a_capture_that_stopped_early_is_counted_as_one() {
let lasted = stats_of(100, 0, 0);
let stopped = stats_of(4, 0, 0);
stopped.stopped_early.store(true, Ordering::Relaxed);
assert_eq!(lasted.snapshot().stopped_early, 0);
assert_eq!(stopped.snapshot().stopped_early, 1);
let guard = guard_over(vec![lasted, stopped, stats_of(7, 0, 0)]);
let counts = guard.counts().expect("three captures");
assert_eq!(counts.stopped_early, 1);
assert_eq!(counts.received, 111, "the frames they did hear still count");
let all_stopped: Vec<_> = (0..3)
.map(|_| {
let stats = stats_of(1, 0, 0);
stats.stopped_early.store(true, Ordering::Relaxed);
stats
})
.collect();
assert_eq!(
guard_over(all_stopped)
.counts()
.expect("three captures")
.stopped_early,
3
);
}
#[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,
stopped_early: 0,
}
);
}
#[test]
fn a_panicked_reader_is_visible_in_the_counts_while_the_guard_is_alive() {
let counters = Arc::new(CaptureStats::default());
let handle = spawn_reader("test0", Arc::clone(&counters), |_| {
panic!("a reader died the way a defect kills one")
})
.expect("a thread starts");
let guard = CaptureGuard {
stop: Arc::new(AtomicBool::new(false)),
handles: vec![handle],
stats: vec![counters],
};
while !guard.handles[0].is_finished() {
std::thread::sleep(Duration::from_millis(1));
}
assert_eq!(
guard.counts().expect("one capture").stopped_early,
1,
"a dead reader is reported only once nobody is reading any more"
);
}
#[test]
fn a_capture_thread_that_finished_is_not_recorded_as_stopping_early() {
let counters = Arc::new(CaptureStats::default());
let guard = CaptureGuard {
stop: Arc::new(AtomicBool::new(false)),
handles: vec![
spawn_reader("test0", Arc::clone(&counters), |_| {}).expect("a thread starts"),
],
stats: vec![Arc::clone(&counters)],
};
drop(guard);
assert!(!counters.stopped_early.load(Ordering::Relaxed));
}
}