use std::net::IpAddr;
use std::time::{Duration, Instant};
use tokio::sync::mpsc;
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::scanner::audit::ProbeAudit;
use crate::scanner::pacing::congestion::CongestionWindow;
use crate::scanner::pacing::deadline::AdaptiveDeadline;
use crate::scanner::pacing::retry::{Due, ProbeLedger, Resolution};
use crate::scanner::report::StopReason;
use crate::scanner::session::{ScanContext, ScannerKind};
use crate::scanner::strategy::PortScanner;
use crate::system::interface::SourceResolver;
use crate::transport::capture::CapturedSegment;
use crate::transport::probe::ProbeTransport;
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 send_failure: Option<String>,
pub audit: ProbeAudit,
pub window: CongestionWindow,
pub send_tick: Duration,
pub batch: usize,
pub max_unresolved: usize,
}
impl<T: Copy + PartialEq> RawProbeScan<T> {
pub fn stop_reason(&self, sending_finished: bool) -> Option<StopReason> {
if self.ctx.handle.should_stop() {
return Some(StopReason::Aborted);
}
if self.deadline.hard_deadline_passed() {
return Some(StopReason::DeadlineExpired);
}
if sending_finished && self.ledger.is_empty() {
return Some(StopReason::AttemptsSpent);
}
None
}
pub fn admitting(&self, sending_finished: bool) -> bool {
!sending_finished && self.window.has_room() && self.ledger.len() < self.max_unresolved
}
pub fn record_send(&mut self, sent: bool, first_attempt: bool) {
self.audit.record_send(sent);
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(), rtt);
}
}
}
pub fn record_host_down(&mut self, ip: IpAddr, sender: IpAddr) {
self.ctx.update_host(ip, |host| {
host.record_evidence(
HostStatus::Down,
StatusReason::new(StatusProtocol::IcmpUnreachable, "destination unreachable")
.from_source(sender),
);
});
}
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 reported \
{silence_verdict} without having been asked: {}",
self.audit.sends_failed,
self.send_failure.as_deref().unwrap_or("cause unrecorded"),
),
);
}
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()),
));
}
}
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);
fn reprobe(&mut self, ip: IpAddr, port: u16, 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 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);
}
self.reprobe(ip, port, now);
}
Due::Exhausted {
key: (ip, port),
payload: position,
attempts,
} => {
if attempts == 1 {
self.core_mut().judge_timeout(ip);
}
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 protocol = self.protocol();
let silence = self.silence_means();
let mut unasked = 0;
while let Ok(target) = targets.try_recv() {
unasked += 1;
if target.protocol() == protocol {
self.record_port(target.ip(), target.port(), silence, None);
self.settle(Outcome::Unasked);
}
}
unasked
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct AuditLabels {
pub tag: &'static str,
pub silence: &'static str,
}
pub async fn run<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 => {
for _ in 0..scanner.core().batch {
match targets.try_recv() {
Ok(target) => {
probes += 1;
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();
scanner.handle_reply(&reply, Instant::now());
}
None => break StopReason::StreamClosed,
}
}
_ = tokio::time::sleep(tick) => {}
}
};
scanner.resolve_remaining();
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,
_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::unbounded_channel();
let core = RawProbeScan {
resolver: SourceResolver::from_interfaces(&[]),
ctx,
transport: ProbeTransport::from_parts(Box::new(NullSender), rx),
deadline: AdaptiveDeadline::new(super::super::DEADLINE_CONFIG, 8),
ledger: ProbeLedger::new(super::super::RETRY_POLICY, 8),
due: Vec::new(),
src_port: 54_321,
send_failure: None,
audit: ProbeAudit::new(),
window: CongestionWindow::new(WindowLimits::fixed(4)),
send_tick: Duration::from_millis(1),
batch: 1,
max_unresolved: 64,
};
(core, session)
}
#[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(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");
}
}