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, Device};
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"
);
#[must_use]
#[derive(Debug, Clone)]
pub struct CaptureOptions {
filter: String,
snaplen: u32,
promiscuous: bool,
buffer_bytes: Option<u32>,
}
impl CaptureOptions {
pub fn for_replies(filter: impl Into<String>) -> Self {
Self {
filter: filter.into(),
snaplen: REPLY_SNAP_LEN,
promiscuous: false,
buffer_bytes: None,
}
}
pub fn for_link_traffic(filter: impl Into<String>) -> 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
}
}
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 interface could be captured for replies, so no answer could be heard \
(opening a capture needs root)"
)]
NoInterface,
#[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,
},
}
impl CaptureError {
fn reason(&self) -> String {
match self {
Self::Open { source, .. } => library_message(source).into_owned(),
Self::UnsupportedLinkType { dlt, .. } => {
format!("it carries data-link type {dlt}, which nothing here parses")
}
other => other.to_string(),
}
}
}
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((capture, link)) => {
info!(verbosity = 3, "capturing on {name} (link type {link:?})");
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,
});
}
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 every_link_failed || carries_default_route {
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: &str) -> Device {
#[cfg(windows)]
{
Device::from(npcap_device_name(name).as_str())
}
#[cfg(not(windows))]
{
Device::from(name)
}
}
#[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()
}
}
fn open(name: &str, options: &CaptureOptions) -> Result<(Capture<Active>, LinkType), CaptureError> {
let refused = |source: pcap::Error| CaptureError::Open {
interface: name.to_owned(),
source,
};
let mut inactive = Capture::from_device(device(name))
.map_err(refused)?
.immediate_mode(true)
.promisc(options.promiscuous)
.snaplen(saturating_i32(options.snaplen))
.timeout(READ_TIMEOUT_MS);
if let Some(bytes) = options.buffer_bytes {
inactive = inactive.buffer_size(saturating_i32(bytes));
}
let capture = inactive.open().map_err(refused)?;
#[cfg(not(windows))]
let capture = capture.setnonblock().map_err(refused)?;
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,
});
}
capture
.filter(&options.filter, true)
.map_err(|source| CaptureError::Filter {
filter: options.filter.clone(),
source,
})?;
Ok((capture, link))
}
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);
}
}
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) {
let mut poll_fd = libc::pollfd {
fd,
events: libc::POLLIN,
revents: 0,
};
unsafe { libc::poll(&mut poll_fd, 1, READ_TIMEOUT_MS) };
}
pub struct FrameSender {
capture: Capture<Active>,
}
impl FrameSender {
pub fn open(link: &str) -> Result<Self, CaptureError> {
let mut capture = Capture::from_device(device(link))
.and_then(|inactive| inactive.snaplen(1).timeout(1).open())
.map_err(|source| CaptureError::Open {
interface: link.to_owned(),
source,
})?;
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>,
}
impl FrameChannel {
pub fn open(
link: &str,
filter: &str,
read_timeout: std::time::Duration,
) -> Result<Self, CaptureError> {
let millis = i32::try_from(read_timeout.as_millis()).unwrap_or(i32::MAX);
let mut capture = Capture::from_device(device(link))
.and_then(|inactive| {
inactive
.immediate_mode(true)
.snaplen(saturating_i32(REPLY_SNAP_LEN))
.timeout(millis)
.open()
})
.map_err(|source| CaptureError::Open {
interface: link.to_owned(),
source,
})?;
capture
.filter(filter, true)
.map_err(|source| CaptureError::Open {
interface: link.to_owned(),
source,
})?;
Ok(Self { capture })
}
pub fn next_frame(&mut self) -> Option<&[u8]> {
match self.capture.next_packet() {
Ok(packet) => Some(packet.data),
Err(_) => None,
}
}
}
impl FrameSink for FrameChannel {
fn send_frame(&mut self, frame: &[u8]) -> Result<(), String> {
self.capture.sendpacket(frame).map_err(|e| e.to_string())
}
}
#[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 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::Aloud,
"no link heard at all"
);
}
#[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));
}
}