halephant_core/auth/
pgpass.rs1use std::path::Path;
2
3pub struct Pgpass {
5 entries: Vec<Entry>,
6}
7
8struct Entry {
9 hostname: Pattern,
10 port: Pattern,
11 database: Pattern,
12 username: Pattern,
13 password: String,
14}
15
16enum Pattern {
17 Any,
18 Exact(String),
19}
20
21impl Pattern {
22 fn parse(s: &str) -> Self {
23 if s == "*" {
24 Self::Any
25 } else {
26 Self::Exact(s.to_owned())
27 }
28 }
29
30 fn matches(&self, value: &str) -> bool {
31 match self {
32 Self::Any => true,
33 Self::Exact(v) => v == value,
34 }
35 }
36}
37
38impl Pgpass {
39 pub fn load(path: &Path) -> Self {
42 match std::fs::read_to_string(path) {
43 Ok(content) => Self::parse(&content),
44 Err(_) => Self {
45 entries: Vec::new(),
46 },
47 }
48 }
49
50 pub fn parse(content: &str) -> Self {
52 let entries = content
61 .lines()
62 .filter(|line| {
63 let trimmed = line.trim();
64 !trimmed.is_empty() && !trimmed.starts_with('#')
65 })
66 .filter_map(parse_line)
67 .collect();
68 Self { entries }
69 }
70
71 pub fn lookup(
74 &self,
75 hostname: &str,
76 port: &str,
77 database: &str,
78 username: &str,
79 ) -> Option<&str> {
80 self.entries
81 .iter()
82 .find(|e| {
83 e.hostname.matches(hostname)
84 && e.port.matches(port)
85 && e.database.matches(database)
86 && e.username.matches(username)
87 })
88 .map(|e| e.password.as_str())
89 }
90
91 pub fn lookup_addr(&self, addr: &str, database: &str, username: &str) -> Option<&str> {
96 let (host, port) = crate::addr::split_addr::split_host_port(addr);
97 self.lookup(host, port, database, username)
98 }
99
100 pub fn is_empty(&self) -> bool {
102 self.entries.is_empty()
103 }
104}
105
106fn parse_line(line: &str) -> Option<Entry> {
112 let mut fields = Vec::with_capacity(5);
113 let mut current = String::new();
114 let chars = line.chars();
115 let mut escaped = false;
116
117 for ch in chars {
118 if escaped {
119 current.push(ch);
120 escaped = false;
121 } else if ch == '\\' {
122 escaped = true;
123 } else if ch == ':' && fields.len() < 4 {
124 fields.push(std::mem::take(&mut current));
125 } else {
126 current.push(ch);
127 }
128 }
129 fields.push(current); if fields.len() != 5 {
132 return None;
133 }
134
135 Some(Entry {
136 hostname: Pattern::parse(&fields[0]),
137 port: Pattern::parse(&fields[1]),
138 database: Pattern::parse(&fields[2]),
139 username: Pattern::parse(&fields[3]),
140 password: fields[4].clone(),
141 })
142}