hickory_resolver/
hosts.rs

1//! Hosts result from a configuration of the system hosts file
2
3use std::collections::HashMap;
4use std::io;
5use std::path::Path;
6use std::str::FromStr;
7use std::sync::Arc;
8
9use proto::op::Query;
10use proto::rr::{Name, RecordType};
11use proto::rr::{RData, Record};
12use tracing::warn;
13
14use crate::dns_lru;
15use crate::lookup::Lookup;
16
17#[derive(Debug, Default)]
18struct LookupType {
19    /// represents the A record type
20    a: Option<Lookup>,
21    /// represents the AAAA record type
22    aaaa: Option<Lookup>,
23}
24
25/// Configuration for the local hosts file
26#[derive(Debug, Default)]
27pub struct Hosts {
28    /// Name -> RDatas map
29    by_name: HashMap<Name, LookupType>,
30}
31
32impl Hosts {
33    /// Creates a new configuration from the system hosts file,
34    /// only works for Windows and Unix-like OSes,
35    /// will return empty configuration on others
36    #[cfg(any(unix, windows))]
37    pub fn new() -> Self {
38        read_hosts_conf(hosts_path()).unwrap_or_default()
39    }
40
41    /// Creates a default configuration for non Windows or Unix-like OSes
42    #[cfg(not(any(unix, windows)))]
43    pub fn new() -> Self {
44        Hosts::default()
45    }
46
47    /// Look up the addresses for the given host from the system hosts file.
48    pub fn lookup_static_host(&self, query: &Query) -> Option<Lookup> {
49        if !self.by_name.is_empty() {
50            if let Some(val) = self.by_name.get(query.name()) {
51                let result = match query.query_type() {
52                    RecordType::A => val.a.clone(),
53                    RecordType::AAAA => val.aaaa.clone(),
54                    _ => None,
55                };
56
57                return result;
58            }
59        }
60        None
61    }
62
63    /// Insert a new Lookup for the associated `Name` and `RecordType`
64    pub fn insert(&mut self, name: Name, record_type: RecordType, lookup: Lookup) {
65        assert!(record_type == RecordType::A || record_type == RecordType::AAAA);
66
67        let lookup_type = self.by_name.entry(name.clone()).or_default();
68
69        let new_lookup = {
70            let old_lookup = match record_type {
71                RecordType::A => lookup_type.a.get_or_insert_with(|| {
72                    let query = Query::query(name.clone(), record_type);
73                    Lookup::new_with_max_ttl(query, Arc::from([]))
74                }),
75                RecordType::AAAA => lookup_type.aaaa.get_or_insert_with(|| {
76                    let query = Query::query(name.clone(), record_type);
77                    Lookup::new_with_max_ttl(query, Arc::from([]))
78                }),
79                _ => {
80                    tracing::warn!("unsupported IP type from Hosts file: {:#?}", record_type);
81                    return;
82                }
83            };
84
85            old_lookup.append(lookup)
86        };
87
88        // replace the appended version
89        match record_type {
90            RecordType::A => lookup_type.a = Some(new_lookup),
91            RecordType::AAAA => lookup_type.aaaa = Some(new_lookup),
92            _ => tracing::warn!("unsupported IP type from Hosts file"),
93        }
94    }
95
96    /// parse configuration from `src`
97    pub fn read_hosts_conf(mut self, src: impl io::Read) -> io::Result<Self> {
98        use std::io::{BufRead, BufReader};
99
100        use proto::rr::domain::TryParseIp;
101
102        // lines in the src should have the form `addr host1 host2 host3 ...`
103        // line starts with `#` will be regarded with comments and ignored,
104        // also empty line also will be ignored,
105        // if line only include `addr` without `host` will be ignored,
106        // the src will be parsed to map in the form `Name -> LookUp`.
107
108        for line in BufReader::new(src).lines() {
109            // Remove comments from the line
110            let line = line?;
111            let line = line.split('#').next().unwrap().trim();
112            if line.is_empty() {
113                continue;
114            }
115
116            let fields: Vec<_> = line.split_whitespace().collect();
117            if fields.len() < 2 {
118                continue;
119            }
120            let addr = if let Some(a) = fields[0].try_parse_ip() {
121                a
122            } else {
123                warn!("could not parse an IP from hosts file");
124                continue;
125            };
126
127            for domain in fields.iter().skip(1).map(|domain| domain.to_lowercase()) {
128                if let Ok(name) = Name::from_str(&domain) {
129                    let record = Record::from_rdata(name.clone(), dns_lru::MAX_TTL, addr.clone());
130
131                    match addr {
132                        RData::A(..) => {
133                            let query = Query::query(name.clone(), RecordType::A);
134                            let lookup = Lookup::new_with_max_ttl(query, Arc::from([record]));
135                            self.insert(name.clone(), RecordType::A, lookup);
136                        }
137                        RData::AAAA(..) => {
138                            let query = Query::query(name.clone(), RecordType::AAAA);
139                            let lookup = Lookup::new_with_max_ttl(query, Arc::from([record]));
140                            self.insert(name.clone(), RecordType::AAAA, lookup);
141                        }
142                        _ => {
143                            warn!("unsupported IP type from Hosts file: {:#?}", addr);
144                            continue;
145                        }
146                    };
147
148                    // TODO: insert reverse lookup as well.
149                };
150            }
151        }
152
153        Ok(self)
154    }
155}
156
157#[cfg(unix)]
158fn hosts_path() -> &'static str {
159    "/etc/hosts"
160}
161
162#[cfg(windows)]
163fn hosts_path() -> std::path::PathBuf {
164    let system_root =
165        std::env::var_os("SystemRoot").expect("Environtment variable SystemRoot not found");
166    let system_root = Path::new(&system_root);
167    system_root.join("System32\\drivers\\etc\\hosts")
168}
169
170/// parse configuration from `path`
171#[cfg(any(unix, windows))]
172#[cfg_attr(docsrs, doc(cfg(any(unix, windows))))]
173pub(crate) fn read_hosts_conf<P: AsRef<Path>>(path: P) -> io::Result<Hosts> {
174    use std::fs::File;
175
176    let file = File::open(path)?;
177    Hosts::default().read_hosts_conf(file)
178}
179
180#[cfg(any(unix, windows))]
181#[cfg(test)]
182mod tests {
183    use super::*;
184    use std::env;
185    use std::net::{Ipv4Addr, Ipv6Addr};
186
187    fn tests_dir() -> String {
188        let server_path = env::var("TDNS_WORKSPACE_ROOT").unwrap_or_else(|_| "../..".to_owned());
189        format! {"{server_path}/crates/resolver/tests"}
190    }
191
192    #[test]
193    fn test_read_hosts_conf() {
194        let path = format!("{}/hosts", tests_dir());
195        let hosts = read_hosts_conf(path).unwrap();
196
197        let name = Name::from_str("localhost").unwrap();
198        let rdatas = hosts
199            .lookup_static_host(&Query::query(name.clone(), RecordType::A))
200            .unwrap()
201            .iter()
202            .map(ToOwned::to_owned)
203            .collect::<Vec<RData>>();
204
205        assert_eq!(rdatas, vec![RData::A(Ipv4Addr::new(127, 0, 0, 1).into())]);
206
207        let rdatas = hosts
208            .lookup_static_host(&Query::query(name, RecordType::AAAA))
209            .unwrap()
210            .iter()
211            .map(ToOwned::to_owned)
212            .collect::<Vec<RData>>();
213
214        assert_eq!(
215            rdatas,
216            vec![RData::AAAA(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1).into())]
217        );
218
219        let name = Name::from_str("broadcasthost").unwrap();
220        let rdatas = hosts
221            .lookup_static_host(&Query::query(name, RecordType::A))
222            .unwrap()
223            .iter()
224            .map(ToOwned::to_owned)
225            .collect::<Vec<RData>>();
226        assert_eq!(
227            rdatas,
228            vec![RData::A(Ipv4Addr::new(255, 255, 255, 255).into())]
229        );
230
231        let name = Name::from_str("example.com").unwrap();
232        let rdatas = hosts
233            .lookup_static_host(&Query::query(name, RecordType::A))
234            .unwrap()
235            .iter()
236            .map(ToOwned::to_owned)
237            .collect::<Vec<RData>>();
238        assert_eq!(rdatas, vec![RData::A(Ipv4Addr::new(10, 0, 1, 102).into())]);
239
240        let name = Name::from_str("a.example.com").unwrap();
241        let rdatas = hosts
242            .lookup_static_host(&Query::query(name, RecordType::A))
243            .unwrap()
244            .iter()
245            .map(ToOwned::to_owned)
246            .collect::<Vec<RData>>();
247        assert_eq!(rdatas, vec![RData::A(Ipv4Addr::new(10, 0, 1, 111).into())]);
248
249        let name = Name::from_str("b.example.com").unwrap();
250        let rdatas = hosts
251            .lookup_static_host(&Query::query(name, RecordType::A))
252            .unwrap()
253            .iter()
254            .map(ToOwned::to_owned)
255            .collect::<Vec<RData>>();
256        assert_eq!(rdatas, vec![RData::A(Ipv4Addr::new(10, 0, 1, 111).into())]);
257    }
258}