use dashmap::DashMap;
use std::net::IpAddr;
use std::sync::{Arc, Mutex};
use tokio::sync::mpsc;
use tracing::error;
use crate::model::host::Host;
use crate::model::technique::TcpScanTechnique;
use crate::scanner::handle::ScanHandle;
use crate::scanner::report::{ProbeStats, ScannerFailure};
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ScannerKind {
Local,
Routed,
SynPort,
TcpPort,
Connect,
ConnectUdp,
UdpPort,
OsEcho,
Composite,
}
impl ScannerKind {
pub const fn for_raw_tcp(technique: TcpScanTechnique) -> Self {
match technique {
TcpScanTechnique::Syn => Self::SynPort,
_ => Self::TcpPort,
}
}
}
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum ScanEvent {
HostUpdated(IpAddr),
ScannerFailed {
scanner: ScannerKind,
reason: String,
},
}
#[derive(Debug, Clone, Default)]
pub struct HostStore {
inner: Arc<DashMap<IpAddr, Host>>,
}
impl HostStore {
fn new(inner: Arc<DashMap<IpAddr, Host>>) -> Self {
Self { inner }
}
pub fn get(&self, ip: &IpAddr) -> Option<Host> {
self.inner.get(ip).map(|entry| entry.value().clone())
}
pub fn contains(&self, ip: &IpAddr) -> bool {
self.inner.contains_key(ip)
}
pub fn len(&self) -> usize {
self.inner.len()
}
pub fn is_empty(&self) -> bool {
self.inner.is_empty()
}
pub fn snapshot(&self) -> Vec<Host> {
let mut hosts: Vec<Host> = self
.inner
.iter()
.map(|entry| entry.value().clone())
.collect();
hosts.sort_by_key(Host::primary_ip);
hosts
}
#[cfg(test)]
pub(crate) fn insert(&self, ip: IpAddr, host: Host) {
self.inner.insert(ip, host);
}
}
#[derive(Debug)]
pub struct ScanEvents {
rx: mpsc::UnboundedReceiver<ScanEvent>,
}
impl ScanEvents {
pub async fn recv(&mut self) -> Option<ScanEvent> {
self.rx.recv().await
}
pub fn try_recv(&mut self) -> Option<ScanEvent> {
self.rx.try_recv().ok()
}
}
pub struct ScanSession {
store: HostStore,
events: ScanEvents,
handle: ScanHandle,
}
impl ScanSession {
pub fn hosts(&self) -> &HostStore {
&self.store
}
pub fn events(&mut self) -> &mut ScanEvents {
&mut self.events
}
pub fn handle(&self) -> &ScanHandle {
&self.handle
}
pub fn into_parts(self) -> (HostStore, ScanEvents, ScanHandle) {
(self.store, self.events, self.handle)
}
}
#[derive(Debug, Default)]
pub(crate) struct ProbeStatsLog {
entries: Mutex<Vec<ProbeStats>>,
}
impl ProbeStatsLog {
fn push(&self, stats: ProbeStats) {
let mut entries = self.entries.lock().unwrap_or_else(|e| e.into_inner());
entries.push(stats);
}
fn drain(&self) -> Vec<ProbeStats> {
let mut entries = self.entries.lock().unwrap_or_else(|e| e.into_inner());
std::mem::take(&mut *entries)
}
fn snapshot(&self) -> Vec<ProbeStats> {
self.entries
.lock()
.unwrap_or_else(|e| e.into_inner())
.clone()
}
}
#[derive(Debug, Default)]
pub(crate) struct FailureLog {
entries: Mutex<Vec<ScannerFailure>>,
}
impl FailureLog {
fn push(&self, failure: ScannerFailure) {
let mut entries = self.entries.lock().unwrap_or_else(|e| e.into_inner());
entries.push(failure);
}
fn drain(&self) -> Vec<ScannerFailure> {
let mut entries = self.entries.lock().unwrap_or_else(|e| e.into_inner());
std::mem::take(&mut *entries)
}
fn snapshot(&self) -> Vec<ScannerFailure> {
self.entries
.lock()
.unwrap_or_else(|e| e.into_inner())
.clone()
}
}
#[derive(Clone)]
pub struct ScanContext {
pub(crate) handle: ScanHandle,
pub(crate) store: Arc<DashMap<IpAddr, Host>>,
pub(crate) events_tx: mpsc::UnboundedSender<ScanEvent>,
pub(crate) failures: Arc<FailureLog>,
pub(crate) probe_stats: Arc<ProbeStatsLog>,
}
impl ScanContext {
pub fn write_host(&self, ip: IpAddr, edit: impl FnOnce(&mut Host) -> bool) -> bool {
let mut is_new = false;
let mut host = self.store.entry(ip).or_insert_with(|| {
is_new = true;
Host::new(ip)
});
let changed = edit(&mut host);
drop(host);
if changed || is_new {
let _ = self.events_tx.send(ScanEvent::HostUpdated(ip));
}
is_new
}
pub fn read_host<R>(&self, ip: &IpAddr, read: impl FnOnce(&Host) -> R) -> Option<R> {
self.store.get(ip).map(|entry| read(entry.value()))
}
pub fn host_addresses(&self) -> Vec<IpAddr> {
self.store.iter().map(|entry| *entry.key()).collect()
}
pub fn record_failure(&self, scanner: ScannerKind, reason: String) {
error!("Scanner {scanner:?} failed: {reason}");
self.failures
.push(ScannerFailure::new(scanner, reason.clone()));
let _ = self
.events_tx
.send(ScanEvent::ScannerFailed { scanner, reason });
}
pub fn record_probe_stats(&self, stats: ProbeStats) {
self.probe_stats.push(stats);
}
pub(crate) fn take_probe_stats(&self) -> Vec<ProbeStats> {
self.probe_stats.drain()
}
pub fn probe_stats_snapshot(&self) -> Vec<ProbeStats> {
self.probe_stats.snapshot()
}
pub(crate) fn take_failures(&self) -> Vec<ScannerFailure> {
self.failures.drain()
}
pub fn failures_snapshot(&self) -> Vec<ScannerFailure> {
self.failures.snapshot()
}
pub fn update_host(&self, ip: IpAddr, update: impl FnOnce(&mut Host)) -> bool {
self.write_host(ip, |host| {
update(host);
true
})
}
}
impl ScanSession {
pub fn new() -> (Self, ScanContext) {
let store = Arc::new(DashMap::new());
let handle = ScanHandle::new();
let (events_tx, rx) = mpsc::unbounded_channel();
let session = Self {
store: HostStore::new(store.clone()),
events: ScanEvents { rx },
handle: handle.clone(),
};
let ctx = ScanContext {
handle,
store,
events_tx,
failures: Arc::new(FailureLog::default()),
probe_stats: Arc::new(ProbeStatsLog::default()),
};
(session, ctx)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_failure_survives_a_consumer_that_never_listens() {
let (session, ctx) = ScanSession::new();
drop(session);
ctx.record_failure(ScannerKind::Routed, "raw socket unavailable".into());
let failures = ctx.take_failures();
assert_eq!(failures.len(), 1);
assert_eq!(failures[0].scanner(), ScannerKind::Routed);
assert_eq!(failures[0].reason(), "raw socket unavailable");
}
#[test]
fn a_failure_reaches_both_the_log_and_the_stream() {
let (mut session, ctx) = ScanSession::new();
ctx.record_failure(ScannerKind::Local, "eth0: no address".into());
match session.events().try_recv() {
Some(ScanEvent::ScannerFailed { scanner, reason }) => {
assert_eq!(scanner, ScannerKind::Local);
assert_eq!(reason, "eth0: no address");
}
other => panic!("expected a ScannerFailed event, got {other:?}"),
}
assert_eq!(ctx.take_failures().len(), 1);
}
#[test]
fn snapshotting_failures_leaves_them_for_the_report() {
let (_session, ctx) = ScanSession::new();
ctx.record_failure(ScannerKind::Local, "eth0: no address".into());
assert_eq!(ctx.failures_snapshot().len(), 1);
assert_eq!(ctx.failures_snapshot().len(), 1, "reading is not taking");
assert_eq!(ctx.take_failures().len(), 1, "and the report still gets it");
}
#[test]
fn taking_failures_empties_the_log() {
let (_session, ctx) = ScanSession::new();
ctx.record_failure(ScannerKind::Connect, "refused".into());
assert_eq!(ctx.take_failures().len(), 1);
assert!(ctx.take_failures().is_empty());
}
#[test]
fn failures_from_every_clone_land_in_one_log() {
let (_session, ctx) = ScanSession::new();
let clone = ctx.clone();
ctx.record_failure(ScannerKind::Local, "eth0".into());
clone.record_failure(ScannerKind::Routed, "gateway".into());
assert_eq!(ctx.take_failures().len(), 2);
}
}