use ambient_authority::AmbientAuthority;
use ipnet::IpNet;
use std::{io, net};
#[derive(Clone)]
enum AddrSet {
Net(IpNet),
}
impl AddrSet {
fn contains(&self, addr: net::IpAddr) -> bool {
match self {
Self::Net(ip_net) => ip_net.contains(&addr),
}
}
}
#[derive(Clone)]
struct IpGrant {
set: AddrSet,
port: u16, }
impl IpGrant {
fn contains(&self, addr: &net::SocketAddr) -> bool {
self.set.contains(addr.ip()) && addr.port() == self.port
}
}
#[derive(Clone)]
pub struct Pool {
grants: Vec<IpGrant>,
}
impl Pool {
pub fn new() -> Self {
Self { grants: Vec::new() }
}
pub fn insert_ip_net(&mut self, ip_net: ipnet::IpNet, port: u16, _: AmbientAuthority) {
self.grants.push(IpGrant {
set: AddrSet::Net(ip_net),
port,
})
}
pub fn insert_socket_addr(&mut self, addr: net::SocketAddr, _: AmbientAuthority) {
self.grants.push(IpGrant {
set: AddrSet::Net(addr.ip().into()),
port: addr.port(),
})
}
pub fn check_addr(&self, addr: &net::SocketAddr) -> io::Result<()> {
if self.grants.iter().any(|grant| grant.contains(addr)) {
Ok(())
} else {
Err(io::Error::new(
io::ErrorKind::PermissionDenied,
"An address was outside the pool",
))
}
}
}
pub const NO_SOCKET_ADDRS: &[net::SocketAddr] = &[];