Skip to main content

ruso_runtime/runtime/
port_cache.rs

1//! TCP port reachability cache (30s TTL), shared across executor runs in one process.
2
3use std::collections::HashMap;
4use std::net::IpAddr;
5use std::sync::{Arc, OnceLock};
6use std::time::{Duration, Instant};
7
8use tokio::net::TcpStream;
9use tokio::sync::Mutex;
10use tokio::time::timeout;
11
12use reqwest::Url;
13
14use crate::runtime::context::VariableValue;
15use crate::runtime::interpolate::interpolate;
16use crate::runtime::spec::{ProbeKind, ProgramSpec};
17
18const CACHE_TTL: Duration = Duration::from_secs(30);
19const CONNECT_TIMEOUT: Duration = Duration::from_millis(1500);
20/// Cap cache size to bound memory growth during long-running bulk scans.
21/// At ~50 bytes per entry plus map overhead this is well under 1 MB.
22const MAX_CACHE_ENTRIES: usize = 4096;
23
24#[derive(Debug, Clone, Copy, PartialEq, Eq)]
25enum Reachability {
26    Open,
27    Closed,
28}
29
30#[derive(Debug)]
31struct Entry {
32    state: Reachability,
33    checked_at: Instant,
34}
35
36/// Result of probing one `host:port` (from cache or live TCP connect).
37#[derive(Debug, Clone, PartialEq, Eq)]
38pub struct PortCheck {
39    /// The host that was probed, with any `{{ var }}` already resolved.
40    pub host: String,
41    /// The port that was probed.
42    pub port: u16,
43    /// Whether a TCP connection succeeded within the connect timeout.
44    pub open: bool,
45}
46
47/// A TTL cache of `host:port` reachability.
48///
49/// A bulk scan aims many checks at the same handful of ports; without this,
50/// every check would pay its own connect timeout against a port that is already
51/// known to be closed. Entries live for 30 seconds and the map is capped so a
52/// long run cannot grow without bound.
53#[derive(Debug)]
54pub struct PortCache {
55    entries: Mutex<HashMap<(String, u16), Entry>>,
56}
57
58impl PortCache {
59    /// An empty cache, independent of the process-wide one.
60    pub fn new() -> Arc<Self> {
61        Arc::new(Self {
62            entries: Mutex::new(HashMap::new()),
63        })
64    }
65
66    /// Process-wide cache so back-to-back checks in `ruso scan` reuse state.
67    pub fn global() -> Arc<Self> {
68        static CACHE: OnceLock<Arc<PortCache>> = OnceLock::new();
69        CACHE.get_or_init(PortCache::new).clone()
70    }
71
72    /// Endpoints to probe before running: socket probes in the spec plus `--target` host:port for HTTP checks.
73    pub fn endpoints_for_run(spec: &ProgramSpec, base_url: &str) -> Vec<(String, u16)> {
74        // Socket probes may use the documented `host "{{scan_host}}"` form,
75        // which the executor resolves from `--target` at send-time. The
76        // pre-run port check must resolve it identically, or it would probe
77        // the literal placeholder, find it "closed", and skip the whole run.
78        let scan_vars = scan_target_variables(base_url);
79        let resolve =
80            |host: &str| interpolate(host, &scan_vars).unwrap_or_else(|_| host.to_string());
81
82        let mut out = Vec::new();
83        for kind in spec.probes.values() {
84            match kind {
85                // Only connection-oriented TCP probes get a TCP-connect liveness
86                // pre-check. UDP and wire-DNS probes are sent as connectionless
87                // datagrams (`exchange_udp`), so a TCP connect to the same port
88                // proves nothing about the UDP service — and would wrongly skip
89                // the entire run for UDP-only hosts (NTP, SNMP, syslog, UDP-only
90                // resolvers, …). Those probes rely on their own read timeout.
91                ProbeKind::Tcp(socket) => {
92                    if let Some(port) = socket.port {
93                        out.push((normalize_host(&resolve(&socket.host)), port));
94                    }
95                }
96                ProbeKind::Udp(_) | ProbeKind::Dns(_) | ProbeKind::Http(_) => {}
97            }
98        }
99
100        let has_http = spec
101            .probes
102            .values()
103            .any(|k| matches!(k, ProbeKind::Http(_)));
104        if has_http && let Some((host, port)) = scan_target_host_port(base_url) {
105            out.push((host, port));
106        }
107
108        dedupe_endpoints(out)
109    }
110
111    /// Probe every endpoint for this run; returns checks and the first closed `(host, port)` if any.
112    pub async fn check_for_run(
113        &self,
114        spec: &ProgramSpec,
115        base_url: &str,
116    ) -> (Vec<PortCheck>, Option<(String, u16)>) {
117        let endpoints = Self::endpoints_for_run(spec, base_url);
118        let mut checks = Vec::with_capacity(endpoints.len());
119        let mut first_closed = None;
120
121        for (host, port) in endpoints {
122            let open = self.is_open(&host, port).await;
123            checks.push(PortCheck {
124                host: host.clone(),
125                port,
126                open,
127            });
128            if !open && first_closed.is_none() {
129                first_closed = Some((host, port));
130            }
131        }
132
133        (checks, first_closed)
134    }
135
136    /// Whether `host:port` is reachable, answering from cache when a probe is
137    /// less than 30 seconds old and connecting otherwise.
138    pub async fn is_open(&self, host: &str, port: u16) -> bool {
139        self.get_state(host, port).await == Reachability::Open
140    }
141
142    async fn get_state(&self, host: &str, port: u16) -> Reachability {
143        let normalized = normalize_host(host);
144        let key = (normalized, port);
145        {
146            let guard = self.entries.lock().await;
147            if let Some(entry) = guard.get(&key)
148                && entry.checked_at.elapsed() < CACHE_TTL
149            {
150                return entry.state;
151            }
152        }
153
154        let state = probe_tcp(&key.0, port).await;
155        let mut guard = self.entries.lock().await;
156        // Evict the oldest entry if we'd otherwise exceed the cap. Linear
157        // scan is fine at the 4K-entry scale — bulk scans grow this slowly.
158        if guard.len() >= MAX_CACHE_ENTRIES
159            && !guard.contains_key(&key)
160            && let Some(oldest_key) = guard
161                .iter()
162                .min_by_key(|(_, e)| e.checked_at)
163                .map(|(k, _)| k.clone())
164        {
165            guard.remove(&oldest_key);
166        }
167        guard.insert(
168            key,
169            Entry {
170                state,
171                checked_at: Instant::now(),
172            },
173        );
174        state
175    }
176}
177
178/// Host and port from CLI `--target` / executor `base_url` (for `{{scan_host}}` / `{{scan_port}}`).
179/// The `host` and effective `port` of a scan target URL, defaulting the port
180/// from the scheme (443 for `https`, 80 otherwise).
181///
182/// Returns `None` when `base_url` does not parse or carries no host.
183pub fn scan_target_host_port(base_url: &str) -> Option<(String, u16)> {
184    let url = Url::parse(base_url).ok()?;
185    let host = url.host_str()?;
186    let port = url
187        .port()
188        .unwrap_or_else(|| if url.scheme() == "https" { 443 } else { 80 });
189    Some((normalize_host(host), port))
190}
191
192/// Build the `{{scan_host}}` / `{{scan_port}}` / `{{scan_url}}` variables from
193/// the CLI `--target` (executor `base_url`). Mirrors the executor's
194/// `inject_scan_target_variables` so the pre-run port check resolves socket
195/// hosts the same way the send path does.
196fn scan_target_variables(base_url: &str) -> HashMap<String, VariableValue> {
197    let mut vars = HashMap::new();
198    if let Some((host, port)) = scan_target_host_port(base_url) {
199        vars.insert("scan_host".to_string(), VariableValue::String(host));
200        vars.insert(
201            "scan_port".to_string(),
202            VariableValue::String(port.to_string()),
203        );
204    }
205    if !base_url.is_empty() {
206        vars.insert(
207            "scan_url".to_string(),
208            VariableValue::String(base_url.to_string()),
209        );
210    }
211    vars
212}
213
214/// Canonicalize a host string so equivalent IPv6 representations
215/// (`::1`, `0:0:0:0:0:0:0:1`) and arbitrary case in hostnames share one
216/// cache entry. Falls back to the original string on unknown formats.
217fn normalize_host(host: &str) -> String {
218    // Strip any surrounding brackets so `[::1]` and `::1` normalize the same.
219    let trimmed = host.trim_start_matches('[').trim_end_matches(']');
220    if let Ok(ip) = trimmed.parse::<IpAddr>() {
221        return ip.to_string();
222    }
223    host.to_ascii_lowercase()
224}
225
226fn dedupe_endpoints(mut endpoints: Vec<(String, u16)>) -> Vec<(String, u16)> {
227    endpoints.sort_unstable();
228    endpoints.dedup();
229    endpoints
230}
231
232/// Format a `host:port` socket address, bracketing literal IPv6 addresses
233/// so they parse correctly via `tokio::net::TcpStream::connect`.
234/// Format `host:port` for display, bracketing bare IPv6 literals so the result
235/// is a valid socket address.
236pub fn format_socket_addr(host: &str, port: u16) -> String {
237    let trimmed = host.trim_start_matches('[').trim_end_matches(']');
238    if trimmed.parse::<std::net::Ipv6Addr>().is_ok() {
239        format!("[{trimmed}]:{port}")
240    } else {
241        format!("{host}:{port}")
242    }
243}
244
245async fn probe_tcp(host: &str, port: u16) -> Reachability {
246    let address = format_socket_addr(host, port);
247    match timeout(CONNECT_TIMEOUT, TcpStream::connect(address.as_str())).await {
248        Ok(Ok(_)) => Reachability::Open,
249        _ => Reachability::Closed,
250    }
251}
252
253#[cfg(test)]
254mod tests {
255    use super::*;
256
257    #[test]
258    fn normalize_ipv6_collapses_long_form() {
259        assert_eq!(normalize_host("::1"), normalize_host("0:0:0:0:0:0:0:1"));
260        assert_eq!(normalize_host("[::1]"), normalize_host("::1"));
261    }
262
263    #[test]
264    fn normalize_hostname_lowercases() {
265        assert_eq!(normalize_host("Example.COM"), "example.com");
266    }
267
268    #[test]
269    fn format_socket_addr_brackets_ipv6() {
270        assert_eq!(format_socket_addr("::1", 443), "[::1]:443");
271    }
272
273    #[test]
274    fn format_socket_addr_passes_through_ipv4() {
275        assert_eq!(format_socket_addr("127.0.0.1", 80), "127.0.0.1:80");
276    }
277
278    #[test]
279    fn format_socket_addr_passes_through_hostname() {
280        assert_eq!(format_socket_addr("example.com", 80), "example.com:80");
281    }
282
283    #[test]
284    fn scan_target_handles_ipv6_url() {
285        let (host, port) = scan_target_host_port("http://[::1]:8080/api").unwrap();
286        assert_eq!(host, "::1");
287        assert_eq!(port, 8080);
288    }
289
290    fn tcp_spec(host: &str) -> ProgramSpec {
291        use crate::runtime::spec::{CheckMetadata, SocketProbeSpec};
292        let mut probes = std::collections::HashMap::new();
293        probes.insert(
294            "svc".to_string(),
295            ProbeKind::Tcp(SocketProbeSpec {
296                host: host.to_string(),
297                port: Some(6379),
298                ..SocketProbeSpec::default()
299            }),
300        );
301        ProgramSpec {
302            probes,
303            metadata: CheckMetadata::default(),
304        }
305    }
306
307    #[test]
308    fn endpoints_interpolate_scan_host_for_socket_probes() {
309        // The pre-run port check must resolve `{{scan_host}}` from --target,
310        // just like the send path — otherwise socket probes are wrongly skipped.
311        let eps = PortCache::endpoints_for_run(&tcp_spec("{{scan_host}}"), "http://127.0.0.1:6379");
312        assert_eq!(eps, vec![("127.0.0.1".to_string(), 6379)]);
313    }
314
315    #[test]
316    fn endpoints_keep_static_host_unchanged() {
317        // A hardcoded host has no placeholder and must pass through verbatim,
318        // with or without a --target (e.g. banner-grab probes).
319        let eps = PortCache::endpoints_for_run(&tcp_spec("scanme.example.com"), "");
320        assert_eq!(eps, vec![("scanme.example.com".to_string(), 6379)]);
321    }
322
323    fn single_probe_spec(kind: ProbeKind) -> ProgramSpec {
324        use crate::runtime::spec::CheckMetadata;
325        let mut probes = std::collections::HashMap::new();
326        probes.insert("svc".to_string(), kind);
327        ProgramSpec {
328            probes,
329            metadata: CheckMetadata::default(),
330        }
331    }
332
333    #[test]
334    fn udp_and_dns_probes_get_no_tcp_precheck() {
335        use crate::runtime::spec::SocketProbeSpec;
336        // UDP and wire-DNS are connectionless; a TCP-connect pre-check to their
337        // port proves nothing and would wrongly skip the run on UDP-only hosts.
338        let udp = single_probe_spec(ProbeKind::Udp(SocketProbeSpec {
339            host: "{{scan_host}}".into(),
340            port: Some(123),
341            ..SocketProbeSpec::default()
342        }));
343        assert!(PortCache::endpoints_for_run(&udp, "http://127.0.0.1").is_empty());
344
345        let dns = single_probe_spec(ProbeKind::Dns(SocketProbeSpec {
346            host: "{{scan_host}}".into(),
347            port: Some(53),
348            ..SocketProbeSpec::default()
349        }));
350        assert!(PortCache::endpoints_for_run(&dns, "http://127.0.0.1").is_empty());
351    }
352}