Refine hosts parser

This commit is contained in:
ClawSeven 2022-04-24 13:18:11 +08:00 committed by volcano
parent a72a86f03d
commit c84c3b7b88

@ -24,33 +24,36 @@ pub struct Hosts {
impl FromStr for HostEntry { impl FromStr for HostEntry {
type Err = error::Error; type Err = error::Error;
fn from_str(line: &str) -> Result<Self> { fn from_str(line: &str) -> Result<Self> {
let slice: Vec<String> = line.split_whitespace().map(|s| s.to_string()).collect(); let slice: Vec<&str> = line.split_whitespace().collect();
// check IP: // check IP:
let ip = match slice.first() { let ip = match slice.first() {
Some(ip) => ip, Some(ip) => ip,
None => { None => {
return_errno!(EINVAL, "malformated ip in hosts file"); return_errno!(EINVAL, "malformated ip in /etc/hosts file");
} }
}; };
let _ip_addr: IpAddr = match ip.parse() { let _ip_addr: IpAddr = match ip.parse() {
Ok(ip) => ip, Ok(ip) => ip,
Err(_) => { Err(_) => {
return_errno!(EINVAL, "malformated ip in hosts file"); return_errno!(EINVAL, "malformated ip in /etc/hosts file");
} }
}; };
let mut hostname: Vec<String> = Vec::new(); let mut hostname: Vec<String> = Vec::new();
for i in slice[1..].to_vec() { if !slice.iter().skip(1).all(|&s| {
if !HOSTNAME_RE.is_match(&i) { let is_match = HOSTNAME_RE.is_match(s);
return_errno!(EINVAL, "malformated hostname in hosts file"); if is_match {
hostname.push(s.to_string());
} }
hostname.push(i.to_owned()); is_match
}) {
return_errno!(EINVAL, "malformated hostname in /etc/hosts file");
} }
if hostname.is_empty() { if hostname.is_empty() {
return_errno!(EINVAL, "malformated hostname in hosts file"); return_errno!(EINVAL, "malformated hostname in /etc/hosts file");
} }
Ok(HostEntry { Ok(HostEntry {
ip: ip.to_string(), ip: ip.to_string(),