This commit is contained in:
Mateusz Gruszczyński committed 2026-11-22 14:21:54 +01:00
commit fa432bebda
189 files changed
+26219

No files matched your search

+21
View File
@@ -0,0 +1,21 @@
[package]
name = "dns-authoritative"
description = "EasyDNS authoritative engine: zones, lookup, Primary/Secondary, AXFR/IXFR, NOTIFY, DDNS"
version.workspace = true
edition.workspace = true
license.workspace = true
[dependencies]
dns-core.workspace = true
dns-config.workspace = true
tokio.workspace = true
tracing.workspace = true
serde.workspace = true
serde_json.workspace = true
thiserror.workspace = true
ipnet.workspace = true
data-encoding.workspace = true
rand.workspace = true
[lints]
workspace = true
+212
View File
@@ -0,0 +1,212 @@
//! Persistent IXFR journal (one JSON object per line, records in wire format, base64).
use std::collections::VecDeque;
use std::io::Write;
use std::path::{Path, PathBuf};
use data_encoding::BASE64;
use dns_core::proto::rr::Record;
use dns_core::proto::serialize::binary::{BinDecodable, BinEncodable};
use serde::{Deserialize, Serialize};
/// One zone version change: `from` → `to`.
#[derive(Debug, Clone)]
pub struct Diff {
pub from_soa: Record,
pub to_soa: Record,
pub removed: Vec<Record>,
pub added: Vec<Record>,
}
impl Diff {
pub fn from_serial(&self) -> u32 {
soa_serial(&self.from_soa)
}
pub fn to_serial(&self) -> u32 {
soa_serial(&self.to_soa)
}
}
pub(crate) fn soa_serial(r: &Record) -> u32 {
match &r.data {
dns_core::proto::rr::RData::SOA(s) => s.serial,
_ => 0,
}
}
#[derive(Serialize, Deserialize)]
struct Line {
from: String,
to: String,
del: Vec<String>,
add: Vec<String>,
}
fn enc(r: &Record) -> Option<String> {
r.to_bytes().ok().map(|b| BASE64.encode(&b))
}
fn dec(s: &str) -> Option<Record> {
let b = BASE64.decode(s.as_bytes()).ok()?;
Record::from_bytes(&b).ok()
}
/// Bounded journal of diffs, oldest first.
#[derive(Debug)]
pub struct Journal {
entries: VecDeque<Diff>,
max: usize,
path: Option<PathBuf>,
}
impl Journal {
pub fn in_memory(max: usize) -> Self {
Self { entries: VecDeque::new(), max: max.max(1), path: None }
}
/// Load a journal; a corrupt or unreadable file is ignored (IXFR then falls back to AXFR).
pub fn load(path: &Path, max: usize) -> Self {
let mut j = Self { entries: VecDeque::new(), max: max.max(1), path: Some(path.to_path_buf()) };
if let Ok(text) = std::fs::read_to_string(path) {
for (i, line) in text.lines().enumerate() {
match Self::parse_line(line) {
Some(d) => j.entries.push_back(d),
None => {
tracing::warn!(file = %path.display(), line = i + 1, "corrupt journal entry; truncating journal");
j.entries.clear();
break;
}
}
}
while j.entries.len() > j.max {
j.entries.pop_front();
}
}
j
}
fn parse_line(line: &str) -> Option<Diff> {
let l: Line = serde_json::from_str(line).ok()?;
Some(Diff {
from_soa: dec(&l.from)?,
to_soa: dec(&l.to)?,
removed: l.del.iter().map(|s| dec(s)).collect::<Option<_>>()?,
added: l.add.iter().map(|s| dec(s)).collect::<Option<_>>()?,
})
}
fn line(d: &Diff) -> Option<String> {
let l = Line {
from: enc(&d.from_soa)?,
to: enc(&d.to_soa)?,
del: d.removed.iter().map(enc).collect::<Option<_>>()?,
add: d.added.iter().map(enc).collect::<Option<_>>()?,
};
serde_json::to_string(&l).ok()
}
/// Append a diff. If it does not continue the chain, the journal is reset.
pub fn push(&mut self, d: Diff) {
if let Some(last) = self.entries.back()
&& last.to_serial() != d.from_serial()
{
self.entries.clear();
}
self.entries.push_back(d);
let mut compact = false;
while self.entries.len() > self.max {
self.entries.pop_front();
compact = true;
}
if let Err(e) = self.persist(compact) {
tracing::error!(error = %e, "failed to persist IXFR journal");
}
}
fn persist(&self, rewrite: bool) -> std::io::Result<()> {
let Some(path) = &self.path else { return Ok(()) };
if rewrite || self.entries.len() == 1 {
let mut s = String::new();
for d in &self.entries {
if let Some(l) = Self::line(d) {
s.push_str(&l);
s.push('\n');
}
}
dns_core::zonefile::atomic_write(path, s.as_bytes()).map_err(std::io::Error::other)
} else if let Some(d) = self.entries.back() {
if let Some(dir) = path.parent() {
std::fs::create_dir_all(dir)?;
}
let mut f = std::fs::OpenOptions::new().create(true).append(true).open(path)?;
if let Some(l) = Self::line(d) {
writeln!(f, "{l}")?;
}
f.sync_data()
} else {
Ok(())
}
}
pub fn clear(&mut self) {
self.entries.clear();
let _ = self.persist(true);
}
pub fn len(&self) -> usize {
self.entries.len()
}
pub fn is_empty(&self) -> bool {
self.entries.is_empty()
}
/// The chain of diffs from `serial` up to the newest version, if available.
pub fn since(&self, serial: u32) -> Option<Vec<Diff>> {
let start = self.entries.iter().position(|d| d.from_serial() == serial)?;
let chain: Vec<Diff> = self.entries.iter().skip(start).cloned().collect();
for w in chain.windows(2) {
if w[0].to_serial() != w[1].from_serial() {
return None;
}
}
Some(chain)
}
}
#[cfg(test)]
mod tests {
use super::*;
use dns_core::proto::rr::{
Name, RData,
rdata::{A, SOA},
};
fn soa(serial: u32) -> Record {
let n = Name::from_ascii("example.com.").unwrap();
Record::from_rdata(n.clone(), 3600, RData::SOA(SOA::new(n.clone(), n, serial, 1, 1, 1, 1)))
}
fn a(last: u8) -> Record {
Record::from_rdata(Name::from_ascii("www.example.com.").unwrap(), 60, RData::A(A::new(192, 0, 2, last)))
}
#[test]
fn chain_and_persistence() {
let dir = std::env::temp_dir().join(format!("edns-jnl-{}", rand::random::<u32>()));
let p = dir.join("example.com.jnl");
let mut j = Journal::load(&p, 3);
for s in 1..=4u32 {
j.push(Diff { from_soa: soa(s), to_soa: soa(s + 1), removed: vec![a(s as u8)], added: vec![a(s as u8 + 1)] });
}
assert_eq!(j.len(), 3);
assert!(j.since(1).is_none());
assert_eq!(j.since(2).unwrap().len(), 3);
assert_eq!(j.since(4).unwrap().len(), 1);
let j2 = Journal::load(&p, 3);
assert_eq!(j2.len(), 3);
assert_eq!(j2.since(3).unwrap()[0].added[0].data, a(4).data);
// a gap resets the journal
let mut j3 = Journal::load(&p, 3);
j3.push(Diff { from_soa: soa(100), to_soa: soa(101), removed: vec![], added: vec![] });
assert_eq!(j3.len(), 1);
let _ = std::fs::remove_dir_all(dir);
}
}
+20
View File
@@ -0,0 +1,20 @@
//! EasyDNS authoritative engine.
//!
//! * [`zone`] – validated immutable zone snapshots and the lookup algorithm.
//! * [`journal`] – persistent IXFR journal.
//! * [`xfr`] – AXFR/IXFR response generation (server side) and IXFR application.
//! * [`store`] – the set of served zones (Primary/Secondary) with atomic swaps.
//! * [`secondary`] – SOA-timer driven synchronisation.
//! * [`update`] – RFC 2136 dynamic updates.
#![cfg_attr(test, allow(clippy::unwrap_used, clippy::expect_used))]
pub mod journal;
pub mod secondary;
pub mod signing;
pub mod store;
pub mod update;
pub mod xfr;
pub mod zone;
pub use store::{ZoneEntry, ZoneKind, ZoneStore, data_generation};
pub use zone::{Lookup, Zone, ZoneError, ZoneRef};
+285
View File
@@ -0,0 +1,285 @@
//! Secondary zone synchronisation driven by SOA timers (RFC 1034 §4.3.5, RFC 1996).
//!
//! * startup: load the last persisted snapshot (if still within EXPIRE),
//! * refresh: SOA query to the primaries; IXFR (fallback AXFR) when the serial is newer,
//! * NOTIFY / manual sync wakes the task immediately,
//! * failure: retry after RETRY; after EXPIRE without success the zone stops being served
//! (queries get SERVFAIL) until a refresh succeeds.
use std::net::SocketAddr;
use std::sync::Arc;
use std::sync::atomic::Ordering;
use std::time::{Duration, Instant};
use dns_config::TransferPreference;
use dns_core::client::{QueryOptions, TransferKind, TransferLimits, query, transfer};
use dns_core::proto::rr::{RData, RecordType};
use dns_core::tsig::now;
use serde::{Deserialize, Serialize};
use crate::store::{TransferEvent, ZoneEntry};
use crate::xfr::{Applied, apply_transfer};
#[derive(Serialize, Deserialize)]
struct Meta {
last_success_unix: u64,
serial: u32,
primary: String,
}
fn meta_path(e: &ZoneEntry) -> std::path::PathBuf {
let mut p = e.file.clone().into_os_string();
p.push(".meta.json");
p.into()
}
/// Load the persisted snapshot at startup.
pub fn load_snapshot(e: &ZoneEntry) {
if !e.file.is_file() {
return;
}
let records = match dns_core::zonefile::parse_file(&e.file, &e.name) {
Ok(r) => r,
Err(err) => {
tracing::error!(zone = %e.name, error = %err, "cannot read secondary snapshot");
return;
}
};
let zone = match crate::zone::Zone::from_records(&e.name, records) {
Ok(z) => z,
Err(err) => {
tracing::error!(zone = %e.name, error = %err, "invalid secondary snapshot");
return;
}
};
let (_, _, expire, _) = zone.soa_timers();
let meta: Option<Meta> = std::fs::read_to_string(meta_path(e)).ok().and_then(|s| serde_json::from_str(&s).ok());
let last = meta.as_ref().map(|m| m.last_success_unix).unwrap_or(0);
let expired = now().saturating_sub(last) > u64::from(expire);
tracing::info!(zone = %e.name, serial = zone.serial(), expired, "loaded secondary snapshot");
e.install(zone, Vec::new());
e.set_expired(expired);
e.update_status(|s| {
s.last_success_unix = (last > 0).then_some(last);
s.expires_at_unix = (last > 0).then_some(last + u64::from(expire));
s.source = meta.map(|m| m.primary);
});
}
fn persist(e: &ZoneEntry, primary: SocketAddr) {
let Some(z) = e.snapshot_any() else { return };
let text = dns_core::zonefile::emit(&e.name, &z.all_records());
if let Err(err) = dns_core::zonefile::atomic_write(&e.file, text.as_bytes()) {
tracing::error!(zone = %e.name, error = %err, "failed to persist snapshot");
return;
}
let meta = Meta { last_success_unix: now(), serial: z.serial(), primary: primary.to_string() };
if let Ok(s) = serde_json::to_string(&meta) {
let _ = dns_core::zonefile::atomic_write(&meta_path(e), s.as_bytes());
}
}
/// Outcome of one refresh attempt.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RefreshOutcome {
UpToDate(u32),
Updated { serial: u32, kind: &'static str },
}
async fn primary_serial(e: &ZoneEntry, primary: SocketAddr) -> Result<u32, String> {
let opts = QueryOptions {
timeout: Duration::from_secs(3),
retries: 1,
recursion_desired: false,
tsig: e.client_key.clone(),
..Default::default()
};
let ex = query(primary, &e.name, RecordType::SOA, &opts).await.map_err(|err| err.to_string())?;
if !ex.message.metadata.authoritative {
return Err(format!("{primary} is not authoritative for {}", e.name));
}
ex.message
.answers
.iter()
.find_map(|r| match &r.data {
RData::SOA(s) if r.name.eq_ignore_root_case(&e.name) => Some(s.serial),
_ => None,
})
.ok_or_else(|| format!("{primary}: no SOA in answer ({})", ex.message.metadata.response_code))
}
async fn do_transfer(e: &ZoneEntry, primary: SocketAddr, ixfr: bool) -> Result<RefreshOutcome, String> {
let current = e.snapshot_any();
let kind = match (&current, ixfr) {
(Some(z), true) => TransferKind::Ixfr { current_soa: Box::new(z.soa().clone()) },
_ => TransferKind::Axfr,
};
let label = if matches!(kind, TransferKind::Axfr) { "AXFR" } else { "IXFR" };
let limits = TransferLimits { timeout: e.config.transfer.timeout, max_records: e.max_records, ..Default::default() };
let started = Instant::now();
let res = transfer(primary, &e.name, &kind, e.client_key.as_ref(), limits).await;
let mut ev = TransferEvent {
time_unix: now(),
direction: "in",
kind: label.to_string(),
peer: primary.to_string(),
serial: None,
records: 0,
ok: false,
error: None,
duration_ms: 0,
};
let outcome = match res {
Err(err) => Err(err.to_string()),
Ok(stream) => {
ev.records = stream.records.len();
match apply_transfer(&e.name, current.as_deref(), &stream.records, e.max_records) {
Ok(Applied::UpToDate) => Ok(RefreshOutcome::UpToDate(current.map(|z| z.serial()).unwrap_or(0))),
Ok(Applied::Full(z)) => {
let serial = z.serial();
let diffs = match &current {
Some(old) if dns_core::serial::is_newer(serial, old.serial()) => {
let (rm, add) = old.diff(&z);
vec![crate::journal::Diff { from_soa: old.soa().clone(), to_soa: z.soa().clone(), removed: rm, added: add }]
}
_ => Vec::new(),
};
e.install(z, diffs);
let kind = if label == "IXFR" { "IXFR(AXFR-style)" } else { "AXFR" };
ev.kind = kind.into();
Ok(RefreshOutcome::Updated { serial, kind })
}
Ok(Applied::Incremental(z, diffs)) => {
let serial = z.serial();
e.install(z, diffs);
Ok(RefreshOutcome::Updated { serial, kind: "IXFR" })
}
Err(err) => Err(format!("transfer rejected: {err}")),
}
}
};
ev.duration_ms = started.elapsed().as_millis() as u64;
match &outcome {
Ok(RefreshOutcome::Updated { serial, .. }) | Ok(RefreshOutcome::UpToDate(serial)) => {
ev.ok = true;
ev.serial = Some(*serial);
}
Err(err) => ev.error = Some(err.clone()),
}
e.record_transfer(ev);
outcome
}
/// One refresh cycle against the configured primaries (in order).
pub async fn refresh_once(e: &ZoneEntry) -> Result<RefreshOutcome, String> {
let mut errors = Vec::new();
for &primary in &e.config.primaries {
let remote = match primary_serial(e, primary).await {
Ok(s) => s,
Err(err) => {
errors.push(err);
continue;
}
};
let current = e.snapshot_any();
if let Some(z) = &current
&& !dns_core::serial::is_newer(remote, z.serial())
{
if remote != z.serial() {
tracing::warn!(zone = %e.name, local = z.serial(), remote, %primary, "primary serial is older than ours; not transferring");
}
persist_meta_only(e, primary);
return Ok(RefreshOutcome::UpToDate(z.serial()));
}
let want_ixfr = e.config.transfer.prefer == TransferPreference::Ixfr && current.is_some();
let res = match do_transfer(e, primary, want_ixfr).await {
Err(err) if want_ixfr && e.config.transfer.fallback_axfr => {
tracing::warn!(zone = %e.name, %primary, error = %err, "IXFR failed; falling back to AXFR");
do_transfer(e, primary, false).await
}
r => r,
};
match res {
Ok(o) => {
persist(e, primary);
e.update_status(|s| s.source = Some(primary.to_string()));
return Ok(o);
}
Err(err) => errors.push(format!("{primary}: {err}")),
}
}
Err(if errors.is_empty() { "no primaries configured".into() } else { errors.join("; ") })
}
fn persist_meta_only(e: &ZoneEntry, primary: SocketAddr) {
if let Some(z) = e.snapshot_any() {
let meta = Meta { last_success_unix: now(), serial: z.serial(), primary: primary.to_string() };
if let Ok(s) = serde_json::to_string(&meta) {
let _ = dns_core::zonefile::atomic_write(&meta_path(e), s.as_bytes());
}
if !e.file.is_file() {
persist(e, primary);
}
}
}
/// Long-running refresh task for one secondary zone.
pub async fn run(e: Arc<ZoneEntry>, on_update: impl Fn(&Arc<ZoneEntry>) + Send + 'static) {
let mut next = Duration::ZERO;
loop {
if e.shutdown.load(Ordering::Acquire) {
tracing::info!(zone = %e.name, "secondary task stopped");
return;
}
e.update_status(|s| s.next_refresh_unix = Some(now() + next.as_secs()));
tokio::select! {
_ = tokio::time::sleep(next) => {}
_ = e.refresh_trigger.notified() => {}
}
if e.shutdown.load(Ordering::Acquire) {
return;
}
let result = refresh_once(&e).await;
let t = now();
let (refresh, retry, expire, _) = e.snapshot_any().map(|z| z.soa_timers()).unwrap_or((3600, 60, 604_800, 300));
// Never hammer primaries: clamp timers to sane minimums.
let (refresh, retry) = (refresh.max(5), retry.max(5));
match result {
Ok(outcome) => {
tracing::info!(zone = %e.name, ?outcome, "refresh ok");
e.set_expired(false);
e.update_status(|s| {
s.last_refresh_unix = Some(t);
s.last_success_unix = Some(t);
s.expires_at_unix = Some(t + u64::from(expire));
s.last_error = None;
});
if matches!(outcome, RefreshOutcome::Updated { .. }) {
on_update(&e);
}
next = Duration::from_secs(u64::from(refresh));
}
Err(err) => {
tracing::warn!(zone = %e.name, error = %err, "refresh failed");
let st = e.status();
let expired = match st.last_success_unix {
Some(last) => t.saturating_sub(last) > u64::from(expire),
None => e.snapshot_any().is_none(),
};
if expired && !e.is_expired() && e.snapshot_any().is_some() {
tracing::error!(zone = %e.name, "zone EXPIRED: no successful refresh within SOA expire; answering SERVFAIL");
}
e.set_expired(expired);
e.update_status(|s| {
s.last_refresh_unix = Some(t);
s.last_error = Some(err);
});
next = Duration::from_secs(u64::from(retry));
}
}
}
}
/// Re-exported so the server can record outbound transfers without depending on internals.
pub fn status_snapshot(e: &ZoneEntry) -> crate::store::ZoneStatus {
crate::store::status_lock(e).clone()
}
+237
View File
@@ -0,0 +1,237 @@
//! Online DNSSEC signing of primary zones (NSEC, RFC 4033–4035).
//!
//! Keys live in `keys_dir` as `<zone>.<tag>.<ksk|zsk|csk>.key` (PKCS#8). A KSK (flag 257)
//! signs the DNSKEY RRset, ZSKs sign everything else, a CSK does both. Rollover is done by
//! adding the new key file, reloading (both keys are published), and removing the old file
//! after the DNSKEY TTL (+ DS TTL for KSKs) has passed.
use std::collections::{BTreeMap, BTreeSet, HashSet};
use std::path::{Path, PathBuf};
use dns_config::DnssecZoneConfig;
use dns_core::dnssec::{ZoneKey, is_dnssec_type, key_file_contents, nsec_record, parse_key_file, rrsig_info};
use dns_core::proto::rr::{LowerName, Name, RData, Record, RecordType};
use crate::zone::Zone;
pub struct ZoneSigner {
pub keys: Vec<ZoneKey>,
pub validity: u32,
pub resign_before: u32,
pub keys_dir: PathBuf,
}
impl std::fmt::Debug for ZoneSigner {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ZoneSigner").field("keys", &self.keys).finish()
}
}
fn zone_prefix(zone: &Name) -> String {
let s = zone.to_ascii().to_ascii_lowercase();
if s == "." { "root.".into() } else { s }
}
impl ZoneSigner {
/// Load keys for `zone`, generating a CSK when allowed and none exist.
pub fn load(cfg: &DnssecZoneConfig, keys_dir: &Path, zone: &Name) -> Result<Self, String> {
let prefix = zone_prefix(zone);
let mut keys = Vec::new();
if let Ok(rd) = std::fs::read_dir(keys_dir) {
let mut files: Vec<PathBuf> = rd.filter_map(|e| e.ok().map(|e| e.path())).collect();
files.sort();
for f in files {
let fname = f.file_name().map(|n| n.to_string_lossy().to_ascii_lowercase()).unwrap_or_default();
if !fname.starts_with(&prefix) || !fname.ends_with(".key") {
continue;
}
let text = std::fs::read_to_string(&f).map_err(|e| format!("{}: {e}", f.display()))?;
keys.push(parse_key_file(&text).map_err(|e| format!("{}: {e}", f.display()))?);
}
}
if keys.is_empty() {
if !cfg.auto_generate {
return Err(format!("no DNSSEC keys for {zone} in {}", keys_dir.display()));
}
let (pk, key) = ZoneKey::generate(cfg.algorithm, true).map_err(|e| e.to_string())?;
std::fs::create_dir_all(keys_dir).map_err(|e| format!("{}: {e}", keys_dir.display()))?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let _ = std::fs::set_permissions(keys_dir, std::fs::Permissions::from_mode(0o700));
}
let path = keys_dir.join(format!("{prefix}{}.csk.key", key.tag));
dns_core::zonefile::atomic_write(&path, key_file_contents(cfg.algorithm, true, &pk).as_bytes()).map_err(|e| e.to_string())?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let _ = std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600));
}
if let Ok(ds) = key.ds_record(zone, 3600) {
tracing::warn!(zone = %zone, key_tag = key.tag, ds = %ds.data, "generated new DNSSEC key: publish this DS record in the parent zone");
}
keys.push(key);
}
if !keys.iter().any(|k| k.ksk) {
return Err(format!("{zone}: at least one KSK/CSK (flags 257) is required"));
}
Ok(Self {
keys,
validity: cfg.signature_validity.as_secs() as u32,
resign_before: cfg.resign_before.as_secs() as u32,
keys_dir: keys_dir.to_path_buf(),
})
}
fn zsks(&self) -> Vec<&ZoneKey> {
let z: Vec<&ZoneKey> = self.keys.iter().filter(|k| !k.ksk).collect();
if z.is_empty() { self.keys.iter().collect() } else { z }
}
/// DS records for the parent.
pub fn ds_records(&self, zone: &Name) -> Vec<Record> {
self.keys.iter().filter(|k| k.ksk).filter_map(|k| k.ds_record(zone, 3600).ok()).collect()
}
/// Sign the unsigned `source` zone, producing a new zone with DNSKEY, NSEC and RRSIG records.
pub fn sign(&self, source: &Zone, now: u32) -> Result<Zone, String> {
let origin = source.origin().clone();
let (_, _, _, minimum) = source.soa_timers();
let neg_ttl = source.soa().ttl.min(minimum);
let inception = now.saturating_sub(3600);
let expiration = now.saturating_add(self.validity);
let mut records: Vec<Record> = source.all_records().into_iter().filter(|r| !is_dnssec_type(r.record_type())).collect();
let dnskey_ttl = source.soa().ttl;
for k in &self.keys {
records.push(k.dnskey_record(&origin, dnskey_ttl));
}
// group RRsets
let mut sets: BTreeMap<(Name, u16), Vec<Record>> = BTreeMap::new();
for r in &records {
sets.entry((r.name.to_lowercase(), u16::from(r.record_type()))).or_default().push(r.clone());
}
let olabels = origin.num_labels();
let cuts: HashSet<LowerName> = sets
.keys()
.filter(|(n, t)| *t == u16::from(RecordType::NS) && n.num_labels() > olabels)
.map(|(n, _)| LowerName::new(n))
.collect();
let below_cut =
|n: &Name| -> bool { (olabels + 1..n.num_labels()).any(|l| cuts.contains(&LowerName::new(&n.trim_to(l as usize)))) };
// NSEC chain over authoritative names + delegation points (canonical order)
let mut names: BTreeMap<Name, BTreeSet<u16>> = BTreeMap::new();
for (n, t) in sets.keys() {
if below_cut(n) {
continue;
}
names.entry(n.clone()).or_default().insert(*t);
}
let ordered: Vec<Name> = names.keys().cloned().collect();
let mut out: Vec<Record> = records.clone();
for (i, n) in ordered.iter().enumerate() {
let next = &ordered[(i + 1) % ordered.len()];
let mut types: Vec<RecordType> = names[n].iter().map(|t| RecordType::from(*t)).collect();
types.push(RecordType::NSEC);
types.push(RecordType::RRSIG);
let nsec = nsec_record(n, next, types, neg_ttl);
sets.insert((n.clone(), u16::from(RecordType::NSEC)), vec![nsec.clone()]);
out.push(nsec);
}
// signatures
for ((n, t), set) in &sets {
let rtype = RecordType::from(*t);
if below_cut(n) {
continue; // glue / occluded data is not signed
}
let at_cut = cuts.contains(&LowerName::new(n));
if at_cut && !matches!(rtype, RecordType::DS | RecordType::NSEC) {
continue; // delegation NS is not signed
}
let signers: Vec<&ZoneKey> =
if rtype == RecordType::DNSKEY { self.keys.iter().filter(|k| k.ksk).collect() } else { self.zsks() };
for k in signers {
out.push(k.sign(&origin, set, inception, expiration).map_err(|e| format!("signing {n} {rtype}: {e}"))?);
}
}
Zone::from_records(&origin, out).map_err(|e| e.to_string())
}
/// Earliest RRSIG expiration in a signed zone.
pub fn min_expiration(zone: &Zone) -> Option<u32> {
zone.all_records()
.iter()
.filter_map(|r| match &r.data {
RData::DNSSEC(dns_core::proto::dnssec::rdata::DNSSECRData::RRSIG(s)) => Some(s.input().sig_expiration.get()),
_ => None,
})
.min()
}
/// Does the zone need re-signing at `now`?
pub fn needs_resign(&self, zone: &Zone, now: u32) -> bool {
match Self::min_expiration(zone) {
Some(exp) => !dns_core::serial::is_newer(exp, now.saturating_add(self.resign_before)),
None => true,
}
}
/// Are all key tags used in the zone still present in the key set?
pub fn keys_match(&self, zone: &Zone) -> bool {
let tags: BTreeSet<u16> = self.keys.iter().map(|k| k.tag).collect();
let used: BTreeSet<u16> = zone.all_records().iter().filter_map(rrsig_info).map(|(_, _, t)| t).collect();
used == tags || (used.is_subset(&tags) && self.keys.len() == 1)
}
}
/// Strip DNSSEC records (to compare a signed zone with its unsigned source).
pub fn unsigned_view(z: &Zone) -> Vec<Record> {
z.all_records().into_iter().filter(|r| !is_dnssec_type(r.record_type())).collect()
}
#[cfg(test)]
mod tests {
use super::*;
use dns_core::zonefile::parse_str;
#[test]
fn sign_zone_and_validate_every_rrset() {
let origin = Name::from_ascii("example.").unwrap();
let text = "$TTL 300\n@ IN SOA ns hm 1 3600 600 86400 60\n@ IN NS ns\nns IN A 192.0.2.1\nwww IN A 192.0.2.2\n*.w IN TXT \"x\"\nsub IN NS ns.sub\nns.sub IN A 192.0.2.3\nsec IN NS ns.sub\nsec IN DS 1 8 2 49FD46E6C4B45C55D4AC69CBD3CD34AC1AFE51DE1A6D5C4C9F2A4DFA2D5E7F3A\n";
let src = Zone::from_records(&origin, parse_str(text, &origin, None).unwrap()).unwrap();
let dir = std::env::temp_dir().join(format!("edns-keys-{}", rand::random::<u32>()));
let cfg = DnssecZoneConfig::default();
let s = ZoneSigner::load(&cfg, &dir, &origin).unwrap();
assert_eq!(s.keys.len(), 1);
let now = 1_800_000_000;
let signed = s.sign(&src, now).unwrap();
let keys: Vec<_> = s.keys.iter().map(|k| k.dnskey.clone()).collect();
let all = signed.all_records();
let sigs: Vec<Record> = all.iter().filter(|r| r.record_type() == RecordType::RRSIG).cloned().collect();
let mut sets: BTreeMap<(Name, RecordType), Vec<Record>> = BTreeMap::new();
for r in all.iter().filter(|r| r.record_type() != RecordType::RRSIG) {
sets.entry((r.name.clone(), r.record_type())).or_default().push(r.clone());
}
let mut signed_sets = 0;
for ((n, t), set) in &sets {
let unsigned_expected =
(*t == RecordType::NS && n.num_labels() > 1) || n.to_string().ends_with("sub.example.") && *t == RecordType::A;
let res = dns_core::dnssec::verify_rrset(n, set, &sigs, &keys, &origin, now);
if unsigned_expected {
assert!(res.is_err(), "{n} {t} must not be signed");
} else {
res.unwrap_or_else(|e| panic!("{n} {t}: {e}"));
signed_sets += 1;
}
}
assert!(signed_sets >= 8);
// the NSEC chain is closed and excludes glue
let nsecs = all.iter().filter(|r| r.record_type() == RecordType::NSEC).count();
assert_eq!(nsecs, 6); // example, ns, sec, sub, www, *.w
// reloading keys gives the same tag; needs_resign logic
let s2 = ZoneSigner::load(&cfg, &dir, &origin).unwrap();
assert_eq!(s2.keys[0].tag, s.keys[0].tag);
assert!(!s.needs_resign(&signed, now));
assert!(s.needs_resign(&signed, now + 8 * 86_400));
assert_eq!(unsigned_view(&signed).len(), src.all_records().len());
let _ = std::fs::remove_dir_all(dir);
}
}
+615
View File
@@ -0,0 +1,615 @@
//! The set of zones served by this node, with atomic snapshot swaps.
use std::collections::VecDeque;
use std::net::IpAddr;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, Mutex, RwLock};
use std::time::Duration;
use dns_config::{Config, ZoneConfig, ZoneType};
use dns_core::proto::rr::{LowerName, Name, RData, Record};
use dns_core::tsig::{KeyRing, TsigKey, now};
use ipnet::IpNet;
use serde::Serialize;
use crate::journal::{Diff, Journal};
use crate::zone::{Zone, ZoneRef};
/// Role of a zone on this node.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum ZoneKind {
Primary,
Secondary,
}
/// Observable zone state (API, metrics, `easydns zones show`).
#[derive(Debug, Clone, Default, Serialize)]
pub struct ZoneStatus {
pub serial: Option<u32>,
pub loaded: bool,
pub expired: bool,
pub records: usize,
pub source: Option<String>,
pub last_refresh_unix: Option<u64>,
pub last_success_unix: Option<u64>,
pub next_refresh_unix: Option<u64>,
pub expires_at_unix: Option<u64>,
pub last_error: Option<String>,
pub notifies_sent: u64,
pub notifies_failed: u64,
}
/// One transfer (in or out) for the history endpoint.
#[derive(Debug, Clone, Serialize)]
pub struct TransferEvent {
pub time_unix: u64,
pub direction: &'static str,
pub kind: String,
pub peer: String,
pub serial: Option<u32>,
pub records: usize,
pub ok: bool,
pub error: Option<String>,
pub duration_ms: u64,
}
fn lock<T>(m: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
m.lock().unwrap_or_else(|e| e.into_inner())
}
/// Changes whenever any zone snapshot is published or a zone expires/recovers. Caches of
/// encoded answers compare it to detect stale entries.
static DATA_GENERATION: AtomicU64 = AtomicU64::new(1);
/// Current zone data generation.
pub fn data_generation() -> u64 {
DATA_GENERATION.load(Ordering::Acquire)
}
fn bump_data_generation() {
DATA_GENERATION.fetch_add(1, Ordering::AcqRel);
}
/// A served zone (primary or secondary).
pub struct ZoneEntry {
pub name: Name,
pub lname: LowerName,
pub kind: ZoneKind,
pub config: ZoneConfig,
pub views: Vec<String>,
data: RwLock<Option<ZoneRef>>,
expired: AtomicBool,
pub journal: Mutex<Journal>,
status: Mutex<ZoneStatus>,
history: Mutex<VecDeque<TransferEvent>>,
/// Wakes the secondary refresh task (NOTIFY / manual sync).
pub refresh_trigger: tokio::sync::Notify,
pub shutdown: AtomicBool,
write_lock: Mutex<()>,
pub transfer_acl: Vec<IpNet>,
pub notify_acl: Vec<IpNet>,
pub update_acl: Vec<IpNet>,
pub transfer_key: Option<TsigKey>,
pub notify_key: Option<TsigKey>,
pub client_key: Option<TsigKey>,
pub update_keys: Vec<TsigKey>,
pub update_policy: Vec<crate::update::PolicyRule>,
/// Primary: zone file. Secondary: snapshot file.
pub file: PathBuf,
pub notify_count: AtomicU64,
pub max_records: usize,
/// DNSSEC signer (primary zones with `dnssec:`).
signer: Mutex<Option<crate::signing::ZoneSigner>>,
/// Unsigned source of a signed zone.
source: Mutex<Option<Zone>>,
signed_file: PathBuf,
keys_dir: Option<PathBuf>,
}
impl std::fmt::Debug for ZoneEntry {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ZoneEntry").field("name", &self.name.to_string()).field("kind", &self.kind).finish()
}
}
fn acl_contains(acl: &[IpNet], ip: IpAddr) -> bool {
let ip = match ip {
IpAddr::V6(v6) => v6.to_ipv4_mapped().map(IpAddr::V4).unwrap_or(IpAddr::V6(v6)),
v4 => v4,
};
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"));
if !new.exists() && old.is_file() {
let meta = |p: &Path| {
let mut m = p.as_os_str().to_owned();
m.push(".meta.json");
PathBuf::from(m)
};
let moved = new
.parent()
.map_or(Ok(()), std::fs::create_dir_all)
.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"),
Err(e) => {
tracing::warn!(path = %old.display(), error = %e, "could not move secondary zone copy; using the old location");
return old;
}
}
}
new
}
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())?;
let key = |k: &Option<String>| -> Result<Option<TsigKey>, String> {
match k {
None => Ok(None),
Some(n) => ring.get_str(n).cloned().map(Some).ok_or_else(|| format!("zone {}: unknown key {n}", zc.name)),
}
};
let mut notify_acl = cfg.expand_acl(&zc.allow_notify)?;
if notify_acl.is_empty() {
notify_acl = zc.primaries.iter().map(|a| IpNet::from(a.ip())).collect();
}
let kind = match zc.zone_type {
ZoneType::Primary => ZoneKind::Primary,
ZoneType::Secondary => ZoneKind::Secondary,
};
let file = match (&zc.file, kind) {
(Some(f), _) => cfg.zone_file_path(f),
(None, _) => default_secondary_file(&cfg.data_dir(), &name.to_ascii()),
};
let journal_path = cfg.data_dir().join("journal").join(format!("{}jnl", name.to_ascii()));
let mut update_keys = Vec::new();
for k in &zc.update_keys {
update_keys.push(ring.get_str(k).cloned().ok_or_else(|| format!("zone {}: unknown key {k}", zc.name))?);
}
let keys_dir = zc.dnssec.as_ref().map(|d| cfg.resolve_path(&d.keys_dir));
let signer = match (&zc.dnssec, &keys_dir) {
(Some(d), Some(dir)) if zc.zone_type == ZoneType::Primary => {
Some(crate::signing::ZoneSigner::load(d, dir, &name).map_err(|e| format!("zone {}: {e}", zc.name))?)
}
_ => None,
};
let signed_file = cfg.data_dir().join("signed").join(format!("{}zone", name.to_ascii()));
Ok(Self {
signer: Mutex::new(signer),
source: Mutex::new(None),
signed_file,
keys_dir,
lname: LowerName::new(&name),
name,
kind,
config: zc.clone(),
views: zc.views.clone(),
data: RwLock::new(None),
expired: AtomicBool::new(false),
journal: Mutex::new(Journal::load(&journal_path, zc.journal_size)),
status: Mutex::new(ZoneStatus::default()),
history: Mutex::new(VecDeque::new()),
refresh_trigger: tokio::sync::Notify::new(),
shutdown: AtomicBool::new(false),
write_lock: Mutex::new(()),
transfer_acl: cfg.expand_acl(&zc.transfer_acl)?,
notify_acl,
update_acl: cfg.expand_acl(&zc.update_acl)?,
transfer_key: key(&zc.transfer_tsig_key)?,
notify_key: key(&zc.notify_tsig_key)?,
client_key: key(&zc.transfer.tsig_key)?,
update_keys,
update_policy: crate::update::compile_policy(&zc.update_policy).map_err(|e| format!("zone {}: update_policy: {e}", zc.name))?,
file,
notify_count: AtomicU64::new(0),
max_records: zc.transfer.max_records,
})
}
/// Current snapshot, or `None` if not loaded / expired.
pub fn current(&self) -> Option<ZoneRef> {
if self.expired.load(Ordering::Acquire) {
return None;
}
self.data.read().unwrap_or_else(|e| e.into_inner()).clone()
}
/// Snapshot regardless of expiry (for refresh logic and diagnostics).
pub fn snapshot_any(&self) -> Option<ZoneRef> {
self.data.read().unwrap_or_else(|e| e.into_inner()).clone()
}
pub fn is_expired(&self) -> bool {
self.expired.load(Ordering::Acquire)
}
pub fn set_expired(&self, v: bool) {
if self.expired.swap(v, Ordering::AcqRel) != v {
bump_data_generation();
}
lock(&self.status).expired = v;
}
/// Atomically publish a new snapshot; queries see either the old or the new zone.
pub fn install(&self, zone: Zone, diffs: Vec<Diff>) {
let serial = zone.serial();
let records = zone.record_count();
{
let mut j = lock(&self.journal);
for d in diffs {
j.push(d);
}
}
*self.data.write().unwrap_or_else(|e| e.into_inner()) = Some(Arc::new(zone));
bump_data_generation();
let mut st = lock(&self.status);
st.serial = Some(serial);
st.loaded = true;
st.records = records;
}
pub fn status(&self) -> ZoneStatus {
lock(&self.status).clone()
}
pub fn update_status(&self, f: impl FnOnce(&mut ZoneStatus)) {
f(&mut lock(&self.status));
}
pub fn record_transfer(&self, ev: TransferEvent) {
let mut h = lock(&self.history);
if h.len() >= 100 {
h.pop_front();
}
h.push_back(ev);
}
pub fn transfers(&self) -> Vec<TransferEvent> {
lock(&self.history).iter().cloned().collect()
}
pub fn transfer_allowed_from(&self, ip: IpAddr) -> bool {
acl_contains(&self.transfer_acl, ip)
}
pub fn notify_allowed_from(&self, ip: IpAddr) -> bool {
acl_contains(&self.notify_acl, ip)
}
/// Whether `ip` is in `update_acl` (true when the list is empty).
pub fn update_allowed_from(&self, ip: IpAddr) -> bool {
self.update_acl.is_empty() || acl_contains(&self.update_acl, ip)
}
pub fn visible_in(&self, view: Option<&str>) -> bool {
self.views.is_empty() || view.is_some_and(|v| self.views.iter().any(|x| x == v))
}
// ---------------- Primary operations ----------------
pub fn is_signed(&self) -> bool {
lock(&self.signer).is_some()
}
/// DS records to publish in the parent (signed zones).
pub fn ds_records(&self) -> Vec<Record> {
lock(&self.signer).as_ref().map(|s| s.ds_records(&self.name)).unwrap_or_default()
}
fn with_serial(zone: &Zone, serial: u32) -> Result<Zone, String> {
let mut soa = zone.soa().clone();
if let RData::SOA(s) = &mut soa.data {
s.serial = serial;
}
zone.apply(&[], &[], soa, usize::MAX).map_err(|e| e.to_string())
}
fn persist_signed(&self, z: &Zone) {
let text = dns_core::zonefile::emit(&self.name, &z.all_records());
if let Err(e) = dns_core::zonefile::atomic_write(&self.signed_file, text.as_bytes()) {
tracing::error!(zone = %self.name, error = %e, "cannot persist signed zone");
}
}
/// Sign `src` with `serial` and publish it (signed zones only).
fn publish_signed(&self, signer: &crate::signing::ZoneSigner, src: Zone, serial: u32) -> Result<(), String> {
let src = Self::with_serial(&src, serial)?;
let signed = signer.sign(&src, now() as u32)?;
let diffs = match self.snapshot_any() {
Some(old) => {
let (rm, add) = old.diff(&signed);
vec![Diff { from_soa: old.soa().clone(), to_soa: signed.soa().clone(), removed: rm, added: add }]
}
None => Vec::new(),
};
self.persist_signed(&signed);
self.install(signed, diffs);
*lock(&self.source) = Some(src);
Ok(())
}
/// (Re)load a primary zone from its file. Returns `Ok(true)` if a new version was published.
pub fn load_primary_file(&self) -> Result<bool, String> {
let _g = lock(&self.write_lock);
let records = dns_core::zonefile::parse_file(&self.file, &self.name).map_err(|e| e.to_string())?;
let records: Vec<Record> =
records.into_iter().filter(|r| !(self.is_signed() && dns_core::dnssec::is_dnssec_type(r.record_type()))).collect();
let new = Zone::from_records(&self.name, records).map_err(|e| format!("{}: {e}", self.file.display()))?;
if self.is_signed() {
return self.load_signed(new);
}
let cur = self.snapshot_any();
let changed = match &cur {
None => {
self.install(new, Vec::new());
true
}
Some(old) => {
let (rm, add) = old.diff(&new);
let soa_changed = old.soa().data != new.soa().data;
if rm.is_empty() && add.is_empty() && !soa_changed {
false
} else if !dns_core::serial::is_newer(new.serial(), old.serial()) {
return Err(format!(
"zone {} changed but SOA serial {} is not newer than {} – keeping the old version",
self.name,
new.serial(),
old.serial()
));
} else {
let diff = Diff { from_soa: old.soa().clone(), to_soa: new.soa().clone(), removed: rm, added: add };
self.install(new, vec![diff]);
true
}
}
};
self.update_status(|s| {
s.source = Some(self.file.display().to_string());
s.last_success_unix = Some(now());
s.last_error = None;
});
Ok(changed)
}
fn load_signed(&self, src: Zone) -> Result<bool, String> {
// refresh keys from disk (rollover: keys added/removed)
if let (Some(dir), Some(d)) = (&self.keys_dir, &self.config.dnssec) {
let fresh = crate::signing::ZoneSigner::load(d, dir, &self.name)?;
*lock(&self.signer) = Some(fresh);
}
let signer_guard = lock(&self.signer);
let Some(signer) = signer_guard.as_ref() else { return Err("signer missing".into()) };
let t = now() as u32;
let same_source = |a: &Zone| {
let (rm, add) = a.diff(&src);
rm.is_empty() && add.is_empty()
};
let cur = self.snapshot_any();
// Startup: reuse the persisted signed zone if it matches the source and keys.
if cur.is_none()
&& self.signed_file.is_file()
&& let Ok(recs) = dns_core::zonefile::parse_file(&self.signed_file, &self.name)
&& let Ok(signed) = Zone::from_records(&self.name, recs)
{
let unsigned = Zone::from_records(&self.name, crate::signing::unsigned_view(&signed)).ok();
let reusable = unsigned.as_ref().is_some_and(&same_source)
&& signer.keys_match(&signed)
&& !signer.needs_resign(&signed, t)
&& !dns_core::serial::is_newer(src.serial(), signed.serial());
let prev_serial = signed.serial();
if reusable {
let serial = signed.serial();
self.install(signed, Vec::new());
*lock(&self.source) = Some(Self::with_serial(&src, serial)?);
tracing::info!(zone = %self.name, serial, "loaded persisted signed zone");
return Ok(true);
}
let serial = if dns_core::serial::is_newer(src.serial(), prev_serial) { src.serial() } else { prev_serial.wrapping_add(1) };
self.publish_signed(signer, src, serial)?;
return Ok(true);
}
match cur {
None => {
let serial = src.serial();
self.publish_signed(signer, src, serial)?;
Ok(true)
}
Some(signed) => {
let unchanged = lock(&self.source).as_ref().is_some_and(&same_source);
if unchanged && signer.keys_match(&signed) && !signer.needs_resign(&signed, t) {
return Ok(false);
}
let serial =
if dns_core::serial::is_newer(src.serial(), signed.serial()) { src.serial() } else { signed.serial().wrapping_add(1) };
self.publish_signed(signer, src, serial)?;
Ok(true)
}
}
}
/// Re-sign a signed zone when signatures approach expiry. Returns `true` when re-signed.
pub fn resign_if_needed(&self) -> Result<bool, String> {
let _g = lock(&self.write_lock);
let signer_guard = lock(&self.signer);
let (Some(signer), Some(cur)) = (signer_guard.as_ref(), self.snapshot_any()) else { return Ok(false) };
if !signer.needs_resign(&cur, now() as u32) {
return Ok(false);
}
let Some(src) = lock(&self.source).clone() else { return Ok(false) };
let serial = dns_core::serial::next_serial(cur.serial(), self.config.serial_strategy, now());
self.publish_signed(signer, src, serial)?;
tracing::info!(zone = %self.name, serial, "zone re-signed");
Ok(true)
}
/// Apply a change to a primary zone (API / dynamic update): bump the serial, validate,
/// persist the zone file atomically, publish and record the IXFR diff.
/// Returns the new serial.
pub fn modify(&self, removed: &[Record], added: &[Record]) -> Result<u32, String> {
if self.kind != ZoneKind::Primary {
return Err("zone is not a primary zone".into());
}
let _g = lock(&self.write_lock);
let cur = self.snapshot_any().ok_or("zone not loaded")?;
if removed.iter().chain(added.iter()).any(|r| self.is_signed() && dns_core::dnssec::is_dnssec_type(r.record_type())) {
return Err("DNSSEC records of a signed zone are managed automatically".into());
}
let base = if self.is_signed() { lock(&self.source).clone().ok_or("source not loaded")? } else { (*cur).clone() };
let mut soa = base.soa().clone();
let new_serial = dns_core::serial::next_serial(cur.serial(), self.config.serial_strategy, now());
if let RData::SOA(s) = &mut soa.data {
s.serial = new_serial;
} else {
return Err("invalid SOA".into());
}
let new_src = base.apply(removed, added, soa, usize::MAX).map_err(|e| e.to_string())?;
let (rm, add) = base.diff(&new_src);
if rm.is_empty() && add.is_empty() {
return Ok(cur.serial());
}
let text = dns_core::zonefile::emit(&self.name, &new_src.all_records());
dns_core::zonefile::atomic_write(&self.file, text.as_bytes()).map_err(|e| e.to_string())?;
let signer_guard = lock(&self.signer);
if let Some(signer) = signer_guard.as_ref() {
self.publish_signed(signer, new_src, new_serial)?;
} else {
let diff = Diff { from_soa: cur.soa().clone(), to_soa: new_src.soa().clone(), removed: rm, added: add };
self.install(new_src, vec![diff]);
}
Ok(new_serial)
}
/// Send NOTIFY to all configured targets (fire-and-forget, with retries).
pub fn send_notifies(self: &Arc<Self>) {
let Some(zone) = self.current() else { return };
for target in self.config.notify.clone() {
let me = Arc::clone(self);
let soa = zone.soa().clone();
tokio::spawn(async move {
let mut ok = false;
for attempt in 0..3u32 {
match dns_core::client::notify(target, &me.name, Some(&soa), me.notify_key.as_ref(), Duration::from_secs(2)).await {
Ok(rc) => {
tracing::info!(zone = %me.name, %target, rcode = %rc, "NOTIFY acknowledged");
ok = true;
break;
}
Err(e) => {
tracing::warn!(zone = %me.name, %target, attempt, error = %e, "NOTIFY failed");
tokio::time::sleep(Duration::from_secs(1 << attempt)).await;
}
}
}
me.notify_count.fetch_add(1, Ordering::Relaxed);
me.update_status(|s| if ok { s.notifies_sent += 1 } else { s.notifies_failed += 1 });
});
}
}
}
/// All zones served by the node.
#[derive(Debug, Default)]
pub struct ZoneStore {
zones: Vec<Arc<ZoneEntry>>,
}
impl ZoneStore {
/// Build the store from configuration, reusing unchanged entries from `previous`
/// (so running secondary tasks and loaded data survive a reload).
pub fn build(cfg: &Config, ring: &KeyRing, previous: Option<&ZoneStore>) -> Result<(Self, Vec<Arc<ZoneEntry>>), String> {
let mut zones = Vec::new();
let mut fresh = Vec::new();
for zc in &cfg.zones {
let reuse =
previous.and_then(|p| p.zones.iter().find(|e| serde_json::to_string(&e.config).ok() == serde_json::to_string(zc).ok()));
match reuse {
Some(e) => {
if e.kind == ZoneKind::Primary {
match e.load_primary_file() {
Ok(true) => e.send_notifies(),
Ok(false) => {}
Err(err) => {
tracing::error!(zone = %e.name, error = %err, "reload failed; keeping previous version");
e.update_status(|s| s.last_error = Some(err));
}
}
}
zones.push(Arc::clone(e));
}
None => {
let e = Arc::new(ZoneEntry::new(cfg, zc, ring)?);
match e.kind {
ZoneKind::Primary => {
e.load_primary_file().map_err(|err| format!("zone {}: {err}", e.name))?;
}
ZoneKind::Secondary => crate::secondary::load_snapshot(&e),
}
fresh.push(Arc::clone(&e));
zones.push(e);
}
}
}
if let Some(p) = previous {
for old in &p.zones {
if !zones.iter().any(|z| Arc::ptr_eq(z, old)) {
old.shutdown.store(true, Ordering::Release);
old.refresh_trigger.notify_one();
}
}
}
Ok((Self { zones }, fresh))
}
/// Longest-match zone for `qname` visible in `view`.
pub fn find(&self, qname: &LowerName, view: Option<&str>) -> Option<Arc<ZoneEntry>> {
self.zones.iter().filter(|z| z.visible_in(view) && z.lname.zone_of(qname)).max_by_key(|z| z.lname.num_labels()).cloned()
}
/// Exact zone by name (any view).
pub fn get(&self, name: &Name) -> Option<Arc<ZoneEntry>> {
let l = LowerName::new(name);
self.zones.iter().find(|z| z.lname == l).cloned()
}
pub fn all(&self) -> &[Arc<ZoneEntry>] {
&self.zones
}
}
pub(crate) fn status_lock(e: &ZoneEntry) -> std::sync::MutexGuard<'_, ZoneStatus> {
lock(&e.status)
}
#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod migration_tests {
use super::*;
#[test]
fn old_secondary_copy_is_moved_to_new_location() {
let d = std::env::temp_dir().join(format!("edns-sec-mig-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&d);
std::fs::create_dir_all(d.join("secondary")).unwrap();
std::fs::write(d.join("secondary/example.com.zone"), "zone").unwrap();
std::fs::write(d.join("secondary/example.com.zone.meta.json"), "{}").unwrap();
let p = default_secondary_file(&d, "example.com.");
assert_eq!(p, d.join("zones/secondary/example.com.zone"));
assert_eq!(std::fs::read_to_string(&p).unwrap(), "zone");
assert!(d.join("zones/secondary/example.com.zone.meta.json").is_file());
assert!(!d.join("secondary/example.com.zone").exists());
// second call: nothing to move, same path
assert_eq!(default_secondary_file(&d, "example.com."), p);
// no old copy at all: new path
assert_eq!(default_secondary_file(&d, "example.net."), d.join("zones/secondary/example.net.zone"));
let _ = std::fs::remove_dir_all(&d);
}
}
+352
View File
@@ -0,0 +1,352 @@
//! RFC 2136 dynamic updates for primary zones.
//!
//! Authorisation models (see `ZoneConfig::update_*`), chosen per zone:
//! * `update_policy` – every updated record must be granted by a rule for the signing key;
//! * `update_keys` – a valid TSIG by one of these keys may change the whole zone;
//! * only `update_acl` – unsigned updates from listed addresses (BIND `allow-update { IPs; }`).
//!
//! `update_acl` also restricts sources in the first two models when set. Every accepted
//! or refused update is logged for the audit trail by the caller.
use std::collections::HashSet;
use dns_core::proto::op::{Message, ResponseCode};
use dns_core::proto::rr::{DNSClass, LowerName, Name, RData, Record, RecordType};
use dns_config::update_policy::{UpdateMatch, UpdateRule};
use crate::store::{ZoneEntry, ZoneKind};
use crate::zone::Zone;
/// Outcome for the audit log.
#[derive(Debug, Clone)]
pub struct UpdateOutcome {
pub rcode: ResponseCode,
pub new_serial: Option<u32>,
pub added: usize,
pub removed: usize,
pub reason: String,
}
fn fail(rcode: ResponseCode, reason: impl Into<String>) -> UpdateOutcome {
UpdateOutcome { rcode, new_serial: None, added: 0, removed: 0, reason: reason.into() }
}
fn same_rdata(a: &RData, b: &RData) -> bool {
a.to_string().eq_ignore_ascii_case(&b.to_string())
}
/// Check RFC 2136 §3.2 prerequisites against `zone`.
fn check_prereqs(zone: &Zone, prereqs: &[Record]) -> Result<(), UpdateOutcome> {
// value-dependent RRset prerequisites are grouped per (name, type)
let mut value_sets: Vec<(LowerName, RecordType, Vec<RData>)> = Vec::new();
for r in prereqs {
let lname = LowerName::new(&r.name);
if !zone.origin_lower().zone_of(&lname) {
return Err(fail(ResponseCode::NotZone, format!("prerequisite {} outside zone", r.name)));
}
if r.ttl != 0 {
return Err(fail(ResponseCode::FormErr, "prerequisite TTL must be 0"));
}
let rtype = r.record_type();
match r.dns_class {
DNSClass::ANY => {
if rtype == RecordType::ANY {
if !zone.name_exists(&lname) {
return Err(fail(ResponseCode::NXDomain, format!("{} is not in use", r.name)));
}
} else if zone.rrset(&lname, rtype).is_none_or(|s| s.records.is_empty()) {
return Err(fail(ResponseCode::NXRRSet, format!("{} {rtype} does not exist", r.name)));
}
}
DNSClass::NONE => {
if rtype == RecordType::ANY {
if zone.name_exists(&lname) {
return Err(fail(ResponseCode::YXDomain, format!("{} is in use", r.name)));
}
} else if zone.rrset(&lname, rtype).is_some_and(|s| !s.records.is_empty()) {
return Err(fail(ResponseCode::YXRRSet, format!("{} {rtype} exists", r.name)));
}
}
DNSClass::IN => match value_sets.iter_mut().find(|(n, t, _)| *n == lname && *t == rtype) {
Some((_, _, v)) => v.push(r.data.clone()),
None => value_sets.push((lname, rtype, vec![r.data.clone()])),
},
_ => return Err(fail(ResponseCode::FormErr, "bad prerequisite class")),
}
}
for (name, rtype, want) in value_sets {
let have: Vec<RData> = zone.rrset(&name, rtype).map(|s| s.records.iter().map(|r| r.data.clone()).collect()).unwrap_or_default();
let ok = have.len() == want.len() && want.iter().all(|w| have.iter().any(|h| same_rdata(h, w)));
if !ok {
return Err(fail(ResponseCode::NXRRSet, format!("{name} {rtype} does not match")));
}
}
Ok(())
}
/// Translate the update section into (removed, added) record lists (RFC 2136 §3.4).
fn plan(zone: &Zone, updates: &[Record]) -> Result<(Vec<Record>, Vec<Record>), UpdateOutcome> {
let apex = zone.origin_lower().clone();
let mut removed: Vec<Record> = Vec::new();
let mut added: Vec<Record> = Vec::new();
let mut removed_keys: HashSet<(LowerName, RecordType, String)> = HashSet::new();
let mut remove = |r: &Record, removed: &mut Vec<Record>| {
let k = (LowerName::new(&r.name), r.record_type(), r.data.to_string());
if removed_keys.insert(k) {
removed.push(r.clone());
}
};
for u in updates {
let lname = LowerName::new(&u.name);
if !zone.origin_lower().zone_of(&lname) {
return Err(fail(ResponseCode::NotZone, format!("update {} outside zone", u.name)));
}
let rtype = u.record_type();
if matches!(rtype, RecordType::AXFR | RecordType::IXFR | RecordType::OPT | RecordType::TSIG) {
return Err(fail(ResponseCode::FormErr, format!("type {rtype} not allowed in updates")));
}
match u.dns_class {
DNSClass::IN => {
if rtype == RecordType::SOA {
// SOA changes are managed by the serial strategy; ignore (RFC 2136 §3.4.2.2 allows).
continue;
}
added.push(u.clone());
}
DNSClass::ANY => {
if u.ttl != 0 || !matches!(u.data, RData::Update0(_)) {
return Err(fail(ResponseCode::FormErr, "delete with ANY class must have TTL 0 and no RDATA"));
}
if rtype == RecordType::ANY {
for t in [
RecordType::A,
RecordType::AAAA,
RecordType::CNAME,
RecordType::MX,
RecordType::TXT,
RecordType::SRV,
RecordType::PTR,
RecordType::CAA,
RecordType::NAPTR,
RecordType::SVCB,
RecordType::HTTPS,
RecordType::NS,
RecordType::DS,
] {
if lname == apex && t == RecordType::NS {
continue;
}
if let Some(s) = zone.rrset(&lname, t) {
for r in &s.records {
remove(r, &mut removed);
}
}
}
} else {
if lname == apex && matches!(rtype, RecordType::SOA | RecordType::NS) {
continue;
}
if let Some(s) = zone.rrset(&lname, rtype) {
for r in &s.records {
remove(r, &mut removed);
}
}
}
}
DNSClass::NONE => {
if u.ttl != 0 {
return Err(fail(ResponseCode::FormErr, "delete with NONE class must have TTL 0"));
}
if rtype == RecordType::SOA {
continue;
}
if let Some(s) = zone.rrset(&lname, rtype) {
let apex_ns_last = lname == apex && rtype == RecordType::NS && s.records.len() <= 1;
if apex_ns_last {
continue;
}
for r in s.records.iter().filter(|r| same_rdata(&r.data, &u.data)) {
remove(r, &mut removed);
}
}
}
_ => return Err(fail(ResponseCode::FormErr, "bad update class")),
}
}
Ok((removed, added))
}
/// Record types a rule without a type list does not cover (as in BIND).
const DEFAULT_EXCLUDED: &[RecordType] = &[RecordType::SOA, RecordType::NS, RecordType::RRSIG, RecordType::NSEC, RecordType::NSEC3];
#[derive(Debug, Clone)]
enum Types {
Default,
Any,
List(Vec<RecordType>),
}
/// A compiled `update_policy` rule.
#[derive(Debug, Clone)]
pub struct PolicyRule {
grant: bool,
/// None = any valid key (`*`).
identity: Option<LowerName>,
matches: UpdateMatch,
/// For `wildcard`: the base name below the `*` label.
name: Option<LowerName>,
types: Types,
}
fn abs_name(s: &str) -> Result<LowerName, String> {
let mut n = Name::from_utf8(s).map_err(|e| format!("{s}: {e}"))?;
n.set_fqdn(true);
Ok(LowerName::new(&n))
}
/// Compile configured rules (names are absolute, as in named.conf).
pub fn compile_policy(rules: &[UpdateRule]) -> Result<Vec<PolicyRule>, String> {
rules
.iter()
.map(|r| {
let identity = if r.identity == "*" { None } else { Some(abs_name(&r.identity)?) };
let name = match (&r.name, r.matches) {
(Some(n), UpdateMatch::Wildcard) => Some(abs_name(n.trim_start_matches("*."))?),
(Some(n), _) => Some(abs_name(n)?),
(None, _) => None,
};
let types = if r.types.is_empty() {
Types::Default
} else if r.types.iter().any(|t| t == "ANY") {
Types::Any
} else {
Types::List(r.types.iter().map(|t| t.parse::<RecordType>().map_err(|e| format!("{t}: {e}"))).collect::<Result<_, _>>()?)
};
Ok(PolicyRule { grant: r.grant, identity, matches: r.matches, name, types })
})
.collect()
}
impl PolicyRule {
fn applies(&self, signer: &LowerName, owner: &LowerName, rtype: RecordType) -> bool {
if self.identity.as_ref().is_some_and(|i| i != signer) {
return false;
}
let name_ok = match (self.matches, &self.name) {
(UpdateMatch::Name, Some(n)) => owner == n,
(UpdateMatch::Subdomain, Some(n)) => n.zone_of(owner),
(UpdateMatch::Wildcard, Some(base)) => base.zone_of(owner) && owner != base,
(UpdateMatch::Zonesub, _) => true, // owner is already checked to be inside the zone
(UpdateMatch::SelfName, _) => owner == signer,
(UpdateMatch::Selfsub, _) => signer.zone_of(owner),
_ => false,
};
name_ok
&& match &self.types {
Types::Any => true,
// deleting all RRsets at a name needs a rule covering every type
Types::Default => rtype != RecordType::ANY && !DEFAULT_EXCLUDED.contains(&rtype),
Types::List(l) => rtype != RecordType::ANY && l.contains(&rtype),
}
}
}
/// First matching rule decides; no match = not permitted.
pub fn policy_permits(rules: &[PolicyRule], signer: &LowerName, owner: &LowerName, rtype: RecordType) -> bool {
rules.iter().find(|r| r.applies(signer, owner, rtype)).is_some_and(|r| r.grant)
}
/// Who is asking: the name of a valid TSIG key (any key known to the server), and whether
/// the source address is in `update_acl`.
#[derive(Debug, Clone, Copy)]
pub struct Requester<'a> {
pub signer: Option<&'a Name>,
pub addr_ok: bool,
}
fn authorize(entry: &ZoneEntry, msg: &Message, who: Requester<'_>) -> Result<(), UpdateOutcome> {
let refuse = |m: String| Err(fail(ResponseCode::Refused, m));
let acl_set = !entry.update_acl.is_empty();
if !entry.update_policy.is_empty() {
let Some(signer) = who.signer else {
return refuse("update_policy requires a TSIG-signed update".into());
};
if acl_set && !who.addr_ok {
return refuse("client address not in update_acl".into());
}
let signer = LowerName::new(signer);
for r in &msg.authorities {
let owner = LowerName::new(&r.name);
if !policy_permits(&entry.update_policy, &signer, &owner, r.record_type()) {
return refuse(format!("{} {} not permitted for key {} by update_policy", r.name, r.record_type(), Name::from(&signer)));
}
}
return Ok(());
}
if !entry.update_keys.is_empty() {
let key_ok = who.signer.is_some_and(|s| entry.update_keys.iter().any(|k| &k.name == s));
if !key_ok {
return refuse("update not signed with an authorised TSIG key".into());
}
if acl_set && !who.addr_ok {
return refuse("client address not in update_acl".into());
}
return Ok(());
}
if acl_set {
// IP-only model (BIND allow-update { addresses; })
return if who.addr_ok { Ok(()) } else { refuse("client address not in update_acl".into()) };
}
refuse("dynamic updates are disabled for this zone".into())
}
/// Process an UPDATE message for `entry`.
pub fn apply(entry: &ZoneEntry, msg: &Message, who: Requester<'_>) -> UpdateOutcome {
if entry.kind != ZoneKind::Primary {
return fail(ResponseCode::NotImp, "updates are only accepted by the primary");
}
if let Err(o) = authorize(entry, msg, who) {
return o;
}
let Some(zone) = entry.current() else {
return fail(ResponseCode::ServFail, "zone not loaded");
};
if let Err(o) = check_prereqs(&zone, &msg.answers) {
return o;
}
let (removed, added) = match plan(&zone, &msg.authorities) {
Ok(p) => p,
Err(o) => return o,
};
if removed.is_empty() && added.is_empty() {
return UpdateOutcome {
rcode: ResponseCode::NoError,
new_serial: Some(zone.serial()),
added: 0,
removed: 0,
reason: "no changes".into(),
};
}
match entry.modify(&removed, &added) {
Ok(serial) => UpdateOutcome {
rcode: ResponseCode::NoError,
new_serial: Some(serial),
added: added.len(),
removed: removed.len(),
reason: "applied".into(),
},
Err(e) => fail(ResponseCode::Refused, format!("update rejected: {e}")),
}
}
/// Helper used by tools and tests: build an UPDATE message for `zone`.
pub fn build_update(zone: &Name, prereqs: Vec<Record>, updates: Vec<Record>) -> Message {
use dns_core::proto::op::{MessageType, OpCode, Query};
let mut m = Message::new(rand::random::<u16>(), MessageType::Query, OpCode::Update);
let mut q = Query::query(zone.clone(), RecordType::SOA);
q.set_query_class(DNSClass::IN);
m.add_query(q);
m.answers = prereqs;
m.authorities = updates;
m
}
+209
View File
@@ -0,0 +1,209 @@
//! Zone transfer responses (server side) and transfer stream application (client side).
use dns_core::proto::op::{Message, MessageType};
use dns_core::proto::rr::{Name, Record, RecordType};
use dns_core::proto::serialize::binary::BinEncodable;
use crate::journal::{Diff, Journal, soa_serial};
use crate::zone::{Zone, ZoneError};
/// Soft limit for a single transfer message (bytes); TCP allows 64 KiB.
pub const MESSAGE_BUDGET: usize = 16 * 1024;
fn new_response(req: &Message) -> Message {
let mut m = Message::new(req.metadata.id, MessageType::Response, req.metadata.op_code);
m.metadata.authoritative = true;
m.queries = req.queries.clone();
m
}
/// Split a record stream into response messages of at most ~[`MESSAGE_BUDGET`] bytes.
pub fn chunk(req: &Message, records: Vec<Record>) -> Vec<Message> {
let mut out = Vec::new();
let mut cur = new_response(req);
let mut size = 64usize;
for r in records {
let rs = r.to_bytes().map(|b| b.len()).unwrap_or(512);
if size + rs > MESSAGE_BUDGET && !cur.answers.is_empty() {
out.push(std::mem::replace(&mut cur, new_response(req)));
cur.queries.clear(); // question only in the first message (RFC 5936 §2.2)
size = 64;
}
size += rs;
cur.answers.push(r);
}
out.push(cur);
out
}
/// Full AXFR record stream: SOA, records..., SOA.
pub fn axfr_records(zone: &Zone) -> Vec<Record> {
let mut v = zone.all_records();
v.push(zone.soa().clone());
v
}
/// IXFR record stream for a client at `client_serial` (RFC 1995).
/// Falls back to AXFR-style when the journal cannot bridge the gap.
pub fn ixfr_records(zone: &Zone, journal: &Journal, client_serial: u32) -> (Vec<Record>, bool) {
if !dns_core::serial::is_newer(zone.serial(), client_serial) {
return (vec![zone.soa().clone()], true);
}
match journal.since(client_serial) {
Some(chain) if chain.last().map(|d| d.to_serial()) == Some(zone.serial()) => {
let mut v = vec![zone.soa().clone()];
for d in chain {
v.push(d.from_soa.clone());
v.extend(d.removed.iter().cloned());
v.push(d.to_soa.clone());
v.extend(d.added.iter().cloned());
}
v.push(zone.soa().clone());
(v, true)
}
_ => (axfr_records(zone), false),
}
}
/// Outcome of applying a received transfer.
#[derive(Debug)]
pub enum Applied {
UpToDate,
Full(Zone),
Incremental(Zone, Vec<Diff>),
}
/// Build a zone from an AXFR (or AXFR-style IXFR) record stream.
pub fn zone_from_axfr(origin: &Name, records: &[Record], limit: usize) -> Result<Zone, String> {
let (Some(first), Some(last)) = (records.first(), records.last()) else {
return Err("empty transfer".into());
};
if first.record_type() != RecordType::SOA || last.record_type() != RecordType::SOA || records.len() < 2 {
return Err("transfer is not framed by SOA records".into());
}
if first.data != last.data {
return Err("first and last SOA differ (zone changed during transfer)".into());
}
if !first.name.eq_ignore_root_case(origin) {
return Err(format!("SOA owner {} does not match zone {origin}", first.name));
}
let body = records[..records.len() - 1].to_vec();
Zone::from_records_limited(origin, body, limit).map_err(|e| e.to_string())
}
/// Apply an IXFR/AXFR stream on top of `current` (if any).
pub fn apply_transfer(origin: &Name, current: Option<&Zone>, records: &[Record], limit: usize) -> Result<Applied, String> {
if records.len() == 1 {
return Ok(Applied::UpToDate);
}
let incremental = records.len() >= 2 && records[1].record_type() == RecordType::SOA;
if !incremental {
return zone_from_axfr(origin, records, limit).map(Applied::Full);
}
let Some(cur) = current else {
return Err("incremental transfer received but no local zone to apply it to".into());
};
let final_serial = soa_serial(&records[0]);
let mut zone = cur.clone();
let mut diffs = Vec::new();
let mut i = 1;
let body_end = records.len() - 1; // last record is the closing SOA
while i < body_end {
let from = &records[i];
if from.record_type() != RecordType::SOA {
return Err("malformed IXFR: expected SOA at start of difference sequence".into());
}
if soa_serial(from) != zone.serial() {
return Err(format!("IXFR difference starts at serial {} but local zone has {}", soa_serial(from), zone.serial()));
}
i += 1;
let mut removed = Vec::new();
while i < body_end && records[i].record_type() != RecordType::SOA {
removed.push(records[i].clone());
i += 1;
}
if i >= body_end {
return Err("malformed IXFR: missing new SOA in difference sequence".into());
}
let to = records[i].clone();
i += 1;
let mut added = Vec::new();
while i < body_end && records[i].record_type() != RecordType::SOA {
added.push(records[i].clone());
i += 1;
}
zone = zone.apply(&removed, &added, to.clone(), limit).map_err(|e: ZoneError| e.to_string())?;
diffs.push(Diff { from_soa: from.clone(), to_soa: to, removed, added });
}
if zone.serial() != final_serial || records[body_end].data != records[0].data {
return Err("IXFR did not end at the announced serial".into());
}
Ok(Applied::Incremental(zone, diffs))
}
#[cfg(test)]
mod tests {
use super::*;
use dns_core::zonefile::parse_str;
const Z1: &str = "$TTL 60\n@ IN SOA ns hm 1 3600 600 86400 60\n@ IN NS ns\nns IN A 192.0.2.1\nwww IN A 192.0.2.10\n";
fn z(text: &str) -> Zone {
let o = Name::from_ascii("example.com.").unwrap();
Zone::from_records(&o, parse_str(text, &o, None).unwrap()).unwrap()
}
#[test]
fn axfr_roundtrip_and_chunking() {
let mut text = Z1.to_string();
for i in 0..2000 {
text.push_str(&format!("h{i} IN TXT \"{:0>100}\"\n", i));
}
let zone = z(&text);
let recs = axfr_records(&zone);
let req = Message::query();
let msgs = chunk(&req, recs.clone());
assert!(msgs.len() > 5);
for m in &msgs {
assert!(m.to_vec().unwrap().len() <= MESSAGE_BUDGET + 600);
}
let flat: Vec<Record> = msgs.into_iter().flat_map(|m| m.answers).collect();
let o = Name::from_ascii("example.com.").unwrap();
let back = zone_from_axfr(&o, &flat, usize::MAX).unwrap();
assert_eq!(back.record_count(), zone.record_count());
// truncated stream is rejected
assert!(zone_from_axfr(&o, &flat[..flat.len() - 1], usize::MAX).is_err());
}
#[test]
fn ixfr_incremental_and_fallback() {
let z1 = z(Z1);
let z2 = z(&Z1.replace("hm 1 ", "hm 2 ").replace("192.0.2.10", "192.0.2.11"));
let z3 = z(&Z1.replace("hm 1 ", "hm 3 ").replace("192.0.2.10", "192.0.2.12"));
let mut j = Journal::in_memory(10);
for (a, b) in [(&z1, &z2), (&z2, &z3)] {
let (rm, add) = a.diff(b);
j.push(Diff { from_soa: a.soa().clone(), to_soa: b.soa().clone(), removed: rm, added: add });
}
let (recs, incr) = ixfr_records(&z3, &j, 1);
assert!(incr);
let o = Name::from_ascii("example.com.").unwrap();
match apply_transfer(&o, Some(&z1), &recs, usize::MAX).unwrap() {
Applied::Incremental(z, diffs) => {
assert_eq!(z.serial(), 3);
assert_eq!(diffs.len(), 2);
assert!(z.diff(&z3).0.is_empty());
}
o => panic!("{o:?}"),
}
// up to date
let (recs, _) = ixfr_records(&z3, &j, 3);
assert!(matches!(apply_transfer(&o, Some(&z3), &recs, usize::MAX).unwrap(), Applied::UpToDate));
// unknown serial -> AXFR style
let (recs, incr) = ixfr_records(&z3, &j, 0);
assert!(!incr);
assert!(matches!(apply_transfer(&o, Some(&z1), &recs, usize::MAX).unwrap(), Applied::Full(_)));
// applying an incremental stream to the wrong base fails
let (recs, _) = ixfr_records(&z3, &j, 2);
assert!(apply_transfer(&o, Some(&z1), &recs, usize::MAX).is_err());
}
}
+701
View File
@@ -0,0 +1,701 @@
//! Immutable zone snapshot and the RFC 1034 §4.3.2 / RFC 4592 lookup algorithm.
use std::collections::{BTreeSet, HashMap, HashSet};
use std::sync::Arc;
use dns_core::proto::rr::{DNSClass, LowerName, Name, RData, Record, RecordType};
/// A set of records with the same owner, class and type.
#[derive(Debug, Clone)]
pub struct RRset {
pub rtype: RecordType,
pub records: Vec<Record>,
pub rrsigs: Vec<Record>,
}
impl RRset {
pub fn ttl(&self) -> u32 {
self.records.iter().map(|r| r.ttl).min().unwrap_or(0)
}
}
#[derive(Debug, Clone, Default)]
struct Node {
rrsets: HashMap<RecordType, RRset>,
}
/// Errors that make a zone unloadable.
#[derive(Debug, thiserror::Error, Clone, PartialEq, Eq)]
pub enum ZoneError {
#[error("zone has no SOA record at the apex")]
NoSoa,
#[error("zone has more than one SOA record")]
MultipleSoa,
#[error("zone has no NS records at the apex")]
NoApexNs,
#[error("record {0} is outside of zone {1}")]
OutOfZone(String, String),
#[error("CNAME at {0} coexists with other data")]
CnameConflict(String),
#[error("CNAME at the zone apex is not allowed")]
CnameAtApex,
#[error("multiple CNAME records at {0}")]
MultipleCname(String),
#[error("unsupported class {0} for record {1}")]
BadClass(String, String),
#[error("zone exceeds limit of {0} records")]
TooLarge(usize),
}
/// Immutable, validated zone contents. Cheap to share via `Arc`.
#[derive(Debug, Clone)]
pub struct Zone {
origin: Name,
origin_lower: LowerName,
nodes: HashMap<LowerName, Node>,
/// All existing names including empty non-terminals.
names: HashSet<LowerName>,
soa: Record,
count: usize,
/// Owners of NSEC records (canonical order) – non-empty for signed zones.
nsec_names: BTreeSet<Name>,
}
/// Result of a lookup within one zone.
#[derive(Debug, Clone)]
pub enum Lookup {
/// Authoritative positive answer (may include a CNAME chain and wildcard expansion).
Answer { answers: Vec<Record>, additional: Vec<Record>, wildcard: bool, authority: Vec<Record> },
/// CNAME whose target is outside this zone; caller may continue resolution.
CnameOut { answers: Vec<Record>, target: Name },
/// Name exists, type does not.
NoData { soa: Record, proof: Vec<Record> },
/// Name does not exist (possibly after following a CNAME: `answers` holds the chain).
NxDomain { soa: Record, answers: Vec<Record>, proof: Vec<Record> },
/// Delegation to a child zone (not authoritative).
Referral { ns: Vec<Record>, glue: Vec<Record>, ds: Vec<Record> },
}
/// Limit on CNAME chains followed inside one zone.
pub const MAX_CNAME_CHAIN: usize = 8;
fn is_meta(t: RecordType) -> bool {
matches!(t, RecordType::RRSIG | RecordType::NSEC | RecordType::NSEC3)
}
impl Zone {
/// Build and validate a zone from records.
pub fn from_records(origin: &Name, records: Vec<Record>) -> Result<Self, ZoneError> {
Self::from_records_limited(origin, records, usize::MAX)
}
pub fn from_records_limited(origin: &Name, records: Vec<Record>, limit: usize) -> Result<Self, ZoneError> {
if records.len() > limit {
return Err(ZoneError::TooLarge(limit));
}
let mut origin = origin.clone();
origin.set_fqdn(true);
let origin_lower = LowerName::new(&origin);
let mut nodes: HashMap<LowerName, Node> = HashMap::new();
let mut soa: Option<Record> = None;
let mut count = 0;
let mut seen: HashSet<(LowerName, RecordType, String)> = HashSet::new();
for r in records {
if r.dns_class != DNSClass::IN {
return Err(ZoneError::BadClass(r.dns_class.to_string(), r.name.to_string()));
}
let lname = LowerName::new(&r.name);
if !origin_lower.zone_of(&lname) {
return Err(ZoneError::OutOfZone(r.name.to_string(), origin.to_string()));
}
let rtype = r.record_type();
if rtype == RecordType::SOA {
if lname != origin_lower {
return Err(ZoneError::OutOfZone(format!("SOA {}", r.name), origin.to_string()));
}
if soa.is_some() {
// identical duplicate SOA lines are tolerated
if soa.as_ref().map(|s| s.data.to_string()) != Some(r.data.to_string()) {
return Err(ZoneError::MultipleSoa);
}
continue;
}
soa = Some(r.clone());
}
// de-duplicate identical RRs (RFC 2181 §5)
if !seen.insert((lname.clone(), rtype, r.data.to_string())) {
continue;
}
let node = nodes.entry(lname).or_default();
let set_type = if rtype == RecordType::RRSIG {
match &r.data {
RData::DNSSEC(dns_core::proto::dnssec::rdata::DNSSECRData::RRSIG(sig)) => sig.input().type_covered,
_ => rtype,
}
} else {
rtype
};
let set = node.rrsets.entry(set_type).or_insert_with(|| RRset { rtype: set_type, records: Vec::new(), rrsigs: Vec::new() });
if rtype == RecordType::RRSIG {
set.rrsigs.push(r);
} else {
set.records.push(r);
}
count += 1;
}
let soa = soa.ok_or(ZoneError::NoSoa)?;
let apex = nodes.get(&origin_lower);
if apex.and_then(|n| n.rrsets.get(&RecordType::NS)).is_none_or(|s| s.records.is_empty()) {
return Err(ZoneError::NoApexNs);
}
for (name, node) in &nodes {
if let Some(c) = node.rrsets.get(&RecordType::CNAME) {
if c.records.len() > 1 {
return Err(ZoneError::MultipleCname(name.to_string()));
}
if *name == origin_lower {
return Err(ZoneError::CnameAtApex);
}
if node.rrsets.iter().any(|(t, s)| *t != RecordType::CNAME && !is_meta(*t) && !s.records.is_empty()) {
return Err(ZoneError::CnameConflict(name.to_string()));
}
}
}
// normalise RRset TTLs (RFC 2181 §5.2): use the minimum
for node in nodes.values_mut() {
for set in node.rrsets.values_mut() {
let ttl = set.ttl();
for r in &mut set.records {
r.ttl = ttl;
}
}
}
let mut names = HashSet::new();
for n in nodes.keys() {
let mut cur: Name = n.into();
loop {
let l = LowerName::new(&cur);
if !names.insert(l.clone()) || l == origin_lower {
break;
}
cur = cur.base_name();
}
}
let nsec_names = nodes
.iter()
.filter(|(_, n)| n.rrsets.get(&RecordType::NSEC).is_some_and(|s| !s.records.is_empty()))
.map(|(k, _)| Name::from(k).to_lowercase())
.collect();
Ok(Self { origin, origin_lower, nodes, names, soa, count, nsec_names })
}
pub fn origin(&self) -> &Name {
&self.origin
}
pub fn origin_lower(&self) -> &LowerName {
&self.origin_lower
}
pub fn soa(&self) -> &Record {
&self.soa
}
pub fn serial(&self) -> u32 {
match &self.soa.data {
RData::SOA(s) => s.serial,
_ => 0,
}
}
/// (refresh, retry, expire, minimum)
pub fn soa_timers(&self) -> (u32, u32, u32, u32) {
match &self.soa.data {
RData::SOA(s) => (s.refresh.max(0) as u32, s.retry.max(0) as u32, s.expire.max(0) as u32, s.minimum),
_ => (3600, 600, 604_800, 300),
}
}
pub fn record_count(&self) -> usize {
self.count
}
/// Negative-answer SOA with TTL = min(SOA TTL, SOA MINIMUM) (RFC 2308 §3).
pub fn negative_soa(&self) -> Record {
let mut s = self.soa.clone();
if let RData::SOA(d) = &self.soa.data {
s.ttl = s.ttl.min(d.minimum);
}
s
}
/// All records, SOA first (AXFR order). RRSIGs included.
pub fn all_records(&self) -> Vec<Record> {
let mut out = Vec::with_capacity(self.count);
out.push(self.soa.clone());
let mut keys: Vec<&LowerName> = self.nodes.keys().collect();
keys.sort();
for k in keys {
if let Some(node) = self.nodes.get(k) {
let mut types: Vec<&RecordType> = node.rrsets.keys().collect();
types.sort_by_key(|t| u16::from(**t));
for t in types {
if let Some(set) = node.rrsets.get(t) {
for r in &set.records {
if r.record_type() != RecordType::SOA {
out.push(r.clone());
}
}
out.extend(set.rrsigs.iter().cloned());
}
}
}
}
out
}
/// Is the zone DNSSEC-signed (has an NSEC chain)?
pub fn is_signed(&self) -> bool {
!self.nsec_names.is_empty()
}
fn with_sigs(&self, name: &LowerName, t: RecordType) -> Vec<Record> {
self.rrset(name, t).map(|s| s.records.iter().chain(s.rrsigs.iter()).cloned().collect()).unwrap_or_default()
}
/// NSEC (+RRSIG) owned by `name`.
fn nsec_at(&self, name: &Name) -> Vec<Record> {
self.with_sigs(&LowerName::new(name), RecordType::NSEC)
}
/// NSEC (+RRSIG) whose span covers `name` (canonical predecessor, wrapping).
fn nsec_covering(&self, name: &Name) -> Vec<Record> {
let key = name.to_lowercase();
let owner = self.nsec_names.range(..=key).next_back().or_else(|| self.nsec_names.iter().next_back());
owner.map(|o| self.nsec_at(o)).unwrap_or_default()
}
/// SOA (+RRSIG) for negative answers.
fn negative_authority(&self, dnssec: bool) -> (Record, Vec<Record>) {
let soa = self.negative_soa();
let sigs =
if dnssec { self.rrset(&self.origin_lower, RecordType::SOA).map(|s| s.rrsigs.clone()).unwrap_or_default() } else { Vec::new() };
(soa, sigs)
}
fn closest_encloser(&self, name: &Name) -> Name {
let mut ce = name.base_name();
while !self.names.contains(&LowerName::new(&ce)) && ce.num_labels() > self.origin.num_labels() {
ce = ce.base_name();
}
if ce.num_labels() < self.origin.num_labels() { self.origin.clone() } else { ce }
}
fn dedup(mut v: Vec<Record>) -> Vec<Record> {
let mut seen = HashSet::new();
v.retain(|r| seen.insert((r.name.to_lowercase(), r.record_type(), r.data.to_string())));
v
}
/// Get an RRset by exact name/type.
pub fn rrset(&self, name: &LowerName, rtype: RecordType) -> Option<&RRset> {
self.nodes.get(name)?.rrsets.get(&rtype)
}
/// Does the name exist (including empty non-terminals)?
pub fn name_exists(&self, name: &LowerName) -> bool {
self.names.contains(name)
}
fn find_cut(&self, qname: &LowerName) -> Option<(LowerName, &RRset)> {
// Walk from just below the apex down to qname.
let q: Name = qname.into();
let total = q.num_labels();
let apex = self.origin.num_labels();
for n in (apex + 1)..=total {
let cand = LowerName::new(&q.trim_to(n as usize));
if let Some(set) = self.rrset(&cand, RecordType::NS)
&& !set.records.is_empty()
{
return Some((cand, set));
}
}
None
}
fn glue_for(&self, targets: impl Iterator<Item = Name>) -> Vec<Record> {
let mut out = Vec::new();
for t in targets {
let l = LowerName::new(&t);
if !self.origin_lower.zone_of(&l) {
continue;
}
for rt in [RecordType::A, RecordType::AAAA] {
if let Some(s) = self.rrset(&l, rt) {
out.extend(s.records.iter().cloned());
}
}
}
out
}
fn additional_targets(records: &[Record]) -> Vec<Name> {
records
.iter()
.filter_map(|r| match &r.data {
RData::MX(mx) => Some(mx.exchange.clone()),
RData::NS(ns) => Some(ns.0.clone()),
RData::SRV(srv) => Some(srv.target.clone()),
_ => None,
})
.collect()
}
/// Lookup `qname`/`qtype`. `qname` must be at or below the origin. With `dnssec`
/// (DO bit) RRSIGs are included and, for signed zones, NSEC denial proofs.
pub fn lookup(&self, qname: &Name, qtype: RecordType, dnssec: bool) -> Lookup {
let proofs = dnssec && self.is_signed();
let mut answers: Vec<Record> = Vec::new();
let mut authority: Vec<Record> = Vec::new();
let mut current = qname.clone();
let mut wildcard_used = false;
let negative = |answers: Vec<Record>, mut proof: Vec<Record>, nx: bool| -> Lookup {
let (soa, sigs) = self.negative_authority(dnssec);
proof.extend(sigs);
let proof = Self::dedup(proof);
if nx {
Lookup::NxDomain { soa, answers, proof }
} else if answers.is_empty() {
Lookup::NoData { soa, proof }
} else {
// CNAME chain ending in NODATA: still a NOERROR answer with the chain.
Lookup::Answer { answers, additional: Vec::new(), wildcard: false, authority: proof }
}
};
for _ in 0..=MAX_CNAME_CHAIN {
let lq = LowerName::new(&current);
if !self.origin_lower.zone_of(&lq) {
return Lookup::CnameOut { answers, target: current };
}
// Delegation (except DS at the cut, which the parent answers).
if let Some((cut, ns)) = self.find_cut(&lq) {
let ds_at_cut = cut == lq && qtype == RecordType::DS;
if !ds_at_cut {
if !answers.is_empty() {
return Lookup::CnameOut { answers, target: current };
}
let glue = self.glue_for(ns.records.iter().filter_map(|r| match &r.data {
RData::NS(n) => Some(n.0.clone()),
_ => None,
}));
let mut ds = Vec::new();
if dnssec {
ds = self.with_sigs(&cut, RecordType::DS);
if ds.is_empty() && proofs {
ds = self.nsec_at(&Name::from(&cut)); // proves the child is unsigned
}
}
return Lookup::Referral { ns: ns.records.clone(), glue, ds };
}
}
let (node, synth_owner) = if let Some(n) = self.nodes.get(&lq) {
(Some(n), None)
} else if self.names.contains(&lq) {
// empty non-terminal
let proof = if proofs { self.nsec_covering(&current) } else { Vec::new() };
return negative(answers, proof, false);
} else {
let ce = self.closest_encloser(&current);
let wc = match Name::from_ascii("*").and_then(|w| w.append_domain(&ce)) {
Ok(w) => w,
Err(_) => return negative(answers, Vec::new(), true),
};
match self.nodes.get(&LowerName::new(&wc)) {
Some(n) => {
wildcard_used = true;
if proofs {
authority.extend(self.nsec_covering(&current)); // no closer match exists
}
(Some(n), Some((current.clone(), wc)))
}
None => {
let mut proof = Vec::new();
if proofs {
proof.extend(self.nsec_covering(&current));
proof.extend(self.nsec_covering(&wc));
}
return negative(answers, proof, true);
}
}
};
let Some(node) = node else {
return negative(answers, Vec::new(), true);
};
let rewrite = |r: &Record| -> Record {
let mut r = r.clone();
if let Some((o, _)) = &synth_owner {
r.name = o.clone();
}
r
};
let push_set = |set: &RRset, out: &mut Vec<Record>| {
out.extend(set.records.iter().map(rewrite));
if dnssec {
out.extend(set.rrsigs.iter().map(rewrite));
}
};
if qtype == RecordType::ANY {
for (t, set) in &node.rrsets {
if *t != RecordType::RRSIG {
push_set(set, &mut answers);
}
}
let add = self.glue_for(Self::additional_targets(&answers).into_iter());
return Lookup::Answer { answers, additional: add, wildcard: wildcard_used, authority: Self::dedup(authority) };
}
if let Some(set) = node.rrsets.get(&qtype).filter(|s| !s.records.is_empty()) {
push_set(set, &mut answers);
let add = self.glue_for(Self::additional_targets(&set.records).into_iter());
return Lookup::Answer { answers, additional: add, wildcard: wildcard_used, authority: Self::dedup(authority) };
}
if qtype != RecordType::CNAME
&& let Some(set) = node.rrsets.get(&RecordType::CNAME).filter(|s| !s.records.is_empty())
{
push_set(set, &mut answers);
let target = match set.records.first().map(|r| &r.data) {
Some(RData::CNAME(c)) => c.0.clone(),
_ => return Lookup::Answer { answers, additional: Vec::new(), wildcard: wildcard_used, authority },
};
current = target;
continue;
}
// NODATA at an existing (or wildcard-synthesised) name.
let mut proof = authority.clone();
if proofs {
match &synth_owner {
Some((_, wc)) => proof.extend(self.nsec_at(wc)),
None => proof.extend(self.nsec_at(&current)),
}
}
return negative(answers, proof, false);
}
// CNAME chain too long
Lookup::Answer { answers, additional: Vec::new(), wildcard: wildcard_used, authority }
}
/// Compute (removed, added) records to go from `self` to `new` (SOA excluded).
pub fn diff(&self, new: &Zone) -> (Vec<Record>, Vec<Record>) {
let key = |r: &Record| (LowerName::new(&r.name), r.record_type(), r.ttl, r.data.to_string());
let old_set: HashMap<_, Record> =
self.all_records().into_iter().filter(|r| r.record_type() != RecordType::SOA).map(|r| (key(&r), r)).collect();
let new_set: HashMap<_, Record> =
new.all_records().into_iter().filter(|r| r.record_type() != RecordType::SOA).map(|r| (key(&r), r)).collect();
let removed = old_set.iter().filter(|(k, _)| !new_set.contains_key(*k)).map(|(_, r)| r.clone()).collect();
let added = new_set.iter().filter(|(k, _)| !old_set.contains_key(*k)).map(|(_, r)| r.clone()).collect();
(removed, added)
}
/// Apply a diff (removing then adding) and install `new_soa`.
pub fn apply(&self, removed: &[Record], added: &[Record], new_soa: Record, limit: usize) -> Result<Zone, ZoneError> {
let key = |r: &Record| (LowerName::new(&r.name), r.record_type(), r.data.to_string());
let rm: HashSet<_> = removed.iter().map(key).collect();
let mut recs: Vec<Record> =
self.all_records().into_iter().filter(|r| r.record_type() != RecordType::SOA && !rm.contains(&key(r))).collect();
recs.extend(added.iter().filter(|r| r.record_type() != RecordType::SOA).cloned());
recs.push(new_soa);
Zone::from_records_limited(&self.origin, recs, limit)
}
}
/// Shared handle to a zone snapshot.
pub type ZoneRef = Arc<Zone>;
/// Non-fatal zone quality findings (named-checkzone style).
pub fn lint(zone: &Zone) -> Vec<String> {
let mut w = Vec::new();
for (name, node) in &zone.nodes {
for set in node.rrsets.values() {
for r in &set.records {
if r.ttl == 0 && r.record_type() != RecordType::SOA {
w.push(format!("{} {}: TTL is 0", r.name, r.record_type()));
}
let target = match &r.data {
RData::MX(mx) => Some(("MX", mx.exchange.clone())),
RData::NS(ns) => Some(("NS", ns.0.clone())),
RData::SRV(s) => Some(("SRV", s.target.clone())),
_ => None,
};
if let Some((kind, t)) = target {
let lt = LowerName::new(&t);
if zone.origin_lower.zone_of(&lt) {
let has_addr = zone.rrset(&lt, RecordType::A).is_some() || zone.rrset(&lt, RecordType::AAAA).is_some();
let is_cname = zone.rrset(&lt, RecordType::CNAME).is_some();
if is_cname {
w.push(format!("{name} {kind} target {t} is a CNAME (RFC 2181 §10.3)"));
} else if !has_addr && !(kind == "SRV" && t.is_root()) {
w.push(format!("{name} {kind} target {t} has no A/AAAA record in the zone"));
}
}
}
}
}
}
let (refresh, retry, expire, minimum) = zone.soa_timers();
if retry >= refresh {
w.push(format!("SOA retry ({retry}) should be lower than refresh ({refresh})"));
}
if expire < refresh.saturating_add(retry) {
w.push(format!("SOA expire ({expire}) should be greater than refresh + retry"));
}
if minimum > 86_400 {
w.push(format!("SOA minimum/negative TTL ({minimum}) is larger than one day"));
}
w.sort();
w
}
#[cfg(test)]
mod tests {
use super::*;
use dns_core::zonefile::parse_str;
pub(crate) const ZONE: &str = r#"
$TTL 3600
@ IN SOA ns1 hostmaster 2024010101 7200 3600 1209600 300
IN NS ns1
IN NS ns2
IN MX 10 mail
ns1 IN A 192.0.2.1
ns2 IN A 192.0.2.2
mail IN A 192.0.2.25
www IN A 192.0.2.10
www IN AAAA 2001:db8::10
alias IN CNAME www
ext IN CNAME www.example.net.
loop1 IN CNAME loop2
loop2 IN CNAME loop1
*.wild IN A 192.0.2.99
a.b.c IN TXT "deep"
sub IN NS ns.sub
ns.sub IN A 192.0.2.53
sub IN DS 12345 8 2 49FD46E6C4B45C55D4AC69CBD3CD34AC1AFE51DE1A6D5C4C9F2A4DFA2D5E7F3A
"#;
pub(crate) fn zone() -> Zone {
let origin = Name::from_ascii("example.com.").unwrap();
Zone::from_records(&origin, parse_str(ZONE, &origin, None).unwrap()).unwrap()
}
fn n(s: &str) -> Name {
Name::from_ascii(s).unwrap()
}
#[test]
fn positive_and_additional() {
let z = zone();
match z.lookup(&n("example.com."), RecordType::MX, false) {
Lookup::Answer { answers, additional, .. } => {
assert_eq!(answers.len(), 1);
assert_eq!(additional.len(), 1);
}
o => panic!("{o:?}"),
}
// case-insensitive
assert!(matches!(z.lookup(&n("WWW.Example.COM."), RecordType::AAAA, false), Lookup::Answer { .. }));
}
#[test]
fn negative() {
let z = zone();
match z.lookup(&n("www.example.com."), RecordType::TXT, false) {
Lookup::NoData { soa, .. } => assert_eq!(soa.ttl, 300),
o => panic!("{o:?}"),
}
assert!(matches!(z.lookup(&n("nope.example.com."), RecordType::A, false), Lookup::NxDomain { .. }));
// empty non-terminal b.c → NODATA, not NXDOMAIN
assert!(matches!(z.lookup(&n("b.c.example.com."), RecordType::A, false), Lookup::NoData { .. }));
assert!(matches!(z.lookup(&n("c.example.com."), RecordType::A, false), Lookup::NoData { .. }));
}
#[test]
fn cname_chain() {
let z = zone();
match z.lookup(&n("alias.example.com."), RecordType::A, false) {
Lookup::Answer { answers, .. } => {
assert_eq!(answers.len(), 2);
assert_eq!(answers[0].record_type(), RecordType::CNAME);
}
o => panic!("{o:?}"),
}
assert!(
matches!(z.lookup(&n("alias.example.com."), RecordType::CNAME, false), Lookup::Answer { ref answers, .. } if answers.len() == 1)
);
assert!(matches!(z.lookup(&n("ext.example.com."), RecordType::A, false), Lookup::CnameOut { .. }));
// loops terminate
let _ = z.lookup(&n("loop1.example.com."), RecordType::A, false);
}
#[test]
fn wildcard() {
let z = zone();
match z.lookup(&n("foo.wild.example.com."), RecordType::A, false) {
Lookup::Answer { answers, wildcard, .. } => {
assert!(wildcard);
assert_eq!(answers[0].name, n("foo.wild.example.com."));
}
o => panic!("{o:?}"),
}
assert!(matches!(z.lookup(&n("x.y.wild.example.com."), RecordType::A, false), Lookup::Answer { .. }));
assert!(matches!(z.lookup(&n("foo.wild.example.com."), RecordType::MX, false), Lookup::NoData { .. }));
}
#[test]
fn delegation() {
let z = zone();
match z.lookup(&n("host.sub.example.com."), RecordType::A, false) {
Lookup::Referral { ns, glue, .. } => {
assert_eq!(ns.len(), 1);
assert_eq!(glue.len(), 1);
}
o => panic!("{o:?}"),
}
// DS at the cut is answered by the parent.
assert!(matches!(z.lookup(&n("sub.example.com."), RecordType::DS, false), Lookup::Answer { .. }));
match z.lookup(&n("sub.example.com."), RecordType::A, true) {
Lookup::Referral { ds, .. } => assert_eq!(ds.len(), 1),
o => panic!("{o:?}"),
}
}
#[test]
fn validation_errors() {
let origin = n("example.com.");
let bad = "@ IN SOA ns hm 1 2 3 4 5\n@ IN NS ns\nx IN CNAME y\nx IN A 192.0.2.1\n";
assert_eq!(
Zone::from_records(&origin, parse_str(bad, &origin, None).unwrap()).unwrap_err(),
ZoneError::CnameConflict("x.example.com.".into())
);
let nons = "@ IN SOA ns hm 1 2 3 4 5\n";
assert_eq!(Zone::from_records(&origin, parse_str(nons, &origin, None).unwrap()).unwrap_err(), ZoneError::NoApexNs);
let oz = "@ IN SOA ns hm 1 2 3 4 5\n@ IN NS ns\nwww.example.org. IN A 192.0.2.1\n";
assert!(matches!(Zone::from_records(&origin, parse_str(oz, &origin, None).unwrap()), Err(ZoneError::OutOfZone(..))));
}
#[test]
fn diff_apply_roundtrip() {
let z = zone();
let origin = n("example.com.");
let text = ZONE.replace("2024010101", "2024010102").replace("192.0.2.10", "192.0.2.11");
let z2 = Zone::from_records(&origin, parse_str(&text, &origin, None).unwrap()).unwrap();
let (rm, add) = z.diff(&z2);
assert_eq!((rm.len(), add.len()), (1, 1));
let z3 = z.apply(&rm, &add, z2.soa().clone(), usize::MAX).unwrap();
assert_eq!(z3.serial(), 2024010102);
let (rm, add) = z3.diff(&z2);
assert!(rm.is_empty() && add.is_empty());
}
#[test]
fn lint_findings() {
let origin = n("example.com.");
let t = "@ IN SOA ns hm 1 3600 7200 100 5\n@ IN NS ns\n@ IN MX 10 nomail\n";
let z = Zone::from_records(&origin, parse_str(t, &origin, None).unwrap()).unwrap();
let w = lint(&z);
assert!(w.iter().any(|s| s.contains("retry")));
assert!(w.iter().any(|s| s.contains("nomail")));
}
}