#[cfg(feature = "cli")]
mod cli;
#[cfg(feature = "cli")]
use anyhow::{Result, bail};
#[cfg(feature = "cli")]
use clap::Parser;
#[cfg(feature = "cli")]
use cli::{Cli, Command};
#[cfg(feature = "cli")]
use config::Profile;
#[cfg(feature = "cli")]
use net::SystemRunner;
#[cfg(feature = "cli")]
use state::State;
#[cfg(feature = "cli")]
use std::path::PathBuf;
#[cfg(feature = "cli")]
use vlanctl::{commands, config, device, net, plan, state};
#[cfg(feature = "cli")]
fn profile_path(dir: &std::path::Path, name: &str) -> PathBuf {
dir.join(format!("{name}.toml"))
}
#[cfg(feature = "cli")]
fn print_planned_commands(commands: &[net::Cmd]) {
for cmd in commands {
if is_read_only_probe(cmd) {
continue;
}
println!("{}", cmd.display());
}
}
#[cfg(feature = "cli")]
struct PreviewRunner {
probe: SystemRunner,
recorded: Vec<net::Cmd>,
}
#[cfg(feature = "cli")]
impl net::CommandRunner for PreviewRunner {
fn run(&mut self, cmd: &net::Cmd) -> Result<String> {
self.recorded.push(cmd.clone());
if is_read_only_probe(cmd) {
self.probe.run(cmd)
} else {
Ok(String::new())
}
}
}
#[cfg(feature = "cli")]
fn is_read_only_probe(cmd: &net::Cmd) -> bool {
let args: Vec<&str> = cmd.args.iter().map(String::as_str).collect();
match cmd.program.as_str() {
"networksetup" => matches!(args.as_slice(), ["-listallhardwareports"]),
"ifconfig" => args.len() <= 1,
"ip" => matches!(
args.as_slice(),
["-json", "link", "show"]
| ["-d", "-json", "link", "show"]
| ["-json", "addr", "show", "dev", _]
),
"cat" | "ls" => {
matches!(args.as_slice(), [path] if path.starts_with("/sys/class/net/"))
}
_ => false,
}
}
#[cfg(feature = "cli")]
fn require_root() -> Result<()> {
let uid = unsafe { libc::getuid() };
if uid != 0 {
bail!("this command modifies network interfaces and must be run with sudo");
}
Ok(())
}
#[cfg(not(feature = "cli"))]
fn main() {
eprintln!("vlanctl was built without the `cli` feature");
std::process::exit(2);
}
#[cfg(feature = "cli")]
fn main() -> Result<()> {
let cli = Cli::parse();
let state_path = State::default_path();
match cli.command {
Command::List => {
for name in commands::list_profiles(&cli.profiles_dir)? {
println!("{name}");
}
}
Command::Show { profile, device } => {
let p = Profile::load(&profile_path(&cli.profiles_dir, &profile))?;
let mut probe = SystemRunner;
let device = device::resolve_device(
&*plan::preview_platform(),
&mut probe,
device.as_deref().or(p.device.as_deref()),
)?;
for line in commands::show_plan(&*plan::preview_platform(), &p, &device) {
println!("{line}");
}
}
Command::Validate { profile } => {
Profile::load(&profile_path(&cli.profiles_dir, &profile))?;
println!("{profile}: ok");
}
Command::Apply {
profile,
dry_run,
device,
} => {
let p = Profile::load(&profile_path(&cli.profiles_dir, &profile))?;
if dry_run {
let mut runner = PreviewRunner {
probe: SystemRunner,
recorded: Vec::new(),
};
commands::apply(
&mut runner,
&*plan::preview_platform(),
&p,
device.as_deref(),
&state_path,
true,
)?;
print_planned_commands(&runner.recorded);
} else {
require_root()?;
let platform = plan::host_platform()?;
let mut runner = SystemRunner;
let created = commands::apply(
&mut runner,
&*platform,
&p,
device.as_deref(),
&state_path,
false,
)?;
println!("applied '{}': {}", p.name, created.join(", "));
}
}
Command::Down { dry_run } => {
if dry_run {
let mut runner = PreviewRunner {
probe: SystemRunner,
recorded: Vec::new(),
};
commands::down(&mut runner, &*plan::preview_platform(), &state_path, true)?;
print_planned_commands(&runner.recorded);
} else {
require_root()?;
let platform = plan::host_platform()?;
let mut runner = SystemRunner;
commands::down(&mut runner, &*platform, &state_path, false)?;
println!("torn down");
}
}
Command::Status => {
let mut runner = SystemRunner;
print!(
"{}",
commands::status(&mut runner, &*plan::preview_platform(), &state_path)?
);
}
}
Ok(())
}
#[cfg(all(test, feature = "cli"))]
mod tests {
use super::*;
use net::Cmd;
#[test]
fn mutating_commands_are_never_classified_read_only() {
let mutations = [
Cmd::new(
"ip",
&[
"link", "add", "link", "eth0", "name", "eth0.11", "type", "vlan", "id", "11",
],
),
Cmd::new("ip", &["link", "set", "eth0", "up"]),
Cmd::new("ip", &["link", "del", "eth0.11"]),
Cmd::new("ip", &["addr", "add", "192.168.11.87/24", "dev", "eth0.11"]),
Cmd::new("ip", &["addr", "del", "192.168.11.87/24", "dev", "eth0"]),
Cmd::new(
"ip",
&["route", "add", "192.168.11.151/32", "dev", "eth0.11"],
),
Cmd::new(
"ip",
&[
"neigh",
"replace",
"192.168.11.151",
"lladdr",
"00:00:5e:00:53:01",
"dev",
"eth0.11",
],
),
Cmd::new("ifconfig", &["vlan11", "create"]),
Cmd::new("ifconfig", &["vlan11", "vlan", "11", "vlandev", "en7"]),
Cmd::new("ifconfig", &["vlan11", "destroy"]),
Cmd::new(
"route",
&["add", "-host", "192.168.10.151", "-interface", "en7"],
),
Cmd::new("arp", &["-s", "192.168.10.151", "00:00:5e:00:53:01"]),
];
for cmd in &mutations {
assert!(
!is_read_only_probe(cmd),
"MUTATION classified as a read-only probe, so a dry run would \
EXECUTE it: {}",
cmd.display()
);
}
}
#[test]
fn the_backends_own_probes_are_classified_read_only() {
let probes = [
Cmd::new("ip", &["-json", "link", "show"]),
Cmd::new("ip", &["-d", "-json", "link", "show"]),
Cmd::new("ip", &["-json", "addr", "show", "dev", "eth0"]),
Cmd::new("cat", &["/sys/class/net/eth0/carrier"]),
Cmd::new("cat", &["/sys/class/net/eth0/operstate"]),
Cmd::new("ls", &["/sys/class/net/eth0"]),
Cmd::new("ifconfig", &["-l"]),
Cmd::new("ifconfig", &["en0"]),
Cmd::new("networksetup", &["-listallhardwareports"]),
];
for cmd in &probes {
assert!(
is_read_only_probe(cmd),
"probe not recognised, so a dry run would stub it out: {}",
cmd.display()
);
}
}
#[test]
fn cat_and_ls_are_confined_to_sys_class_net() {
assert!(!is_read_only_probe(&Cmd::new("cat", &["/etc/shadow"])));
assert!(!is_read_only_probe(&Cmd::new("ls", &["/"])));
assert!(!is_read_only_probe(&Cmd::new("cat", &[])));
}
}