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