config: rustfmt
Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
This commit is contained in:
@ -1,12 +1,12 @@
|
||||
use std::path::Path;
|
||||
use std::process::Command;
|
||||
use std::collections::HashMap;
|
||||
use std::os::unix::io::{AsRawFd, FromRawFd};
|
||||
use std::path::Path;
|
||||
use std::process::Command;
|
||||
|
||||
use anyhow::{Error, bail, format_err};
|
||||
use anyhow::{bail, format_err, Error};
|
||||
use lazy_static::lazy_static;
|
||||
use nix::ioctl_read_bad;
|
||||
use nix::sys::socket::{socket, AddressFamily, SockType, SockFlag};
|
||||
use nix::sys::socket::{socket, AddressFamily, SockFlag, SockType};
|
||||
use regex::Regex;
|
||||
|
||||
use pbs_api_types::*; // for IP macros
|
||||
@ -77,7 +77,13 @@ pub fn check_netmask(mask: u8, is_v6: bool) -> Result<(), Error> {
|
||||
};
|
||||
|
||||
if !(mask >= min && mask <= max) {
|
||||
bail!("{} mask '{}' is out of range ({}..{}).", ver, mask, min, max);
|
||||
bail!(
|
||||
"{} mask '{}' is out of range ({}..{}).",
|
||||
ver,
|
||||
mask,
|
||||
min,
|
||||
max
|
||||
);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
@ -85,14 +91,11 @@ pub fn check_netmask(mask: u8, is_v6: bool) -> Result<(), Error> {
|
||||
|
||||
// parse ip address with optional cidr mask
|
||||
pub fn parse_address_or_cidr(cidr: &str) -> Result<(String, Option<u8>, bool), Error> {
|
||||
|
||||
lazy_static! {
|
||||
pub static ref CIDR_V4_REGEX: Regex = Regex::new(
|
||||
concat!(r"^(", IPV4RE!(), r")(?:/(\d{1,2}))?$")
|
||||
).unwrap();
|
||||
pub static ref CIDR_V6_REGEX: Regex = Regex::new(
|
||||
concat!(r"^(", IPV6RE!(), r")(?:/(\d{1,3}))?$")
|
||||
).unwrap();
|
||||
pub static ref CIDR_V4_REGEX: Regex =
|
||||
Regex::new(concat!(r"^(", IPV4RE!(), r")(?:/(\d{1,2}))?$")).unwrap();
|
||||
pub static ref CIDR_V6_REGEX: Regex =
|
||||
Regex::new(concat!(r"^(", IPV6RE!(), r")(?:/(\d{1,3}))?$")).unwrap();
|
||||
}
|
||||
|
||||
if let Some(caps) = CIDR_V4_REGEX.captures(cidr) {
|
||||
@ -119,7 +122,6 @@ pub fn parse_address_or_cidr(cidr: &str) -> Result<(String, Option<u8>, bool), E
|
||||
}
|
||||
|
||||
pub fn get_network_interfaces() -> Result<HashMap<String, bool>, Error> {
|
||||
|
||||
const PROC_NET_DEV: &str = "/proc/net/dev";
|
||||
|
||||
#[repr(C)]
|
||||
@ -130,7 +132,7 @@ pub fn get_network_interfaces() -> Result<HashMap<String, bool>, Error> {
|
||||
|
||||
ioctl_read_bad!(get_interface_flags, libc::SIOCGIFFLAGS, ifreq);
|
||||
|
||||
lazy_static!{
|
||||
lazy_static! {
|
||||
static ref IFACE_LINE_REGEX: Regex = Regex::new(r"^\s*([^:\s]+):").unwrap();
|
||||
}
|
||||
let raw = std::fs::read_to_string(PROC_NET_DEV)
|
||||
@ -163,13 +165,26 @@ pub fn get_network_interfaces() -> Result<HashMap<String, bool>, Error> {
|
||||
if let Some(cap) = IFACE_LINE_REGEX.captures(line) {
|
||||
let ifname = &cap[1];
|
||||
|
||||
let mut req = ifreq { ifr_name: *b"0000000000000000", ifru_flags: 0 };
|
||||
for (i, b) in std::ffi::CString::new(ifname)?.as_bytes_with_nul().iter().enumerate() {
|
||||
if i < (libc::IFNAMSIZ-1) { req.ifr_name[i] = *b as libc::c_uchar; }
|
||||
let mut req = ifreq {
|
||||
ifr_name: *b"0000000000000000",
|
||||
ifru_flags: 0,
|
||||
};
|
||||
for (i, b) in std::ffi::CString::new(ifname)?
|
||||
.as_bytes_with_nul()
|
||||
.iter()
|
||||
.enumerate()
|
||||
{
|
||||
if i < (libc::IFNAMSIZ - 1) {
|
||||
req.ifr_name[i] = *b as libc::c_uchar;
|
||||
}
|
||||
}
|
||||
let res = unsafe { get_interface_flags(sock.as_raw_fd(), &mut req)? };
|
||||
if res != 0 {
|
||||
bail!("ioctl get_interface_flags for '{}' failed ({})", ifname, res);
|
||||
bail!(
|
||||
"ioctl get_interface_flags for '{}' failed ({})",
|
||||
ifname,
|
||||
res
|
||||
);
|
||||
}
|
||||
let is_up = (req.ifru_flags & (libc::IFF_UP as libc::c_short)) != 0;
|
||||
interface_list.insert(ifname.to_string(), is_up);
|
||||
@ -180,7 +195,6 @@ pub fn get_network_interfaces() -> Result<HashMap<String, bool>, Error> {
|
||||
}
|
||||
|
||||
pub fn compute_file_diff(filename: &str, shadow: &str) -> Result<String, Error> {
|
||||
|
||||
let output = Command::new("diff")
|
||||
.arg("-b")
|
||||
.arg("-u")
|
||||
@ -204,7 +218,6 @@ pub fn assert_ifupdown2_installed() -> Result<(), Error> {
|
||||
}
|
||||
|
||||
pub fn network_reload() -> Result<(), Error> {
|
||||
|
||||
let output = Command::new("ifreload")
|
||||
.arg("-a")
|
||||
.output()
|
||||
@ -213,6 +226,5 @@ pub fn network_reload() -> Result<(), Error> {
|
||||
proxmox_sys::command::command_output(output, None)
|
||||
.map_err(|err| format_err!("ifreload failed: {}", err))?;
|
||||
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
@ -1,6 +1,6 @@
|
||||
use std::collections::{HashMap, VecDeque};
|
||||
use std::io::BufRead;
|
||||
use std::iter::Iterator;
|
||||
use std::collections::{HashMap, VecDeque};
|
||||
|
||||
use lazy_static::lazy_static;
|
||||
|
||||
@ -67,10 +67,13 @@ pub struct Lexer<R> {
|
||||
cur_line: Option<VecDeque<(Token, String)>>,
|
||||
}
|
||||
|
||||
impl <R: BufRead> Lexer<R> {
|
||||
|
||||
impl<R: BufRead> Lexer<R> {
|
||||
pub fn new(input: R) -> Self {
|
||||
Self { input, eof_count: 0, cur_line: None }
|
||||
Self {
|
||||
input,
|
||||
eof_count: 0,
|
||||
cur_line: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn split_line(line: &str) -> VecDeque<(Token, String)> {
|
||||
@ -79,10 +82,13 @@ impl <R: BufRead> Lexer<R> {
|
||||
res.push_back((Token::Comment, comment.trim().to_string()));
|
||||
return res;
|
||||
}
|
||||
let mut list: VecDeque<(Token, String)> = line.split_ascii_whitespace().map(|text| {
|
||||
let token = KEYWORDS.get(text).unwrap_or(&Token::Text);
|
||||
(*token, text.to_string())
|
||||
}).collect();
|
||||
let mut list: VecDeque<(Token, String)> = line
|
||||
.split_ascii_whitespace()
|
||||
.map(|text| {
|
||||
let token = KEYWORDS.get(text).unwrap_or(&Token::Text);
|
||||
(*token, text.to_string())
|
||||
})
|
||||
.collect();
|
||||
|
||||
if line.starts_with(|c: char| c.is_ascii_whitespace() && c != '\n') {
|
||||
list.push_front((Token::Attribute, String::from("\t")));
|
||||
@ -91,8 +97,7 @@ impl <R: BufRead> Lexer<R> {
|
||||
}
|
||||
}
|
||||
|
||||
impl <R: BufRead> Iterator for Lexer<R> {
|
||||
|
||||
impl<R: BufRead> Iterator for Lexer<R> {
|
||||
type Item = Result<(Token, String), std::io::Error>;
|
||||
|
||||
fn next(&mut self) -> Option<Self::Item> {
|
||||
@ -102,7 +107,9 @@ impl <R: BufRead> Iterator for Lexer<R> {
|
||||
Err(err) => return Some(Err(err)),
|
||||
Ok(0) => {
|
||||
self.eof_count += 1;
|
||||
if self.eof_count == 1 { return Some(Ok((Token::EOF, String::new()))); }
|
||||
if self.eof_count == 1 {
|
||||
return Some(Ok((Token::EOF, String::new())));
|
||||
}
|
||||
return None;
|
||||
}
|
||||
_ => {}
|
||||
@ -111,7 +118,7 @@ impl <R: BufRead> Iterator for Lexer<R> {
|
||||
}
|
||||
|
||||
match self.cur_line {
|
||||
Some(ref mut cur_line) => {
|
||||
Some(ref mut cur_line) => {
|
||||
if cur_line.is_empty() {
|
||||
self.cur_line = None;
|
||||
Some(Ok((Token::Newline, String::from("\n"))))
|
||||
@ -120,9 +127,7 @@ impl <R: BufRead> Iterator for Lexer<R> {
|
||||
Some(Ok((token, text)))
|
||||
}
|
||||
}
|
||||
None => {
|
||||
None
|
||||
}
|
||||
None => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -1,10 +1,10 @@
|
||||
use std::io::{Write};
|
||||
use std::collections::{HashSet, HashMap, BTreeMap};
|
||||
use std::collections::{BTreeMap, HashMap, HashSet};
|
||||
use std::io::Write;
|
||||
|
||||
use anyhow::{Error, format_err, bail};
|
||||
use serde::de::{value, IntoDeserializer, Deserialize};
|
||||
use anyhow::{bail, format_err, Error};
|
||||
use lazy_static::lazy_static;
|
||||
use regex::Regex;
|
||||
use serde::de::{value, Deserialize, IntoDeserializer};
|
||||
|
||||
use proxmox_sys::{fs::replace_file, fs::CreateOptions};
|
||||
|
||||
@ -17,11 +17,13 @@ pub use lexer::*;
|
||||
mod parser;
|
||||
pub use parser::*;
|
||||
|
||||
use pbs_api_types::{Interface, NetworkConfigMethod, NetworkInterfaceType, LinuxBondMode, BondXmitHashPolicy};
|
||||
use pbs_api_types::{
|
||||
BondXmitHashPolicy, Interface, LinuxBondMode, NetworkConfigMethod, NetworkInterfaceType,
|
||||
};
|
||||
|
||||
use crate::{open_backup_lockfile, BackupLockGuard};
|
||||
|
||||
lazy_static!{
|
||||
lazy_static! {
|
||||
static ref PHYSICAL_NIC_REGEX: Regex = Regex::new(r"^(?:eth\d+|en[^:.]+|ib\d+)$").unwrap();
|
||||
}
|
||||
|
||||
@ -61,7 +63,6 @@ pub fn bond_xmit_hash_policy_to_str(policy: &BondXmitHashPolicy) -> &'static str
|
||||
|
||||
// Write attributes not depending on address family
|
||||
fn write_iface_attributes(iface: &Interface, w: &mut dyn Write) -> Result<(), Error> {
|
||||
|
||||
static EMPTY_LIST: Vec<String> = Vec::new();
|
||||
|
||||
match iface.interface_type {
|
||||
@ -86,10 +87,12 @@ fn write_iface_attributes(iface: &Interface, w: &mut dyn Write) -> Result<(), Er
|
||||
}
|
||||
|
||||
if let Some(xmit_policy) = &iface.bond_xmit_hash_policy {
|
||||
if mode == LinuxBondMode::ieee802_3ad ||
|
||||
mode == LinuxBondMode::balance_xor
|
||||
{
|
||||
writeln!(w, "\tbond_xmit_hash_policy {}", bond_xmit_hash_policy_to_str(xmit_policy))?;
|
||||
if mode == LinuxBondMode::ieee802_3ad || mode == LinuxBondMode::balance_xor {
|
||||
writeln!(
|
||||
w,
|
||||
"\tbond_xmit_hash_policy {}",
|
||||
bond_xmit_hash_policy_to_str(xmit_policy)
|
||||
)?;
|
||||
}
|
||||
}
|
||||
|
||||
@ -111,7 +114,11 @@ fn write_iface_attributes(iface: &Interface, w: &mut dyn Write) -> Result<(), Er
|
||||
}
|
||||
|
||||
// Write attributes depending on address family inet (IPv4)
|
||||
fn write_iface_attributes_v4(iface: &Interface, w: &mut dyn Write, method: NetworkConfigMethod) -> Result<(), Error> {
|
||||
fn write_iface_attributes_v4(
|
||||
iface: &Interface,
|
||||
w: &mut dyn Write,
|
||||
method: NetworkConfigMethod,
|
||||
) -> Result<(), Error> {
|
||||
if method == NetworkConfigMethod::Static {
|
||||
if let Some(address) = &iface.cidr {
|
||||
writeln!(w, "\taddress {}", address)?;
|
||||
@ -135,7 +142,11 @@ fn write_iface_attributes_v4(iface: &Interface, w: &mut dyn Write, method: Netwo
|
||||
}
|
||||
|
||||
/// Write attributes depending on address family inet6 (IPv6)
|
||||
fn write_iface_attributes_v6(iface: &Interface, w: &mut dyn Write, method: NetworkConfigMethod) -> Result<(), Error> {
|
||||
fn write_iface_attributes_v6(
|
||||
iface: &Interface,
|
||||
w: &mut dyn Write,
|
||||
method: NetworkConfigMethod,
|
||||
) -> Result<(), Error> {
|
||||
if method == NetworkConfigMethod::Static {
|
||||
if let Some(address) = &iface.cidr6 {
|
||||
writeln!(w, "\taddress {}", address)?;
|
||||
@ -159,7 +170,6 @@ fn write_iface_attributes_v6(iface: &Interface, w: &mut dyn Write, method: Netwo
|
||||
}
|
||||
|
||||
fn write_iface(iface: &Interface, w: &mut dyn Write) -> Result<(), Error> {
|
||||
|
||||
fn method_to_str(method: NetworkConfigMethod) -> &'static str {
|
||||
match method {
|
||||
NetworkConfigMethod::Static => "static",
|
||||
@ -169,7 +179,9 @@ fn write_iface(iface: &Interface, w: &mut dyn Write) -> Result<(), Error> {
|
||||
}
|
||||
}
|
||||
|
||||
if iface.method.is_none() && iface.method6.is_none() { return Ok(()); }
|
||||
if iface.method.is_none() && iface.method6.is_none() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
if iface.autostart {
|
||||
writeln!(w, "auto {}", iface.name)?;
|
||||
@ -195,7 +207,8 @@ fn write_iface(iface: &Interface, w: &mut dyn Write) -> Result<(), Error> {
|
||||
if !skip_v6 {
|
||||
writeln!(w, "iface {} inet6 {}", iface.name, method_to_str(method6))?;
|
||||
write_iface_attributes_v6(iface, w, method6)?;
|
||||
if iface.method.is_none() { // only write common attributes once
|
||||
if iface.method.is_none() {
|
||||
// only write common attributes once
|
||||
write_iface_attributes(iface, w)?;
|
||||
}
|
||||
writeln!(w)?;
|
||||
@ -220,8 +233,7 @@ pub struct NetworkConfig {
|
||||
|
||||
use std::convert::TryFrom;
|
||||
|
||||
impl TryFrom<NetworkConfig> for String {
|
||||
|
||||
impl TryFrom<NetworkConfig> for String {
|
||||
type Error = Error;
|
||||
|
||||
fn try_from(config: NetworkConfig) -> Result<Self, Self::Error> {
|
||||
@ -233,7 +245,6 @@ impl TryFrom<NetworkConfig> for String {
|
||||
}
|
||||
|
||||
impl NetworkConfig {
|
||||
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
interfaces: BTreeMap::new(),
|
||||
@ -242,16 +253,18 @@ impl NetworkConfig {
|
||||
}
|
||||
|
||||
pub fn lookup(&self, name: &str) -> Result<&Interface, Error> {
|
||||
let interface = self.interfaces.get(name).ok_or_else(|| {
|
||||
format_err!("interface '{}' does not exist.", name)
|
||||
})?;
|
||||
let interface = self
|
||||
.interfaces
|
||||
.get(name)
|
||||
.ok_or_else(|| format_err!("interface '{}' does not exist.", name))?;
|
||||
Ok(interface)
|
||||
}
|
||||
|
||||
pub fn lookup_mut(&mut self, name: &str) -> Result<&mut Interface, Error> {
|
||||
let interface = self.interfaces.get_mut(name).ok_or_else(|| {
|
||||
format_err!("interface '{}' does not exist.", name)
|
||||
})?;
|
||||
let interface = self
|
||||
.interfaces
|
||||
.get_mut(name)
|
||||
.ok_or_else(|| format_err!("interface '{}' does not exist.", name))?;
|
||||
Ok(interface)
|
||||
}
|
||||
|
||||
@ -261,8 +274,12 @@ impl NetworkConfig {
|
||||
let mut check_port_usage = |iface, ports: &Vec<String>| {
|
||||
for port in ports.iter() {
|
||||
if let Some(prev_iface) = used_ports.get(port) {
|
||||
bail!("iface '{}' port '{}' is already used on interface '{}'",
|
||||
iface, port, prev_iface);
|
||||
bail!(
|
||||
"iface '{}' port '{}' is already used on interface '{}'",
|
||||
iface,
|
||||
port,
|
||||
prev_iface
|
||||
);
|
||||
}
|
||||
used_ports.insert(port.to_string(), iface);
|
||||
}
|
||||
@ -270,18 +287,25 @@ impl NetworkConfig {
|
||||
};
|
||||
|
||||
for (iface, interface) in self.interfaces.iter() {
|
||||
if let Some(ports) = &interface.bridge_ports { check_port_usage(iface, ports)?; }
|
||||
if let Some(slaves) = &interface.slaves { check_port_usage(iface, slaves)?; }
|
||||
if let Some(ports) = &interface.bridge_ports {
|
||||
check_port_usage(iface, ports)?;
|
||||
}
|
||||
if let Some(slaves) = &interface.slaves {
|
||||
check_port_usage(iface, slaves)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Check if child mtu is less or equal than parent mtu
|
||||
pub fn check_mtu(&self, parent_name: &str, child_name: &str) -> Result<(), Error> {
|
||||
|
||||
let parent = self.interfaces.get(parent_name)
|
||||
let parent = self
|
||||
.interfaces
|
||||
.get(parent_name)
|
||||
.ok_or_else(|| format_err!("check_mtu - missing parent interface '{}'", parent_name))?;
|
||||
let child = self.interfaces.get(child_name)
|
||||
let child = self
|
||||
.interfaces
|
||||
.get(child_name)
|
||||
.ok_or_else(|| format_err!("check_mtu - missing child interface '{}'", child_name))?;
|
||||
|
||||
let child_mtu = match child.mtu {
|
||||
@ -301,8 +325,13 @@ impl NetworkConfig {
|
||||
};
|
||||
|
||||
if parent_mtu < child_mtu {
|
||||
bail!("interface '{}' - mtu {} is lower than '{}' - mtu {}\n",
|
||||
parent_name, parent_mtu, child_name, child_mtu);
|
||||
bail!(
|
||||
"interface '{}' - mtu {} is lower than '{}' - mtu {}\n",
|
||||
parent_name,
|
||||
parent_mtu,
|
||||
child_name,
|
||||
child_mtu
|
||||
);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
@ -316,8 +345,13 @@ impl NetworkConfig {
|
||||
match self.interfaces.get(slave) {
|
||||
Some(entry) => {
|
||||
if entry.interface_type != NetworkInterfaceType::Eth {
|
||||
bail!("bond '{}' - wrong interface type on slave '{}' ({:?} != {:?})",
|
||||
iface, slave, entry.interface_type, NetworkInterfaceType::Eth);
|
||||
bail!(
|
||||
"bond '{}' - wrong interface type on slave '{}' ({:?} != {:?})",
|
||||
iface,
|
||||
slave,
|
||||
entry.interface_type,
|
||||
NetworkInterfaceType::Eth
|
||||
);
|
||||
}
|
||||
}
|
||||
None => {
|
||||
@ -333,7 +367,7 @@ impl NetworkConfig {
|
||||
|
||||
/// Check if bridge ports exists
|
||||
pub fn check_bridge_ports(&self) -> Result<(), Error> {
|
||||
lazy_static!{
|
||||
lazy_static! {
|
||||
static ref VLAN_INTERFACE_REGEX: Regex = Regex::new(r"^(\S+)\.(\d+)$").unwrap();
|
||||
}
|
||||
|
||||
@ -341,7 +375,11 @@ impl NetworkConfig {
|
||||
if let Some(ports) = &interface.bridge_ports {
|
||||
for port in ports.iter() {
|
||||
let captures = VLAN_INTERFACE_REGEX.captures(port);
|
||||
let port = if let Some(ref caps) = captures { &caps[1] } else { port.as_str() };
|
||||
let port = if let Some(ref caps) = captures {
|
||||
&caps[1]
|
||||
} else {
|
||||
port.as_str()
|
||||
};
|
||||
if !self.interfaces.contains_key(port) {
|
||||
bail!("bridge '{}' - unable to find port '{}'", iface, port);
|
||||
}
|
||||
@ -353,7 +391,6 @@ impl NetworkConfig {
|
||||
}
|
||||
|
||||
pub fn write_config(&self, w: &mut dyn Write) -> Result<(), Error> {
|
||||
|
||||
self.check_port_usage()?;
|
||||
self.check_bond_slaves()?;
|
||||
self.check_bridge_ports()?;
|
||||
@ -363,13 +400,15 @@ impl NetworkConfig {
|
||||
let mut last_entry_was_comment = false;
|
||||
|
||||
for entry in self.order.iter() {
|
||||
match entry {
|
||||
match entry {
|
||||
NetworkOrderEntry::Comment(comment) => {
|
||||
writeln!(w, "#{}", comment)?;
|
||||
last_entry_was_comment = true;
|
||||
}
|
||||
NetworkOrderEntry::Option(option) => {
|
||||
if last_entry_was_comment { writeln!(w)?; }
|
||||
if last_entry_was_comment {
|
||||
writeln!(w)?;
|
||||
}
|
||||
last_entry_was_comment = false;
|
||||
writeln!(w, "{}", option)?;
|
||||
writeln!(w)?;
|
||||
@ -380,10 +419,14 @@ impl NetworkConfig {
|
||||
None => continue,
|
||||
};
|
||||
|
||||
if last_entry_was_comment { writeln!(w)?; }
|
||||
if last_entry_was_comment {
|
||||
writeln!(w)?;
|
||||
}
|
||||
last_entry_was_comment = false;
|
||||
|
||||
if done.contains(name) { continue; }
|
||||
if done.contains(name) {
|
||||
continue;
|
||||
}
|
||||
done.insert(name);
|
||||
|
||||
write_iface(interface, w)?;
|
||||
@ -392,7 +435,9 @@ impl NetworkConfig {
|
||||
}
|
||||
|
||||
for (name, interface) in &self.interfaces {
|
||||
if done.contains(name) { continue; }
|
||||
if done.contains(name) {
|
||||
continue;
|
||||
}
|
||||
write_iface(interface, w)?;
|
||||
}
|
||||
Ok(())
|
||||
@ -407,15 +452,16 @@ pub fn lock_config() -> Result<BackupLockGuard, Error> {
|
||||
open_backup_lockfile(NETWORK_LOCKFILE, None, true)
|
||||
}
|
||||
|
||||
pub fn config() -> Result<(NetworkConfig, [u8;32]), Error> {
|
||||
|
||||
let content = match proxmox_sys::fs::file_get_optional_contents(NETWORK_INTERFACES_NEW_FILENAME)? {
|
||||
Some(content) => content,
|
||||
None => {
|
||||
let content = proxmox_sys::fs::file_get_optional_contents(NETWORK_INTERFACES_FILENAME)?;
|
||||
content.unwrap_or_default()
|
||||
}
|
||||
};
|
||||
pub fn config() -> Result<(NetworkConfig, [u8; 32]), Error> {
|
||||
let content =
|
||||
match proxmox_sys::fs::file_get_optional_contents(NETWORK_INTERFACES_NEW_FILENAME)? {
|
||||
Some(content) => content,
|
||||
None => {
|
||||
let content =
|
||||
proxmox_sys::fs::file_get_optional_contents(NETWORK_INTERFACES_FILENAME)?;
|
||||
content.unwrap_or_default()
|
||||
}
|
||||
};
|
||||
|
||||
let digest = openssl::sha::sha256(&content);
|
||||
|
||||
@ -427,7 +473,6 @@ pub fn config() -> Result<(NetworkConfig, [u8;32]), Error> {
|
||||
}
|
||||
|
||||
pub fn changes() -> Result<String, Error> {
|
||||
|
||||
if !std::path::Path::new(NETWORK_INTERFACES_NEW_FILENAME).exists() {
|
||||
return Ok(String::new());
|
||||
}
|
||||
@ -436,7 +481,6 @@ pub fn changes() -> Result<String, Error> {
|
||||
}
|
||||
|
||||
pub fn save_config(config: &NetworkConfig) -> Result<(), Error> {
|
||||
|
||||
let mut raw = Vec::new();
|
||||
config.write_config(&mut raw)?;
|
||||
|
||||
@ -461,7 +505,6 @@ pub fn complete_interface_name(_arg: &str, _param: &HashMap<String, String>) ->
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
pub fn complete_port_list(arg: &str, _param: &HashMap<String, String>) -> Vec<String> {
|
||||
let mut ports = Vec::new();
|
||||
match config() {
|
||||
@ -476,20 +519,26 @@ pub fn complete_port_list(arg: &str, _param: &HashMap<String, String>) -> Vec<St
|
||||
};
|
||||
|
||||
let arg = arg.trim();
|
||||
let prefix = if let Some(idx) = arg.rfind(',') { &arg[..idx+1] } else { "" };
|
||||
ports.iter().map(|port| format!("{}{}", prefix, port)).collect()
|
||||
let prefix = if let Some(idx) = arg.rfind(',') {
|
||||
&arg[..idx + 1]
|
||||
} else {
|
||||
""
|
||||
};
|
||||
ports
|
||||
.iter()
|
||||
.map(|port| format!("{}{}", prefix, port))
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
|
||||
use anyhow::{Error};
|
||||
use anyhow::Error;
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_network_config_create_lo_1() -> Result<(), Error> {
|
||||
|
||||
let input = "";
|
||||
|
||||
let mut parser = NetworkParser::new(input.as_bytes());
|
||||
@ -515,7 +564,6 @@ mod test {
|
||||
|
||||
#[test]
|
||||
fn test_network_config_create_lo_2() -> Result<(), Error> {
|
||||
|
||||
let input = "#c1\n\n#c2\n\niface test inet manual\n";
|
||||
|
||||
let mut parser = NetworkParser::new(input.as_bytes());
|
||||
|
@ -1,15 +1,18 @@
|
||||
use std::io::{BufRead};
|
||||
use std::iter::{Peekable, Iterator};
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::io::BufRead;
|
||||
use std::iter::{Iterator, Peekable};
|
||||
|
||||
use anyhow::{Error, bail, format_err};
|
||||
use anyhow::{bail, format_err, Error};
|
||||
use lazy_static::lazy_static;
|
||||
use regex::Regex;
|
||||
|
||||
use super::helper::*;
|
||||
use super::lexer::*;
|
||||
|
||||
use super::{NetworkConfig, NetworkOrderEntry, Interface, NetworkConfigMethod, NetworkInterfaceType, bond_mode_from_str, bond_xmit_hash_policy_from_str};
|
||||
use super::{
|
||||
bond_mode_from_str, bond_xmit_hash_policy_from_str, Interface, NetworkConfig,
|
||||
NetworkConfigMethod, NetworkInterfaceType, NetworkOrderEntry,
|
||||
};
|
||||
|
||||
fn set_method_v4(iface: &mut Interface, method: NetworkConfigMethod) -> Result<(), Error> {
|
||||
if iface.method.is_none() {
|
||||
@ -65,11 +68,18 @@ fn set_gateway_v6(iface: &mut Interface, gateway: String) -> Result<(), Error> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn set_interface_type(iface: &mut Interface, interface_type: NetworkInterfaceType) -> Result<(), Error> {
|
||||
fn set_interface_type(
|
||||
iface: &mut Interface,
|
||||
interface_type: NetworkInterfaceType,
|
||||
) -> Result<(), Error> {
|
||||
if iface.interface_type == NetworkInterfaceType::Unknown {
|
||||
iface.interface_type = interface_type;
|
||||
} else if iface.interface_type != interface_type {
|
||||
bail!("interface type already defined - cannot change from {:?} to {:?}", iface.interface_type, interface_type);
|
||||
bail!(
|
||||
"interface type already defined - cannot change from {:?} to {:?}",
|
||||
iface.interface_type,
|
||||
interface_type
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@ -79,8 +89,7 @@ pub struct NetworkParser<R: BufRead> {
|
||||
line_nr: usize,
|
||||
}
|
||||
|
||||
impl <R: BufRead> NetworkParser<R> {
|
||||
|
||||
impl<R: BufRead> NetworkParser<R> {
|
||||
pub fn new(reader: R) -> Self {
|
||||
let input = Lexer::new(reader).peekable();
|
||||
Self { input, line_nr: 1 }
|
||||
@ -91,9 +100,7 @@ impl <R: BufRead> NetworkParser<R> {
|
||||
Some(Err(err)) => {
|
||||
bail!("input error - {}", err);
|
||||
}
|
||||
Some(Ok((token, _))) => {
|
||||
Ok(*token)
|
||||
}
|
||||
Some(Ok((token, _))) => Ok(*token),
|
||||
None => {
|
||||
bail!("got unexpected end of stream (inside peek)");
|
||||
}
|
||||
@ -106,7 +113,9 @@ impl <R: BufRead> NetworkParser<R> {
|
||||
bail!("input error - {}", err);
|
||||
}
|
||||
Some(Ok((token, text))) => {
|
||||
if token == Token::Newline { self.line_nr += 1; }
|
||||
if token == Token::Newline {
|
||||
self.line_nr += 1;
|
||||
}
|
||||
Ok((token, text))
|
||||
}
|
||||
None => {
|
||||
@ -136,14 +145,13 @@ impl <R: BufRead> NetworkParser<R> {
|
||||
loop {
|
||||
match self.next()? {
|
||||
(Token::Text, iface) => {
|
||||
auto_flag.insert(iface.to_string());
|
||||
auto_flag.insert(iface.to_string());
|
||||
}
|
||||
(Token::Newline, _) => break,
|
||||
unexpected => {
|
||||
bail!("expected {:?}, got {:?}", Token::Text, unexpected);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
Ok(())
|
||||
@ -153,7 +161,7 @@ impl <R: BufRead> NetworkParser<R> {
|
||||
self.eat(Token::Netmask)?;
|
||||
let netmask = self.next_text()?;
|
||||
|
||||
let mask = if let Some(mask) = IPV4_MASK_HASH_LOCALNET.get(netmask.as_str()) {
|
||||
let mask = if let Some(mask) = IPV4_MASK_HASH_LOCALNET.get(netmask.as_str()) {
|
||||
*mask
|
||||
} else {
|
||||
match u8::from_str_radix(netmask.as_str(), 10) {
|
||||
@ -236,7 +244,9 @@ impl <R: BufRead> NetworkParser<R> {
|
||||
match self.next()? {
|
||||
(Token::Newline, _) => return Ok(line),
|
||||
(_, text) => {
|
||||
if !line.is_empty() { line.push(' '); }
|
||||
if !line.is_empty() {
|
||||
line.push(' ');
|
||||
}
|
||||
line.push_str(&text);
|
||||
}
|
||||
}
|
||||
@ -255,7 +265,10 @@ impl <R: BufRead> NetworkParser<R> {
|
||||
list.push(text);
|
||||
}
|
||||
}
|
||||
_ => bail!("unable to parse interface list - unexpected token '{:?}'", token),
|
||||
_ => bail!(
|
||||
"unable to parse interface list - unexpected token '{:?}'",
|
||||
token
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
@ -268,23 +281,28 @@ impl <R: BufRead> NetworkParser<R> {
|
||||
address_family_v4: bool,
|
||||
address_family_v6: bool,
|
||||
) -> Result<(), Error> {
|
||||
|
||||
let mut netmask = None;
|
||||
let mut address_list = Vec::new();
|
||||
|
||||
loop {
|
||||
match self.peek()? {
|
||||
Token::Attribute => { self.eat(Token::Attribute)?; },
|
||||
Token::Attribute => {
|
||||
self.eat(Token::Attribute)?;
|
||||
}
|
||||
Token::Comment => {
|
||||
let comment = self.eat(Token::Comment)?;
|
||||
if !address_family_v4 && address_family_v6 {
|
||||
let mut comments = interface.comments6.take().unwrap_or_default();
|
||||
if !comments.is_empty() { comments.push('\n'); }
|
||||
if !comments.is_empty() {
|
||||
comments.push('\n');
|
||||
}
|
||||
comments.push_str(&comment);
|
||||
interface.comments6 = Some(comments);
|
||||
} else {
|
||||
let mut comments = interface.comments.take().unwrap_or_default();
|
||||
if !comments.is_empty() { comments.push('\n'); }
|
||||
if !comments.is_empty() {
|
||||
comments.push('\n');
|
||||
}
|
||||
comments.push_str(&comment);
|
||||
interface.comments = Some(comments);
|
||||
}
|
||||
@ -343,7 +361,8 @@ impl <R: BufRead> NetworkParser<R> {
|
||||
interface.bond_xmit_hash_policy = Some(policy);
|
||||
self.eat(Token::Newline)?;
|
||||
}
|
||||
_ => { // parse addon attributes
|
||||
_ => {
|
||||
// parse addon attributes
|
||||
let option = self.parse_to_eol()?;
|
||||
if !option.is_empty() {
|
||||
if !address_family_v4 && address_family_v6 {
|
||||
@ -351,8 +370,8 @@ impl <R: BufRead> NetworkParser<R> {
|
||||
} else {
|
||||
interface.options.push(option);
|
||||
}
|
||||
};
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -362,7 +381,7 @@ impl <R: BufRead> NetworkParser<R> {
|
||||
bail!("unable to apply netmask to multiple addresses (please use cidr notation)");
|
||||
} else if address_list.len() == 1 {
|
||||
let (mut cidr, mask, is_v6) = address_list.pop().unwrap();
|
||||
if mask.is_some() {
|
||||
if mask.is_some() {
|
||||
// address already has a mask - ignore netmask
|
||||
} else {
|
||||
check_netmask(netmask, is_v6)?;
|
||||
@ -449,12 +468,18 @@ impl <R: BufRead> NetworkParser<R> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn parse_interfaces(&mut self, existing_interfaces: Option<&HashMap<String, bool>>) -> Result<NetworkConfig, Error> {
|
||||
pub fn parse_interfaces(
|
||||
&mut self,
|
||||
existing_interfaces: Option<&HashMap<String, bool>>,
|
||||
) -> Result<NetworkConfig, Error> {
|
||||
self._parse_interfaces(existing_interfaces)
|
||||
.map_err(|err| format_err!("line {}: {}", self.line_nr, err))
|
||||
}
|
||||
|
||||
pub fn _parse_interfaces(&mut self, existing_interfaces: Option<&HashMap<String, bool>>) -> Result<NetworkConfig, Error> {
|
||||
pub fn _parse_interfaces(
|
||||
&mut self,
|
||||
existing_interfaces: Option<&HashMap<String, bool>>,
|
||||
) -> Result<NetworkConfig, Error> {
|
||||
let mut config = NetworkConfig::new();
|
||||
|
||||
let mut auto_flag: HashSet<String> = HashSet::new();
|
||||
@ -494,31 +519,38 @@ impl <R: BufRead> NetworkParser<R> {
|
||||
}
|
||||
}
|
||||
|
||||
lazy_static!{
|
||||
lazy_static! {
|
||||
static ref INTERFACE_ALIAS_REGEX: Regex = Regex::new(r"^\S+:\d+$").unwrap();
|
||||
static ref VLAN_INTERFACE_REGEX: Regex = Regex::new(r"^\S+\.\d+$").unwrap();
|
||||
}
|
||||
|
||||
if let Some(existing_interfaces) = existing_interfaces {
|
||||
for (iface, active) in existing_interfaces.iter() {
|
||||
for (iface, active) in existing_interfaces.iter() {
|
||||
if let Some(interface) = config.interfaces.get_mut(iface) {
|
||||
interface.active = *active;
|
||||
if interface.interface_type == NetworkInterfaceType::Unknown && super::is_physical_nic(iface) {
|
||||
if interface.interface_type == NetworkInterfaceType::Unknown
|
||||
&& super::is_physical_nic(iface)
|
||||
{
|
||||
interface.interface_type = NetworkInterfaceType::Eth;
|
||||
}
|
||||
} else if super::is_physical_nic(iface) { // also add all physical NICs
|
||||
} else if super::is_physical_nic(iface) {
|
||||
// also add all physical NICs
|
||||
let mut interface = Interface::new(iface.clone());
|
||||
set_method_v4(&mut interface, NetworkConfigMethod::Manual)?;
|
||||
interface.interface_type = NetworkInterfaceType::Eth;
|
||||
interface.active = *active;
|
||||
config.interfaces.insert(interface.name.clone(), interface);
|
||||
config.order.push(NetworkOrderEntry::Iface(iface.to_string()));
|
||||
config
|
||||
.order
|
||||
.push(NetworkOrderEntry::Iface(iface.to_string()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (name, interface) in config.interfaces.iter_mut() {
|
||||
if interface.interface_type != NetworkInterfaceType::Unknown { continue; }
|
||||
if interface.interface_type != NetworkInterfaceType::Unknown {
|
||||
continue;
|
||||
}
|
||||
if name == "lo" {
|
||||
interface.interface_type = NetworkInterfaceType::Loopback;
|
||||
continue;
|
||||
@ -548,11 +580,14 @@ impl <R: BufRead> NetworkParser<R> {
|
||||
let mut new_order = Vec::new();
|
||||
let mut added_lo = false;
|
||||
for entry in config.order {
|
||||
if added_lo { new_order.push(entry); continue; } // copy the rest
|
||||
if added_lo {
|
||||
new_order.push(entry);
|
||||
continue;
|
||||
} // copy the rest
|
||||
match entry {
|
||||
NetworkOrderEntry::Comment(_) => {
|
||||
new_order.push(entry);
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
new_order.push(NetworkOrderEntry::Iface(String::from("lo")));
|
||||
added_lo = true;
|
||||
|
Reference in New Issue
Block a user