add plain HOSTS file support

* put hosts in ./hosts.txt and it will also override DNS reponses.
* This is for convenience using hosts ad-blocking lists
This commit is contained in:
Peter Cai 2021-04-05 20:18:23 +08:00
parent a856ca10b4
commit 400299cc78
4 changed files with 31 additions and 1 deletions

3
.gitignore vendored
View File

@ -4,4 +4,5 @@
/pkg
/dist
/worker
/config.json
/config.json
/hosts.txt

1
Cargo.lock generated
View File

@ -324,6 +324,7 @@ dependencies = [
"domain",
"getrandom",
"js-sys",
"lazy_static",
"once_cell",
"serde",
"serde_json",

View File

@ -20,6 +20,7 @@ domain = "0.6"
# we need to enable the `js` feature for it to build on WASM
getrandom = { version = "0.2", features = [ "js" ] }
js-sys = "0.3"
lazy_static = "1.4"
# Required by async_static
once_cell = "1"
serde = { version = "1.0", features = [ "derive" ] }

View File

@ -1,9 +1,34 @@
use crate::trie_map::TrieMap;
use domain::base::{rdata::UnknownRecordData, Compose, Dname, Question, Record, Rtype};
use domain::rdata::{Aaaa, AllRecordData, A};
use lazy_static::lazy_static;
use std::collections::HashMap;
use std::net::IpAddr;
lazy_static! {
static ref PLAIN_HOSTS_MAP: HashMap<String, IpAddr> = parse_plain_hosts_file();
}
fn parse_plain_hosts_file() -> HashMap<String, IpAddr> {
let mut ret = HashMap::new();
for line in include_str!("../hosts.txt").lines() {
if line.is_empty() {
continue;
}
if line.starts_with("#") {
continue;
}
if let [ip, domain] = line.split_whitespace().collect::<Vec<_>>().as_slice() {
if let Ok(addr) = ip.parse() {
ret.insert(domain.to_string(), addr);
}
}
}
ret
}
pub struct OverrideResolver {
simple_matches: HashMap<String, IpAddr>,
suffix_matches: TrieMap<IpAddr>,
@ -59,6 +84,8 @@ impl OverrideResolver {
let name = question.qname().to_string();
if let Some(addr) = self.simple_matches.get(&name) {
self.respond_with_addr(question, addr)
} else if let Some(addr) = PLAIN_HOSTS_MAP.get(&name) {
self.respond_with_addr(question, addr)
} else if let Some(addr) = self
.suffix_matches
.get_by_prefix(name.chars().rev().collect::<String>())