use dashmap::DashMap;
use std::net::IpAddr;
use std::sync::Arc;
use tokio::sync::mpsc;
use crate::core::handle::ScanHandle;
use crate::core::models::host::Host;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ScannerKind {
Local,
Routed,
SynPort,
Connect,
UdpPort,
Composite,
}
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum ScanEvent {
HostUpdated(IpAddr),
ScannerFailed {
scanner: ScannerKind,
reason: String,
},
}
pub struct ScanSession {
pub store: Arc<DashMap<IpAddr, Host>>,
pub events: mpsc::UnboundedReceiver<ScanEvent>,
pub handle: ScanHandle,
}
#[derive(Clone)]
pub struct ScanContext {
pub handle: ScanHandle,
pub store: Arc<DashMap<IpAddr, Host>>,
pub events_tx: mpsc::UnboundedSender<ScanEvent>,
}
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 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: store.clone(),
events: rx,
handle: handle.clone(),
};
let ctx = ScanContext {
handle,
store,
events_tx,
};
(session, ctx)
}
}