Use /sys/ for get_interfaces()
This makes the get_interfaces() function in kernel inteface much easier
by using native linux /sys/ properties rather than building a regex and
parsing the output of 'ip'
@@ -2,22 +2,24 @@ use crate::file_io::get_lines;
use crate::KernelInterface;
use crate::KernelInterfaceError as Error;
use regex::Regex;
+use std::fs::read_dir;
use std::net::IpAddr;
use std::str::from_utf8;
impl dyn KernelInterface {
/// Returns all existing interfaces
pub fn get_interfaces(&self) -> Result<Vec<String>, Error> {
- let links = String::from_utf8(self.run_command("ip", &["link"])?.stdout)?;
+ let links = read_dir("/sys/class/net/")?;
let mut vec = Vec::new();
-
- lazy_static! {
- static ref RE: Regex =
- Regex::new(r"[0-9]+: (.*?)(:|@)").expect("Unable to compile regular expression");
+ for dir in links {
+ let dir = dir?;
+ if dir.path().is_dir() {
+ // this could fail if the interface contains any characters
+ // not allowed in unicode. I don't think the kernel allows
+ // this in the first place
+ vec.push(dir.file_name().to_str().unwrap().to_string());
}
- for caps in RE.captures_iter(&links) {
- vec.push(String::from(&caps[1]));
}
trace!("interfaces: {:?}", vec);
@@ -196,42 +198,6 @@ impl dyn KernelInterface {
}
}
-#[test]
-fn test_get_interfaces_linux() {
- use crate::KI;
-
- use std::os::unix::process::ExitStatusExt;
- use std::process::ExitStatus;
- use std::process::Output;
-
- KI.set_mock(Box::new(move |program, args| {
- assert_eq!(program, "ip");
- assert_eq!(args, &["link"]);
-
- Ok(Output {
- stdout: b"
- 1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN mode DEFAULT group default qlen 1000
- link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
-2: dummy: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UNKNOWN mode DEFAULT group default qlen 1000
- link/ether 22:8a:b6:9e:2d:1e brd ff:ff:ff:ff:ff:ff
-3: wg0: <POINTOPOINT,NOARP,UP,LOWER_UP> mtu 1420 qdisc noqueue state UNKNOWN mode DEFAULT group default qlen 1000
- link/none
-2843: veth-1-6@if2842: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc netem state UP mode DEFAULT group default qlen 1000
- link/ether 76:d1:f5:3d:32:53 brd ff:ff:ff:ff:ff:ff link-netnsid 1"
- .to_vec(),
- stderr: b"".to_vec(),
- status: ExitStatus::from_raw(0),
- })
- }));
-
- let interfaces = KI.get_interfaces().unwrap();
-
- assert_eq!(interfaces[0].to_string(), "lo");
- assert_eq!(interfaces[1].to_string(), "dummy");
- assert_eq!(interfaces[2].to_string(), "wg0");
- assert_eq!(interfaces[3].to_string(), "veth-1-6");
-}
-
#[test]
fn test_get_wg_remote_ip() {
use crate::KI;
