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, Mutex};
12
13static HOST_TABLE: LazyLock<Mutex<Option<HashMap<String, IpAddr>>>> =
14    LazyLock::new(|| Mutex::new(create_host_table()));
15
16fn create_host_table() -> Option<HashMap<String, IpAddr>> {
17    let path = env::var_os("HOST_FILE")?;
18
19    let file = File::open(path).ok()?;
20    let mut reader = BufReader::new(file);
21
22    let mut lines = String::new();
23    reader.read_to_string(&mut lines).ok()?;
24
25    Some(parse_hostsfile(&lines))
26}
27
28pub fn replace_host_table(table: HashMap<String, IpAddr>) {
29    *HOST_TABLE.lock().unwrap() = Some(table);
30}
31
32pub fn parse_hostsfile(hostsfile_content: &str) -> HashMap<String, IpAddr> {
33    hostsfile_content
34        .lines()
35        .filter_map(|line| {
36            let mut iter = line.split('#').next().unwrap().split_whitespace();
37            Some((iter.next()?.parse().ok()?, iter))
38        })
39        .flat_map(|(ip, hosts)| {
40            hosts
41                .filter(|host| {
42                    let invalid = [
43                        '\0', '\t', '\n', '\r', ' ', '#', '%', '/', ':', '?', '@', '[', '\\', ']',
44                    ];
45                    host.parse::<Ipv4Addr>().is_err() && !host.contains(&invalid[..])
46                })
47                .map(move |host| (host.to_owned(), ip))
48        })
49        .collect()
50}
51
52pub fn replace_host(host: &str) -> Cow<'_, str> {
53    HOST_TABLE
54        .lock()
55        .unwrap()
56        .as_ref()
57        .and_then(|table| table.get(host))
58        .map_or(host.into(), |replaced_host| {
59            replaced_host.to_string().into()
60        })
61}