1use 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);
20const 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#[derive(Debug, Clone, PartialEq, Eq)]
38pub struct PortCheck {
39 pub host: String,
41 pub port: u16,
43 pub open: bool,
45}
46
47#[derive(Debug)]
54pub struct PortCache {
55 entries: Mutex<HashMap<(String, u16), Entry>>,
56}
57
58impl PortCache {
59 pub fn new() -> Arc<Self> {
61 Arc::new(Self {
62 entries: Mutex::new(HashMap::new()),
63 })
64 }
65
66 pub fn global() -> Arc<Self> {
68 static CACHE: OnceLock<Arc<PortCache>> = OnceLock::new();
69 CACHE.get_or_init(PortCache::new).clone()
70 }
71
72 pub fn endpoints_for_run(spec: &ProgramSpec, base_url: &str) -> Vec<(String, u16)> {
74 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 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 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 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 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
178pub 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
192fn 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
214fn normalize_host(host: &str) -> String {
218 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
232pub 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 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 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 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}