use crate::model::ip::set::IpSet;
use crate::model::port::{PortSet, Protocol};
use std::{net::IpAddr, sync::Arc};
use thiserror::Error;
#[non_exhaustive]
#[derive(Error, Debug, PartialEq, Eq)]
pub enum TargetError {
#[error("Target calculation resulted in an integer overflow")]
CapacityOverflow,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Target {
pub ip: IpAddr,
pub port: u16,
pub protocol: Protocol,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct PlannedTarget {
pub position: u64,
pub target: Target,
}
impl PlannedTarget {
pub fn new(position: u64, target: Target) -> Self {
Self { position, target }
}
pub fn ip(&self) -> IpAddr {
self.target.ip
}
pub fn port(&self) -> u16 {
self.target.port
}
pub fn protocol(&self) -> Protocol {
self.target.protocol
}
}
#[derive(Debug, Clone, Default)]
pub struct TargetSet {
ips: IpSet,
ports: PortSet,
}
impl TargetSet {
pub fn new(mut ips: IpSet, ports: PortSet) -> Self {
ips.canonicalize();
Self { ips, ports }
}
pub fn ips(&self) -> &IpSet {
&self.ips
}
pub fn into_ips(self) -> IpSet {
self.ips
}
pub fn into_parts(self) -> (IpSet, PortSet) {
(self.ips, self.ports)
}
pub fn ports(&self) -> &PortSet {
&self.ports
}
pub fn ip_count(&self) -> u128 {
self.ips.len()
}
pub fn port_count(&self) -> usize {
self.ports.len()
}
pub fn total_targets(&self) -> Result<u128, TargetError> {
let port_len = self.ports.len() as u128;
self.ips
.len()
.checked_mul(port_len)
.ok_or(TargetError::CapacityOverflow)
}
pub fn iter(&self) -> impl Iterator<Item = Target> + Send + '_ {
let ports_arc: Arc<[(u16, Protocol)]> = self.ports.to_vec().into();
self.ips.iter().flat_map(move |ip| {
let ports = Arc::clone(&ports_arc);
(0..ports.len()).map(move |i| {
let (port, protocol) = ports[i];
Target { ip, port, protocol }
})
})
}
pub fn is_empty(&self) -> bool {
self.ips.is_empty() || self.ports.is_empty()
}
}
#[derive(Debug, Clone, Default)]
pub struct TargetMap {
pub units: Vec<TargetSet>,
}
impl TargetMap {
pub fn new() -> Self {
Self::default()
}
pub fn add_unit(&mut self, unit: TargetSet) {
self.units.push(unit);
}
pub fn gross_targets(&self) -> Result<u128, TargetError> {
let mut total: u128 = 0;
for unit in &self.units {
let unit_total = unit.total_targets()?;
total = total
.checked_add(unit_total)
.ok_or(TargetError::CapacityOverflow)?;
}
Ok(total)
}
pub fn gross_ips(&self) -> Result<u128, TargetError> {
let mut total: u128 = 0;
for unit in &self.units {
total = total
.checked_add(unit.ip_count())
.ok_or(TargetError::CapacityOverflow)?;
}
Ok(total)
}
pub fn is_empty(&self) -> bool {
self.units.is_empty() || self.units.iter().all(|u| u.is_empty())
}
pub fn iter(&self) -> impl Iterator<Item = Target> + Send + '_ {
self.units.iter().flat_map(|unit| unit.iter())
}
}
#[cfg(test)]
mod tests {
use super::*;
fn ips(written: &str) -> IpSet {
written.parse().expect("a valid address specification")
}
fn ports(written: &str) -> PortSet {
written.parse().expect("a valid port specification")
}
#[test]
fn a_sets_target_count_is_its_addresses_times_its_ports() {
let ts = TargetSet::new(ips("192.168.1.0/24"), ports("80, 443"));
assert_eq!(ts.total_targets().unwrap(), 256 * 2);
}
#[test]
fn a_target_set_merges_its_addresses_on_construction() {
let mut overlapping = ips("192.168.1.0/24");
overlapping.insert_range("192.168.1.128/25".parse().expect("valid range"));
let ts = TargetSet::new(overlapping, ports("80"));
assert_eq!(ts.ip_count(), 256);
assert_eq!(ts.total_targets().unwrap(), 256);
}
#[test]
fn a_set_yields_every_address_paired_with_every_port() {
let ts = TargetSet::new(ips("10.0.0.1-10.0.0.2"), ports("80, u:53"));
let mut targets: Vec<(String, u16, Protocol)> = ts
.iter()
.map(|target| (target.ip.to_string(), target.port, target.protocol))
.collect();
targets.sort();
assert_eq!(
targets,
vec![
("10.0.0.1".to_string(), 53, Protocol::Udp),
("10.0.0.1".to_string(), 80, Protocol::Tcp),
("10.0.0.2".to_string(), 53, Protocol::Udp),
("10.0.0.2".to_string(), 80, Protocol::Tcp),
]
);
}
#[test]
fn a_map_iterates_its_units_in_the_order_they_were_added() {
let mut map = TargetMap::new();
map.add_unit(TargetSet::new(ips("10.0.0.1"), ports("80")));
map.add_unit(TargetSet::new(ips("10.0.0.2"), ports("u:53")));
let targets: Vec<(String, u16, Protocol)> = map
.iter()
.map(|target| (target.ip.to_string(), target.port, target.protocol))
.collect();
assert_eq!(
targets,
vec![
("10.0.0.1".to_string(), 80, Protocol::Tcp),
("10.0.0.2".to_string(), 53, Protocol::Udp),
]
);
}
#[test]
fn a_target_count_too_large_to_represent_is_refused_rather_than_wrapped() {
let two_ports = TargetSet::new(ips("::/0"), ports("80, 443"));
assert_eq!(
two_ports.total_targets(),
Err(TargetError::CapacityOverflow)
);
let one_port = TargetSet::new(ips("::/0"), ports("80"));
assert_eq!(one_port.total_targets().unwrap(), u128::MAX);
}
#[test]
fn a_maps_total_is_the_sum_of_its_units() {
let mut map = TargetMap::new();
map.add_unit(TargetSet::new(ips("10.0.0.1-10.0.0.5"), ports("80,443")));
assert_eq!(map.gross_targets().unwrap(), 10);
}
}