pub mod idle;
pub mod sctp;
pub mod tcp;
pub mod udp;
pub use idle::IdlePortScanner;
pub use sctp::{SctpPortScanner, SctpToken};
pub use tcp::{TcpPortScanner, TcpToken};
pub use udp::UdpPortScanner;
use std::net::IpAddr;
use std::num::NonZeroU32;
use std::time::{Duration, Instant};
use tokio::sync::mpsc;
use crate::config::ProbeTuning;
use crate::evasion::SegmentShaping;
use crate::journal::settle::Outcome;
use crate::model::host::{HostStatus, StatusProtocol, StatusReason};
use crate::model::port::{PortState, Protocol};
use crate::model::target::PlannedTarget;
use crate::report::ScannerKind;
use crate::report::StopReason;
use crate::scanner::audit::ProbeAudit;
use crate::scanner::pacing::congestion::{CongestionWindow, WindowLimits};
use crate::scanner::pacing::deadline::{AdaptiveDeadline, AdaptiveDeadlineConfig};
use crate::scanner::pacing::retry::{Due, ProbeLedger, Resolution, RetryPolicy, SilentHostPolicy};
use crate::scanner::session::ScanContext;
use crate::scanner::strategy::PortScanner;
use crate::system::interface::SourceResolver;
use crate::transport::capture::CapturedSegment;
use crate::transport::probe::{Emission, ProbeTransport};
const PORT_RETRY_POLICY: RetryPolicy = RetryPolicy::new(
3,
Duration::from_millis(200),
Duration::from_millis(25),
Duration::from_secs(2),
3.0,
0.3,
Some(SilentHostPolicy::new(32, 2)),
);
const TCP_PORT_WINDOW: WindowLimits = WindowLimits::new(32, 16, 1_024, 64);
const TCP_PORT_UNRESOLVED: usize = 8_192;
const TCP_PORT_RATE_CEILING: NonZeroU32 = NonZeroU32::new(20_000).expect("a non-zero rate");
const UDP_PORT_RATE_PER_SEC: NonZeroU32 = NonZeroU32::new(400).expect("a non-zero rate");
pub type ProbeTarget = (IpAddr, u16);
pub struct RawProbeScan<T> {
pub resolver: SourceResolver,
pub ctx: ScanContext,
pub transport: ProbeTransport,
pub deadline: AdaptiveDeadline,
pub ledger: ProbeLedger<ProbeTarget, T, u64>,
pub due: Vec<Due<ProbeTarget, u64>>,
pub src_port: u16,
pub emission: Emission,
pub shaping: SegmentShaping,
pub decoys: Vec<IpAddr>,
pub send_failure: Option<String>,
pub unasked_unsent: u64,
pub audit: ProbeAudit,
pub window: CongestionWindow,
pub send_tick: Duration,
pub batch: usize,
pub max_unresolved: usize,
pub held: std::collections::BinaryHeap<HeldProbe>,
}
pub(super) struct CoreParts<'a> {
pub resolver: SourceResolver,
pub ctx: ScanContext,
pub transport: ProbeTransport,
pub tuning: &'a ProbeTuning,
pub src_port: u16,
pub target_count: usize,
pub retry: RetryPolicy,
pub rate: NonZeroU32,
pub deadline: AdaptiveDeadlineConfig,
pub pace: Duration,
pub window: WindowLimits,
pub max_unresolved: usize,
}
impl<T: Copy + PartialEq> RawProbeScan<T> {
pub(super) fn new(parts: CoreParts<'_>) -> Self {
let CoreParts {
resolver,
ctx,
transport,
tuning,
src_port,
target_count,
retry,
rate,
deadline,
pace,
window,
max_unresolved,
} = parts;
let (send_tick, batch) = super::raw::pacing_for(rate);
let deadline = deadline
.allowing_for(retry.worst_case_probe_lifetime())
.allowing_pace_of(pace, target_count);
let mut core = Self {
resolver,
ctx,
transport,
deadline: AdaptiveDeadline::new(deadline, target_count),
ledger: ProbeLedger::new(retry, target_count.min(max_unresolved)),
due: Vec::new(),
src_port,
emission: tuning.evasion.emission(),
shaping: tuning.evasion.segment_shaping(),
decoys: tuning.evasion.decoys.clone(),
send_failure: None,
unasked_unsent: 0,
audit: ProbeAudit::new(),
window: CongestionWindow::new(window),
send_tick,
batch,
max_unresolved,
held: std::collections::BinaryHeap::new(),
};
core.seed_timing();
core
}
pub fn stop_reason(&self, sending_finished: bool) -> Option<StopReason> {
if let Some(cause) = self.ctx.handle.stopped() {
return Some(cause.into());
}
if self.deadline.hard_deadline_passed() {
return Some(StopReason::DeadlineExpired);
}
if sending_finished && self.ledger.is_empty() && self.held.is_empty() {
return Some(StopReason::AttemptsSpent);
}
None
}
pub fn admitting(&self, sending_finished: bool) -> bool {
let anything_to_send = !sending_finished || !self.held.is_empty();
anything_to_send && self.window.has_room() && self.ledger.len() < self.max_unresolved
}
pub fn held_is_full(&self) -> bool {
self.held.len() >= self.max_unresolved
}
fn hold(&mut self, ip: IpAddr, port: u16, position: Option<u64>, ready: Instant) {
self.held.push(HeldProbe {
ip,
port,
position,
ready,
});
}
fn take_ready(&mut self, now: Instant) -> Option<HeldProbe> {
while let Some(next) = self.held.peek() {
if next.ready > now {
return None;
}
let mut entry = self.held.pop().expect("peeked");
match self.ctx.host_ready_at(entry.ip, now) {
None => return Some(entry),
Some(ready) => {
entry.ready = ready;
self.held.push(entry);
}
}
}
None
}
pub fn record_send(&mut self, host: IpAddr, sent: bool, first_attempt: bool) {
self.audit.record_send(sent);
if sent {
self.ctx.host_probed(host, Instant::now());
}
match (sent, first_attempt) {
(false, _) => self.window.record_congestion(),
(true, true) => self.window.record_send(),
(true, false) => self.window.record_resend(),
}
}
pub fn judge_timeout(&mut self, host: IpAddr) {
self.window.release();
if self.ledger.host_has_answered(&host) {
self.window.record_congestion();
} else {
self.window.record_progress();
}
}
pub fn record_answer<P: Copy>(&mut self, resolution: &Resolution<P>) {
self.deadline.mark_activity();
if let Some(rtt) = resolution.rtt {
self.deadline.record_rtt(rtt);
}
match (resolution.attempts, resolution.answered_attempt) {
(1, _) => {
self.window.release();
self.window.record_progress();
}
(_, Some(attempt)) if attempt > 1 => self.window.record_congestion(),
_ => {}
}
self.audit.record_host_found(resolution.answered_attempt);
}
pub fn tick_delay(&self, now: Instant) -> Duration {
let until_deadline_tick = self.deadline.time_until_next_tick();
match self.ledger.next_due() {
Some(due) => until_deadline_tick.min(due.saturating_duration_since(now)),
None => until_deadline_tick,
}
}
pub fn seed_timing(&mut self) {
for host in self.ctx.store.iter() {
if let Some(rtt) = host.value().median_rtt() {
self.ledger.seed_host_rtt(host.key().addr(), rtt);
}
}
}
pub fn record_host_down(
&mut self,
key: &ProbeTarget,
token: Option<T>,
sender: IpAddr,
) -> bool {
if !self.ledger.names_attempt(key, token.as_ref()) {
self.audit.record_off_target();
return false;
}
let mut recorded = false;
self.ctx.update_host(key.0, |host| {
host.record_evidence(
HostStatus::Down,
StatusReason::new(StatusProtocol::IcmpUnreachable, "destination unreachable")
.from_source(sender),
);
recorded = true;
});
recorded
}
pub fn finish(
&mut self,
kind: ScannerKind,
audit_tag: &str,
silence_verdict: &str,
probes: u128,
reason: StopReason,
) {
if self.audit.sends_failed > 0 {
self.ctx.record_failure(
kind,
format!(
"{} probes could not be sent, so their ports are recorded \
unasked rather than {silence_verdict}: {}",
self.audit.sends_failed,
self.send_failure.as_deref().unwrap_or("cause unrecorded"),
),
);
}
if self.unasked_unsent > 0 {
let deaf = self
.transport
.capture_counts()
.is_some_and(|counts| counts.stopped_early > 0);
let cause = if deaf {
"a capture stopped early, so their probes may have left unseen"
} else {
"this machine accepted their probes and never put them on the wire"
};
self.ctx.record_failure(
kind,
format!(
"{} recorded unasked rather than {silence_verdict}: {cause}",
crate::logging::counted(u128::from(self.unasked_unsent), "port", "ports"),
),
);
}
let capture = self.transport.capture_counts();
self.audit.report(
audit_tag,
probes,
reason,
capture,
Some(self.window.summary()),
);
self.ctx.record_probe_stats(self.audit.stats(
kind,
probes,
reason,
capture,
Some(self.window.summary()),
));
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct HeldProbe {
ip: IpAddr,
port: u16,
position: Option<u64>,
ready: Instant,
}
impl Ord for HeldProbe {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
other
.ready
.cmp(&self.ready)
.then_with(|| self.port.cmp(&other.port))
}
}
impl PartialOrd for HeldProbe {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
Some(self.cmp(other))
}
}
pub trait RawPortScan: PortScanner {
type Token: Copy + PartialEq;
fn core(&self) -> &RawProbeScan<Self::Token>;
fn core_mut(&mut self) -> &mut RawProbeScan<Self::Token>;
fn protocol(&self) -> Protocol;
fn silence_means(&self) -> PortState;
fn audit_labels(&self) -> AuditLabels;
fn probe(&mut self, ip: IpAddr, port: u16, position: u64, now: Instant) {
self.send(ip, port, Some(position), now);
if !self.core().ledger.contains(&(ip, port)) {
self.record_unasked_endpoint(ip, port);
}
}
fn reprobe(&mut self, ip: IpAddr, port: u16, now: Instant) {
self.send(ip, port, None, now);
}
fn send(&mut self, ip: IpAddr, port: u16, position: Option<u64>, now: Instant);
fn handle_reply(&mut self, reply: &CapturedSegment, now: Instant);
fn record_port(&mut self, ip: IpAddr, port: u16, state: PortState, sender: Option<IpAddr>);
fn settle(&mut self, outcome: Outcome) {
self.core().ctx.record_outcome(outcome);
}
fn send_probe(&mut self, planned: PlannedTarget) {
if planned.protocol() == self.protocol() {
self.probe(
planned.ip(),
planned.port(),
planned.position,
Instant::now(),
);
}
}
fn hold_probe(&mut self, planned: PlannedTarget, ready: Instant) {
if planned.protocol() == self.protocol() {
self.core_mut()
.hold(planned.ip(), planned.port(), Some(planned.position), ready);
}
}
fn send_held(&mut self, held: HeldProbe, now: Instant) {
match held.position {
Some(position) => self.probe(held.ip, held.port, position, now),
None => self.reprobe(held.ip, held.port, now),
}
}
fn resolve_held(&mut self) {
let held = std::mem::take(&mut self.core_mut().held);
for entry in held {
if entry.position.is_some() {
self.record_unasked_endpoint(entry.ip, entry.port);
}
}
}
fn service_retries(&mut self, now: Instant) {
let core = self.core_mut();
core.ledger.drain_due(now, &mut core.due);
let due = std::mem::take(&mut self.core_mut().due);
let silence = self.silence_means();
for event in &due {
match *event {
Due::Retry {
key: (ip, port),
attempt,
} => {
if attempt == 2 {
self.core_mut().judge_timeout(ip);
}
match self.core().ctx.host_ready_at(ip, now) {
Some(ready) => self.core_mut().hold(ip, port, None, ready),
None => self.reprobe(ip, port, now),
}
}
Due::Exhausted {
key: (ip, port),
payload: position,
attempts,
witnessed,
} => {
if attempts == 1 {
self.core_mut().judge_timeout(ip);
}
if witnessed == 0 && self.core().audit.witnesses_its_sends() {
self.core_mut().unasked_unsent += 1;
self.record_unasked_endpoint(ip, port);
continue;
}
self.record_port(ip, port, silence, None);
self.settle(Outcome::Exhausted { position });
}
}
}
let core = self.core_mut();
core.due = due;
core.due.clear();
}
fn resolve_remaining(&mut self) {
self.core_mut().window.release_all();
let silence = self.silence_means();
for (ip, port) in self.core_mut().ledger.drain_unresolved() {
self.record_port(ip, port, silence, None);
self.settle(Outcome::Interrupted);
}
}
fn resolve_unasked(&mut self, targets: &mut mpsc::Receiver<PlannedTarget>) -> u128 {
let mut unasked = 0;
while let Ok(target) = targets.try_recv() {
unasked += 1;
self.record_unasked(target);
}
unasked
}
fn record_unasked(&mut self, target: PlannedTarget) {
if target.protocol() != self.protocol() {
return;
}
self.record_unasked_endpoint(target.ip(), target.port());
}
fn record_unasked_endpoint(&mut self, ip: IpAddr, port: u16) {
self.record_port(ip, port, PortState::Unasked, None);
self.settle(Outcome::Unasked);
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct AuditLabels {
pub tag: &'static str,
pub silence: &'static str,
}
pub async fn drive<S: RawPortScan>(scanner: &mut S, mut targets: mpsc::Receiver<PlannedTarget>) {
let mut send_tick = tokio::time::interval(scanner.core().send_tick);
send_tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
let mut sending_finished = false;
let mut probes = 0u128;
let reason = loop {
let now = Instant::now();
scanner.service_retries(now);
if let Some(reason) = scanner.core().stop_reason(sending_finished) {
break reason;
}
let admitting = scanner.core().admitting(sending_finished);
let tick = scanner.core().tick_delay(now);
tokio::select! {
_ = send_tick.tick(), if admitting => {
let now = Instant::now();
for _ in 0..scanner.core().batch {
if let Some(held) = scanner.core_mut().take_ready(now) {
scanner.send_held(held, now);
if !scanner.core().admitting(sending_finished) {
break;
}
continue;
}
if scanner.core().held_is_full() {
break;
}
match targets.try_recv() {
Ok(target) => {
probes += 1;
if scanner.core().ctx.host_expired(target.ip()) {
scanner.record_unasked(target);
} else if let Some(ready) =
scanner.core().ctx.host_ready_at(target.ip(), now)
{
scanner.hold_probe(target, ready);
} else {
scanner.send_probe(target);
}
}
Err(mpsc::error::TryRecvError::Empty) => break,
Err(mpsc::error::TryRecvError::Disconnected) => {
sending_finished = true;
break;
}
}
if !scanner.core().admitting(sending_finished) {
break;
}
}
}
res = scanner.core_mut().transport.rx.recv() => {
match res {
Some(reply) => {
scanner.core_mut().audit.record_segment();
let received_at = reply.received_at;
scanner.handle_reply(&reply, received_at);
}
None => break StopReason::StreamClosed,
}
}
_ = tokio::time::sleep(tick) => {}
}
};
scanner.resolve_remaining();
scanner.resolve_held();
probes += scanner.resolve_unasked(&mut targets);
let kind = scanner.kind();
let labels = scanner.audit_labels();
scanner
.core_mut()
.finish(kind, labels.tag, labels.silence, probes, reason);
}
#[cfg(test)]
mod tests {
use super::*;
use std::net::Ipv4Addr;
use crate::scanner::pacing::congestion::WindowLimits;
use crate::scanner::session::ScanSession;
use crate::transport::probe::{Emission, ProbeSender, ProbeTransport, SendError};
#[derive(Default)]
struct NullSender;
impl ProbeSender for NullSender {
fn send(
&self,
_segment: &[u8],
_src: IpAddr,
_dst: IpAddr,
_zone: Option<u32>,
_emission: Emission,
) -> Result<(), SendError> {
Ok(())
}
}
const TARGET: IpAddr = IpAddr::V4(Ipv4Addr::new(192, 0, 2, 10));
fn core() -> (RawProbeScan<()>, ScanSession) {
let (session, ctx) = ScanSession::new();
let (_tx, rx) = tokio::sync::mpsc::channel(1024);
let core = RawProbeScan {
resolver: SourceResolver::from_links(&[]),
ctx,
transport: ProbeTransport::from_parts(Box::new(NullSender), rx),
deadline: AdaptiveDeadline::new(super::super::raw::DEADLINE_CONFIG, 8),
ledger: ProbeLedger::new(super::super::raw::RETRY_POLICY, 8),
due: Vec::new(),
src_port: 54_321,
emission: Emission::routed(),
shaping: SegmentShaping::default(),
decoys: Vec::new(),
send_failure: None,
unasked_unsent: 0,
audit: ProbeAudit::new(),
window: CongestionWindow::new(WindowLimits::fixed(4)),
send_tick: Duration::from_millis(1),
batch: 1,
max_unresolved: 64,
held: std::collections::BinaryHeap::new(),
};
(core, session)
}
fn unsent_failure(core: &mut RawProbeScan<()>) -> String {
core.unasked_unsent = 2;
core.finish(
ScannerKind::SynPort,
"syn-port",
"filtered",
2,
StopReason::AllResponded,
);
let failures = core.ctx.failures_snapshot();
assert_eq!(failures.len(), 1, "{failures:?}");
failures[0].reason().to_owned()
}
#[test]
fn ports_unseen_after_a_capture_died_are_not_blamed_on_sending() {
let (mut core, _session) = core();
let (_tx, rx) = tokio::sync::mpsc::channel(1024);
core.transport = ProbeTransport::from_parts_deaf(Box::new(NullSender), rx);
let reason = unsent_failure(&mut core);
assert!(
reason.contains("a capture stopped early"),
"the dead capture goes unnamed: {reason}"
);
assert!(!reason.contains("never put them on the wire"), "{reason}");
}
#[test]
fn ports_unseen_with_every_capture_listening_are_blamed_on_sending() {
let (mut core, _session) = core();
let reason = unsent_failure(&mut core);
assert!(reason.contains("never put them on the wire"), "{reason}");
assert!(
!reason.contains(" "),
"the sentence carries a run of spaces from its source: {reason:?}"
);
}
fn spaced_core(gap: Duration) -> (RawProbeScan<()>, ScanSession) {
let (session, ctx) = ScanSession::builder()
.host_probe_interval(Some(gap))
.build();
let (_tx, rx) = tokio::sync::mpsc::channel(1024);
let core = RawProbeScan {
resolver: SourceResolver::from_links(&[]),
ctx,
transport: ProbeTransport::from_parts(Box::new(NullSender), rx),
deadline: AdaptiveDeadline::new(super::super::raw::DEADLINE_CONFIG, 8),
ledger: ProbeLedger::new(super::super::raw::RETRY_POLICY, 8),
due: Vec::new(),
src_port: 54_321,
emission: Emission::routed(),
shaping: SegmentShaping::default(),
decoys: Vec::new(),
send_failure: None,
unasked_unsent: 0,
audit: ProbeAudit::new(),
window: CongestionWindow::new(WindowLimits::fixed(4)),
send_tick: Duration::from_millis(1),
batch: 1,
max_unresolved: 64,
held: std::collections::BinaryHeap::new(),
};
(core, session)
}
#[test]
fn the_earliest_slot_comes_off_the_queue_first() {
let (mut core, _session) = spaced_core(Duration::from_secs(3600));
let now = Instant::now();
core.hold(TARGET, 80, Some(0), now + Duration::from_secs(30));
core.hold(TARGET, 22, Some(1), now + Duration::from_secs(10));
core.hold(TARGET, 443, Some(2), now + Duration::from_secs(20));
assert!(
core.take_ready(now).is_none(),
"nothing is ready yet, and nothing is handed back early"
);
let first = core
.take_ready(now + Duration::from_secs(15))
.expect("the ten-second slot has come round");
assert_eq!(first.port, 22);
}
#[test]
fn a_slot_that_moved_after_the_probe_was_held_is_re_checked() {
let gap = Duration::from_secs(3600);
let (mut core, _session) = spaced_core(gap);
let now = Instant::now();
core.hold(TARGET, 80, Some(0), now);
core.ctx.host_probed(TARGET, now);
assert!(
core.take_ready(now).is_none(),
"the stored instant said now; the host says otherwise and the host wins"
);
assert_eq!(
core.held.len(),
1,
"and the probe is still held, not dropped"
);
assert!(
core.take_ready(now + gap).is_some(),
"once the gap has really run, it is handed back"
);
}
#[test]
fn a_held_probe_keeps_the_scan_open_after_the_stream_ends() {
let (mut core, _session) = spaced_core(Duration::from_secs(3600));
let now = Instant::now();
core.hold(TARGET, 80, Some(0), now + Duration::from_secs(1));
assert_eq!(
core.stop_reason(true),
None,
"the stream is done and the ledger empty, but a probe is still owed"
);
assert!(
core.admitting(true),
"and the send path stays open, since it is the only thing that empties the queue"
);
let _ = core.take_ready(now + Duration::from_secs(1));
core.held.clear();
assert_eq!(
core.stop_reason(true),
Some(StopReason::AttemptsSpent),
"with the queue empty too, waiting cannot change what this found"
);
}
#[test]
fn a_full_queue_stops_the_stream_and_not_the_sending() {
let (mut core, _session) = spaced_core(Duration::from_secs(3600));
let now = Instant::now();
for port in 0..core.max_unresolved {
core.hold(TARGET, port as u16, Some(port as u64), now);
}
assert!(core.held_is_full());
assert!(
core.admitting(false),
"a full queue must not close the one path that drains it"
);
}
#[test]
fn an_empty_ledger_does_not_end_a_scan_that_still_has_targets_coming() {
let (core, _session) = core();
assert_eq!(
core.stop_reason(false),
None,
"the target stream is still open, so nothing has been concluded"
);
assert_eq!(
core.stop_reason(true),
Some(StopReason::AttemptsSpent),
"with the stream done and nothing outstanding, waiting cannot help"
);
}
#[test]
fn an_outstanding_probe_holds_the_scan_open_past_a_dry_target_stream() {
let (mut core, _session) = core();
core.ledger.arm(TARGET, (TARGET, 80), (), 0, Instant::now());
assert_eq!(
core.stop_reason(true),
None,
"a probe is still within its retry schedule"
);
}
#[test]
fn an_abort_outranks_every_other_reason() {
let (mut core, _session) = core();
core.ledger.arm(TARGET, (TARGET, 80), (), 0, Instant::now());
core.ctx.handle.abort();
assert_eq!(core.stop_reason(false), Some(StopReason::Aborted));
}
#[test]
fn the_ledger_stops_admitting_at_the_window() {
let (mut core, _session) = core();
assert!(core.admitting(false), "an empty ledger admits");
for _ in 0..core.window.capacity() {
core.window.record_send();
}
assert!(
!core.admitting(false),
"admitting past the window grows correlation state for nothing"
);
assert!(
!core.admitting(true),
"a finished stream never admits, window or not"
);
}
#[test]
fn the_attempt_that_answered_is_what_moves_the_window() {
let (mut core, _session) = core();
core.window = CongestionWindow::new(WindowLimits::new(64, 4, 512, 512));
core.record_answer(&Resolution {
payload: 0u64,
rtt: None,
attempts: 1,
answered_attempt: Some(1),
});
assert!(core.window.capacity() > 64, "a clean answer buys headroom");
let grown = core.window.capacity();
core.record_answer(&Resolution {
payload: 0u64,
rtt: None,
attempts: 2,
answered_attempt: Some(2),
});
assert!(
core.window.capacity() < grown,
"an answer that needed a retry is loss, and loss cuts the window"
);
}
#[test]
fn a_send_the_kernel_refused_cuts_the_window() {
let (mut core, _session) = core();
core.window = CongestionWindow::new(WindowLimits::new(64, 4, 512, 512));
core.record_send("192.0.2.1".parse().expect("a literal address"), false, true);
assert!(
core.window.capacity() < 64,
"the local stack refusing is the least ambiguous evidence there is"
);
assert_eq!(
core.window.in_flight(),
0,
"and a probe that never left takes no slot"
);
}
#[test]
fn silence_from_a_host_that_never_answered_opens_the_window() {
let (mut core, _session) = core();
core.window = CongestionWindow::new(WindowLimits::new(64, 4, 512, 512));
core.window.record_send();
core.judge_timeout(TARGET);
assert!(
core.window.capacity() >= 64,
"nothing this host did says the path is busy"
);
assert_eq!(core.window.in_flight(), 0, "and the slot went back");
}
#[test]
fn silence_from_a_host_that_is_answering_cuts_the_window() {
let (mut core, _session) = core();
core.window = CongestionWindow::new(WindowLimits::new(64, 4, 512, 512));
let now = Instant::now();
core.ledger.arm(TARGET, (TARGET, 22), (), 0, now);
core.ledger.resolve(&(TARGET, 22), None, now);
core.window.record_send();
core.judge_timeout(TARGET);
assert!(
core.window.capacity() < 64,
"a host that talks and then goes quiet is being outrun"
);
assert_eq!(core.window.in_flight(), 0, "and the slot still went back");
}
#[test]
fn a_host_down_filed_against_a_host_already_known_reports_it_was_recorded() {
let (mut core, session) = core();
let router: IpAddr = "198.51.100.1".parse().expect("a literal address");
core.ctx.update_host(TARGET, |_| {});
core.ledger.arm(TARGET, (TARGET, 80), (), 0, Instant::now());
assert!(
core.record_host_down(&(TARGET, 80), Some(()), router),
"an unreachable naming a live probe is on the host's record"
);
assert_eq!(
session.hosts().get(TARGET).map(|host| host.status()),
Some(HostStatus::Down)
);
}
#[test]
fn a_host_down_about_an_excluded_address_reports_nothing_recorded() {
let (mut core, _) = core();
let mut excluded = crate::model::ip::set::IpSet::new();
excluded.insert_range("192.0.2.0/24".parse().expect("a valid range"));
let (session, ctx) = ScanSession::builder()
.excluding(crate::model::exclusion::Exclusions::new(excluded))
.build();
core.ctx = ctx;
let router: IpAddr = "198.51.100.1".parse().expect("a literal address");
core.ledger.arm(TARGET, (TARGET, 80), (), 0, Instant::now());
assert!(!core.record_host_down(&(TARGET, 80), Some(()), router));
assert!(session.hosts().get(TARGET).is_none());
}
}