use std::net::Ipv4Addr;
use std::path::Path;
use crate::error::{Error, Result};
use crate::util::parse;
#[derive(Debug)]
pub struct RouteEntry {
pub iface: Box<str>,
pub destination: Ipv4Addr,
pub gateway: Ipv4Addr,
pub mask: Ipv4Addr,
pub flags: u16,
pub refcnt: u16,
pub use_: u32,
pub metric: u32,
pub mtu: u32,
pub window: u32,
pub irtt: u32,
}
pub fn route() -> impl Iterator<Item = Result<RouteEntry>> {
let path = Path::new("/proc/net/route");
let bytes = match parse::read_file(path) {
Ok(b) => b,
Err(e) => return vec![Err(e)].into_iter(),
};
let mut entries = Vec::new();
for line in bytes
.split(|&b| b == b'\n')
.filter(|l| !l.is_empty())
.skip(1)
{
let fields = parse::SplitFields::<11>::new(line);
if fields.len() < 11 {
entries.push(Err(Error::Parse {
path: path.to_path_buf(),
line: 0,
msg: "not enough fields",
}));
continue;
}
let iface = std::str::from_utf8(fields[0])
.unwrap_or("")
.to_string()
.into_boxed_str();
let destination = parse_hex_ipv4(fields[1]);
let gateway = parse_hex_ipv4(fields[2]);
let mask = parse_hex_ipv4(fields[7]);
let flags = parse::parse_hex_fast(fields[3]) as u16;
let refcnt = parse::parse_dec_fast(fields[4]) as u16;
let use_ = parse::parse_dec_fast(fields[5]) as u32;
let metric = parse::parse_dec_fast(fields[6]) as u32;
let mtu = parse::parse_dec_fast(fields[8]) as u32;
let window = parse::parse_dec_fast(fields[9]) as u32;
let irtt = parse::parse_dec_fast(fields[10]) as u32;
entries.push(Ok(RouteEntry {
iface,
destination,
gateway,
mask,
flags,
refcnt,
use_,
metric,
mtu,
window,
irtt,
}));
}
entries.into_iter()
}
fn parse_hex_ipv4(s: &[u8]) -> Ipv4Addr {
if s.len() != 8 {
return Ipv4Addr::UNSPECIFIED;
}
Ipv4Addr::from(parse::decode_ipv4_fast(s))
}