diff options
author | Josh Matthews <josh@joshmatthews.net> | 2017-04-05 18:32:19 -0400 |
---|---|---|
committer | Josh Matthews <josh@joshmatthews.net> | 2017-04-06 19:25:47 +0900 |
commit | 6f590a87bfaefd6daeafa6e422e9f1eee5c0cd94 (patch) | |
tree | ed6292bdd859509426fee7efeb0dfb35cd31b37f /components/net/hosts.rs | |
parent | e772086b8c380a94e3b925213526b9374e162bc6 (diff) | |
download | servo-6f590a87bfaefd6daeafa6e422e9f1eee5c0cd94.tar.gz servo-6f590a87bfaefd6daeafa6e422e9f1eee5c0cd94.zip |
Move hosts module into net crate. Remove obsolete functions.
Diffstat (limited to 'components/net/hosts.rs')
-rw-r--r-- | components/net/hosts.rs | 63 |
1 files changed, 63 insertions, 0 deletions
diff --git a/components/net/hosts.rs b/components/net/hosts.rs new file mode 100644 index 00000000000..adc46e870ea --- /dev/null +++ b/components/net/hosts.rs @@ -0,0 +1,63 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +use parse_hosts::HostsFile; +use std::borrow::Cow; +use std::collections::HashMap; +use std::env; +use std::fs::File; +use std::io::{BufReader, Read}; +use std::net::IpAddr; +use std::sync::Mutex; + +lazy_static! { + static ref HOST_TABLE: Mutex<Option<HashMap<String, IpAddr>>> = Mutex::new(create_host_table()); +} + +fn create_host_table() -> Option<HashMap<String, IpAddr>> { + // TODO: handle bad file path + let path = match env::var("HOST_FILE") { + Ok(host_file_path) => host_file_path, + Err(_) => return None, + }; + + let mut file = match File::open(&path) { + Ok(f) => BufReader::new(f), + Err(_) => return None, + }; + + let mut lines = String::new(); + match file.read_to_string(&mut lines) { + Ok(_) => (), + Err(_) => return None, + }; + + Some(parse_hostsfile(&lines)) +} + +pub fn replace_host_table(table: HashMap<String, IpAddr>) { + *HOST_TABLE.lock().unwrap() = Some(table); +} + +pub fn parse_hostsfile(hostsfile_content: &str) -> HashMap<String, IpAddr> { + let mut host_table = HashMap::new(); + + for line in HostsFile::read_buffered(hostsfile_content.as_bytes()).lines() { + if let Ok(ref line) = line { + for host in line.hosts() { + if let Some(ip) = line.ip() { + host_table.insert(host.to_owned(), ip); + } + } + } + } + + host_table +} + +pub fn replace_host(host: &str) -> Cow<str> { + HOST_TABLE.lock().unwrap().as_ref() + .and_then(|table| table.get(host)) + .map_or(host.into(), |replaced_host| replaced_host.to_string().into()) +} |