This commit is contained in:
Mateusz Gruszczyński committed 2026-11-23 09:31:05 +01:00
1 parent 6e57b9e1b8
commit 7b8c7e93fb
48 files changed
+1010 -116

No files matched your search

+1 -1
View File
@@ -225,7 +225,7 @@ pub async fn zone_create(State(st): St, Extension(c): Extension<Caller>, Json(b)
if let Err(e) = dns_authoritative::Zone::from_records(&name, records) {
return error(StatusCode::UNPROCESSABLE_ENTITY, &e.to_string());
}
let file = rt.cfg.data_dir().join("zones").join(format!("{}zone", name.to_ascii()));
let file = rt.cfg.data_dir().join("zones").join("primary").join(format!("{}zone", name.to_ascii()));
if let Err(e) = dns_core::zonefile::atomic_write(&file, text.as_bytes()) {
return error(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string());
}
+46 -11
View File
@@ -121,14 +121,10 @@ fn acl_contains(acl: &[IpNet], ip: IpAddr) -> bool {
acl.iter().any(|n| n.contains(&ip))
}
/// Default copy of a secondary zone: `<data_dir>/zones/secondary/<zone>.zone`.
///
/// Versions before 0.1.x-unreleased kept it in `<data_dir>/secondary/`. An existing old
/// copy (with its `.meta.json`) is moved to the new place, so an upgrade keeps serving
/// the zone from the local copy instead of transferring everything again.
fn default_secondary_file(data_dir: &Path, zone_ascii: &str) -> PathBuf {
let new = data_dir.join("zones").join("secondary").join(format!("{zone_ascii}zone"));
let old = data_dir.join("secondary").join(format!("{zone_ascii}zone"));
/// Move a server-written file from its pre-0.1.2 location to the current one (together
/// with `<file>.meta.json` when present), so an upgrade keeps using it. Returns the path
/// to use: the new one, or the old one when it could not be moved.
fn migrate_default(new: PathBuf, old: PathBuf, what: &str) -> PathBuf {
if !new.exists() && old.is_file() {
let meta = |p: &Path| {
let mut m = p.as_os_str().to_owned();
@@ -141,9 +137,9 @@ fn default_secondary_file(data_dir: &Path, zone_ascii: &str) -> PathBuf {
.and_then(|_| std::fs::rename(&old, &new))
.and_then(|_| if meta(&old).exists() { std::fs::rename(meta(&old), meta(&new)) } else { Ok(()) });
match moved {
Ok(()) => tracing::info!(from = %old.display(), to = %new.display(), "moved secondary zone copy to the new location"),
Ok(()) => tracing::info!(from = %old.display(), to = %new.display(), "moved {what} to the new location"),
Err(e) => {
tracing::warn!(path = %old.display(), error = %e, "could not move secondary zone copy; using the old location");
tracing::warn!(path = %old.display(), error = %e, "could not move {what}; using the old location");
return old;
}
}
@@ -151,6 +147,31 @@ fn default_secondary_file(data_dir: &Path, zone_ascii: &str) -> PathBuf {
new
}
/// Default copy of a secondary zone: `<data_dir>/zones/secondary/<zone>.zone`.
///
/// Versions before 0.1.1 kept it in `<data_dir>/secondary/`. An existing old copy (with
/// its `.meta.json`) is moved to the new place, so an upgrade keeps serving the zone from
/// the local copy instead of transferring everything again.
fn default_secondary_file(data_dir: &Path, zone_ascii: &str) -> PathBuf {
migrate_default(
data_dir.join("zones").join("secondary").join(format!("{zone_ascii}zone")),
data_dir.join("secondary").join(format!("{zone_ascii}zone")),
"secondary zone copy",
)
}
/// Last signed version of a DNSSEC zone: `<data_dir>/zones/signed/<zone>.zone`.
///
/// Versions before 0.1.2 kept it in `<data_dir>/signed/`; it is moved, so the first start
/// after an upgrade reuses the signatures instead of re-signing under the same serial.
fn default_signed_file(data_dir: &Path, zone_ascii: &str) -> PathBuf {
migrate_default(
data_dir.join("zones").join("signed").join(format!("{zone_ascii}zone")),
data_dir.join("signed").join(format!("{zone_ascii}zone")),
"signed zone",
)
}
impl ZoneEntry {
fn new(cfg: &Config, zc: &ZoneConfig, ring: &KeyRing) -> Result<Self, String> {
let name = dns_core::names::parse_name(&zc.name).map_err(|e| e.to_string())?;
@@ -184,7 +205,7 @@ impl ZoneEntry {
}
_ => None,
};
let signed_file = cfg.data_dir().join("signed").join(format!("{}zone", name.to_ascii()));
let signed_file = default_signed_file(&cfg.data_dir(), &name.to_ascii());
Ok(Self {
signer: Mutex::new(signer),
source: Mutex::new(None),
@@ -612,4 +633,18 @@ mod migration_tests {
assert_eq!(default_secondary_file(&d, "example.net."), d.join("zones/secondary/example.net.zone"));
let _ = std::fs::remove_dir_all(&d);
}
#[test]
fn old_signed_zone_is_moved_to_new_location() {
let d = std::env::temp_dir().join(format!("edns-sig-mig-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&d);
std::fs::create_dir_all(d.join("signed")).unwrap();
std::fs::write(d.join("signed/example.com.zone"), "signed").unwrap();
let p = default_signed_file(&d, "example.com.");
assert_eq!(p, d.join("zones/signed/example.com.zone"));
assert_eq!(std::fs::read_to_string(&p).unwrap(), "signed");
assert!(!d.join("signed/example.com.zone").exists());
assert_eq!(default_signed_file(&d, "example.net."), d.join("zones/signed/example.net.zone"));
let _ = std::fs::remove_dir_all(&d);
}
}
+1 -1
View File
@@ -120,7 +120,7 @@ enum ConfigCmd {
#[derive(Subcommand)]
enum ZonesCmd {
/// Create a new primary zone with minimal records (SOA, NS, glue) in <data_dir>/zones/
/// Create a new primary zone with minimal records (SOA, NS, glue) in <data_dir>/zones/primary/
Create(zonecreate::CreateArgs),
List,
Show {
+5 -5
View File
@@ -1,6 +1,6 @@
//! `easydns zone create`: write a minimal, valid primary zone and its definition.
//!
//! Creates `<data_dir>/zones/<zone>.zone` (SOA, NS, glue for in-zone name servers and
//! Creates `<data_dir>/zones/primary/<zone>.zone` (SOA, NS, glue for in-zone name servers and
//! optional apex addresses) and `<config dir>/zones.d/<zone>.yaml`, which the default
//! configuration includes. Nothing is overwritten without `--force`, and the zone is
//! parsed and checked before anything is written.
@@ -136,7 +136,7 @@ pub fn render(a: &CreateArgs, serial: u32) -> Result<(String, String), String> {
}
let _ = glue_used_apex;
let file = format!("zones/{bare}.zone");
let file = format!("zones/primary/{bare}.zone");
let mut def = format!("# {bare} – created by `easydns zone create`\n- name: {bare}\n type: primary\n file: {file}\n");
let list = |v: &[String]| v.iter().map(|x| format!("\"{x}\"")).collect::<Vec<_>>().join(", ");
if !a.allow_transfer.is_empty() {
@@ -192,7 +192,7 @@ pub fn create(cfg: &Config, config_path: &Path, a: &CreateArgs) -> Result<Create
let records = dns_core::zonefile::parse_str(&text, &zone, None).map_err(|e| format!("generated zone does not parse: {e}"))?;
dns_authoritative::Zone::from_records(&zone, records).map_err(|e| format!("generated zone is invalid: {e}"))?;
let zone_file = cfg.data_dir().join("zones").join(format!("{bare}.zone"));
let zone_file = cfg.data_dir().join("zones").join("primary").join(format!("{bare}.zone"));
let conf_dir = config_path.parent().map(Path::to_path_buf).unwrap_or_default();
let includes_zones_d = cfg.include.iter().any(|p| p.starts_with("zones.d/"));
let definition_file = (!a.no_config && includes_zones_d).then(|| conf_dir.join("zones.d").join(format!("{bare}.yaml")));
@@ -244,7 +244,7 @@ mod tests {
assert!(t.contains("ns1\tIN A 192.0.2.1"));
assert!(t.contains("@\tIN A 192.0.2.1"));
assert_eq!(valid(&t, "example.com"), 4); // SOA, NS, glue, apex A
assert!(def.contains("file: zones/example.com.zone"));
assert!(def.contains("file: zones/primary/example.com.zone"));
}
#[test]
@@ -279,7 +279,7 @@ mod tests {
let mut a = args("example.com");
a.ns = vec!["ns.example.net".into()];
let c = create(&cfg, &cfgp, &a).unwrap();
assert!(c.zone_file.ends_with("data/zones/example.com.zone") && c.zone_file.is_file());
assert!(c.zone_file.ends_with("data/zones/primary/example.com.zone") && c.zone_file.is_file());
assert!(d.join("zones.d/example.com.yaml").is_file());
// the new definition is picked up and the zone loads
let cfg2 = Config::load(&cfgp).unwrap();
+78 -3
View File
@@ -42,6 +42,8 @@ pub struct Config {
pub resolution: ResolutionConfig,
pub cache: CacheConfig,
pub policy: PolicyConfig,
/// Names answered from hosts files (`/etc/hosts` format) before anything else, like dnsmasq.
pub hosts: HostsConfig,
pub rate_limit: RateLimitConfig,
pub tls: TlsConfig,
pub api: ApiConfig,
@@ -277,8 +279,8 @@ pub struct ZoneConfig {
pub name: String,
#[serde(rename = "type")]
pub zone_type: ZoneType,
/// Zone file. A relative path is relative to `server.data_dir` (e.g. `zones/example.com.zone`
/// = `<data_dir>/zones/example.com.zone`). Primary: required. Secondary: optional; defaults to
/// Zone file. A relative path is relative to `server.data_dir` (e.g. `zones/primary/example.com.zone`
/// = `<data_dir>/zones/primary/example.com.zone`). Primary: required. Secondary: optional; defaults to
/// `<data_dir>/zones/secondary/<zone>.zone`.
#[serde(default)]
pub file: Option<PathBuf>,
@@ -505,6 +507,43 @@ fn yes() -> bool {
true
}
/// Hosts files answered locally (dnsmasq `addn-hosts` / reading `/etc/hosts`).
///
/// Every `address name [alias...]` line yields A/AAAA records for the names and a PTR
/// record for the address (first name). Names found here are answered before local
/// zones, forwarding and recursion, to clients allowed to resolve
/// (`recursion.allowed_clients`). Off while `files` is empty.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(deny_unknown_fields, default)]
pub struct HostsConfig {
/// Files in hosts format, e.g. `["/etc/hosts", "/etc/hosts.d/*.hosts"]`. Relative paths
/// are resolved against the configuration directory; `*`/`?` globs are allowed in the
/// file name. A missing file is a warning, not an error (it is picked up once it appears).
pub files: Vec<String>,
/// TTL of the answers (dnsmasq `local-ttl`, default 0: clients do not cache them).
pub ttl: u32,
/// Domain appended to names without a dot (dnsmasq `expand-hosts` + `domain=`):
/// with `domain: lan` the line `192.168.1.10 nas` answers both `nas` and `nas.lan`.
#[serde(skip_serializing_if = "Option::is_none")]
pub domain: Option<String>,
/// How often the files are checked for changes (modification time and size); changed
/// files are re-read without a reload. `0s` turns it off (then only `easydns reload`).
#[serde(with = "duration")]
pub reload_interval: Duration,
}
impl Default for HostsConfig {
fn default() -> Self {
Self { files: Vec::new(), ttl: 0, domain: None, reload_interval: Duration::from_secs(5) }
}
}
impl HostsConfig {
pub fn enabled(&self) -> bool {
!self.files.is_empty()
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields, default)]
pub struct PolicyConfig {
@@ -853,6 +892,27 @@ impl Config {
}
}
/// Expand `hosts.files` (paths relative to the config directory, `*`/`?` globs in the
/// file name). Returns the existing files (sorted per pattern, without duplicates) and
/// the literal paths that do not exist.
pub fn hosts_file_paths(&self) -> (Vec<PathBuf>, Vec<PathBuf>) {
let base = self.server.base_dir.clone().unwrap_or_default();
let (mut found, mut missing) = (Vec::new(), Vec::new());
for pat in &self.hosts.files {
match include::expand(&base, pat) {
Ok(v) => {
for f in v {
if !found.contains(&f) {
found.push(f);
}
}
}
Err(_) => missing.push(self.resolve_path(Path::new(pat))),
}
}
(found, missing)
}
/// Resolve a path relative to the config file directory.
pub fn resolve_path(&self, p: &Path) -> PathBuf {
if p.is_absolute() {
@@ -875,7 +935,7 @@ impl Config {
}
/// Resolve a zone `file:`. Relative paths are relative to the data directory
/// (`zones/example.com.zone` → `<data_dir>/zones/example.com.zone`). For configurations
/// (`zones/primary/example.com.zone` → `<data_dir>/zones/primary/example.com.zone`). For configurations
/// written before this rule, a relative path that exists only relative to the config
/// directory is still accepted.
pub fn zone_file_path(&self, p: &Path) -> PathBuf {
@@ -959,6 +1019,21 @@ impl Config {
#[cfg(test)]
mod tests {
#[test]
fn hosts_section_parses_and_validates() {
let c: super::Config =
serde_norway::from_str("hosts: { files: [/etc/hosts, /nonexistent/x.hosts], ttl: 60, domain: lan, reload_interval: 2s }\n")
.unwrap();
assert!(c.hosts.enabled());
assert_eq!(c.hosts.ttl, 60);
assert_eq!(c.hosts.reload_interval, std::time::Duration::from_secs(2));
let issues = c.validate();
assert!(issues.iter().any(|i| i.path == "hosts.files" && !i.is_error()), "{issues:?}");
let bad: super::Config = serde_norway::from_str("hosts: { files: [/etc/hosts], domain: \"a..b\" }\n").unwrap();
assert!(bad.validate().iter().any(|i| i.path == "hosts.domain" && i.is_error()));
assert!(!super::Config::default().hosts.enabled());
}
#[test]
fn zone_path_with_parent_dir_before_data_dir_exists() {
let d = std::env::temp_dir().join(format!("edns-zp-{}", std::process::id()));
+14
View File
@@ -364,6 +364,20 @@ pub(crate) fn validate(c: &Config) -> Vec<ValidationIssue> {
v.err(format!("{p}.url"), "only https:// URLs are allowed");
}
}
if c.hosts.enabled() {
let (_, missing) = c.hosts_file_paths();
for m in missing {
v.warn("hosts.files", format!("file not found: {} (it is read once it exists)", m.display()));
}
if let Some(d) = &c.hosts.domain
&& dns_core::names::parse_lower(d).is_err()
{
v.err("hosts.domain", format!("invalid domain name '{d}'"));
}
if !c.hosts.reload_interval.is_zero() && c.hosts.reload_interval < std::time::Duration::from_secs(1) {
v.warn("hosts.reload_interval", "intervals below 1s only add load; 1s or more is plenty");
}
}
if let Err(e) = c.expand_acl(&c.policy.exempt_clients) {
v.err("policy.exempt_clients", e);
}
+2 -2
View File
@@ -4,8 +4,8 @@
//! * [`RateLimiter`] – per-client token buckets with a global ceiling,
//! * [`BlockPolicy`] – allow/block lists with exact, suffix, wildcard and (bounded) regex rules.
//!
//! Processing order (documented in docs/security.md): rate limit → ACL/view →
//! local zones → allowlist → blocklist → resolution.
//! Processing order (documented in docs/hybrid.md): rate limit → ACL/view →
//! hosts files → local zones → allowlist → blocklist → resolution.
#![cfg_attr(test, allow(clippy::unwrap_used, clippy::expect_used))]
use std::collections::{HashMap, HashSet};
+16
View File
@@ -336,6 +336,15 @@ async fn handle_query(ctx: &Ctx<'_>, req: &Message, mut resp: Message) -> Reply
let view = rt.views.classify(ip);
let qname = q.name.clone();
// 0. Hosts files (dnsmasq-style), for clients allowed to resolve.
if rt.hosts.enabled() && rt.recursion_acl.contains(ip) {
if let Some(records) = rt.hosts.table().lookup(&qname, q.query_type, rt.hosts.ttl) {
resp.metadata.authoritative = true;
resp.answers = records;
return ctx.finish(req, resp, Source::Local, Some("hosts file"));
}
}
// 1. Local authoritative data.
if let Some(entry) = rt.zones.find(&LowerName::new(&qname), view) {
let Some(zone) = entry.current() else {
@@ -435,6 +444,13 @@ async fn resolve_target(
let mut out = Answer::new(ResponseCode::NoError, Source::Authoritative);
let mut cur = target.clone();
for _ in 0..MAX_CROSS_CNAME {
if ctx.rt.hosts.enabled()
&& ctx.rt.recursion_acl.contains(ip)
&& let Some(records) = ctx.rt.hosts.table().lookup(&cur, qtype, ctx.rt.hosts.ttl)
{
out.answers.extend(records);
return out;
}
if let Some(entry) = ctx.rt.zones.find(&LowerName::new(&cur), view) {
let Some(zone) = entry.current() else { return Answer::servfail(Source::Authoritative, "zone unavailable") };
match zone.lookup(&cur, qtype, dnssec_ok) {
+330
View File
@@ -0,0 +1,330 @@
//! Answers from hosts files (`/etc/hosts` format), like dnsmasq.
//!
//! Each line `address name [alias...]` gives A/AAAA records for every name and a PTR record
//! for the address pointing at the first name. Comments (`#`) and blank lines are ignored,
//! as are lines that do not parse (counted and logged once per load). A name that is
//! present answers authoritatively: a type the file has no data for gets NODATA, so the
//! question never leaves the host (the dnsmasq behaviour).
//!
//! The table is swapped atomically when the files change (see [`HostsStore::refresh`]);
//! lookups take a read lock only long enough to clone an `Arc`.
use std::collections::HashMap;
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex, RwLock};
use std::time::SystemTime;
use dns_config::Config;
use dns_core::proto::rr::rdata::{A, AAAA, PTR};
use dns_core::proto::rr::{LowerName, Name, RData, Record, RecordType};
#[derive(Debug, Default, Clone)]
struct Addrs {
v4: Vec<Ipv4Addr>,
v6: Vec<Ipv6Addr>,
}
/// One parsed set of hosts files.
#[derive(Debug, Default)]
pub struct HostsTable {
by_name: HashMap<LowerName, Addrs>,
by_addr: HashMap<LowerName, Name>,
/// Lines that could not be parsed.
pub skipped: usize,
}
impl HostsTable {
/// Parse hosts-format text. `domain` is appended to names without a dot.
pub fn parse_into(&mut self, text: &str, domain: Option<&Name>) {
for line in text.lines() {
let line = line.split('#').next().unwrap_or("").trim();
if line.is_empty() {
continue;
}
let mut parts = line.split_whitespace();
let Some(addr) = parts.next() else { continue };
// link-local zone index (`fe80::1%eth0`) is meaningless in DNS
let addr = addr.split('%').next().unwrap_or(addr);
let Ok(ip) = addr.parse::<IpAddr>() else {
self.skipped += 1;
continue;
};
let mut first: Option<Name> = None;
let mut any = false;
for raw in parts {
let Some(name) = parse_host_name(raw) else {
self.skipped += 1;
continue;
};
any = true;
let bare = name.num_labels() == 1;
if first.is_none() {
// PTR prefers the qualified form when the name is bare
first = Some(match (bare, domain) {
(true, Some(d)) => name.clone().append_domain(d).unwrap_or_else(|_| name.clone()),
_ => name.clone(),
});
}
self.add(&name, ip);
if bare
&& let Some(d) = domain
&& let Ok(q) = name.clone().append_domain(d)
{
self.add(&q, ip);
}
}
if !any {
self.skipped += 1;
continue;
}
if let Some(f) = first
&& !ip.is_unspecified()
{
// first line for an address wins, like dnsmasq / glibc
self.by_addr.entry(LowerName::new(&dns_core::names::reverse_name(ip))).or_insert(f);
}
}
}
fn add(&mut self, name: &Name, ip: IpAddr) {
let e = self.by_name.entry(LowerName::new(name)).or_default();
match ip {
IpAddr::V4(v4) if !e.v4.contains(&v4) => e.v4.push(v4),
IpAddr::V6(v6) => {
// v4-mapped addresses are IPv4 hosts
match v6.to_ipv4_mapped() {
Some(v4) if !e.v4.contains(&v4) => e.v4.push(v4),
Some(_) => {}
None if !e.v6.contains(&v6) => e.v6.push(v6),
None => {}
}
}
_ => {}
}
}
/// Number of distinct names.
pub fn names(&self) -> usize {
self.by_name.len()
}
pub fn is_empty(&self) -> bool {
self.by_name.is_empty() && self.by_addr.is_empty()
}
/// Records for `qname`/`qtype`. `None`: the name is not in the files (continue normally);
/// `Some(empty)`: the name is known but has no data of this type (NODATA).
pub fn lookup(&self, qname: &Name, qtype: RecordType, ttl: u32) -> Option<Vec<Record>> {
let key = LowerName::new(qname);
if let Some(e) = self.by_name.get(&key) {
let mut out = Vec::new();
if matches!(qtype, RecordType::A | RecordType::ANY) {
out.extend(e.v4.iter().map(|a| Record::from_rdata(qname.clone(), ttl, RData::A(A::from(*a)))));
}
if matches!(qtype, RecordType::AAAA | RecordType::ANY) {
out.extend(e.v6.iter().map(|a| Record::from_rdata(qname.clone(), ttl, RData::AAAA(AAAA::from(*a)))));
}
return Some(out);
}
if let Some(target) = self.by_addr.get(&key) {
let mut out = Vec::new();
if matches!(qtype, RecordType::PTR | RecordType::ANY) {
out.push(Record::from_rdata(qname.clone(), ttl, RData::PTR(PTR(target.clone()))));
}
return Some(out);
}
None
}
}
/// Host names in hosts files are plain ASCII/IDN labels; anything else is skipped.
fn parse_host_name(raw: &str) -> Option<Name> {
if raw.is_empty() || raw.starts_with('.') || raw.contains("..") {
return None;
}
dns_core::names::parse_name(raw).ok().filter(|n| !n.is_root())
}
/// Modification time and size of every file: a change in either triggers a re-read.
type Stamp = Vec<(PathBuf, Option<SystemTime>, u64)>;
fn stamp(files: &[PathBuf]) -> Stamp {
files
.iter()
.map(|f| match std::fs::metadata(f) {
Ok(m) => (f.clone(), m.modified().ok(), m.len()),
Err(_) => (f.clone(), None, 0),
})
.collect()
}
/// Hosts data of one runtime: the configuration plus the current table.
pub struct HostsStore {
cfg: Arc<Config>,
domain: Option<Name>,
pub ttl: u32,
table: RwLock<Arc<HostsTable>>,
last: Mutex<Stamp>,
}
impl HostsStore {
/// Read the configured files. Unreadable files are logged and skipped; the server
/// still starts (dnsmasq does the same).
pub fn build(cfg: Arc<Config>) -> Result<Self, String> {
let domain = match &cfg.hosts.domain {
Some(d) => Some(dns_core::names::parse_name(d).map_err(|e| format!("hosts.domain: {e}"))?),
None => None,
};
let s = Self { ttl: cfg.hosts.ttl, cfg, domain, table: RwLock::new(Arc::new(HostsTable::default())), last: Mutex::new(Vec::new()) };
if s.enabled() {
s.refresh(true);
}
Ok(s)
}
pub fn enabled(&self) -> bool {
self.cfg.hosts.enabled()
}
pub fn table(&self) -> Arc<HostsTable> {
self.table.read().unwrap_or_else(|e| e.into_inner()).clone()
}
/// Re-read the files if the set of files, a modification time or a size changed (or
/// always with `force`). Returns true when the table was replaced.
pub fn refresh(&self, force: bool) -> bool {
if !self.enabled() {
return false;
}
let (files, _missing) = self.cfg.hosts_file_paths();
let now = stamp(&files);
{
let mut last = self.last.lock().unwrap_or_else(|e| e.into_inner());
if !force && *last == now {
return false;
}
*last = now;
}
let table = load(&files, self.domain.as_ref());
tracing::info!(files = files.len(), names = table.names(), skipped_lines = table.skipped, "hosts files loaded");
*self.table.write().unwrap_or_else(|e| e.into_inner()) = Arc::new(table);
true
}
}
fn load(files: &[PathBuf], domain: Option<&Name>) -> HostsTable {
let mut t = HostsTable::default();
for f in files {
match read(f) {
Ok(text) => t.parse_into(&text, domain),
Err(e) => tracing::warn!(file = %f.display(), error = %e, "hosts file not readable"),
}
}
t
}
/// Hosts files are small; refuse absurd sizes instead of exhausting memory.
const MAX_FILE: u64 = 64 << 20;
fn read(p: &Path) -> std::io::Result<String> {
let len = std::fs::metadata(p)?.len();
if len > MAX_FILE {
return Err(std::io::Error::other(format!("larger than {} MiB", MAX_FILE >> 20)));
}
let bytes = std::fs::read(p)?;
Ok(String::from_utf8_lossy(&bytes).into_owned())
}
#[cfg(test)]
mod tests {
use super::*;
fn n(s: &str) -> Name {
dns_core::names::parse_name(s).unwrap()
}
const HOSTS: &str = "\
127.0.0.1\tlocalhost
::1 localhost ip6-localhost ip6-loopback
# comment line
192.168.1.10 nas nas.home # trailing comment
192.168.1.11 NAS # second address for the same name
fd00::10 nas
fe80::1%eth0 router
0.0.0.0 ads.example.com
not-an-ip broken
10.0.0.1
";
#[test]
fn parses_names_aliases_and_comments() {
let mut t = HostsTable::default();
t.parse_into(HOSTS, None);
let a = t.lookup(&n("nas"), RecordType::A, 0).unwrap();
assert_eq!(a.len(), 2);
let aaaa = t.lookup(&n("NAS."), RecordType::AAAA, 0).unwrap();
assert_eq!(aaaa.len(), 1);
assert_eq!(t.lookup(&n("nas.home"), RecordType::A, 0).unwrap().len(), 1);
assert_eq!(t.lookup(&n("ip6-localhost"), RecordType::AAAA, 0).unwrap().len(), 1);
assert_eq!(t.lookup(&n("router"), RecordType::AAAA, 0).unwrap().len(), 1);
assert_eq!(t.lookup(&n("ads.example.com"), RecordType::A, 0).unwrap().len(), 1);
assert_eq!(t.skipped, 2);
assert!(t.lookup(&n("example.com"), RecordType::A, 0).is_none());
}
#[test]
fn known_name_without_data_is_nodata() {
let mut t = HostsTable::default();
t.parse_into("192.168.1.10 printer\n", None);
assert_eq!(t.lookup(&n("printer"), RecordType::AAAA, 0), Some(vec![]));
assert_eq!(t.lookup(&n("printer"), RecordType::MX, 0), Some(vec![]));
assert_eq!(t.lookup(&n("printer"), RecordType::ANY, 0).unwrap().len(), 1);
}
#[test]
fn ptr_uses_first_name_and_first_line() {
let mut t = HostsTable::default();
t.parse_into("192.168.1.10 nas nas.home\n192.168.1.10 other\n0.0.0.0 blocked\n", None);
let r = t.lookup(&n("10.1.168.192.in-addr.arpa"), RecordType::PTR, 0).unwrap();
assert_eq!(r.len(), 1);
assert_eq!(r[0].data, RData::PTR(PTR(n("nas"))));
assert!(t.lookup(&dns_core::names::reverse_name("0.0.0.0".parse().unwrap()), RecordType::PTR, 0).is_none());
let v6 = dns_core::names::reverse_name("fd00::10".parse().unwrap());
assert!(t.lookup(&v6, RecordType::PTR, 0).is_none());
}
#[test]
fn domain_expands_bare_names() {
let mut t = HostsTable::default();
t.parse_into("192.168.1.10 nas\n192.168.1.20 tv.other\n", Some(&n("lan")));
assert!(t.lookup(&n("nas"), RecordType::A, 0).is_some());
assert!(t.lookup(&n("nas.lan"), RecordType::A, 0).is_some());
assert!(t.lookup(&n("tv.other.lan"), RecordType::A, 0).is_none());
let r = t.lookup(&n("10.1.168.192.in-addr.arpa"), RecordType::PTR, 0).unwrap();
assert_eq!(r[0].data, RData::PTR(PTR(n("nas.lan"))));
}
#[test]
fn ttl_is_applied() {
let mut t = HostsTable::default();
t.parse_into("192.168.1.10 nas\n", None);
assert_eq!(t.lookup(&n("nas"), RecordType::A, 42).unwrap()[0].ttl, 42);
}
#[test]
fn store_reloads_on_change() {
let d = std::env::temp_dir().join(format!("edns-hosts-{}", std::process::id()));
std::fs::create_dir_all(&d).unwrap();
let f = d.join("hosts");
std::fs::write(&f, "192.168.1.10 nas\n").unwrap();
let mut cfg = Config::default();
cfg.hosts.files = vec![f.display().to_string(), d.join("missing").display().to_string()];
let s = HostsStore::build(Arc::new(cfg)).unwrap();
assert!(s.table().lookup(&n("nas"), RecordType::A, 0).is_some());
assert!(!s.refresh(false), "unchanged files are not re-read");
std::fs::write(&f, "192.168.1.10 nas\n192.168.1.11 tv\n").unwrap();
assert!(s.refresh(false));
assert!(s.table().lookup(&n("tv"), RecordType::A, 0).is_some());
let _ = std::fs::remove_dir_all(&d);
}
}
+3 -1
View File
@@ -4,7 +4,8 @@
//! 1. parse / FORMERR, drop responses, rate limit (UDP),
//! 2. TSIG verification, opcode dispatch (QUERY / NOTIFY / UPDATE),
//! 3. zone transfers (AXFR/IXFR) with ACL + TSIG,
//! 4. most specific local authoritative zone visible in the client's view → AA answer,
//! 4. names from hosts files (`hosts.files`, for clients allowed to resolve) → AA answer,
//! then the most specific local authoritative zone visible in the client's view → AA answer,
//! 5. clients without recursion permission → REFUSED (no open resolver, no leaks),
//! 6. local-only names (RFC 6761/6303) → NXDOMAIN without leaving the host,
//! 7. allow/block policy,
@@ -16,6 +17,7 @@ pub mod audit;
pub mod check;
pub mod coalesce;
pub mod handler;
pub mod hosts;
pub mod listener;
pub mod packet_cache;
pub mod router;
+6 -1
View File
@@ -26,6 +26,8 @@ pub struct Runtime {
pub local_only: SuffixSet,
pub router: Router,
pub resolver: Option<Arc<dns_recursive::Resolver>>,
/// Hosts files (`hosts:`), answered before local zones.
pub hosts: crate::hosts::HostsStore,
}
impl Runtime {
@@ -67,9 +69,12 @@ impl Runtime {
let ratelimit = RateLimiter::from_config(&cfg)?;
let policy = BlockPolicy::from_config(&cfg)?;
let recursion_acl = Acl(cfg.expand_acl(&cfg.recursion.allowed_clients)?);
let cfg = Arc::new(cfg);
let hosts = crate::hosts::HostsStore::build(Arc::clone(&cfg))?;
// Zones last: building the store has side effects (stopping removed secondaries).
let (zones, fresh) = ZoneStore::build(&cfg, &ring, previous.map(|p| p.zones.as_ref()))?;
let rt = Runtime {
hosts,
recursion_acl,
views,
ratelimit,
@@ -79,7 +84,7 @@ impl Runtime {
resolver,
zones: Arc::new(zones),
ring,
cfg: Arc::new(cfg),
cfg,
};
Ok((rt, fresh))
}
+26
View File
@@ -130,6 +130,32 @@ impl Server {
}
}));
}
// Hosts files: re-read when they change (modification time / size).
{
let shared = Arc::clone(&shared);
let mut rx = rx.clone();
tasks.push(tokio::spawn(async move {
loop {
let rt = shared.rt();
let interval = rt.cfg.hosts.reload_interval;
let active = rt.hosts.enabled() && !interval.is_zero();
drop(rt);
tokio::select! {
_ = tokio::time::sleep(if active { interval } else { Duration::from_secs(5) }) => {}
_ = rx.changed() => return,
}
if !active {
continue;
}
let rt = shared.rt();
let changed = tokio::task::spawn_blocking(move || rt.hosts.refresh(false)).await.unwrap_or(false);
if changed {
// cached answers may contain the old addresses
shared.packet_cache.invalidate();
}
}
}));
}
// Upstream health checks.
{
let shared = Arc::clone(&shared);
+130
View File
@@ -0,0 +1,130 @@
//! Hosts files (`hosts:`): dnsmasq-style answers before local zones and forwarding.
#![allow(clippy::unwrap_used, clippy::expect_used)]
mod common;
use std::time::Duration;
use common::*;
use dns_core::proto::op::ResponseCode;
use dns_core::proto::rr::RecordType;
/// Upstream: an authoritative server for `example.org`.
async fn upstream(dir: &std::path::Path, port: u16) -> dns_server::ServerHandle {
let d = dir.join("upstream");
std::fs::create_dir_all(&d).unwrap();
write(
&d,
"example.zone",
"$TTL 300\n@ SOA ns hm 1 3600 600 86400 300\n@ NS ns\nns A 127.0.0.3\nwww A 203.0.113.80\noverride A 203.0.113.99\n",
);
start(
&d,
&format!(
"server: {{ listen: [\"127.0.0.3:{port}\"], data_dir: data }}\napi: {{ enabled: false }}\nrate_limit: {{ enabled: false }}\n\
zones:\n - {{ name: example.org, type: primary, file: ../example.zone }}\n"
),
)
.await
}
fn forwarder_yaml(port: u16, upstream_port: u16, extra: &str) -> String {
format!(
"server: {{ mode: hybrid, listen: [\"127.0.0.2:{port}\"], data_dir: data }}\napi: {{ enabled: false }}\n\
rate_limit: {{ enabled: false }}\nupstreams: {{ servers: [\"127.0.0.3:{upstream_port}\"] }}\n\
resolution: {{ default: forward }}\n{extra}"
)
}
#[tokio::test(flavor = "multi_thread")]
async fn hosts_answer_first_then_forward() {
let dir = tmpdir("hosts");
let (port, up_port) = (free_port(), free_port());
let _up = upstream(&dir, up_port).await;
write(
&dir,
"hosts",
"127.0.0.1 localhost\n192.168.1.10 nas nas.home\nfd00::10 nas\n192.168.1.50 override.example.org\n10.9.9.9 shadow.local.example.net\n",
);
write(
&dir,
"local.zone",
"$TTL 300\n@ SOA ns hm 1 3600 600 86400 300\n@ NS ns\nns A 127.0.0.2\nshadow A 10.0.0.1\nzoneonly A 10.0.0.2\n",
);
let yaml = forwarder_yaml(
port,
up_port,
"recursion: { allowed_clients: [\"127.0.0.0/8\"] }\n\
hosts: { files: [hosts, missing.hosts], ttl: 30, domain: lan, reload_interval: 100ms }\n\
zones:\n - { name: local.example.net, type: primary, file: ../local.zone }\n",
);
let s = start(&dir, &yaml).await;
let addr = s.bound.dns[0];
// names from the hosts file, with the domain appended to bare names
let m = q(addr, "nas.", RecordType::A).await;
assert_eq!(answers(&m), vec!["A 192.168.1.10"]);
assert!(m.metadata.authoritative);
assert_eq!(m.answers[0].ttl, 30);
assert_eq!(answers(&q(addr, "nas.lan.", RecordType::A).await), vec!["A 192.168.1.10"]);
assert_eq!(answers(&q(addr, "nas.home.", RecordType::AAAA).await), Vec::<String>::new());
assert_eq!(answers(&q(addr, "nas.", RecordType::AAAA).await), vec!["AAAA fd00::10"]);
// known name, no data of that type: NODATA, not forwarded
let m = q(addr, "nas.", RecordType::MX).await;
assert_eq!(m.metadata.response_code, ResponseCode::NoError);
assert!(m.answers.is_empty());
// reverse lookup from the same file (private range would otherwise be NXDOMAIN locally)
let m = q(addr, "10.1.168.192.in-addr.arpa.", RecordType::PTR).await;
assert_eq!(answers(&m), vec!["PTR nas.lan."]);
// hosts override both the upstream and local zones
assert_eq!(answers(&q(addr, "override.example.org.", RecordType::A).await), vec!["A 192.168.1.50"]);
assert_eq!(answers(&q(addr, "shadow.local.example.net.", RecordType::A).await), vec!["A 10.9.9.9"]);
assert_eq!(answers(&q(addr, "zoneonly.local.example.net.", RecordType::A).await), vec!["A 10.0.0.2"]);
// everything else goes on to the upstream
assert_eq!(answers(&q(addr, "www.example.org.", RecordType::A).await), vec!["A 203.0.113.80"]);
// edits are picked up without a reload
write(&dir, "hosts", "192.168.1.11 nas\n192.168.1.60 tv\n");
eventually("hosts file change", || async { answers(&q(addr, "tv.", RecordType::A).await) == vec!["A 192.168.1.60"] }).await;
assert_eq!(answers(&q(addr, "nas.", RecordType::A).await), vec!["A 192.168.1.11"]);
// removed name falls through to the upstream again
assert_eq!(answers(&q(addr, "override.example.org.", RecordType::A).await), vec!["A 203.0.113.99"]);
// a file that appears later is read too
write(&dir, "missing.hosts", "192.168.1.70 printer\n");
eventually("new hosts file", || async { answers(&q(addr, "printer.", RecordType::A).await) == vec!["A 192.168.1.70"] }).await;
s.shutdown().await;
}
#[tokio::test(flavor = "multi_thread")]
async fn hosts_not_served_to_clients_without_resolution() {
let dir = tmpdir("hosts-acl");
let (port, up_port) = (free_port(), free_port());
write(&dir, "hosts", "192.168.1.10 nas\n");
let yaml =
forwarder_yaml(port, up_port, "recursion: { allowed_clients: [\"10.0.0.0/8\"] }\nhosts: { files: [hosts], reload_interval: 0s }\n");
let s = start(&dir, &yaml).await;
let m = q(s.bound.dns[0], "nas.", RecordType::A).await;
assert_eq!(m.metadata.response_code, ResponseCode::Refused);
tokio::time::sleep(Duration::from_millis(10)).await;
s.shutdown().await;
}
#[tokio::test(flavor = "multi_thread")]
async fn hosts_follow_reload() {
let dir = tmpdir("hosts-reload");
let (port, up_port) = (free_port(), free_port());
write(&dir, "a.hosts", "192.168.1.10 nas\n");
write(&dir, "b.hosts", "192.168.1.20 nas\n");
let base = "recursion: { allowed_clients: [\"127.0.0.0/8\"] }\n";
let s = start(&dir, &forwarder_yaml(port, up_port, &format!("{base}hosts: {{ files: [a.hosts], reload_interval: 0s }}\n"))).await;
let addr = s.bound.dns[0];
assert_eq!(answers(&q(addr, "nas.", RecordType::A).await), vec!["A 192.168.1.10"]);
write(&dir, "config.yaml", &forwarder_yaml(port, up_port, &format!("{base}hosts: {{ files: [\"*.hosts\"], reload_interval: 0s }}\n")));
s.reload().unwrap();
assert_eq!(answers(&q(addr, "nas.", RecordType::A).await), vec!["A 192.168.1.10", "A 192.168.1.20"]);
s.shutdown().await;
}