feat(dns): publish live config and aggregate distinct zones (#2819)

Publish complete DNS configuration and node routes from each local
instance, and combine contributions from distinct static zones. Reject
conflicts while retaining accepted contributions until replacement or
connection withdrawal.

Accept requests from released clients that omit instance_id by owning
their records through the local publishing connection. Delay DNS RPC
registration until the internally managed route, zones, and packet
resolver are ready.

Validation: contribution and protocol lifecycle tests, released v2.6.4
client interoperability, root/TUN regression tests, fmt, strict Clippy,
and the required CI checks passed on the reviewed head. Native
Windows/macOS route-failure injection was not performed.

Retain the disclosed deferred minors and the pre-existing shared-TUN
external-route readiness boundary; these are not claimed fixed.
This commit is contained in:
KKRainbow
2026-11-12 10:26:21 +08:00
committed by GitHub
parent 2abb1676b4
commit 4f36fc1ffc
13 changed files with 1719 additions and 621 deletions
+35 -15
View File
@@ -1,4 +1,4 @@
# Local Magic DNS records
# Magic DNS records
Enable Magic DNS and configure static records in the same TOML file:
@@ -136,7 +136,10 @@ example, `[dns]` followed by `domain = "mesh.test."` changes only the domain.
`easytier-cli dns clear` clears static zones and preserves the domain. Writes
require one instance; use `--instance-id` or `--instance-name` when necessary.
The CLI reads the configuration back before reporting success. This checks
saved configuration, not DNS answers; restart the instance to publish changes.
saved configuration. The running instance publishes the current DNS configuration
through its existing local Magic DNS connection every 500 ms, together with its
node routes, even when the routes have not changed. Saving does not wait for
publication or verify DNS answers.
As with other patches, the instance's backing file is updated when configured.
For instances without a backing file, export the updated configuration and use
it on restart.
@@ -154,18 +157,35 @@ core capabilities. This adds no DNS form or runtime status to the Web UI.
## Runtime boundary
Static records come from the local configuration of the EasyTier instance that
wins the local Magic DNS server election. They coexist with automatically
generated node records and survive route updates. Configuration changes take
effect when the instance restarts. If the elected instance has no `[dns]`
configuration, no static records are served, even when another local instance
has some. Records are not distributed to other machines.
Every participating EasyTier instance publishes its complete static configuration
to the elected Magic DNS server on the same machine. Different static zone origins
are combined and coexist with automatically generated node records. An update
replaces that instance's entire contribution: changing or clearing zones removes
its old records, while other instances' contributions remain. Disconnecting a
publishing connection withdraws its contribution. After server election or
reconnection, the periodic upload restores the current configuration. This is
eventually consistent and adds no publication acknowledgement or status API.
Records are not distributed to other machines.
Only the elected instance's configured zones are added to the system resolver
match list, after the default zone. Configured zones are authoritative: a name
missing from a configured zone does not fall back to system DNS. Queries outside
those zones retain the existing forwarding behavior.
Released local DNS clients such as v2.6.4 can continue publishing automatic
node routes without an instance UUID. Their contributions remain owned by the
publishing connection and are replaced on update and withdrawn on disconnect.
Static DNS contributions require a supporting client.
This does not change Magic DNS activation, the fixed DNS address, TUN
requirements, platform DNS setup or node record RPC. Systems without automatic
DNS setup must continue to configure their resolver manually.
Static zone origins must be distinct across active publishers after normalization.
An update that overlaps another instance's static origin is rejected as a whole;
its previously accepted contribution remains until a later valid upload or
disconnect. The first accepted contribution retains that origin. Automatic node
routes can still share a zone. An automatic node name that conflicts with a
configured CNAME also rejects the update. This does not add record-level conflict
resolution or merge static RRsets from different instances.
The system resolver match list includes active node domains and configured
origins, with the elected instance's current default domain first. Configured
zones are authoritative: a name missing from a configured zone does not fall back
to system DNS. Removing a static-only zone restores the existing forwarding
behavior there; empty former node zones remain authoritative as before.
This does not change Magic DNS activation, the fixed DNS address or TUN
requirements. Systems without automatic DNS setup must continue to configure
their resolver manually.
+2
View File
@@ -1,8 +1,10 @@
mod configuration;
mod records;
#[cfg(feature = "proxy-packet")]
mod packet;
pub use configuration::{Zone, configured_zones, dns_domain, normalized_dns, parse_origin};
pub use records::{
MagicDnsRecordSnapshot, MagicDnsRecordStore, MagicDnsRoute, MagicDnsRouteAdvertisement,
MagicDnsRoutePublisher, MagicDnsRouteSnapshot, MagicDnsRouteSource,
@@ -0,0 +1,86 @@
use crate::config::dns::compile_dns;
pub use crate::config::dns::{DnsZone as Zone, parse_origin};
use crate::config::toml::{ConfigLoader, DEFAULT_ET_DNS_ZONE, DnsConfig};
use anyhow::Context;
use hickory_proto::rr::LowerName;
use std::collections::BTreeMap;
/// Resolves the default Magic DNS zone origin from `dns.domain`, falling back
/// to the deprecated `flags.tld_dns_zone` patch when `dns.domain` is unset, and
/// finally to [`DEFAULT_ET_DNS_ZONE`].
#[allow(deprecated)]
pub fn dns_domain(config: &impl ConfigLoader) -> anyhow::Result<LowerName> {
let dns = config.get_dns();
if let Some(domain) = dns.as_ref().and_then(|dns| dns.domain.as_deref()) {
return parse_origin(domain).context("invalid dns.domain");
}
if let Some(legacy) = config.get_flags_patch().tld_dns_zone.as_deref()
&& !legacy.is_empty()
{
return parse_origin(legacy).context("invalid flags.tld_dns_zone");
}
parse_origin(DEFAULT_ET_DNS_ZONE)
}
/// Compiles the complete contribution using shared configuration validation.
pub fn configured_zones(dns: Option<&DnsConfig>) -> anyhow::Result<BTreeMap<LowerName, Vec<Zone>>> {
let Some(dns) = dns else {
return Ok(BTreeMap::new());
};
Ok(compile_dns(dns)?
.into_iter()
.map(|(origin, zone)| (origin, vec![zone]))
.collect())
}
/// Resolves contribution metadata without rewriting structured record input.
pub fn normalized_dns(config: &impl ConfigLoader) -> anyhow::Result<DnsConfig> {
let dns = config.get_dns();
if let Some(dns) = &dns {
compile_dns(dns)?;
}
let mut zones = dns.and_then(|dns| dns.zone).unwrap_or_default().items;
for zone in &mut zones {
zone.origin = parse_origin(&zone.origin)?.to_string();
}
zones.sort_by(|left, right| left.origin.cmp(&right.origin));
Ok(DnsConfig {
domain: Some(dns_domain(config)?.to_string()),
zone: Some(zones.into()),
})
}
#[cfg(test)]
mod tests {
use super::*;
use crate::config::toml::TomlConfig;
#[test]
fn contribution_normalization_preserves_structured_record_input() {
let config = TomlConfig::new_from_str(
r#"
[dns]
domain = "MESH.test"
[[dns.zone]]
origin = "RECORDS.test"
ttl = 60
records = [
{ name = "info", type = "TXT", ttl = 0, value = '"space quote\" slash\\ semicolon;" "tail"' },
{ name = "alias", type = "CNAME", value = "info" },
]
"#,
)
.unwrap();
let original = config.get_dns().unwrap();
let normalized = normalized_dns(&config).unwrap();
assert_eq!(normalized.domain.as_deref(), Some("mesh.test."));
let zone = &normalized.zone.as_ref().unwrap().items[0];
assert_eq!(zone.origin, "records.test.");
assert_eq!(
zone.records,
original.zone.as_ref().unwrap().items[0].records
);
config.set_dns(Some(normalized.clone()));
assert_eq!(normalized_dns(&config).unwrap(), normalized);
}
}
+134 -189
View File
@@ -82,110 +82,135 @@ pub trait MagicDnsRoutePublisher: Send {
pub async fn run_magic_dns_route_publisher<S, P>(
source: &S,
publisher: &mut P,
unchanged_interval: Duration,
interval: Duration,
) -> anyhow::Result<()>
where
S: MagicDnsRouteSource + ?Sized,
P: MagicDnsRoutePublisher + ?Sized,
{
let mut published_revision = None;
publisher.handshake().await?;
loop {
publisher.heartbeat().await?;
let snapshot = source.snapshot().await;
if published_revision == Some(snapshot.revision) {
crate::foundation::time::sleep(unchanged_interval).await;
continue;
}
publisher.publish(&snapshot).await?;
if source.revision().await == snapshot.revision {
published_revision = Some(snapshot.revision);
}
crate::foundation::time::sleep(interval).await;
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
/// One instance's contribution, owned by its long-lived publishing connection.
#[derive(Debug, Clone, PartialEq)]
pub struct MagicDnsClientRecord {
pub source: Option<String>,
pub zone: LowerName,
pub routes: Vec<MagicDnsRoute>,
pub configured: BTreeMap<LowerName, Vec<super::Zone>>,
}
#[derive(Debug, Clone, Default)]
pub struct MagicDnsRecordSnapshot {
pub clients: BTreeMap<String, MagicDnsClientRecord>,
pub zones: BTreeMap<LowerName, Vec<MagicDnsRoute>>,
}
impl MagicDnsRecordSnapshot {
pub fn from_clients(clients: BTreeMap<String, MagicDnsClientRecord>) -> Self {
let mut zones: BTreeMap<LowerName, Vec<MagicDnsRoute>> = BTreeMap::new();
for client in clients.values() {
zones
.entry(client.zone.clone())
.or_default()
.extend(client.routes.clone());
}
Self { clients, zones }
}
pub fn configured_origins(&self) -> impl Iterator<Item = &LowerName> {
self.clients
.values()
.flat_map(|client| client.configured.keys())
}
}
#[derive(Debug, Default)]
pub struct MagicDnsRecordStore {
zones: Mutex<BTreeMap<LowerName, BTreeMap<String, Vec<MagicDnsRoute>>>>,
clients: Mutex<BTreeMap<String, MagicDnsClientRecord>>,
}
impl MagicDnsRecordStore {
/// Replaces one client's routes within a zone.
///
/// Returns `true` when the update removed the final client from an
/// existing zone. The host can use that signal to keep an empty zone
/// authoritative.
pub fn replace_client_routes(
/// Prepares a replacement without changing accepted state. The caller must
/// serialize preparation and commit with its authority application lock.
pub fn replacement(
&self,
instance_id: String,
source: Option<String>,
zone: LowerName,
client: String,
routes: Vec<MagicDnsRoute>,
) -> bool {
let mut zones = self.zones.lock().unwrap();
let Some(routes_by_client) = zones.get_mut(&zone) else {
if !routes.is_empty() {
zones.entry(zone).or_default().insert(client, routes);
}
return false;
dns: crate::config::toml::DnsConfig,
) -> anyhow::Result<MagicDnsRecordSnapshot> {
// Released DNS clients omit the instance UUID and own their records
// through the publishing connection, as before static DNS support.
let instance_id = if instance_id.is_empty() {
let source = source
.as_ref()
.ok_or_else(|| anyhow::anyhow!("Legacy DNS records require a connection"))?;
format!("legacy:{source}")
} else {
uuid::Uuid::parse_str(&instance_id)?.to_string()
};
routes_by_client.remove(&client);
if !routes.is_empty() {
routes_by_client.insert(client, routes);
let mut clients = self.clients.lock().unwrap().clone();
let previous = clients.get(&instance_id);
if let Some(owner) = previous.and_then(|client| client.source.as_ref()) {
anyhow::ensure!(
Some(owner) == source.as_ref(),
"DNS instance {instance_id} belongs to another active connection"
);
}
if !routes_by_client.is_empty() {
return false;
if let Some(source) = source.as_ref() {
anyhow::ensure!(
!clients.iter().any(
|(id, client)| id != &instance_id && client.source.as_ref() == Some(source)
),
"DNS connection already belongs to another instance"
);
}
zones.remove(&zone);
true
let configured = super::configured_zones(Some(&dns))?;
for origin in configured.keys() {
anyhow::ensure!(
!clients.iter().any(|(id, client)| {
id != &instance_id && client.configured.contains_key(origin)
}),
"DNS zone {origin} is already configured by another instance"
);
}
clients.insert(
instance_id,
MagicDnsClientRecord {
source,
zone,
routes,
configured,
},
);
Ok(MagicDnsRecordSnapshot::from_clients(clients))
}
/// Removes a disconnected client from every zone and returns the zones
/// that became empty.
pub fn remove_client(&self, client: &str) -> Vec<LowerName> {
let mut zones = self.zones.lock().unwrap();
let mut removed_zones = Vec::new();
zones.retain(|zone, routes_by_client| {
routes_by_client.remove(client);
let retain = !routes_by_client.is_empty();
if !retain {
removed_zones.push(zone.clone());
}
retain
});
removed_zones
pub fn without_source(&self, source: &str) -> MagicDnsRecordSnapshot {
let mut clients = self.clients.lock().unwrap().clone();
clients.retain(|_, client| client.source.as_deref() != Some(source));
MagicDnsRecordSnapshot::from_clients(clients)
}
pub fn commit(&self, snapshot: MagicDnsRecordSnapshot) {
*self.clients.lock().unwrap() = snapshot.clients;
}
pub fn snapshot(&self) -> MagicDnsRecordSnapshot {
let zones = self.zones.lock().unwrap();
MagicDnsRecordSnapshot {
zones: zones
.iter()
.map(|(zone, routes_by_client)| {
(
zone.clone(),
routes_by_client
.values()
.flat_map(|routes| routes.iter().cloned())
.collect(),
)
})
.collect(),
}
MagicDnsRecordSnapshot::from_clients(self.clients.lock().unwrap().clone())
}
}
#[cfg(test)]
mod tests {
use std::sync::Arc;
use super::*;
#[test]
@@ -224,14 +249,14 @@ mod tests {
}
struct TestRouteSource {
revision: Mutex<Instant>,
revision: Instant,
}
#[async_trait]
impl MagicDnsRouteSource for TestRouteSource {
async fn snapshot(&self) -> MagicDnsRouteSnapshot {
MagicDnsRouteSnapshot {
revision: *self.revision.lock().unwrap(),
revision: self.revision,
routes: vec![MagicDnsRouteAdvertisement {
hostname: "node-a".to_owned(),
ipv4_addr: Some("10.1.0.1/24".parse::<cidr::Ipv4Inet>().unwrap().into()),
@@ -240,15 +265,13 @@ mod tests {
}
async fn revision(&self) -> Instant {
*self.revision.lock().unwrap()
self.revision
}
}
struct TestRoutePublisher {
source: Arc<TestRouteSource>,
heartbeat_calls: usize,
fail_heartbeat_at: usize,
change_revision_on_first_publish: bool,
handshake_calls: usize,
snapshots: Vec<MagicDnsRouteSnapshot>,
}
@@ -270,147 +293,69 @@ mod tests {
async fn publish(&mut self, snapshot: &MagicDnsRouteSnapshot) -> anyhow::Result<()> {
self.snapshots.push(snapshot.clone());
if self.change_revision_on_first_publish && self.snapshots.len() == 1 {
*self.source.revision.lock().unwrap() = snapshot.revision + Duration::from_secs(1);
}
Ok(())
}
}
fn test_publisher(source: Arc<TestRouteSource>) -> TestRoutePublisher {
fn test_publisher() -> TestRoutePublisher {
TestRoutePublisher {
source,
heartbeat_calls: 0,
fail_heartbeat_at: 3,
change_revision_on_first_publish: false,
handshake_calls: 0,
snapshots: Vec::new(),
}
}
#[tokio::test]
async fn route_publisher_skips_unchanged_snapshot() {
let source = Arc::new(TestRouteSource {
revision: Mutex::new(Instant::now()),
});
let mut publisher = test_publisher(source.clone());
async fn route_publisher_repeats_complete_unchanged_snapshot() {
let source = TestRouteSource {
revision: Instant::now(),
};
let mut publisher = test_publisher();
let error = run_magic_dns_route_publisher(
source.as_ref(),
&mut publisher,
Duration::from_millis(1),
)
.await
.unwrap_err();
let error =
run_magic_dns_route_publisher(&source, &mut publisher, Duration::from_millis(1))
.await
.unwrap_err();
assert!(error.to_string().contains("stop test publisher"));
assert_eq!(publisher.handshake_calls, 1);
assert_eq!(publisher.snapshots.len(), 1);
}
#[tokio::test]
async fn route_publisher_retries_change_during_publish() {
let source = Arc::new(TestRouteSource {
revision: Mutex::new(Instant::now()),
});
let mut publisher = test_publisher(source.clone());
publisher.change_revision_on_first_publish = true;
let error = run_magic_dns_route_publisher(
source.as_ref(),
&mut publisher,
Duration::from_millis(1),
)
.await
.unwrap_err();
assert!(error.to_string().contains("stop test publisher"));
assert_eq!(publisher.snapshots.len(), 2);
assert_ne!(
publisher.snapshots[0].revision,
publisher.snapshots[1].revision
);
assert_eq!(publisher.snapshots[0], publisher.snapshots[1]);
}
fn route(hostname: &str, addr: [u8; 4]) -> MagicDnsRoute {
MagicDnsRoute {
hostname: hostname.to_owned(),
ipv4_addr: Some(addr.into()),
}
fn contribution(
store: &MagicDnsRecordStore,
id: &str,
source: &str,
dns: crate::config::toml::DnsConfig,
) -> anyhow::Result<MagicDnsRecordSnapshot> {
store.replacement(
id.to_owned(),
Some(source.to_owned()),
"et.net.".parse().unwrap(),
vec![],
dns,
)
}
#[test]
fn replaces_routes_for_the_same_client_without_touching_other_clients() {
let zone: LowerName = "et.net.".parse().unwrap();
fn contribution_ownership_replacement_and_withdrawal() {
let store = MagicDnsRecordStore::default();
assert!(!store.replace_client_routes(
zone.clone(),
"tcp://client-a".to_owned(),
vec![route("old-a", [10, 0, 0, 1])],
));
assert!(!store.replace_client_routes(
zone.clone(),
"tcp://client-b".to_owned(),
vec![route("peer-b", [10, 0, 0, 2])],
));
assert!(!store.replace_client_routes(
zone.clone(),
"tcp://client-a".to_owned(),
vec![route("new-a", [10, 0, 0, 3])],
));
let routes = &store.snapshot().zones[&zone];
assert_eq!(routes.len(), 2);
assert!(routes.iter().any(|route| route.hostname == "new-a"));
assert!(routes.iter().any(|route| route.hostname == "peer-b"));
assert!(!routes.iter().any(|route| route.hostname == "old-a"));
}
#[test]
fn empty_update_removes_only_the_target_client_and_reports_empty_zone() {
let zone: LowerName = "et.net.".parse().unwrap();
let store = MagicDnsRecordStore::default();
store.replace_client_routes(
zone.clone(),
"tcp://client-a".to_owned(),
vec![route("peer-a", [10, 0, 0, 1])],
);
store.replace_client_routes(
zone.clone(),
"tcp://client-b".to_owned(),
vec![route("peer-b", [10, 0, 0, 2])],
);
assert!(!store.replace_client_routes(
zone.clone(),
"tcp://client-a".to_owned(),
Vec::new(),
));
assert!(store.replace_client_routes(zone, "tcp://client-b".to_owned(), Vec::new()));
assert!(store.snapshot().zones.is_empty());
}
#[test]
fn disconnect_removes_client_from_all_zones() {
let store = MagicDnsRecordStore::default();
let zone_a: LowerName = "a.et.net.".parse().unwrap();
let zone_b: LowerName = "b.et.net.".parse().unwrap();
for zone in [&zone_a, &zone_b] {
store.replace_client_routes(
zone.clone(),
"tcp://client-a".to_owned(),
vec![route("peer-a", [10, 0, 0, 1])],
);
}
store.replace_client_routes(
zone_b.clone(),
"tcp://client-b".to_owned(),
vec![route("peer-b", [10, 0, 0, 2])],
);
assert_eq!(store.remove_client("tcp://client-a"), vec![zone_a]);
let snapshot = store.snapshot();
assert_eq!(snapshot.zones.len(), 1);
assert_eq!(snapshot.zones[&zone_b][0].hostname, "peer-b");
let id = uuid::Uuid::new_v4().to_string();
let dns = crate::config::toml::DnsConfig {
domain: Some("et.net.".to_owned()),
zone: Some(vec![].into()),
};
store.commit(contribution(&store, &id, "client-a", dns.clone()).unwrap());
assert_eq!(store.snapshot().clients.len(), 1);
assert!(contribution(&store, &id, "client-b", dns.clone()).is_err());
store.commit(contribution(&store, &id, "client-a", dns.clone()).unwrap());
assert!(store.snapshot().clients[&id].configured.is_empty());
store.commit(store.without_source("client-b"));
assert_eq!(store.snapshot().clients.len(), 1);
store.commit(store.without_source("client-a"));
assert!(store.snapshot().clients.is_empty());
assert!(contribution(&store, &id, "client-b", dns).is_ok());
}
}
+3
View File
@@ -3,6 +3,7 @@ syntax = "proto3";
import "google/protobuf/timestamp.proto";
import "common.proto";
import "api_instance.proto";
import "core_config.proto";
package magic_dns;
@@ -31,6 +32,8 @@ message DnsRecordList {
message UpdateDnsRecordRequest {
string zone = 1;
repeated api.instance.Route routes = 2;
string instance_id = 3;
core_config.DnsConfigRaw dns = 4;
}
message GetDnsRecordResponse {
@@ -1,20 +1,23 @@
use std::{sync::Arc, time::Duration};
use easytier_core::gateway::magic_dns::{
MagicDnsRoutePublisher, MagicDnsRouteSnapshot, run_magic_dns_route_publisher,
MagicDnsRoutePublisher, MagicDnsRouteSnapshot, normalized_dns, run_magic_dns_route_publisher,
};
use easytier_core::instance::CorePacketPlane;
use hickory_proto::rr::LowerName;
use tokio::task::JoinSet;
use crate::proto::{
api::instance::Route,
common::Void,
magic_dns::{
HandshakeRequest, MagicDnsServerRpc, MagicDnsServerRpcClientFactory, UpdateDnsRecordRequest,
use crate::{
common::global_ctx::ArcGlobalCtx,
proto::{
api::instance::Route,
common::Void,
magic_dns::{
HandshakeRequest, MagicDnsServerRpc, MagicDnsServerRpcClientFactory,
UpdateDnsRecordRequest,
},
rpc::standalone::{RuntimeRpcClient, runtime_rpc_client},
rpc_types::{controller::BaseController, error::Error as RpcError},
},
rpc::standalone::{RuntimeRpcClient, runtime_rpc_client},
rpc_types::controller::BaseController,
};
use super::MAGIC_DNS_INSTANCE_ADDR;
@@ -23,13 +26,13 @@ pub struct MagicDnsClientInstance {
rpc_client: RuntimeRpcClient,
rpc_stub: Option<Box<dyn MagicDnsServerRpc<Controller = BaseController> + Send>>,
route_source: Arc<CorePacketPlane>,
zone: LowerName,
global_ctx: ArcGlobalCtx,
tasks: JoinSet<()>,
}
struct RpcMagicDnsRoutePublisher {
rpc_stub: Box<dyn MagicDnsServerRpc<Controller = BaseController> + Send>,
zone: LowerName,
global_ctx: ArcGlobalCtx,
}
#[async_trait::async_trait]
@@ -49,6 +52,7 @@ impl MagicDnsRoutePublisher for RpcMagicDnsRoutePublisher {
}
async fn publish(&mut self, snapshot: &MagicDnsRouteSnapshot) -> anyhow::Result<()> {
let dns = normalized_dns(&self.global_ctx.config)?;
let request = UpdateDnsRecordRequest {
routes: snapshot
.routes
@@ -59,23 +63,30 @@ impl MagicDnsRoutePublisher for RpcMagicDnsRoutePublisher {
..Default::default()
})
.collect(),
zone: self.zone.to_string(),
zone: dns.domain.clone().unwrap(),
instance_id: self.global_ctx.get_id().to_string(),
dns: Some(dns),
};
tracing::debug!(
"MagicDnsClientInstance::update_dns_task: update dns records: {:?}",
request
);
self.rpc_stub
match self
.rpc_stub
.update_dns_record(BaseController::default(), request)
.await?;
Ok(())
.await
{
Ok(_) => Ok(()),
Err(RpcError::ExecutionError(error)) => {
// Keep accepted records and this connection until a later snapshot succeeds.
tracing::warn!(?error, "DNS contribution rejected");
Ok(())
}
Err(error) => Err(error.into()),
}
}
}
impl MagicDnsClientInstance {
pub(crate) async fn new(
route_source: Arc<CorePacketPlane>,
zone: LowerName,
global_ctx: ArcGlobalCtx,
) -> Result<Self, anyhow::Error> {
let mut rpc_client = runtime_rpc_client(MAGIC_DNS_INSTANCE_ADDR.parse().unwrap());
let rpc_stub = rpc_client
@@ -85,42 +96,35 @@ impl MagicDnsClientInstance {
rpc_client,
rpc_stub: Some(rpc_stub),
route_source,
zone,
global_ctx,
tasks: JoinSet::new(),
})
}
async fn update_dns_task(
route_source: Arc<CorePacketPlane>,
rpc_stub: Box<dyn MagicDnsServerRpc<Controller = BaseController> + Send>,
zone: LowerName,
) -> Result<(), anyhow::Error> {
let mut publisher = RpcMagicDnsRoutePublisher { rpc_stub, zone };
run_magic_dns_route_publisher(
route_source.as_ref(),
&mut publisher,
Duration::from_millis(500),
)
.await
}
pub async fn run_and_wait(&mut self) {
let rpc_stub = self.rpc_stub.take().unwrap();
let route_source = self.route_source.clone();
let zone = self.zone.clone();
let mut publisher = RpcMagicDnsRoutePublisher {
rpc_stub: self.rpc_stub.take().unwrap(),
global_ctx: self.global_ctx.clone(),
};
self.tasks.spawn(async move {
let ret = Self::update_dns_task(route_source, rpc_stub, zone).await;
if let Err(e) = ret {
tracing::error!("MagicDnsServerInstanceData::run_and_wait: {:?}", e);
if let Err(error) = run_magic_dns_route_publisher(
route_source.as_ref(),
&mut publisher,
Duration::from_millis(500),
)
.await
{
tracing::error!(?error, "DNS publishing task exited");
}
});
tokio::select! {
_ = self.tasks.join_next() => {
tracing::warn!("MagicDnsServerInstanceData::run_and_wait: dns record update task exited");
tracing::warn!("DNS record update task exited");
}
_ = self.rpc_client.wait() => {
tracing::warn!("MagicDnsServerInstanceData::run_and_wait: rpc client exited");
tracing::warn!("DNS RPC client exited");
}
}
}
+2
View File
@@ -9,6 +9,8 @@ pub(crate) mod zone;
#[cfg(all(feature = "magic-dns", feature = "tun"))]
pub mod client_instance;
#[cfg(all(feature = "magic-dns", feature = "tun"))]
mod records;
#[cfg(all(feature = "magic-dns", feature = "tun"))]
pub mod runner;
#[cfg(all(feature = "magic-dns", feature = "tun"))]
pub mod server_instance;
@@ -0,0 +1,89 @@
use std::{
collections::{BTreeMap, BTreeSet},
sync::Arc,
time::Duration,
};
use easytier_core::gateway::magic_dns::MagicDnsRecordSnapshot;
use hickory_proto::rr::{LowerName, Name, Record, RecordType, RrKey};
use hickory_server::{authority::ZoneType, store::in_memory::InMemoryAuthority};
use super::config::{RecordBuilder, RecordType as ConfigRecordType};
pub(super) fn build_authorities(
snapshot: &MagicDnsRecordSnapshot,
origins: BTreeSet<LowerName>,
) -> anyhow::Result<BTreeMap<LowerName, Arc<InMemoryAuthority>>> {
let configured: BTreeMap<_, _> = snapshot
.clients
.values()
.flat_map(|client| &client.configured)
.collect();
let mut authorities = BTreeMap::new();
for origin in origins {
let mut authority = InMemoryAuthority::empty(Name::from(&origin), ZoneType::Primary, false);
for route in snapshot.zones.get(&origin).into_iter().flatten() {
if route.hostname.is_empty() {
continue;
}
let Some(address) = route.ipv4_addr else {
continue;
};
let record = RecordBuilder::default()
.rr_type(ConfigRecordType::A)
.name(format!("{}.{}", route.hostname, origin))
.value(address.to_string())
.ttl(Duration::from_secs(1))
.build()?;
let record: Record = match (&record).try_into() {
Ok(record) => record,
Err(error) => {
tracing::warn!(?error, "invalid DNS node name");
continue;
}
};
anyhow::ensure!(
!configured
.get(&origin)
.into_iter()
.flat_map(|zones| zones.iter())
.any(|zone| {
zone.records.contains_key(&RrKey::new(
LowerName::new(record.name()),
RecordType::CNAME,
))
}),
"automatic DNS record {} conflicts with configured records in {origin}",
record.name()
);
// A route can be advertised by several local instances.
authority.upsert_mut(record, 0);
}
let mut has_soa = false;
if let Some(zones) = configured.get(&origin) {
for record in zones
.iter()
.flat_map(|zone| zone.records.values())
.flat_map(|set| set.records_without_rrsigs())
{
has_soa |= record.record_type() == RecordType::SOA;
// Preserve configured TTLs when static and automatic A
// records share an RRset, as at local-only startup.
authority.upsert_mut(record.clone(), 0);
}
}
if !has_soa {
let soa = RecordBuilder::default()
.rr_type(ConfigRecordType::SOA)
.name(origin.to_string())
.value(format!(
"ns.{origin} hostmaster.{origin} 2023101001 7200 3600 1209600 86400"
))
.ttl(Duration::from_secs(60))
.build()?;
authority.upsert_mut((&soa).try_into()?, 0);
}
authorities.insert(origin, Arc::new(authority));
}
Ok(authorities)
}
+4 -2
View File
@@ -143,8 +143,10 @@ impl DnsRunner {
tokio::select! {
_ = cancel_token.cancelled() => Ok(()),
ret = async {
let zone = super::zone::dns_domain(&self.global_ctx.config)?;
let client = MagicDnsClientInstance::new(self.packet_plane.clone(), zone).await?;
let client = MagicDnsClientInstance::new(
self.packet_plane.clone(),
self.global_ctx.clone(),
).await?;
self.client = Some(client);
self.client.as_mut().unwrap().run_and_wait().await;
Err(anyhow::anyhow!("Client instance exit"))
+152 -23
View File
@@ -12,13 +12,15 @@ use hickory_server::authority::{
use hickory_server::server::{Request, RequestHandler, RequestInfo, ResponseHandler, ResponseInfo};
use hickory_server::store::forwarder::ForwardConfig;
use hickory_server::store::{forwarder::ForwardAuthority, in_memory::InMemoryAuthority};
use std::collections::{BTreeMap, HashSet};
use std::collections::{BTreeMap, BTreeSet, HashSet};
use std::net::SocketAddr;
use std::str::FromStr;
use std::sync::Arc;
use std::time::Duration;
use tokio::net::{TcpListener, UdpSocket};
use tokio::sync::{RwLock, RwLockReadGuard};
use tokio::sync::RwLock;
#[cfg(test)]
use tokio::sync::RwLockReadGuard;
use crate::common::dns::get_default_resolver_config;
@@ -182,14 +184,27 @@ impl RequestHandler for CatalogRequestHandler {
request: &Request,
response_handle: R,
) -> ResponseInfo {
self.catalog
.read()
.await
.handle_request(request, response_handle)
.await
handle_request(&self.catalog, request, response_handle).await
}
}
async fn handle_request<R: ResponseHandler>(
catalog: &RwLock<Catalog>,
request: &Request,
response_handle: R,
) -> ResponseInfo {
let mut selected = Catalog::new();
if let Ok(info) = request.request_info() {
let name = info.query.name();
if let Some(authorities) = catalog.read().await.find(name).cloned() {
selected.upsert(name.clone(), authorities);
}
}
// Only authority selection needs the shared index. Upstream I/O must not
// hold its lock or delay publication of a new batch.
selected.handle_request(request, response_handle).await
}
pub fn build_authority(origin: &rr::LowerName, records: &[Record]) -> Result<InMemoryAuthority> {
let zone = rr::Name::from(origin);
let mut authority = InMemoryAuthority::empty(zone, ZoneType::Primary, false);
@@ -336,30 +351,51 @@ impl Server {
Ok(())
}
pub async fn upsert(&self, name: LowerName, authority: Arc<InMemoryAuthority>) {
// Requests hold the Catalog read lock. Publish the local lookup index
// under the same write lock, without reentering Catalog during lookup.
let mut catalog = self.catalog.write().await;
self.local_zones
.write()
.await
.insert(name.clone(), authority.clone());
catalog.upsert(
name,
vec![Arc::new(LocalAuthority {
inner: authority,
zones: self.local_zones.clone(),
})],
);
pub async fn local_origins(&self) -> BTreeSet<LowerName> {
self.local_zones.read().await.keys().cloned().collect()
}
/// Publishes a complete batch under the same Catalog write lock used by
/// authority selection. Keep the local CNAME lookup index in the same batch.
pub async fn replace_zones(
&self,
replacements: BTreeMap<LowerName, Arc<InMemoryAuthority>>,
removals: BTreeSet<LowerName>,
) {
let mut catalog = self.catalog.write().await;
let mut local_zones = self.local_zones.write().await;
for name in removals {
catalog.remove(&name);
local_zones.remove(&name);
}
for (name, authority) in replacements {
local_zones.insert(name.clone(), authority.clone());
catalog.upsert(
name,
vec![Arc::new(LocalAuthority {
inner: authority,
zones: self.local_zones.clone(),
})],
);
}
}
pub async fn handle_request<R: ResponseHandler>(
&self,
request: &Request,
response_handle: R,
) -> ResponseInfo {
handle_request(&self.catalog, request, response_handle).await
}
#[cfg(test)]
pub async fn read_catalog(&self) -> RwLockReadGuard<'_, Catalog> {
self.catalog.read().await
}
}
#[cfg(test)]
mod tests {
pub(super) mod tests {
use super::*;
use crate::instance::dns_server::config::{
GeneralConfigBuilder, RecordBuilder, RecordType, RunConfigBuilder,
@@ -443,4 +479,97 @@ mod tests {
server.shutdown().await?;
Ok(())
}
pub(in crate::instance::dns_server) async fn forwarding_server(
upstream: SocketAddr,
) -> Result<Server> {
use hickory_proto::xfer::Protocol;
use hickory_resolver::config::NameServerConfig;
let config = RunConfigBuilder::default()
.general(
GeneralConfigBuilder::default()
.listen_udp("127.0.0.1:0")
.build()?,
)
.build()?;
let server = Server::new(config);
let mut options = ResolverOpts::default();
options.timeout = Duration::from_secs(10);
options.attempts = 1;
let forwarder = ForwardAuthority::builder_with_config(
ForwardConfig {
name_servers: vec![NameServerConfig::new(upstream, Protocol::Udp)].into(),
options: Some(options),
},
TokioConnectionProvider::default(),
)
.build()
.map_err(anyhow::Error::msg)?;
server
.catalog
.write()
.await
.upsert(".".parse()?, vec![Arc::new(forwarder)]);
Ok(server)
}
#[tokio::test]
async fn slow_forwarding_does_not_block_catalog_publication_or_local_queries() -> Result<()> {
use hickory_proto::op::{Message, Query, ResponseCode};
async fn query(address: SocketAddr, name: &str) -> Result<Message> {
let socket = UdpSocket::bind("127.0.0.1:0").await?;
let mut request = Message::new();
request.set_recursion_desired(true);
request.add_query(Query::query(name.parse()?, rr::RecordType::A));
socket.send_to(&request.to_vec()?, address).await?;
let mut response = [0; 4096];
let length = socket.recv(&mut response).await?;
Ok(Message::from_vec(&response[..length])?)
}
let upstream = UdpSocket::bind("127.0.0.1:0").await?;
let mut server = forwarding_server(upstream.local_addr()?).await?;
server.run().await?;
let address = server.udp_local_addr().unwrap();
let forwarding = tokio::spawn(query(address, "slow.example.org."));
let mut packet = [0; 4096];
let (length, source) =
tokio::time::timeout(Duration::from_secs(1), upstream.recv_from(&mut packet)).await??;
tokio::time::timeout(Duration::from_secs(1), async {
let origin = "local.test.".parse()?;
let record = RecordBuilder::default()
.rr_type(RecordType::A)
.name("svc.local.test.".to_owned())
.value("192.0.2.8".to_owned())
.ttl(Duration::from_secs(42))
.build()?;
server
.replace_zones(
BTreeMap::from([(
origin,
Arc::new(build_authority(&"local.test.".parse()?, &[record])?),
)]),
BTreeSet::new(),
)
.await;
let response = query(address, "svc.local.test.").await?;
assert_eq!(response.answers().len(), 1);
assert_eq!(response.answers()[0].ttl(), 42);
assert!(!forwarding.is_finished());
anyhow::Ok(())
})
.await??;
let mut response = Message::from_vec(&packet[..length])?;
response
.set_message_type(hickory_proto::op::MessageType::Response)
.set_response_code(ResponseCode::NXDomain);
upstream.send_to(&response.to_vec()?, source).await?;
assert_eq!(forwarding.await??.response_code(), ResponseCode::NXDomain);
server.shutdown().await?;
Ok(())
}
}
File diff suppressed because it is too large Load Diff
+254 -19
View File
@@ -7,7 +7,6 @@ use std::time::Duration;
use cidr::Ipv4Inet;
use easytier_core::{
config::toml::{DnsConfig, DnsZoneConfig},
gateway::magic_dns::MagicDnsRoute,
host::packet::{HostPacket, HostPacketChannelSink, HostPacketReceiver},
process_runtime::CoreProcessRuntime,
};
@@ -39,7 +38,9 @@ pub async fn prepare_env(
prepare_env_with_tld_dns_zone(dns_name, tun_ip, None).await
}
async fn build_test_core(ctx: ArcGlobalCtx) -> (Arc<NativeCoreInstance>, HostPacketReceiver) {
pub(super) async fn build_test_core(
ctx: ArcGlobalCtx,
) -> (Arc<NativeCoreInstance>, HostPacketReceiver) {
let (packet_sink, packet_receiver) = tokio::sync::mpsc::channel::<HostPacket>(128);
let adapters = runtime_core_host_adapters(
ctx.clone(),
@@ -153,25 +154,28 @@ async fn test_magic_dns_server_instance() {
check_dns_record(&fake_ip, "svc.example.test", "10.0.0.9").await;
let routes = [
MagicDnsRoute {
hostname: "test1".to_string(),
ipv4_addr: Some("8.8.8.8".parse().unwrap()),
},
MagicDnsRoute {
hostname: "中文".to_string(),
ipv4_addr: Some("8.8.8.8".parse().unwrap()),
},
MagicDnsRoute {
hostname: ".invalid".to_string(),
ipv4_addr: Some("8.8.8.8".parse().unwrap()),
},
];
let mut ctrl = BaseController::default();
ctrl.set_tunnel_info(Some(crate::proto::common::TunnelInfo {
remote_addr: Some(url::Url::parse("tcp://127.0.0.1:54321").unwrap().into()),
..Default::default()
}));
dns_server_inst
.data
.update_dns_records(
routes.iter(),
&super::zone::parse_origin(DEFAULT_ET_DNS_ZONE).unwrap(),
.update_dns_record(
ctrl,
UpdateDnsRecordRequest {
zone: DEFAULT_ET_DNS_ZONE.to_string(),
instance_id: uuid::Uuid::from_u128(2).to_string(),
dns: None,
routes: ["test1", "中文", ".invalid"]
.into_iter()
.map(|hostname| Route {
hostname: hostname.to_owned(),
ipv4_addr: Some("8.8.8.8/32".parse::<Ipv4Inet>().unwrap().into()),
..Default::default()
})
.collect(),
},
)
.await
.unwrap();
@@ -303,6 +307,8 @@ async fn test_magic_dns_update_replaces_records_for_same_client() {
ctrl.clone(),
UpdateDnsRecordRequest {
zone: DEFAULT_ET_DNS_ZONE.to_string(),
instance_id: uuid::Uuid::from_u128(2).to_string(),
dns: None,
routes: vec![Route {
hostname: "test1".to_string(),
ipv4_addr: Some(Ipv4Inet::from_str("8.8.8.8/32").unwrap().into()),
@@ -319,6 +325,8 @@ async fn test_magic_dns_update_replaces_records_for_same_client() {
ctrl,
UpdateDnsRecordRequest {
zone: DEFAULT_ET_DNS_ZONE.to_string(),
instance_id: uuid::Uuid::from_u128(2).to_string(),
dns: None,
routes: vec![Route {
hostname: "test1".to_string(),
ipv4_addr: Some(Ipv4Inet::from_str("1.1.1.1/32").unwrap().into()),
@@ -371,6 +379,8 @@ async fn test_magic_dns_update_replaces_records_for_same_client() {
ctrl,
UpdateDnsRecordRequest {
zone: DEFAULT_ET_DNS_ZONE.to_string(),
instance_id: uuid::Uuid::from_u128(2).to_string(),
dns: None,
routes: vec![],
},
)
@@ -387,3 +397,228 @@ async fn test_magic_dns_update_replaces_records_for_same_client() {
.unwrap();
assert!(!dns_records.records.contains_key(DEFAULT_ET_DNS_ZONE));
}
#[cfg(target_os = "linux")]
async fn dns_address(server: &MagicDnsServerInstance, name: &str) -> Option<Ipv4Addr> {
use easytier_core::gateway::magic_dns::{MagicDnsQuery, MagicDnsQueryResolver};
use hickory_proto::op::{Message, Query};
let mut message = Message::new();
message.add_query(Query::query(name.parse().unwrap(), rr::RecordType::A));
let bytes = server
.data
.resolve(MagicDnsQuery {
source: "127.0.0.1:5353".parse().unwrap(),
payload: message.to_vec().unwrap(),
})
.await
.unwrap();
Message::from_vec(&bytes)
.unwrap()
.answers()
.iter()
.find_map(|record| record.data().as_a().map(|address| address.0))
}
#[cfg(target_os = "linux")]
#[tokio::test]
async fn test_magic_dns_live_configuration_and_publisher_lifecycle() {
let ctx = get_mock_global_ctx();
ctx.set_hostname("live-node".to_owned());
let tun_ip = "100.100.100.0/24".parse::<Ipv4Inet>().unwrap();
ctx.set_ipv4(Some(tun_ip));
let (core, _packets) = build_test_core(ctx.clone()).await;
let server = MagicDnsServerInstance::new(
core.packet_plane(),
ctx.clone(),
None,
tun_ip,
MAGIC_DNS_FAKE_IP.parse().unwrap(),
)
.await
.unwrap();
let mut client =
super::client_instance::MagicDnsClientInstance::new(core.packet_plane(), ctx.clone())
.await
.unwrap();
let publisher = tokio::spawn(async move { client.run_and_wait().await });
let mut dns = DnsConfig {
domain: Some("live.test".to_owned()),
zone: Some(
vec![DnsZoneConfig {
origin: "first.test".to_owned(),
ttl: Some(60),
records: Some(
vec![DnsRecordRaw {
name: "svc".to_owned(),
r#type: DnsRecordType::A as i32,
value: Some("10.0.0.8".to_owned()),
..Default::default()
}]
.into(),
),
}]
.into(),
),
};
ctx.config.set_dns(Some(dns.clone()));
tokio::time::timeout(Duration::from_secs(5), async {
loop {
if server
.data
.dns_server
.local_origins()
.await
.contains(&"first.test.".parse().unwrap())
&& dns_address(&server, "svc.first.test.").await
== Some("10.0.0.8".parse().unwrap())
&& dns_address(&server, "live-node.live.test.").await == Some(tun_ip.address())
{
break;
}
tokio::time::sleep(Duration::from_millis(50)).await;
}
})
.await
.unwrap();
dns.zone.as_mut().unwrap().items[0]
.records
.as_mut()
.unwrap()
.items[0]
.value = Some("10.0.0.9".to_owned());
ctx.config.set_dns(Some(dns.clone()));
tokio::time::timeout(Duration::from_secs(5), async {
while dns_address(&server, "svc.first.test.").await != Some("10.0.0.9".parse().unwrap()) {
tokio::time::sleep(Duration::from_millis(50)).await;
}
})
.await
.unwrap();
dns.zone = Some(vec![].into());
ctx.config.set_dns(Some(dns));
tokio::time::timeout(Duration::from_secs(5), async {
while server
.data
.dns_server
.local_origins()
.await
.contains(&"first.test.".parse().unwrap())
{
tokio::time::sleep(Duration::from_millis(50)).await;
}
})
.await
.unwrap();
assert_eq!(
dns_address(&server, "live-node.live.test.").await,
Some(tun_ip.address())
);
publisher.abort();
assert!(publisher.await.unwrap_err().is_cancelled());
tokio::time::timeout(Duration::from_secs(5), async {
while dns_address(&server, "live-node.live.test.").await.is_some() {
tokio::time::sleep(Duration::from_millis(50)).await;
}
})
.await
.unwrap();
server.clean_env().await;
}
#[cfg(target_os = "linux")]
#[tokio::test]
#[ignore = "requires root/TUN and EASYTIER_TEST_LEGACY_CORE pointing to v2.6.4"]
async fn test_magic_dns_released_client_connection_lifecycle() {
let legacy_core = std::env::var_os("EASYTIER_TEST_LEGACY_CORE")
.expect("set EASYTIER_TEST_LEGACY_CORE to the released v2.6.4 core");
let ctx = get_mock_global_ctx();
ctx.set_hostname("modern-node".to_owned());
let tun_ip = "100.100.100.0/24".parse::<Ipv4Inet>().unwrap();
ctx.set_ipv4(Some(tun_ip));
let (core, _packets) = build_test_core(ctx.clone()).await;
let server = MagicDnsServerInstance::new(
core.packet_plane(),
ctx.clone(),
None,
tun_ip,
MAGIC_DNS_FAKE_IP.parse().unwrap(),
)
.await
.unwrap();
let mut client = super::client_instance::MagicDnsClientInstance::new(core.packet_plane(), ctx)
.await
.unwrap();
let publisher = tokio::spawn(async move { client.run_and_wait().await });
let configs = tempfile::tempdir().unwrap();
let config = configs.path().join("legacy.toml");
for address in ["100.100.100.8", "100.100.100.9"] {
std::fs::write(
&config,
format!(
r#"
instance_id = "00000000-0000-0000-0000-000000000064"
hostname = "legacy-node"
ipv4 = "{address}/24"
listeners = []
[flags]
accept_dns = true
tld_dns_zone = "legacy.test."
dev_name = "etlegacydns"
"#
),
)
.unwrap();
let mut legacy = tokio::process::Command::new(&legacy_core)
.arg("--config-file")
.arg(&config)
.kill_on_drop(true)
.spawn()
.unwrap();
tokio::time::timeout(Duration::from_secs(15), async {
loop {
assert!(legacy.try_wait().unwrap().is_none(), "released core exited");
if server
.data
.dns_server
.local_origins()
.await
.contains(&"legacy.test.".parse().unwrap())
&& dns_address(&server, "legacy-node.legacy.test.").await
== Some(address.parse().unwrap())
{
break;
}
tokio::time::sleep(Duration::from_millis(50)).await;
}
})
.await
.unwrap();
assert_eq!(
dns_address(&server, "modern-node.et.net.").await,
Some(tun_ip.address())
);
legacy.kill().await.unwrap();
tokio::time::timeout(Duration::from_secs(5), async {
while dns_address(&server, "legacy-node.legacy.test.")
.await
.is_some()
{
tokio::time::sleep(Duration::from_millis(50)).await;
}
})
.await
.unwrap();
assert_eq!(
dns_address(&server, "modern-node.et.net.").await,
Some(tun_ip.address())
);
}
publisher.abort();
assert!(publisher.await.unwrap_err().is_cancelled());
server.clean_env().await;
}
+1 -72
View File
@@ -1,75 +1,4 @@
use crate::proto::utils::RepeatedMessageModel;
use anyhow::Context;
use easytier_core::config::dns::compile_dns;
pub(crate) use easytier_core::config::dns::parse_origin;
use easytier_core::config::toml::{ConfigLoader, DEFAULT_ET_DNS_ZONE, DnsConfig};
use hickory_proto::rr::{LowerName, Record, RecordSet, RrKey};
use hickory_server::store::in_memory::InMemoryAuthority;
use std::collections::BTreeMap;
/// Resolves the default Magic DNS zone origin from `dns.domain`, falling back
/// to the deprecated `flags.tld_dns_zone` patch when `dns.domain` is unset, and
/// finally to [`DEFAULT_ET_DNS_ZONE`].
#[allow(deprecated)]
pub(crate) fn dns_domain(config: &impl ConfigLoader) -> anyhow::Result<LowerName> {
let dns = config.get_dns();
if let Some(domain) = dns.as_ref().and_then(|dns| dns.domain.as_deref()) {
return parse_origin(domain).context("invalid dns.domain");
}
if let Some(legacy) = config.get_flags_patch().tld_dns_zone.as_deref()
&& !legacy.is_empty()
{
return parse_origin(legacy).context("invalid flags.tld_dns_zone");
}
parse_origin(DEFAULT_ET_DNS_ZONE)
}
#[derive(Debug, Clone, Default)]
pub(crate) struct Zone {
records: BTreeMap<RrKey, RecordSet>,
}
impl Zone {
pub fn iter_records(&self) -> impl Iterator<Item = &Record> {
self.records
.values()
.flat_map(RecordSet::records_without_rrsigs)
}
}
pub(crate) type ZoneGroup = RepeatedMessageModel<Zone>;
impl ZoneGroup {
/// Merges records of every zone into one authority, since an in-memory
/// authority answers authoritatively and never falls through to another.
pub fn extend_authority(&self, authority: &mut InMemoryAuthority) {
for record in self.iter().flat_map(Zone::iter_records) {
authority.upsert_mut(record.clone(), 0);
}
}
}
/// Parses the local static records once, grouped by origin. Called before the
/// server election so an invalid local configuration cannot win the listener.
pub(crate) fn configured_zones(
dns: Option<&DnsConfig>,
) -> anyhow::Result<BTreeMap<LowerName, ZoneGroup>> {
let Some(dns) = dns else {
return Ok(BTreeMap::new());
};
Ok(compile_dns(dns)?
.into_iter()
.map(|(origin, zone)| {
(
origin,
std::iter::once(Zone {
records: zone.records,
})
.collect(),
)
})
.collect())
}
pub(crate) use easytier_core::gateway::magic_dns::{dns_domain, parse_origin};
#[cfg(test)]
mod tests {