use std::collections::HashMap;
use std::net::{IpAddr, Ipv4Addr};
use std::panic::{RefUnwindSafe, UnwindSafe};
use std::sync::{Arc, Condvar, Mutex, MutexGuard};
use std::time::{Duration, Instant};
use crate::model::mac::MacAddr;
use crate::protocols::mac::IntoCoreMac;
use pnet_packet::Packet;
use pnet_packet::arp::{ArpOperations, ArpPacket};
use pnet_packet::ethernet::{EtherTypes, EthernetPacket};
use crate::protocols::arp;
use crate::transport::capture::{self, FrameSink};
use crate::transport::kernel_neighbors::NeighborState;
use crate::transport::neighbor;
use crate::transport::probe::SendError;
pub(crate) const ARP_TIMEOUT: Duration = Duration::from_secs(3);
const ARP_REQUESTS: u32 = 3;
const NEIGHBOR_UNREACHABLE_TTL: Duration = Duration::from_secs(30);
const CHANNEL_READ_TIMEOUT: Duration = Duration::from_millis(50);
const WAIT_GUARD: Duration = Duration::from_secs(10);
pub(super) trait ResolutionLink: FrameSink {
fn next_frame(&mut self) -> Option<&[u8]>;
fn now(&self) -> Instant {
Instant::now()
}
}
impl ResolutionLink for capture::FrameChannel {
fn next_frame(&mut self) -> Option<&[u8]> {
capture::FrameChannel::next_frame(self)
}
}
pub(super) type Opener = Box<
dyn Fn(&str) -> Result<Box<dyn ResolutionLink>, String>
+ Send
+ Sync
+ UnwindSafe
+ RefUnwindSafe,
>;
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct Ask {
pub(crate) interface: String,
pub(crate) src_mac: MacAddr,
pub(crate) src_ip: Ipv4Addr,
pub(crate) target: Ipv4Addr,
}
impl Ask {
fn requests(&self) -> Vec<Vec<u8>> {
let broadcast = arp::build_request(self.src_mac, self.src_ip, self.target);
match neighbor::heard_neighbor(&self.interface, IpAddr::V4(self.target)) {
Some(heard) => vec![
arp::build_unicast_request(self.src_mac, heard, self.src_ip, self.target),
broadcast,
],
None => vec![broadcast],
}
}
}
pub(crate) struct Resolutions {
state: Mutex<State>,
concluded: Condvar,
open: Opener,
}
#[derive(Default)]
struct State {
links: HashMap<String, LinkResolutions>,
unanswered: UnansweredNeighbors,
}
#[derive(Default)]
struct LinkResolutions {
pending: HashMap<Ipv4Addr, Pending>,
driven: bool,
refused: HashMap<Ipv4Addr, String>,
}
struct Pending {
requests: Vec<Vec<u8>>,
started: Option<Instant>,
sent: u32,
}
impl Resolutions {
pub(crate) fn from_system() -> Self {
Self::over(Box::new(|interface| {
capture::FrameChannel::open(interface, "arp", CHANNEL_READ_TIMEOUT)
.map(|channel| Box::new(channel) as Box<dyn ResolutionLink>)
.map_err(|error| format!("no datalink channel on {interface}: {error}"))
}))
}
pub(super) fn over(open: Opener) -> Self {
Self {
state: Mutex::new(State::default()),
concluded: Condvar::new(),
open,
}
}
pub(crate) fn state(self: &Arc<Self>, ask: &Ask) -> Option<NeighborState> {
let target = IpAddr::V4(ask.target);
if neighbor::learned_neighbor(&ask.interface, target).is_some() {
return Some(NeighborState::Resolved);
}
let mut state = self.lock();
if state
.unanswered
.is_fresh(&ask.interface, target, Instant::now())
{
return Some(NeighborState::Failed);
}
let link = state.links.entry(ask.interface.clone()).or_default();
if link.pending.contains_key(&ask.target) {
return Some(NeighborState::Resolving);
}
if link.refused.contains_key(&ask.target) {
return None;
}
drop(self.begin(state, ask));
Some(NeighborState::Resolving)
}
pub(crate) fn ask_again(self: &Arc<Self>, ask: &Ask) -> Option<NeighborState> {
self.lock()
.unanswered
.clear(&ask.interface, IpAddr::V4(ask.target));
self.state(ask)
}
pub(crate) fn resolve(self: &Arc<Self>, ask: &Ask) -> Result<MacAddr, SendError> {
let target = IpAddr::V4(ask.target);
let give_up = Instant::now() + WAIT_GUARD;
let mut state = self.lock();
let link = state.links.entry(ask.interface.clone()).or_default();
if !link.pending.contains_key(&ask.target) {
link.refused.remove(&ask.target);
}
loop {
if let Some(mac) = neighbor::learned_neighbor(&ask.interface, target) {
return Ok(mac);
}
if state
.unanswered
.is_fresh(&ask.interface, target, Instant::now())
{
return Err(unanswered_neighbor(target, &ask.interface));
}
let link = state.links.entry(ask.interface.clone()).or_default();
if let Some(reason) = link.refused.get(&ask.target) {
return Err(SendError::Refused(format!(
"sending an ARP request: {reason}"
)));
}
if !link.pending.contains_key(&ask.target) {
state = self.begin(state, ask);
}
let left = give_up.saturating_duration_since(Instant::now());
if left.is_zero() {
return Err(SendError::Refused(format!(
"the address resolution of {target} on {} did not conclude",
ask.interface
)));
}
state = self
.concluded
.wait_timeout(state, left)
.unwrap_or_else(|held| held.into_inner())
.0;
}
}
fn begin<'a>(
self: &'a Arc<Self>,
mut state: MutexGuard<'a, State>,
ask: &Ask,
) -> MutexGuard<'a, State> {
let link = state.links.entry(ask.interface.clone()).or_default();
link.refused.remove(&ask.target);
link.pending.insert(
ask.target,
Pending {
requests: ask.requests(),
started: None,
sent: 0,
},
);
if link.driven {
return state;
}
link.driven = true;
let resolutions = Arc::clone(self);
let interface = ask.interface.clone();
let spawned = std::thread::Builder::new()
.name(format!("zond-arp-{interface}"))
.spawn(move || resolutions.drive_link(&interface));
if let Err(error) = spawned {
let link = state.links.entry(ask.interface.clone()).or_default();
refuse_all(link, &format!("no thread to resolve on: {error}"));
self.concluded.notify_all();
}
state
}
fn drive_link(&self, interface: &str) {
let _released = UndrivenOnUnwind {
resolutions: self,
interface,
};
match (self.open)(interface) {
Ok(mut link) => self.drive(interface, link.as_mut()),
Err(reason) => {
let mut state = self.lock();
let link = state.links.entry(interface.to_owned()).or_default();
refuse_all(link, &reason);
link.driven = false;
drop(state);
self.concluded.notify_all();
}
}
}
fn drive<L: ResolutionLink + ?Sized>(&self, interface: &str, link: &mut L) {
loop {
let now = link.now();
let (due, concluded, idle) = {
let mut state = self.lock();
let State { links, unanswered } = &mut *state;
let resolutions = links.entry(interface.to_owned()).or_default();
let step = step(&mut resolutions.pending, now);
for target in &step.unanswered {
unanswered.note(interface, IpAddr::V4(*target), now);
}
let idle = resolutions.pending.is_empty();
if idle {
resolutions.driven = false;
}
(step.due, !step.unanswered.is_empty(), idle)
};
if concluded {
self.concluded.notify_all();
}
if idle {
return;
}
for frame in &due {
if let Err(reason) = link.send_frame(frame) {
let mut state = self.lock();
let resolutions = state.links.entry(interface.to_owned()).or_default();
refuse_all(resolutions, &reason);
resolutions.driven = false;
drop(state);
self.concluded.notify_all();
return;
}
}
let Some((address, mac)) = link.next_frame().and_then(parse_arp_reply) else {
continue; };
let mut state = self.lock();
let resolutions = state.links.entry(interface.to_owned()).or_default();
if resolutions.pending.remove(&address).is_some() {
neighbor::learn_neighbor(interface, IpAddr::V4(address), mac);
state.unanswered.clear(interface, IpAddr::V4(address));
drop(state);
self.concluded.notify_all();
}
}
}
fn lock(&self) -> MutexGuard<'_, State> {
self.state.lock().unwrap_or_else(|held| held.into_inner())
}
}
struct UndrivenOnUnwind<'a> {
resolutions: &'a Resolutions,
interface: &'a str,
}
impl Drop for UndrivenOnUnwind<'_> {
fn drop(&mut self) {
if !std::thread::panicking() {
return;
}
let mut state = self.resolutions.lock();
let link = state.links.entry(self.interface.to_owned()).or_default();
refuse_all(link, "the thread resolving on the link panicked");
link.driven = false;
drop(state);
self.resolutions.concluded.notify_all();
}
}
struct Step {
due: Vec<Vec<u8>>,
unanswered: Vec<Ipv4Addr>,
}
fn step(pending: &mut HashMap<Ipv4Addr, Pending>, now: Instant) -> Step {
let spacing = ARP_TIMEOUT / ARP_REQUESTS;
let mut due = Vec::new();
let mut unanswered = Vec::new();
for (target, resolution) in pending.iter_mut() {
let started = *resolution.started.get_or_insert(now);
let elapsed = now.saturating_duration_since(started);
if elapsed >= ARP_TIMEOUT {
unanswered.push(*target);
} else if resolution.sent < ARP_REQUESTS && elapsed >= spacing * resolution.sent {
due.extend(resolution.requests.iter().cloned());
resolution.sent += 1;
}
}
for target in &unanswered {
pending.remove(target);
}
Step { due, unanswered }
}
fn refuse_all(link: &mut LinkResolutions, reason: &str) {
for (target, _) in link.pending.drain() {
link.refused.insert(target, reason.to_owned());
}
}
#[derive(Default)]
struct UnansweredNeighbors {
seen: HashMap<(String, IpAddr), Instant>,
}
impl UnansweredNeighbors {
fn note(&mut self, interface: &str, next_hop: IpAddr, at: Instant) {
self.seen.insert((interface.to_string(), next_hop), at);
}
fn clear(&mut self, interface: &str, next_hop: IpAddr) {
self.seen.remove(&(interface.to_string(), next_hop));
}
fn is_fresh(&self, interface: &str, next_hop: IpAddr, now: Instant) -> bool {
self.seen
.get(&(interface.to_string(), next_hop))
.is_some_and(|at| now.saturating_duration_since(*at) < NEIGHBOR_UNREACHABLE_TTL)
}
}
pub(super) fn unanswered_neighbor(next_hop: IpAddr, interface: &str) -> SendError {
SendError::Unresolved(format!(
"{next_hop} did not answer address resolution on {interface}"
))
}
fn parse_arp_reply(frame: &[u8]) -> Option<(Ipv4Addr, MacAddr)> {
let eth = EthernetPacket::new(frame)?;
if eth.get_ethertype() != EtherTypes::Arp {
return None;
}
let arp = ArpPacket::new(eth.payload())?;
(arp.get_operation() == ArpOperations::Reply).then(|| {
(
arp.get_sender_proto_addr(),
arp.get_sender_hw_addr().into_core(),
)
})
}
#[cfg(test)]
pub(crate) mod tests {
use super::*;
use crate::protocols::mac::IntoPnetMac;
use pnet_packet::arp::{ArpHardwareTypes, MutableArpPacket};
use pnet_packet::ethernet::MutableEthernetPacket;
const LOCAL_MAC: MacAddr = MacAddr::new(0x02, 0, 0, 0, 0, 0x01);
const LOCAL_IP: Ipv4Addr = Ipv4Addr::new(192, 0, 2, 1);
pub(crate) fn arp_reply(sender_ip: Ipv4Addr, sender_mac: MacAddr) -> Vec<u8> {
let mut buf = vec![0u8; 42];
{
let mut eth = MutableEthernetPacket::new(&mut buf[..14]).unwrap();
eth.set_ethertype(EtherTypes::Arp);
eth.set_source(sender_mac.into_pnet());
eth.set_destination(LOCAL_MAC.into_pnet());
}
{
let mut a = MutableArpPacket::new(&mut buf[14..]).unwrap();
a.set_hardware_type(ArpHardwareTypes::Ethernet);
a.set_protocol_type(EtherTypes::Ipv4);
a.set_hw_addr_len(6);
a.set_proto_addr_len(4);
a.set_operation(ArpOperations::Reply);
a.set_sender_hw_addr(sender_mac.into_pnet());
a.set_sender_proto_addr(sender_ip);
a.set_target_proto_addr(LOCAL_IP);
}
buf
}
pub(crate) fn ask(interface: &str, target: Ipv4Addr) -> Ask {
Ask {
interface: interface.to_owned(),
src_mac: LOCAL_MAC,
src_ip: LOCAL_IP,
target,
}
}
const QUIET_READ: Duration = Duration::from_millis(5);
#[derive(Clone, Copy)]
pub(crate) enum Answers {
Request(u32),
After(Duration),
OnlyAddressed,
AwakeFrom(Instant),
}
pub(crate) struct Segment {
neighbours: HashMap<Ipv4Addr, (MacAddr, Answers)>,
pub(crate) asked: HashMap<Ipv4Addr, Vec<(Duration, bool)>>,
replies: Vec<(Duration, Vec<u8>)>,
reply: Vec<u8>,
epoch: Instant,
pub(crate) clock: Duration,
real_time: bool,
}
impl Segment {
pub(crate) fn new() -> Self {
Self {
neighbours: HashMap::new(),
asked: HashMap::new(),
replies: Vec::new(),
reply: Vec::new(),
epoch: Instant::now(),
clock: Duration::ZERO,
real_time: false,
}
}
pub(crate) fn in_real_time(mut self) -> Self {
self.real_time = true;
self
}
pub(crate) fn with(mut self, ip: Ipv4Addr, mac: MacAddr, answers: Answers) -> Self {
self.neighbours.insert(ip, (mac, answers));
self
}
fn requests_to(&self, ip: Ipv4Addr) -> u32 {
self.asked.get(&ip).map_or(0, |sent| sent.len() as u32)
}
fn elapsed(&self) -> Duration {
self.now().saturating_duration_since(self.epoch)
}
}
impl FrameSink for Segment {
fn send_frame(&mut self, frame: &[u8]) -> Result<(), String> {
let eth = EthernetPacket::new(frame).expect("a frame");
let request = ArpPacket::new(eth.payload()).expect("an ARP request");
let target = request.get_target_proto_addr();
let addressed = eth.get_destination().into_core() != MacAddr::BROADCAST;
let at = self.elapsed();
self.asked.entry(target).or_default().push((at, addressed));
let Some(&(mac, answers)) = self.neighbours.get(&target) else {
return Ok(());
};
let asked = self.requests_to(target);
let answer_at = match answers {
Answers::Request(n) => (asked == n).then_some(at),
Answers::After(delay) => (asked == 1).then_some(at + delay),
Answers::OnlyAddressed => {
let first_addressed = self.asked[&target]
.iter()
.filter(|(_, addressed)| *addressed)
.count()
== 1;
(addressed && first_addressed).then_some(at)
}
Answers::AwakeFrom(awake) => (self.now() >= awake).then_some(at),
};
if let Some(at) = answer_at {
self.replies.push((at, arp_reply(target, mac)));
}
Ok(())
}
}
impl ResolutionLink for Segment {
fn next_frame(&mut self) -> Option<&[u8]> {
let now = self.elapsed();
if let Some(ready) = self.replies.iter().position(|(at, _)| *at <= now) {
self.reply = self.replies.remove(ready).1;
return Some(&self.reply);
}
if self.real_time {
std::thread::sleep(QUIET_READ);
} else {
self.clock += QUIET_READ;
}
None
}
fn now(&self) -> Instant {
if self.real_time {
Instant::now()
} else {
self.epoch + self.clock
}
}
}
fn undriven() -> Arc<Resolutions> {
Arc::new(Resolutions::over(Box::new(|interface| {
Err(format!("{interface} is driven by the test"))
})))
}
fn queue(resolutions: &Arc<Resolutions>, asks: &[Ask]) {
for ask in asks {
let mut state = resolutions.lock();
state.links.entry(ask.interface.clone()).or_default().driven = true;
drop(resolutions.begin(state, ask));
}
}
#[test]
fn a_neighbour_that_hears_a_broadcast_only_at_its_next_beacon_is_resolved() {
let interface = "test-doze0";
let dozing = Ipv4Addr::new(192, 0, 2, 20);
let mac = MacAddr::new(0x02, 0, 0, 0, 0, 0x20);
let resolutions = undriven();
let mut segment =
Segment::new().with(dozing, mac, Answers::After(Duration::from_millis(627)));
queue(&resolutions, &[ask(interface, dozing)]);
resolutions.drive(interface, &mut segment);
assert_eq!(
neighbor::learned_neighbor(interface, IpAddr::V4(dozing)),
Some(mac)
);
assert_eq!(
resolutions.state(&ask(interface, dozing)),
Some(NeighborState::Resolved)
);
}
#[test]
fn neighbours_that_never_answer_cost_one_timeout_together() {
let interface = "test-dead0";
let dead: Vec<Ipv4Addr> = (10..=209).map(|n| Ipv4Addr::new(192, 0, 2, n)).collect();
let resolutions = undriven();
let mut segment = Segment::new();
let asks: Vec<Ask> = dead.iter().map(|ip| ask(interface, *ip)).collect();
queue(&resolutions, &asks);
resolutions.drive(interface, &mut segment);
assert!(
segment.clock >= ARP_TIMEOUT && segment.clock < ARP_TIMEOUT + QUIET_READ,
"{} dead neighbours cost {:?}",
dead.len(),
segment.clock
);
let spacing = ARP_TIMEOUT / ARP_REQUESTS;
for ip in &dead {
let sent = &segment.asked[ip];
assert_eq!(sent.len() as u32, ARP_REQUESTS, "{ip} asked on schedule");
for (n, (at, _)) in sent.iter().enumerate() {
let due = spacing * n as u32;
assert!(
*at >= due && *at < due + QUIET_READ,
"{ip}'s request due at {due:?} went out at {at:?}"
);
}
assert_eq!(
resolutions.state(&ask(interface, *ip)),
Some(NeighborState::Failed),
"{ip} given up"
);
}
}
#[test]
fn a_neighbour_answering_only_a_later_request_is_resolved() {
let mac = MacAddr::new(0x02, 0, 0, 0, 0, 0xc8);
for answers in 2..=ARP_REQUESTS.max(2) {
let interface = format!("test-lossy{answers}");
let ip = Ipv4Addr::new(192, 0, 2, 200);
let resolutions = undriven();
let mut segment = Segment::new().with(ip, mac, Answers::Request(answers));
queue(&resolutions, &[ask(&interface, ip)]);
resolutions.drive(&interface, &mut segment);
assert_eq!(
neighbor::learned_neighbor(&interface, IpAddr::V4(ip)),
Some(mac),
"answering request {answers}"
);
assert_eq!(segment.requests_to(ip), answers, "and asked no further");
}
}
#[test]
fn a_neighbour_heard_before_is_also_asked_at_its_own_address() {
let interface = "test-heard2";
let ip = Ipv4Addr::new(192, 0, 2, 30);
let mac = MacAddr::new(0x02, 0, 0, 0, 0, 0x30);
let resolutions = undriven();
let mut segment = Segment::new().with(ip, mac, Answers::OnlyAddressed);
queue(&resolutions, &[ask(interface, ip)]);
resolutions.drive(interface, &mut segment);
assert_eq!(
segment.asked[&ip].iter().filter(|(_, to)| *to).count(),
0,
"a neighbour never heard from has no address to ask at"
);
assert!(neighbor::learned_neighbor(interface, IpAddr::V4(ip)).is_none());
neighbor::learn_neighbor_at(
interface,
IpAddr::V4(ip),
mac,
Instant::now() - Duration::from_secs(3600),
);
assert!(neighbor::learned_neighbor(interface, IpAddr::V4(ip)).is_none());
let resolutions = undriven();
let mut segment = Segment::new().with(ip, mac, Answers::OnlyAddressed);
queue(&resolutions, &[ask(interface, ip)]);
resolutions.drive(interface, &mut segment);
assert_eq!(
neighbor::learned_neighbor(interface, IpAddr::V4(ip)),
Some(mac)
);
assert_eq!(
segment.asked[&ip],
vec![(Duration::ZERO, true), (Duration::ZERO, false)],
"asked at its own address, and by broadcast beside it"
);
}
#[test]
fn a_dead_neighbour_is_asked_once_and_refused_after() {
let interface = "test-dead1";
let ip = Ipv4Addr::new(192, 0, 2, 40);
let resolutions = undriven();
let mut segment = Segment::new();
queue(&resolutions, &[ask(interface, ip)]);
resolutions.drive(interface, &mut segment);
for _ in 0..5 {
assert_eq!(
resolutions.state(&ask(interface, ip)),
Some(NeighborState::Failed)
);
assert!(matches!(
resolutions.resolve(&ask(interface, ip)),
Err(SendError::Unresolved(_))
));
}
assert!(
resolutions.lock().links[interface].pending.is_empty(),
"nothing asked again"
);
}
#[test]
fn a_link_that_will_not_open_refuses_without_writing_anyone_off() {
let interface = "test-shut0";
let ip = Ipv4Addr::new(192, 0, 2, 50);
let resolutions = undriven();
assert!(matches!(
resolutions.resolve(&ask(interface, ip)),
Err(SendError::Refused(_))
));
assert_eq!(resolutions.state(&ask(interface, ip)), None);
assert!(
!resolutions
.lock()
.unanswered
.is_fresh(interface, IpAddr::V4(ip), Instant::now()),
"a refusal is not an unanswered neighbour"
);
}
#[test]
fn a_neighbour_a_sweep_heard_is_not_asked_again() {
let interface = "test-heard0";
let ip = Ipv4Addr::new(192, 0, 2, 31);
let mac = MacAddr::new(0x02, 0, 0, 0, 0, 0x31);
let resolutions = undriven();
resolutions
.lock()
.unanswered
.note(interface, IpAddr::V4(ip), Instant::now());
neighbor::learn_neighbor(interface, IpAddr::V4(ip), mac);
assert_eq!(resolutions.resolve(&ask(interface, ip)).ok(), Some(mac));
assert_eq!(
resolutions.state(&ask(interface, ip)),
Some(NeighborState::Resolved)
);
}
#[test]
fn a_resolution_one_sender_ran_serves_the_next() {
let interface = "test-heard1";
let ip = Ipv4Addr::new(192, 0, 2, 32);
let mac = MacAddr::new(0x02, 0, 0, 0, 0, 0x32);
let first = undriven();
let mut segment = Segment::new().with(ip, mac, Answers::Request(1));
queue(&first, &[ask(interface, ip)]);
first.drive(interface, &mut segment);
let second = undriven();
assert_eq!(second.resolve(&ask(interface, ip)).ok(), Some(mac));
}
struct Panicking;
impl FrameSink for Panicking {
fn send_frame(&mut self, _frame: &[u8]) -> Result<(), String> {
panic!("the link's driver panics, as the test asks");
}
}
impl ResolutionLink for Panicking {
fn next_frame(&mut self) -> Option<&[u8]> {
None
}
}
#[test]
fn a_driver_that_panics_releases_its_link() {
use std::sync::atomic::{AtomicUsize, Ordering};
let interface = "test-panic0";
let ip = Ipv4Addr::new(192, 0, 2, 60);
let mac = MacAddr::new(0x02, 0, 0, 0, 0, 0x60);
let opened = Arc::new(AtomicUsize::new(0));
let opens = Arc::clone(&opened);
let resolutions = Arc::new(Resolutions::over(Box::new(move |_| {
let link: Box<dyn ResolutionLink> = if opens.fetch_add(1, Ordering::SeqCst) == 0 {
Box::new(Panicking)
} else {
Box::new(
Segment::new()
.in_real_time()
.with(ip, mac, Answers::Request(1)),
)
};
Ok(link)
})));
let first = resolutions.resolve(&ask(interface, ip));
assert!(
matches!(&first, Err(SendError::Refused(reason)) if reason.contains("panicked")),
"the resolution the driver was running is refused for the panic: {first:?}"
);
assert!(
!resolutions
.lock()
.unanswered
.is_fresh(interface, IpAddr::V4(ip), Instant::now()),
"and not held against the neighbour"
);
assert_eq!(
resolutions.resolve(&ask(interface, ip)).ok(),
Some(mac),
"the next ask drives the link again"
);
assert_eq!(opened.load(Ordering::SeqCst), 2);
}
#[test]
fn a_failure_is_remembered_per_next_hop_and_link_until_it_ages_out() {
let dead = IpAddr::V4(Ipv4Addr::new(192, 0, 2, 200));
let other = IpAddr::V4(Ipv4Addr::new(192, 0, 2, 201));
let t0 = Instant::now();
let mut unanswered = UnansweredNeighbors::default();
assert!(!unanswered.is_fresh("en0", dead, t0), "nothing on record");
unanswered.note("en0", dead, t0);
assert!(unanswered.is_fresh("en0", dead, t0 + Duration::from_secs(1)));
assert!(!unanswered.is_fresh("en0", other, t0), "another next hop");
assert!(!unanswered.is_fresh("en1", dead, t0), "another link");
assert!(
!unanswered.is_fresh("en0", dead, t0 + NEIGHBOR_UNREACHABLE_TTL),
"aged out"
);
unanswered.clear("en0", dead);
assert!(
!unanswered.is_fresh("en0", dead, t0),
"cleared by an answer"
);
}
#[test]
fn parses_an_arp_reply_and_nothing_else() {
let ip = Ipv4Addr::new(192, 0, 2, 200);
let mac = MacAddr::new(0x02, 0, 0, 0, 0, 0x01);
assert_eq!(parse_arp_reply(&arp_reply(ip, mac)), Some((ip, mac)));
let request = arp::build_request(mac, ip, LOCAL_IP);
assert_eq!(parse_arp_reply(&request), None, "a request");
let mut ipv4 = vec![0u8; 42];
MutableEthernetPacket::new(&mut ipv4)
.unwrap()
.set_ethertype(EtherTypes::Ipv4);
assert_eq!(parse_arp_reply(&ipv4), None, "not ARP");
}
}