device_daemon_core/
tcp_scan.rs1use anyhow::{bail, Context, Result};
5use async_trait::async_trait;
6use std::time::Duration;
7use tokio::{sync::watch, time};
8
9#[derive(Debug, Clone, PartialEq, Eq)]
10pub struct TcpScanProfile {
11 pub default_address: Option<u8>,
12 pub broadcast_address: Option<u8>,
13 pub addresses: Vec<u8>,
14 pub operation_timeout: Duration,
15 pub delay_between_probes: Duration,
16 pub stop_after_first_match: bool,
17}
18
19impl TcpScanProfile {
20 fn validate(&self) -> Result<()> {
21 if self.default_address.is_none()
22 && self.broadcast_address.is_none()
23 && self.addresses.is_empty()
24 {
25 bail!("TCP scan address plan must contain at least one address");
26 }
27 if self.operation_timeout.is_zero() {
28 bail!("TCP scan operation timeout must be greater than zero");
29 }
30 Ok(())
31 }
32
33 fn ordered_addresses(&self) -> Vec<u8> {
34 let mut addresses = Vec::with_capacity(
35 self.addresses.len()
36 + usize::from(self.default_address.is_some())
37 + usize::from(self.broadcast_address.is_some()),
38 );
39 for address in self
40 .default_address
41 .into_iter()
42 .chain(self.broadcast_address)
43 .chain(self.addresses.iter().copied())
44 {
45 if !addresses.contains(&address) {
46 addresses.push(address);
47 }
48 }
49 addresses
50 }
51}
52
53#[derive(Debug, Clone, PartialEq, Eq)]
54pub struct TcpScanMatch<T> {
55 pub address: u8,
56 pub details: T,
57}
58
59#[derive(Debug, Clone, PartialEq, Eq)]
60pub struct TcpScanReport<T> {
61 pub matches: Vec<TcpScanMatch<T>>,
62 pub probes_attempted: usize,
63 pub cancelled: bool,
64}
65
66#[async_trait]
67pub trait TcpProbe: Send {
68 type Match: Send;
69
70 async fn probe(&mut self, address: u8) -> Result<Option<Self::Match>>;
72}
73
74pub async fn scan<P: TcpProbe>(
77 profile: &TcpScanProfile,
78 probe: &mut P,
79 mut shutdown: watch::Receiver<bool>,
80) -> Result<TcpScanReport<P::Match>> {
81 profile.validate()?;
82 let mut report = TcpScanReport {
83 matches: Vec::new(),
84 probes_attempted: 0,
85 cancelled: false,
86 };
87
88 for (index, address) in profile.ordered_addresses().into_iter().enumerate() {
89 if *shutdown.borrow() {
90 report.cancelled = true;
91 break;
92 }
93 if index > 0 && !profile.delay_between_probes.is_zero() {
94 tokio::select! {
95 _ = time::sleep(profile.delay_between_probes) => {}
96 changed = shutdown.changed() => {
97 if changed.is_err() || *shutdown.borrow() {
98 report.cancelled = true;
99 break;
100 }
101 }
102 }
103 }
104
105 report.probes_attempted += 1;
106 let result = tokio::select! {
107 result = time::timeout(profile.operation_timeout, probe.probe(address)) => {
108 result.context("Timed out probing TCP scan address")??
109 }
110 changed = shutdown.changed() => {
111 if changed.is_err() || *shutdown.borrow() {
112 report.cancelled = true;
113 break;
114 }
115 continue;
116 }
117 };
118 if let Some(details) = result {
119 report.matches.push(TcpScanMatch { address, details });
120 if profile.stop_after_first_match {
121 break;
122 }
123 }
124 }
125 Ok(report)
126}
127
128#[cfg(test)]
129mod tests {
130 use super::*;
131 use std::sync::{Arc, Mutex};
132
133 struct FakeProbe {
134 seen: Arc<Mutex<Vec<u8>>>,
135 matches: Vec<u8>,
136 }
137
138 #[async_trait]
139 impl TcpProbe for FakeProbe {
140 type Match = u8;
141
142 async fn probe(&mut self, address: u8) -> Result<Option<Self::Match>> {
143 self.seen.lock().unwrap().push(address);
144 Ok(self.matches.contains(&address).then_some(address))
145 }
146 }
147
148 fn profile() -> TcpScanProfile {
149 TcpScanProfile {
150 default_address: Some(1),
151 broadcast_address: Some(0),
152 addresses: vec![0, 2, 3],
153 operation_timeout: Duration::from_secs(1),
154 delay_between_probes: Duration::ZERO,
155 stop_after_first_match: true,
156 }
157 }
158
159 #[tokio::test]
160 async fn scans_unique_addresses_in_order_and_stops_at_first_match() {
161 let seen = Arc::new(Mutex::new(Vec::new()));
162 let mut probe = FakeProbe {
163 seen: Arc::clone(&seen),
164 matches: vec![2, 3],
165 };
166 let (_sender, receiver) = watch::channel(false);
167 let report = scan(&profile(), &mut probe, receiver).await.unwrap();
168
169 assert_eq!(*seen.lock().unwrap(), vec![1, 0, 2]);
170 assert_eq!(report.probes_attempted, 3);
171 assert_eq!(
172 report.matches,
173 vec![TcpScanMatch {
174 address: 2,
175 details: 2
176 }]
177 );
178 }
179
180 #[tokio::test]
181 async fn rejects_empty_address_plan_and_zero_timeout() {
182 let mut invalid = profile();
183 invalid.default_address = None;
184 invalid.broadcast_address = None;
185 invalid.addresses.clear();
186 let (_sender, receiver) = watch::channel(false);
187 let mut probe = FakeProbe {
188 seen: Arc::new(Mutex::new(Vec::new())),
189 matches: Vec::new(),
190 };
191 assert!(scan(&invalid, &mut probe, receiver).await.is_err());
192
193 let mut invalid = profile();
194 invalid.operation_timeout = Duration::ZERO;
195 let (_sender, receiver) = watch::channel(false);
196 assert!(scan(&invalid, &mut probe, receiver).await.is_err());
197 }
198}