use std::collections::HashSet;
use std::net::IpAddr;
use std::sync::Mutex;
use std::time::{Duration, Instant};
use crate::config::limits::NEIGHBOUR_PATH_FINDING_TIMEOUT;
use crate::logging::info;
use crate::scanner::strategy::raw::neighbors::{HoldDowns, NEIGHBOR_ROUNDS, unreached};
use crate::transport::kernel_neighbors::{KernelNeighbors, NeighborState};
pub(super) struct Neighbours {
table: Option<KernelNeighbors>,
given_up: Mutex<HashSet<IpAddr>>,
filed: Mutex<HashSet<IpAddr>>,
holds: Mutex<HoldDowns>,
}
impl Neighbours {
pub(super) fn of_system() -> Self {
Self::reading(KernelNeighbors::from_system())
}
pub(super) fn reading(table: Option<KernelNeighbors>) -> Self {
Self {
table,
given_up: Mutex::default(),
filed: Mutex::default(),
holds: Mutex::default(),
}
}
#[cfg(all(test, unix))]
pub(super) fn holding_down_for(self, hold_down_for: Duration) -> Self {
lock(&self.holds).hold_down_for = hold_down_for;
self
}
pub(super) fn holding(&self, host: IpAddr) -> Option<NeighborState> {
let table = self.table.as_ref()?;
let neighbour = table.next_hop(host)?;
table
.state(neighbour, Instant::now())
.filter(|state| state.is_unresolved())
}
pub(super) fn held_until(&self, host: IpAddr) -> Option<Instant> {
lock(&self.holds).until(host, Instant::now())
}
pub(super) fn hold_down(&self, host: IpAddr, why: &std::io::Error) -> Option<Instant> {
let now = Instant::now();
let (held, until, hold_down_for) = {
let mut holds = lock(&self.holds);
let held = holds.until(host, now).is_some();
(held, holds.hold(host, now), holds.hold_down_for)
};
match until {
Some(_) if !held => info!(
verbosity = 2,
"{host} held down by the kernel, asked again in {}s ({why})",
hold_down_for.as_secs()
),
Some(_) => {}
None => self.give_up(host),
}
until
}
pub(super) fn unreached(&self, host: IpAddr) -> bool {
let neighbour = self.neighbour_of(host);
let given_up = lock(&self.given_up).contains(&neighbour);
if given_up {
self.file(host, neighbour);
}
given_up
}
pub(super) fn give_up(&self, host: IpAddr) {
let neighbour = self.neighbour_of(host);
lock(&self.given_up).insert(neighbour);
self.file(host, neighbour);
}
fn neighbour_of(&self, host: IpAddr) -> IpAddr {
self.table
.as_ref()
.and_then(|table| table.next_hop(host))
.unwrap_or(host)
}
fn file(&self, host: IpAddr, neighbour: IpAddr) {
if lock(&self.filed).insert(host) {
let why = unreached(host, Some(neighbour), NeighborState::Failed);
info!(verbosity = 2, "{host} unreachable ({why})");
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum Held {
Again(Duration),
Unreached,
}
#[derive(Debug, Default)]
pub(super) struct HeldConnects {
unanswered: u8,
outwaited: bool,
}
impl HeldConnects {
pub(super) fn after(&mut self, state: NeighborState, concluded: bool) -> Held {
let again = Held::Again(NEIGHBOUR_PATH_FINDING_TIMEOUT);
if !concluded && state == NeighborState::Resolving && !self.outwaited {
self.outwaited = true;
return again;
}
self.unanswered = self.unanswered.saturating_add(1);
if self.unanswered < NEIGHBOR_ROUNDS {
again
} else {
Held::Unreached
}
}
}
impl Default for Neighbours {
fn default() -> Self {
Self::reading(None)
}
}
fn lock<T>(held: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
held.lock().unwrap_or_else(|poisoned| poisoned.into_inner())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::transport::kernel_neighbors::NeighborTable;
use std::net::Ipv4Addr;
const HOST: IpAddr = IpAddr::V4(Ipv4Addr::new(192, 0, 2, 7));
const ROUTED: IpAddr = IpAddr::V4(Ipv4Addr::new(198, 51, 100, 7));
const GATEWAY: IpAddr = IpAddr::V4(Ipv4Addr::new(192, 0, 2, 254));
fn reading(table: NeighborTable) -> Neighbours {
let table = KernelNeighbors::with_reader(Box::new(move || Ok(table.clone()))).routing(
Box::new(|address| Ok(Some(if address == ROUTED { GATEWAY } else { address }))),
);
Neighbours::reading(Some(table))
}
#[test]
fn only_an_unresolved_neighbour_holds_a_connect() {
for state in [NeighborState::Failed, NeighborState::Resolving] {
let neighbours = reading(NeighborTable::from([(HOST, state), (GATEWAY, state)]));
assert_eq!(neighbours.holding(HOST), Some(state));
assert_eq!(
neighbours.holding(ROUTED),
Some(state),
"read at its gateway"
);
}
let answered = reading(NeighborTable::from([
(HOST, NeighborState::Resolved),
(GATEWAY, NeighborState::Resolved),
]));
assert_eq!(answered.holding(HOST), None);
assert_eq!(answered.holding(ROUTED), None);
assert_eq!(reading(NeighborTable::new()).holding(HOST), None);
assert_eq!(Neighbours::default().holding(HOST), None);
}
#[test]
fn a_gateway_given_up_leaves_every_host_behind_it_unreached() {
let neighbours = reading(NeighborTable::new());
let beside = IpAddr::V4(Ipv4Addr::new(198, 51, 100, 8));
assert!(!neighbours.unreached(ROUTED));
neighbours.give_up(beside);
assert!(
!neighbours.unreached(ROUTED),
"{beside} is its own neighbour"
);
neighbours.give_up(ROUTED);
assert!(neighbours.unreached(ROUTED));
assert!(!neighbours.unreached(HOST));
}
#[test]
fn a_port_is_given_up_after_its_second_unanswered_resolution() {
let mut held = HeldConnects::default();
let again = Held::Again(NEIGHBOUR_PATH_FINDING_TIMEOUT);
assert_eq!(held.after(NeighborState::Resolving, false), again);
assert_eq!(held.after(NeighborState::Failed, true), again);
assert_eq!(held.after(NeighborState::Failed, true), Held::Unreached);
let mut held = HeldConnects::default();
assert_eq!(held.after(NeighborState::Resolving, false), again);
assert_eq!(held.after(NeighborState::Resolving, false), again);
assert_eq!(
held.after(NeighborState::Resolving, false),
Held::Unreached,
"a resolution that never concludes still ends"
);
}
}