zond-engine 0.15.0

The core networking library powering Zond. Raw packet injection, protocol parsing, service and OS fingerprinting, and asynchronous network scanning.
Documentation
// Copyright (c) 2026 Erik Lening (hollowpointer) and Contributors
//
// This file is part of Zond Engine, licensed under the GNU Affero General
// Public License, version 3 or later. See the LICENSE file for details, or
// <https://www.gnu.org/licenses/agpl-3.0.html>.
//
// SPDX-License-Identifier: AGPL-3.0-or-later

//! # What became of a target, and whether a resume may skip it
//!
//! A raw port scan gives the same verdict to a target whose retry budget ran out
//! and to one still mid-schedule when the scan stopped. Both were asked and
//! neither answered; how many times the question was repeated is the difference,
//! and a report reads them as one silence. A target no probe was sent to is
//! recorded [`PortState::Unasked`](crate::model::port::PortState::Unasked)
//! instead, since it is a fact about the scan rather than a reading of silence.
//!
//! A resume can afford neither blurring. A cursor advanced over a target nobody
//! probed produces a second sitting that skips it and a merged report claiming
//! coverage it never had.
//!
//! [`Outcome`] makes the distinction unforgeable. Only the settled variants carry
//! a position, and a position is the only thing a cursor can advance over.
//!
//! | Outcome | Decided at | Position |
//! |---|---|---|
//! | [`Answered`](Outcome::Answered) | `ledger.resolve(..) -> Some` | yes |
//! | [`Exhausted`](Outcome::Exhausted) | `Due::Exhausted` | yes |
//! | [`Skipped`](Outcome::Skipped) | the liveness pass found no host | yes |
//! | [`Interrupted`](Outcome::Interrupted) | `ledger.drain_unresolved()` | no |
//! | [`Unasked`](Outcome::Unasked) | no probe was sent | no |
//! | [`Unroutable`](Outcome::Unroutable) | no scanner for the protocol, or no route | no |
//!
//! Unsettled outcomes are counted, not stored. Their total is worth reporting;
//! which targets they were is not, since every one is re-probed anyway.

use std::sync::Mutex;
use std::sync::atomic::{AtomicU64, Ordering};

use super::cursor::{Checkpoint, Cursor};

/// The two outcomes a probe earns, before the position is attached.
///
/// A caller that has earned a verdict says which of these it earned, and
/// something that knows the plan attaches the position. See
/// [`ScanContext::settle_address`](crate::scanner::session::ScanContext::settle_address),
/// which is how a sweep settles an address it does not know the number of.
///
/// Not every settled outcome is here, since not every one is earned by a probe.
/// [`Skipped`](Outcome::Skipped) is the liveness pass deciding no probe was owed,
/// and whatever reaches that conclusion already knows the position, so it builds
/// the outcome directly. The unsettled outcomes carry no position, so there is
/// nothing to attach and they are recorded straight through
/// [`Settlements::record`].
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Settled {
    /// The target answered.
    Answered,
    /// Its retry budget was spent without an answer.
    Exhausted,
}

impl Settled {
    /// The outcome this settlement is, at `position`.
    pub fn at(self, position: u64) -> Outcome {
        match self {
            Settled::Answered => Outcome::Answered { position },
            Settled::Exhausted => Outcome::Exhausted { position },
        }
    }
}

/// What became of one target in one sitting.
///
/// Settled variants carry the target's position in the plan's enumeration; see
/// [`PlannedTarget`](crate::model::target::PlannedTarget).
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Outcome {
    /// The target answered. Settled.
    Answered {
        /// Its position in the plan.
        position: u64,
    },

    /// The retry budget was spent without an answer: silence, asked for as many
    /// times as the policy allows. Settled, since waiting longer could not have
    /// changed it.
    Exhausted {
        /// Its position in the plan.
        position: u64,
    },

    /// Its host answered nothing in the liveness pass, so no probe was owed.
    ///
    /// Settled, and the one settled outcome no probe was sent for. The evidence
    /// is still earned: the scan asked whether the host was there and heard
    /// nothing, so declining to spend a probe per port on it is work decided
    /// against rather than work missed. That is the difference between this and
    /// [`Unasked`](Outcome::Unasked).
    ///
    /// So a resumed scan does not revisit those ports even if the host answers
    /// next time. A resume continues one job, and that job's finding about the
    /// host was that it was down; asking again is a new scan, which is what
    /// [`JournalManifest`](crate::journal::manifest::JournalManifest) says about
    /// a plan that has moved.
    /// [`ZondConfig::assume_up`](crate::config::ZondConfig::assume_up) is how a
    /// caller declines the bargain.
    Skipped {
        /// Its position in the plan.
        position: u64,
    },

    /// Outstanding mid-retry-schedule when the scan stopped. The schedule was
    /// cut off rather than spent.
    Interrupted,

    /// No probe was sent: the target was still queued when the scan stopped, its
    /// host had already spent its own budget, or this machine's sender refused
    /// the send.
    Unasked,

    /// No scanner spoke its protocol, or the host had no route. Usually a missing
    /// privilege rather than a fact about the target, and privileges can differ
    /// between sittings.
    Unroutable,
}

impl Outcome {
    /// The position a resume may skip, or `None` where the scan did not earn
    /// one.
    pub fn settled_position(self) -> Option<u64> {
        match self {
            Outcome::Answered { position }
            | Outcome::Exhausted { position }
            | Outcome::Skipped { position } => Some(position),
            Outcome::Interrupted | Outcome::Unasked | Outcome::Unroutable => None,
        }
    }

    /// Whether a resume may skip this target.
    pub fn is_settled(self) -> bool {
        self.settled_position().is_some()
    }

    /// The wire name, for diagnostics and for reporting a sitting's shape.
    pub fn name(self) -> &'static str {
        match self {
            Outcome::Answered { .. } => "answered",
            Outcome::Exhausted { .. } => "exhausted",
            Outcome::Skipped { .. } => "skipped",
            Outcome::Interrupted => "interrupted",
            Outcome::Unasked => "unasked",
            Outcome::Unroutable => "unroutable",
        }
    }
}

/// How a sitting ended for each of its targets: a cursor over what settled, and
/// counts of what did not.
///
/// Memory follows how far out of order the scan settled, never how many targets
/// it had. A plan of sixteen billion costs the same here as one of a thousand.
#[derive(Debug, Default)]
pub struct Settlements {
    cursor: Mutex<Cursor>,
    answered: AtomicU64,
    exhausted: AtomicU64,
    skipped: AtomicU64,
    interrupted: AtomicU64,
    unasked: AtomicU64,
    unroutable: AtomicU64,
}

impl Settlements {
    /// Begins from a checkpoint, so a resumed sitting keeps what the first
    /// settled.
    pub fn resuming(checkpoint: &Checkpoint) -> Self {
        Self {
            cursor: Mutex::new(Cursor::from_checkpoint(checkpoint)),
            ..Self::default()
        }
    }

    /// Records what became of one target.
    pub fn record(&self, outcome: Outcome) {
        self.counter(outcome).fetch_add(1, Ordering::Relaxed);

        if let Some(position) = outcome.settled_position() {
            self.with_cursor(|cursor| cursor.settle(position));
        }
    }

    /// Records `count` targets ending the same way.
    ///
    /// For the unsettled outcomes, which are counted rather than stored. A sweep
    /// cut short can leave millions of addresses unasked, and they are one fact
    /// rather than a million. A settled outcome names one position, so repeating
    /// it here would count one target many times; those go through
    /// [`record`](Self::record) one at a time.
    pub fn record_many(&self, outcome: Outcome, count: u64) {
        debug_assert!(
            !outcome.is_settled(),
            "a settled outcome names one position and cannot stand for many"
        );
        self.counter(outcome).fetch_add(count, Ordering::Relaxed);
    }

    /// A snapshot to write down.
    pub fn checkpoint(&self) -> Checkpoint {
        self.with_cursor(|cursor| cursor.checkpoint())
    }

    /// How many targets are settled in total, this sitting and any it resumed.
    pub fn settled_count(&self) -> u64 {
        self.with_cursor(|cursor| cursor.settled_count())
    }

    /// How many targets ended in `outcome`'s variant this sitting. The position
    /// of a settled variant is ignored, so any will do.
    pub fn count(&self, outcome: Outcome) -> u64 {
        self.counter(outcome).load(Ordering::Relaxed)
    }

    fn counter(&self, outcome: Outcome) -> &AtomicU64 {
        match outcome {
            Outcome::Answered { .. } => &self.answered,
            Outcome::Exhausted { .. } => &self.exhausted,
            Outcome::Skipped { .. } => &self.skipped,
            Outcome::Interrupted => &self.interrupted,
            Outcome::Unasked => &self.unasked,
            Outcome::Unroutable => &self.unroutable,
        }
    }

    fn with_cursor<R>(&self, read: impl FnOnce(&mut Cursor) -> R) -> R {
        let mut cursor = self.cursor.lock().unwrap_or_else(|e| e.into_inner());
        read(&mut cursor)
    }
}

// ╔════════════════════════════════════════════╗
// ║ ████████╗███████╗███████╗████████╗███████╗ ║
// ║ ╚══██╔══╝██╔════╝██╔════╝╚══██╔══╝██╔════╝ ║
// ║    ██║   █████╗  ███████╗   ██║   ███████╗ ║
// ║    ██║   ██╔══╝  ╚════██║   ██║   ╚════██║ ║
// ║    ██║   ███████╗███████║   ██║   ███████║ ║
// ║    ╚═╝   ╚══════╝╚══════╝   ╚═╝   ╚══════╝ ║
// ╚════════════════════════════════════════════╝

#[cfg(test)]
mod tests {
    use super::*;

    /// The rule the type exists to enforce.
    #[test]
    fn only_an_earned_outcome_carries_a_position() {
        assert_eq!(
            Outcome::Answered { position: 7 }.settled_position(),
            Some(7)
        );
        assert_eq!(
            Outcome::Exhausted { position: 7 }.settled_position(),
            Some(7)
        );

        assert_eq!(Outcome::Skipped { position: 7 }.settled_position(), Some(7));

        for assigned in [Outcome::Interrupted, Outcome::Unasked, Outcome::Unroutable] {
            assert_eq!(assigned.settled_position(), None, "{}", assigned.name());
            assert!(!assigned.is_settled());
        }
    }

    /// A sitting cut short gives every outstanding and unasked target the same
    /// verdict as an exhausted one, and advances the cursor over none.
    #[test]
    fn a_cut_short_sitting_settles_only_what_it_earned() {
        let settlements = Settlements::default();

        settlements.record(Outcome::Answered { position: 0 });
        settlements.record(Outcome::Exhausted { position: 1 });
        for _ in 0..500 {
            settlements.record(Outcome::Interrupted);
            settlements.record(Outcome::Unasked);
        }

        let checkpoint = settlements.checkpoint();
        assert_eq!(checkpoint.watermark, 2);
        assert!(checkpoint.settled_above.is_empty());
        assert_eq!(settlements.settled_count(), 2);
        assert_eq!(settlements.count(Outcome::Interrupted), 500);
    }

    /// Unsettled outcomes cost a counter each, whatever their number, so a scan
    /// that abandons millions of targets pays no memory for them.
    #[test]
    fn unsettled_outcomes_are_counted_rather_than_stored() {
        let settlements = Settlements::default();
        for _ in 0..100_000 {
            settlements.record(Outcome::Unasked);
        }

        assert_eq!(settlements.count(Outcome::Unasked), 100_000);
        assert_eq!(settlements.settled_count(), 0);
        assert_eq!(settlements.checkpoint(), Checkpoint::default());
    }

    /// One unearned position holds the watermark however much settles above it.
    #[test]
    fn one_unearned_position_stalls_the_watermark() {
        let settlements = Settlements::default();

        settlements.record(Outcome::Answered { position: 0 });
        // Position 1 was interrupted: it carries no position, so it is re-probed.
        settlements.record(Outcome::Interrupted);
        for position in 2..1_000 {
            settlements.record(Outcome::Answered { position });
        }

        assert_eq!(settlements.checkpoint().watermark, 1);
        assert_eq!(settlements.settled_count(), 999);
    }

    /// A resumed sitting starts from what the first settled, and counts only its
    /// own work.
    #[test]
    fn resuming_keeps_the_earlier_sittings_progress() {
        let first = Settlements::default();
        for position in 0..10 {
            first.record(Outcome::Answered { position });
        }

        let second = Settlements::resuming(&first.checkpoint());
        assert_eq!(second.settled_count(), 10);
        assert_eq!(second.count(Outcome::Answered { position: 0 }), 0);

        second.record(Outcome::Exhausted { position: 10 });
        assert_eq!(second.checkpoint().watermark, 11);
    }
}