net/
hosts.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5use std::borrow::Cow;
6use std::collections::HashMap;
7use std::env;
8use std::fs::File;
9use std::io::{BufReader, Read};
10use std::net::{IpAddr, Ipv4Addr};
11use std::sync::LazyLock;
12
13use parking_lot::Mutex;
14
15static HOST_TABLE: LazyLock<Mutex<Option<HashMap<String, IpAddr>>>> =
16    LazyLock::new(|| Mutex::new(create_host_table()));
17
18fn create_host_table() -> Option<HashMap<String, IpAddr>> {
19    let path = env::var_os("HOST_FILE")?;
20
21    let file = File::open(path).ok()?;
22    let mut reader = BufReader::new(file);
23
24    let mut lines = String::new();
25    reader.read_to_string(&mut lines).ok()?;
26
27    Some(parse_hostsfile(&lines))
28}
29
30#[cfg_attr(not(feature = "test-util"), expect(dead_code))]
31pub fn replace_host_table(table: HashMap<String, IpAddr>) {
32    *HOST_TABLE.lock() = Some(table);
33}
34
35pub fn parse_hostsfile(hostsfile_content: &str) -> HashMap<String, IpAddr> {
36    hostsfile_content
37        .lines()
38        .filter_map(|line| {
39            let mut iter = line.split('#').next().unwrap().split_whitespace();
40            Some((iter.next()?.parse().ok()?, iter))
41        })
42        .flat_map(|(ip, hosts)| {
43            hosts
44                .filter(|host| {
45                    let invalid = [
46                        '\0', '\t', '\n', '\r', ' ', '#', '%', '/', ':', '?', '@', '[', '\\', ']',
47                    ];
48                    host.parse::<Ipv4Addr>().is_err() && !host.contains(&invalid[..])
49                })
50                .map(move |host| (host.to_owned(), ip))
51        })
52        .collect()
53}
54
55pub fn replace_host(host: &str) -> Cow<'_, str> {
56    HOST_TABLE
57        .lock()
58        .as_ref()
59        .and_then(|table| table.get(host))
60        .map_or(host.into(), |replaced_host| {
61            replaced_host.to_string().into()
62        })
63}