use anyhow::{bail, Context, Result};
use async_trait::async_trait;
use std::time::Duration;
use tokio::{sync::watch, time};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TcpScanProfile {
pub default_address: Option<u8>,
pub broadcast_address: Option<u8>,
pub addresses: Vec<u8>,
pub operation_timeout: Duration,
pub delay_between_probes: Duration,
pub stop_after_first_match: bool,
}
impl TcpScanProfile {
fn validate(&self) -> Result<()> {
if self.default_address.is_none()
&& self.broadcast_address.is_none()
&& self.addresses.is_empty()
{
bail!("TCP scan address plan must contain at least one address");
}
if self.operation_timeout.is_zero() {
bail!("TCP scan operation timeout must be greater than zero");
}
Ok(())
}
fn ordered_addresses(&self) -> Vec<u8> {
let mut addresses = Vec::with_capacity(
self.addresses.len()
+ usize::from(self.default_address.is_some())
+ usize::from(self.broadcast_address.is_some()),
);
for address in self
.default_address
.into_iter()
.chain(self.broadcast_address)
.chain(self.addresses.iter().copied())
{
if !addresses.contains(&address) {
addresses.push(address);
}
}
addresses
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TcpScanMatch<T> {
pub address: u8,
pub details: T,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TcpScanReport<T> {
pub matches: Vec<TcpScanMatch<T>>,
pub probes_attempted: usize,
pub cancelled: bool,
}
#[async_trait]
pub trait TcpProbe: Send {
type Match: Send;
async fn probe(&mut self, address: u8) -> Result<Option<Self::Match>>;
}
pub async fn scan<P: TcpProbe>(
profile: &TcpScanProfile,
probe: &mut P,
mut shutdown: watch::Receiver<bool>,
) -> Result<TcpScanReport<P::Match>> {
profile.validate()?;
let mut report = TcpScanReport {
matches: Vec::new(),
probes_attempted: 0,
cancelled: false,
};
for (index, address) in profile.ordered_addresses().into_iter().enumerate() {
if *shutdown.borrow() {
report.cancelled = true;
break;
}
if index > 0 && !profile.delay_between_probes.is_zero() {
tokio::select! {
_ = time::sleep(profile.delay_between_probes) => {}
changed = shutdown.changed() => {
if changed.is_err() || *shutdown.borrow() {
report.cancelled = true;
break;
}
}
}
}
report.probes_attempted += 1;
let result = tokio::select! {
result = time::timeout(profile.operation_timeout, probe.probe(address)) => {
result.context("Timed out probing TCP scan address")??
}
changed = shutdown.changed() => {
if changed.is_err() || *shutdown.borrow() {
report.cancelled = true;
break;
}
continue;
}
};
if let Some(details) = result {
report.matches.push(TcpScanMatch { address, details });
if profile.stop_after_first_match {
break;
}
}
}
Ok(report)
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::{Arc, Mutex};
struct FakeProbe {
seen: Arc<Mutex<Vec<u8>>>,
matches: Vec<u8>,
}
#[async_trait]
impl TcpProbe for FakeProbe {
type Match = u8;
async fn probe(&mut self, address: u8) -> Result<Option<Self::Match>> {
self.seen.lock().unwrap().push(address);
Ok(self.matches.contains(&address).then_some(address))
}
}
fn profile() -> TcpScanProfile {
TcpScanProfile {
default_address: Some(1),
broadcast_address: Some(0),
addresses: vec![0, 2, 3],
operation_timeout: Duration::from_secs(1),
delay_between_probes: Duration::ZERO,
stop_after_first_match: true,
}
}
#[tokio::test]
async fn scans_unique_addresses_in_order_and_stops_at_first_match() {
let seen = Arc::new(Mutex::new(Vec::new()));
let mut probe = FakeProbe {
seen: Arc::clone(&seen),
matches: vec![2, 3],
};
let (_sender, receiver) = watch::channel(false);
let report = scan(&profile(), &mut probe, receiver).await.unwrap();
assert_eq!(*seen.lock().unwrap(), vec![1, 0, 2]);
assert_eq!(report.probes_attempted, 3);
assert_eq!(
report.matches,
vec![TcpScanMatch {
address: 2,
details: 2
}]
);
}
#[tokio::test]
async fn rejects_empty_address_plan_and_zero_timeout() {
let mut invalid = profile();
invalid.default_address = None;
invalid.broadcast_address = None;
invalid.addresses.clear();
let (_sender, receiver) = watch::channel(false);
let mut probe = FakeProbe {
seen: Arc::new(Mutex::new(Vec::new())),
matches: Vec::new(),
};
assert!(scan(&invalid, &mut probe, receiver).await.is_err());
let mut invalid = profile();
invalid.operation_timeout = Duration::ZERO;
let (_sender, receiver) = watch::channel(false);
assert!(scan(&invalid, &mut probe, receiver).await.is_err());
}
}