use crate::error::{Error, Result};
use ipnet::{IpNet, Ipv4Net, Ipv6Net};
use std::collections::HashSet;
use std::net::IpAddr;
#[derive(Debug, Clone)]
pub struct IpPool {
subnet: IpNet,
gateway: IpAddr,
allocated: HashSet<IpAddr>,
}
impl IpPool {
pub fn new(subnet: IpNet) -> Result<Self> {
let gateway = Self::first_usable(&subnet)?;
let mut allocated = HashSet::new();
allocated.insert(gateway);
Ok(Self {
subnet,
gateway,
allocated,
})
}
pub fn with_gateway(subnet: IpNet, gateway: IpAddr) -> Result<Self> {
if !subnet.contains(&gateway) {
return Err(Error::Network(format!(
"Gateway {gateway} is not in subnet {subnet}"
)));
}
let mut allocated = HashSet::new();
allocated.insert(gateway);
Ok(Self {
subnet,
gateway,
allocated,
})
}
pub fn allocate(&mut self) -> Result<IpAddr> {
match self.subnet {
IpNet::V4(net) => self.allocate_v4(net),
IpNet::V6(net) => self.allocate_v6(net),
}
}
pub fn allocate_specific(&mut self, addr: IpAddr) -> Result<()> {
if !self.subnet.contains(&addr) {
return Err(Error::Network(format!(
"Address {} is not in subnet {}",
addr, self.subnet
)));
}
if self.allocated.contains(&addr) {
return Err(Error::Network(format!(
"Address {addr} is already allocated"
)));
}
self.allocated.insert(addr);
Ok(())
}
pub fn release(&mut self, addr: &IpAddr) {
if *addr != self.gateway {
self.allocated.remove(addr);
}
}
fn allocate_from_hosts(
allocated: &mut HashSet<IpAddr>,
hosts: impl Iterator<Item = IpAddr>,
subnet: impl std::fmt::Display,
) -> Result<IpAddr> {
for ip in hosts {
if allocated.insert(ip) {
return Ok(ip);
}
}
Err(Error::Network(format!(
"No available addresses in {subnet}"
)))
}
fn allocate_v4(&mut self, net: Ipv4Net) -> Result<IpAddr> {
Self::allocate_from_hosts(&mut self.allocated, net.hosts().map(IpAddr::V4), net)
}
fn allocate_v6(&mut self, net: Ipv6Net) -> Result<IpAddr> {
Self::allocate_from_hosts(
&mut self.allocated,
net.hosts().take(65536).map(IpAddr::V6),
net,
)
}
fn first_usable(subnet: &IpNet) -> Result<IpAddr> {
match subnet {
IpNet::V4(net) => net
.hosts()
.next()
.map(IpAddr::V4)
.ok_or_else(|| Error::Network("Network too small for gateway".to_string())),
IpNet::V6(net) => net
.hosts()
.next()
.map(IpAddr::V6)
.ok_or_else(|| Error::Network("Network too small for gateway".to_string())),
}
}
#[cfg(test)]
pub const fn subnet(&self) -> IpNet {
self.subnet
}
pub const fn gateway(&self) -> IpAddr {
self.gateway
}
#[cfg(test)]
pub fn is_available(&self, addr: &IpAddr) -> bool {
self.subnet.contains(addr) && !self.allocated.contains(addr)
}
#[cfg(test)]
pub fn allocated_count(&self) -> usize {
self.allocated.len()
}
}
#[derive(Debug, Default)]
pub struct IpAllocator {
pools: std::collections::HashMap<String, IpPool>,
}
impl IpAllocator {
pub fn new() -> Self {
Self::default()
}
pub fn add_pool(&mut self, name: String, pool: IpPool) {
self.pools.insert(name, pool);
}
pub fn get_pool_mut(&mut self, name: &str) -> Option<&mut IpPool> {
self.pools.get_mut(name)
}
pub fn allocate(&mut self, network: &str) -> Result<IpAddr> {
let pool = self
.pools
.get_mut(network)
.ok_or_else(|| Error::Network(format!("Network '{network}' not found")))?;
pool.allocate()
}
pub fn release(&mut self, network: &str, addr: &IpAddr) {
if let Some(pool) = self.pools.get_mut(network) {
pool.release(addr);
}
}
}
#[cfg(test)]
mod tests;