Skip to main content

zond_engine/scanner/
handle.rs

1// Copyright (c) 2026 Erik Lening (hollowpointer) and Contributors
2//
3// This file is part of Zond Engine, licensed under the GNU Affero General
4// Public License, version 3 or later. See the LICENSE file for details, or
5// <https://www.gnu.org/licenses/agpl-3.0.html>.
6//
7// SPDX-License-Identifier: AGPL-3.0-or-later
8
9//! # Stopping a scan
10//!
11//! A scan spawns strategies that outlive the call that started them.
12//! [`ScanHandle`] is one flag and one deadline shared by all of them, cheap
13//! enough to read on every pass of every probing loop.
14//!
15//! A scan stops early when the caller asks or when its wall-clock budget runs
16//! out. Both wind the strategies down through the same check, and [`StopCause`]
17//! tells them apart in the report.
18
19use std::sync::Arc;
20use std::sync::atomic::{AtomicBool, Ordering};
21use std::time::{Duration, Instant};
22
23use tokio::sync::Notify;
24
25use crate::report::StopReason;
26use crate::scanner::pacing::timer::later;
27
28/// Why a scan is winding down.
29///
30/// Answered by [`ScanHandle::stopped`] and read by the probing loops to name
31/// their own stop. A scan stopped either way keeps what it had already learned.
32#[non_exhaustive]
33#[derive(Debug, Clone, Copy, PartialEq, Eq)]
34pub enum StopCause {
35    /// The caller asked the scan to stop, through [`ScanHandle::abort`].
36    Aborted,
37    /// The wall-clock budget the scan was given ran out. See
38    /// [`ZondConfig::scan_timeout`](crate::config::ZondConfig::scan_timeout).
39    TimedOut,
40}
41
42/// The means to stop a running scan, and the budget that stops it unasked.
43///
44/// Every strategy a scan spawned reads this on every pass of its loop, so a scan
45/// of a large range stops promptly.
46///
47/// Stopping does not cancel. The scan winds down and still produces its
48/// [`ScanReport`](crate::report::ScanReport), with the hosts found so far, and
49/// the report's [`StopReason`] marks it as shortened.
50///
51/// Clones share the same flag and deadline, including the copy on a
52/// [`ScanSession`](crate::scanner::session::ScanSession).
53#[derive(Debug, Clone)]
54pub struct ScanHandle {
55    stop: Arc<Stop>,
56}
57
58/// The shared half: what every clone of a handle reads.
59#[derive(Debug)]
60struct Stop {
61    aborted: AtomicBool,
62    /// Wakes whatever is waiting in [`ScanHandle::stopping`] when the scan is
63    /// aborted. The deadline needs no waking: a waiter sleeps until it.
64    woken: Notify,
65    /// When this scan's budget runs out, for one that was given a budget.
66    /// Monotonic, so a clock stepped mid-scan cannot end it early or late.
67    deadline: Option<Instant>,
68}
69
70impl Default for ScanHandle {
71    fn default() -> Self {
72        Self::new()
73    }
74}
75
76impl ScanHandle {
77    /// A handle for a scan with no budget, which stops only when asked.
78    pub fn new() -> Self {
79        Self::bounded(None)
80    }
81
82    /// A handle for a scan that stops on its own after `budget`, and `None` for
83    /// one that does not.
84    ///
85    /// The clock starts here, where the scan is assembled, so the budget covers
86    /// the whole call and not only the probing.
87    pub fn bounded(budget: Option<Duration>) -> Self {
88        let deadline = budget.map(|budget| later(Instant::now(), budget));
89        Self {
90            stop: Arc::new(Stop {
91                aborted: AtomicBool::new(false),
92                woken: Notify::new(),
93                deadline,
94            }),
95        }
96    }
97
98    /// Asks the scan to stop.
99    ///
100    /// Returns immediately; the strategies notice on their next pass. Await the
101    /// [`ScanTask`](crate::scanner::ScanTask) to know when they have all
102    /// finished and to collect the report.
103    ///
104    /// Idempotent and permanent.
105    pub fn abort(&self) {
106        self.stop.aborted.store(true, Ordering::SeqCst);
107        self.stop.woken.notify_waiters();
108    }
109
110    /// Resolves once the scan is asked to stop or outlives its budget, and at
111    /// once for one that already has.
112    ///
113    /// For one long wait on a peer that the probing loops cannot interrupt, such
114    /// as identifying a service on a port that accepts and says nothing (up to
115    /// half a minute). Raced against this, the wait ends when the scan does. See
116    /// [`or_stopped`](Self::or_stopped).
117    pub(crate) async fn stopping(&self) {
118        loop {
119            // Registered before the flag is read, so an abort in between still
120            // wakes this one.
121            let woken = self.stop.woken.notified();
122            tokio::pin!(woken);
123            woken.as_mut().enable();
124            if self.should_stop() {
125                return;
126            }
127            match self.stop.deadline {
128                Some(deadline) => tokio::select! {
129                    () = woken => {}
130                    () = tokio::time::sleep_until(deadline.into()) => return,
131                },
132                None => woken.await,
133            }
134        }
135    }
136
137    /// Runs `work` to its end unless the scan stops first, and `None` where it
138    /// did.
139    ///
140    /// The race favours the work, so an answer and a stop landing together keep
141    /// the answer.
142    pub(crate) async fn or_stopped<T>(&self, work: impl Future<Output = T>) -> Option<T> {
143        tokio::select! {
144            biased;
145            done = work => Some(done),
146            () = self.stopping() => None,
147        }
148    }
149
150    /// Whether the scan has been asked to stop, or has outlived its budget.
151    ///
152    /// Called by every probing loop each time round. Without a budget it reads one
153    /// atomic.
154    pub fn should_stop(&self) -> bool {
155        self.stopped().is_some()
156    }
157
158    /// Why the scan is stopping, or `None` while it is still running.
159    ///
160    /// The budget is read first, so an abort arriving after it expired does not
161    /// turn a timed-out scan into an aborted one.
162    pub fn stopped(&self) -> Option<StopCause> {
163        if self
164            .stop
165            .deadline
166            .is_some_and(|deadline| Instant::now() >= deadline)
167        {
168            return Some(StopCause::TimedOut);
169        }
170        if self.stop.aborted.load(Ordering::SeqCst) {
171            return Some(StopCause::Aborted);
172        }
173        None
174    }
175
176    /// When this scan's budget runs out, or `None` for a scan without one.
177    ///
178    /// The clock starts inside the call that assembles the scan, so a front end
179    /// showing the time left needs this and not the budget it asked for.
180    pub fn deadline(&self) -> Option<Instant> {
181        self.stop.deadline
182    }
183}
184
185impl From<StopCause> for StopReason {
186    /// The one mapping every probing loop uses to record why it stopped.
187    fn from(cause: StopCause) -> Self {
188        match cause {
189            StopCause::Aborted => StopReason::Aborted,
190            StopCause::TimedOut => StopReason::TimedOut,
191        }
192    }
193}
194
195// ╔════════════════════════════════════════════╗
196// ║ ████████╗███████╗███████╗████████╗███████╗ ║
197// ║ ╚══██╔══╝██╔════╝██╔════╝╚══██╔══╝██╔════╝ ║
198// ║    ██║   █████╗  ███████╗   ██║   ███████╗ ║
199// ║    ██║   ██╔══╝  ╚════██║   ██║   ╚════██║ ║
200// ║    ██║   ███████╗███████║   ██║   ███████║ ║
201// ║    ╚═╝   ╚══════╝╚══════╝   ╚═╝   ╚══════╝ ║
202// ╚════════════════════════════════════════════╝
203
204#[cfg(test)]
205mod tests {
206    use super::*;
207
208    /// Without a budget only an abort stops the scan.
209    #[test]
210    fn a_handle_with_no_budget_stops_only_when_asked() {
211        let handle = ScanHandle::new();
212        assert_eq!(handle.stopped(), None);
213        handle.abort();
214        assert_eq!(handle.stopped(), Some(StopCause::Aborted));
215    }
216
217    /// An expired budget stops the scan with nobody asking.
218    #[test]
219    fn an_expired_budget_stops_a_scan_nobody_touched() {
220        let handle = ScanHandle::bounded(Some(Duration::ZERO));
221        assert_eq!(handle.stopped(), Some(StopCause::TimedOut));
222        assert!(handle.should_stop());
223    }
224
225    /// A budget that has not run out yet leaves the scan running, and the
226    /// clones read the same deadline.
227    #[test]
228    fn a_budget_still_running_stops_nothing() {
229        let handle = ScanHandle::bounded(Some(Duration::from_secs(3600)));
230        let clone = handle.clone();
231        assert_eq!(handle.stopped(), None);
232        assert_eq!(clone.deadline(), handle.deadline());
233    }
234
235    /// `Duration::MAX` is past what the clock can count to, and must not panic.
236    #[test]
237    fn the_longest_budget_is_one_that_never_runs_out() {
238        let handle = ScanHandle::bounded(Some(Duration::MAX));
239        assert_eq!(handle.stopped(), None);
240        assert!(handle.deadline().is_some());
241    }
242
243    /// An in-flight identification ends with the scan, not after its own ceiling.
244    #[tokio::test]
245    async fn a_wait_raced_against_the_stop_ends_when_the_scan_is_aborted() {
246        let handle = ScanHandle::new();
247        let aborter = handle.clone();
248        let waiting =
249            tokio::spawn(async move { handle.or_stopped(std::future::pending::<()>()).await });
250        tokio::task::yield_now().await;
251        aborter.abort();
252
253        assert_eq!(waiting.await.expect("the wait ends"), None);
254    }
255
256    /// The budget ends the wait the same way, with nobody asking.
257    #[tokio::test]
258    async fn a_wait_raced_against_the_stop_ends_when_the_budget_runs_out() {
259        let handle = ScanHandle::bounded(Some(Duration::from_millis(10)));
260
261        let raced = handle.or_stopped(std::future::pending::<()>()).await;
262
263        assert_eq!(raced, None);
264        assert!(handle.should_stop());
265    }
266
267    /// Work that finishes is kept, even on a stopped scan: the race favours the
268    /// answer.
269    #[tokio::test]
270    async fn work_that_finishes_is_kept() {
271        let handle = ScanHandle::new();
272        assert_eq!(handle.or_stopped(async { 7 }).await, Some(7));
273        handle.abort();
274        assert_eq!(handle.or_stopped(async { 7 }).await, Some(7));
275        assert_eq!(handle.or_stopped(std::future::pending::<u8>()).await, None);
276    }
277
278    /// An abort after the budget expired leaves the cause as `TimedOut`.
279    #[test]
280    fn a_late_abort_does_not_rename_an_expired_budget() {
281        let handle = ScanHandle::bounded(Some(Duration::ZERO));
282        handle.abort();
283        assert_eq!(handle.stopped(), Some(StopCause::TimedOut));
284    }
285}