use std::path::Path;
pub struct Pgpass {
entries: Vec<Entry>,
}
struct Entry {
hostname: Pattern,
port: Pattern,
database: Pattern,
username: Pattern,
password: String,
}
enum Pattern {
Any,
Exact(String),
}
impl Pattern {
fn parse(s: &str) -> Self {
if s == "*" {
Self::Any
} else {
Self::Exact(s.to_owned())
}
}
fn matches(&self, value: &str) -> bool {
match self {
Self::Any => true,
Self::Exact(v) => v == value,
}
}
}
impl Pgpass {
pub fn load(path: &Path) -> Self {
match std::fs::read_to_string(path) {
Ok(content) => Self::parse(&content),
Err(_) => Self {
entries: Vec::new(),
},
}
}
pub fn parse(content: &str) -> Self {
let entries = content
.lines()
.filter(|line| {
let trimmed = line.trim();
!trimmed.is_empty() && !trimmed.starts_with('#')
})
.filter_map(parse_line)
.collect();
Self { entries }
}
pub fn lookup(
&self,
hostname: &str,
port: &str,
database: &str,
username: &str,
) -> Option<&str> {
self.entries
.iter()
.find(|e| {
e.hostname.matches(hostname)
&& e.port.matches(port)
&& e.database.matches(database)
&& e.username.matches(username)
})
.map(|e| e.password.as_str())
}
pub fn lookup_addr(&self, addr: &str, database: &str, username: &str) -> Option<&str> {
let (host, port) = crate::addr::split_addr::split_host_port(addr);
self.lookup(host, port, database, username)
}
pub fn is_empty(&self) -> bool {
self.entries.is_empty()
}
}
fn parse_line(line: &str) -> Option<Entry> {
let mut fields = Vec::with_capacity(5);
let mut current = String::new();
let chars = line.chars();
let mut escaped = false;
for ch in chars {
if escaped {
current.push(ch);
escaped = false;
} else if ch == '\\' {
escaped = true;
} else if ch == ':' && fields.len() < 4 {
fields.push(std::mem::take(&mut current));
} else {
current.push(ch);
}
}
fields.push(current);
if fields.len() != 5 {
return None;
}
Some(Entry {
hostname: Pattern::parse(&fields[0]),
port: Pattern::parse(&fields[1]),
database: Pattern::parse(&fields[2]),
username: Pattern::parse(&fields[3]),
password: fields[4].clone(),
})
}