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
30pub fn replace_host_table(table: HashMap<String, IpAddr>) {
31    *HOST_TABLE.lock() = Some(table);
32}
33
34pub fn parse_hostsfile(hostsfile_content: &str) -> HashMap<String, IpAddr> {
35    hostsfile_content
36        .lines()
37        .filter_map(|line| {
38            let mut iter = line.split('#').next().unwrap().split_whitespace();
39            Some((iter.next()?.parse().ok()?, iter))
40        })
41        .flat_map(|(ip, hosts)| {
42            hosts
43                .filter(|host| {
44                    let invalid = [
45                        '\0', '\t', '\n', '\r', ' ', '#', '%', '/', ':', '?', '@', '[', '\\', ']',
46                    ];
47                    host.parse::<Ipv4Addr>().is_err() && !host.contains(&invalid[..])
48                })
49                .map(move |host| (host.to_owned(), ip))
50        })
51        .collect()
52}
53
54pub fn replace_host(host: &str) -> Cow<'_, str> {
55    HOST_TABLE
56        .lock()
57        .as_ref()
58        .and_then(|table| table.get(host))
59        .map_or(host.into(), |replaced_host| {
60            replaced_host.to_string().into()
61        })
62}