use crate::error::Result;
use crate::network::{Bridge, EpairInterface};
use std::net::IpAddr;
#[derive(Debug, Clone)]
pub struct VnetConfig {
pub bridge: String,
pub ip: String,
pub gateway: IpAddr,
pub mac_address: Option<String>,
}
impl VnetConfig {
pub fn new(bridge: String, ip: String, gateway: IpAddr) -> Self {
Self {
bridge,
ip,
gateway,
mac_address: None,
}
}
pub fn with_mac_address(mut self, mac: String) -> Self {
self.mac_address = Some(mac);
self
}
}
#[derive(Debug, Clone)]
pub struct VnetSetup {
pub epair: EpairInterface,
pub bridge_name: String,
pub config: VnetConfig,
}
impl VnetSetup {
pub fn create(jail_name: &str, config: VnetConfig) -> Result<Self> {
let bridge = Bridge::create_or_open(&config.bridge)?;
let epair = EpairInterface::create_for_jail(jail_name)?;
if let Some(ref mac) = config.mac_address {
epair.set_mac_address(mac)?;
}
bridge.add_member(epair.host_side())?;
Ok(Self {
epair,
bridge_name: config.bridge.clone(),
config,
})
}
pub fn jail_interface(&self) -> &str {
self.epair.jail_side()
}
pub fn attach_to_jail(&self, jid: i32) -> Result<()> {
self.epair.move_to_jail(jid)?;
EpairInterface::configure_in_jail(
jid,
self.jail_interface(),
&self.config.ip,
Some(&self.config.gateway.to_string()),
)?;
Ok(())
}
pub fn cleanup(&self) -> Result<()> {
if let Ok(bridge) = Bridge::open(&self.bridge_name) {
let _ = bridge.remove_member(self.epair.host_side());
}
self.epair.destroy()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_vnet_config() {
let config = VnetConfig::new(
"blackship0".to_string(),
"10.0.1.10/24".to_string(),
"10.0.1.1".parse().unwrap(),
);
assert_eq!(config.bridge, "blackship0");
assert_eq!(config.ip, "10.0.1.10/24");
}
}