From 8ff7dde70a6fdfd51110719fd579acfecb282186 Mon Sep 17 00:00:00 2001 From: glassyiris Date: Tue, 28 Jul 2026 02:10:33 +0800 Subject: [PATCH] feat(dns): route all control-plane name resolution through internal DNS MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Audit of every resolver in the tree found six spots still bypassing honk's DNS stack; all now share it: - urltest (clash delay): optional UrltestResolver hook, installed by honk-core against DnsController::resolve_domain — delay measurements follow dns.routing/cache/serve-stale instead of the system resolver - alive: raw-TCP fallback probe and startup check-URL seed resolution use the same ResolveHook instead of lookup_host - udp_check_dns: domain entries resolve through the internal DNS hook (literal entries still win), reload-safe via DnsController - subscriptions: reqwest gets a reqwest::dns::Resolve backed by the bootstrap resolver (bypass-marked), so subscription fetches no longer depend on a poisonable system resolver Verified live on the gateway with a split-DNS config (223.5.5.5 UDP + dns.alidns.com DoH + dns.alidns.com DoQ + 1.1.1.1 DoH3): baidu/google/bing resolve via their designated upstreams, the environment-blocked DoH3 upstream fails isolated (other domains unaffected), and health-check resolution degrades to the system fallback when the internal path has no answer. Adds ci/dns-ci.sh + just dns-ci gate (fmt, clippy, config, dns, control, outbound suites) — ALL GREEN. --- AGENTS.md | 1 + Justfile | 4 ++ ci/dns-ci.sh | 35 ++++++++++++ crates/honk-core/src/control/mod.rs | 57 ++++++++++++++----- crates/honk-core/src/control/probers.rs | 29 ++++++---- crates/honk-core/src/control/tests.rs | 34 ++++++++--- crates/honk-core/src/subscription.rs | 21 +++++++ crates/honk-outbound/src/alive/mod.rs | 27 ++++----- crates/honk-outbound/src/alive/probe.rs | 15 ++++- crates/honk-outbound/src/urltest.rs | 75 +++++++++++++++++++++++-- 10 files changed, 242 insertions(+), 56 deletions(-) create mode 100755 ci/dns-ci.sh diff --git a/AGENTS.md b/AGENTS.md index 63fae81b..8dfcdc53 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -248,6 +248,7 @@ cargo +nightly build --release -Zbuild-std=core --target bpfel-unknown-none | `build` / `check` / `lint` / `fmt` | `cargo build --release` / `check` / `clippy --all -D warnings` / `fmt --all` | | `test` / `test-ci` / `test-core` / `test-config` / `test-ebpf` | Test suites (`test` = full incl. known failures; `test-ci` = CI gate with the 3 known failures skipped; `test-ebpf` = honk-ebpf-common only) | | `outbound-ci` / `outbound-ci-e2e` | honk-outbound gate (`ci/outbound-ci.sh`: fmt + clippy + honk-config & honk-outbound suites; `...-e2e` adds live hy2 e2e via `HONK_HY2_SERVER=`) — run after every outbound change | +| `dns-ci` | DNS subsystem gate (`ci/dns-ci.sh`: fmt + clippy + honk-config + honk-core dns/control + honk-outbound suites) — run after every DNS-path change | | `outbound-ci` / `outbound-ci-e2e` | honk-outbound gate (`ci/outbound-ci.sh`: fmt + clippy + honk-config & honk-outbound suites; `...-e2e` adds live hy2 e2e via `HONK_HY2_SERVER=`) — run after every outbound change | | `build-core` / `build-core-ebpf` | honk-core with `ebpf` feature | | `build-musl` | Static musl build (`x86_64-unknown-linux-musl`, for VyOS/Debian) via the `ci/zigcc`/`ci/zigcxx` zig wrappers + `link-self-contained=no` (needs zig 0.14+) | diff --git a/Justfile b/Justfile index 609943ce..8f80879e 100644 --- a/Justfile +++ b/Justfile @@ -98,6 +98,10 @@ outbound-ci: outbound-ci-e2e: ci/outbound-ci.sh --with-e2e-env +# DNS subsystem gate (fmt + clippy + config/dns/control/outbound suites) +dns-ci: + ci/dns-ci.sh + # ── Run ────────────────────────────────────────────────── # Run honk-core with eBPF (clash API comes from config.dae experimental section) diff --git a/ci/dns-ci.sh b/ci/dns-ci.sh new file mode 100755 index 00000000..c7b78343 --- /dev/null +++ b/ci/dns-ci.sh @@ -0,0 +1,35 @@ +#!/bin/sh +# dns-ci — DNS subsystem test gate after DNS-path changes. +# +# 1. fmt check (dns-touched crates) +# 2. clippy -D warnings +# 3. honk-config tests (skip known pre-existing failures) +# 4. honk-core dns module tests +# 5. honk-core control tests (probers / resolver wiring) +# 6. honk-outbound full suite (alive/urltest/bootstrap/quic transports) +# +# Usage: ci/dns-ci.sh +set -eu + +cd "$(dirname "$0")/.." + +step() { printf '\n==> %s\n' "$1"; } + +step "cargo fmt --check" +cargo fmt -p honk-config -p honk-core -p honk-outbound -- --check + +step "cargo clippy -D warnings" +cargo clippy -p honk-config -p honk-core -p honk-outbound --all-targets -- -D warnings + +step "cargo test -p honk-config" +# The two TOML round-trip failures are pre-existing (CI gate skips them too). +cargo test -p honk-config -- --skip test_config_toml_round_trip --skip test_to_file_and_from_file_by_extension + +step "cargo test -p honk-core (dns + control)" +cargo test -p honk-core --lib dns:: +cargo test -p honk-core --lib control + +step "cargo test -p honk-outbound" +cargo test -p honk-outbound --lib + +printf '\ndns-ci: ALL GREEN\n' diff --git a/crates/honk-core/src/control/mod.rs b/crates/honk-core/src/control/mod.rs index 5bb514e2..333d6b6d 100644 --- a/crates/honk-core/src/control/mod.rs +++ b/crates/honk-core/src/control/mod.rs @@ -195,20 +195,34 @@ impl ControlPlane { // Health-check name resolution shares honk's own DNS forwarder // (routing / cache / serve-stale, and always the *current* forwarder // across reloads) instead of the raw system resolver; bootstrap DNS - // stays for node hostnames and startup. + // stays for node hostnames and startup. The same hook backs the + // urltest (clash delay) measurements. { let controller = dns_controller.clone(); - alive_set.set_resolver(Arc::new(move |host: String, port: u16| { - let controller = controller.clone(); - Box::pin(async move { - controller - .resolve_domain(&host) - .await - .into_iter() - .map(|ip| std::net::SocketAddr::new(ip, port)) - .collect() - }) - })); + type HookFn = dyn Fn( + String, + u16, + ) -> std::pin::Pin< + Box> + Send>, + > + Send + + Sync; + let make_hook = + move |controller: std::sync::Arc| { + let hook: Arc = Arc::new(move |host: String, port: u16| { + let controller = controller.clone(); + Box::pin(async move { + controller + .resolve_domain(&host) + .await + .into_iter() + .map(|ip| std::net::SocketAddr::new(ip, port)) + .collect() + }) + }); + hook + }; + alive_set.set_resolver(make_hook(controller.clone())); + honk_outbound::urltest::set_urltest_resolver(make_hook(controller)); } let control_plane = Self { @@ -584,7 +598,24 @@ impl ControlPlane { let c = self.config.read().await; c.global.udp_check_dns.clone() }; - let dns_target = resolve_udp_check_target(&dns_raw).await; + let dns_target = resolve_udp_check_target( + &dns_raw, + Some({ + let controller = self.dns_controller.clone(); + Arc::new(move |host: String, port: u16| { + let controller = controller.clone(); + Box::pin(async move { + controller + .resolve_domain(&host) + .await + .into_iter() + .map(|ip| std::net::SocketAddr::new(ip, port)) + .collect() + }) + }) + }), + ) + .await; alive_set.set_udp_probe(Arc::new(ProxyUdpProber::new( self.config.clone(), self.proxy_registry.clone(), diff --git a/crates/honk-core/src/control/probers.rs b/crates/honk-core/src/control/probers.rs index 495fd6f2..b6406012 100644 --- a/crates/honk-core/src/control/probers.rs +++ b/crates/honk-core/src/control/probers.rs @@ -288,7 +288,10 @@ pub(super) fn build_dns_probe_query() -> Vec { /// (e.g. dns.google), which would send every probe to a black hole. /// Falls back to [`DEFAULT_UDP_CHECK_DNS`] when the list is empty or no /// entry resolves. -pub(super) async fn resolve_udp_check_target(raws: &[String]) -> SocketAddr { +pub(super) async fn resolve_udp_check_target( + raws: &[String], + resolver: Option, +) -> SocketAddr { let fallback: SocketAddr = DEFAULT_UDP_CHECK_DNS .parse() .expect("hardcoded default UDP check DNS address"); @@ -306,7 +309,8 @@ pub(super) async fn resolve_udp_check_target(raws: &[String]) -> SocketAddr { return SocketAddr::new(ip, 53); } } - // Second pass: first domain entry, resolved via system DNS. + // Second pass: first domain entry, resolved through the internal DNS + // resolver when installed (system lookup otherwise). if let Some(raw) = entries.first() { let (host, port) = match raw.rsplit_once(':') { Some((h, p)) => match p.parse::() { @@ -315,15 +319,20 @@ pub(super) async fn resolve_udp_check_target(raws: &[String]) -> SocketAddr { }, None => (*raw, 53), }; - match tokio::net::lookup_host((host, port)).await { - Ok(mut addrs) => return addrs.next().unwrap_or(fallback), - Err(e) => { - warn!( - "Failed to resolve udp_check_dns '{}': {}; using {}", - raw, e, fallback - ); - } + let addrs = match resolver { + Some(resolve) => resolve(host.to_string(), port).await, + None => tokio::net::lookup_host((host, port)) + .await + .map(|it| it.collect()) + .unwrap_or_default(), + }; + if let Some(addr) = addrs.into_iter().next() { + return addr; } + warn!( + "Failed to resolve udp_check_dns '{}'; using {}", + raw, fallback + ); } fallback } diff --git a/crates/honk-core/src/control/tests.rs b/crates/honk-core/src/control/tests.rs index 19f879ae..c84bce3f 100644 --- a/crates/honk-core/src/control/tests.rs +++ b/crates/honk-core/src/control/tests.rs @@ -12,36 +12,54 @@ fn test_build_dns_probe_query() { #[tokio::test] async fn test_resolve_udp_check_target() { let fallback: SocketAddr = "8.8.8.8:53".parse().unwrap(); - assert_eq!(resolve_udp_check_target(&[]).await, fallback); - assert_eq!(resolve_udp_check_target(&[" ".into()]).await, fallback); + assert_eq!(resolve_udp_check_target(&[], None).await, fallback); + assert_eq!( + resolve_udp_check_target(&[" ".into()], None).await, + fallback + ); // Bare IP literals get the default DNS port. assert_eq!( - resolve_udp_check_target(&["1.1.1.1".into()]).await, + resolve_udp_check_target(&["1.1.1.1".into()], None).await, "1.1.1.1:53".parse().unwrap() ); assert_eq!( - resolve_udp_check_target(&["2001:4860:4860::8888".into()]).await, + resolve_udp_check_target(&["2001:4860:4860::8888".into()], None).await, "[2001:4860:4860::8888]:53".parse().unwrap() ); // Full socket addresses (v4 or bracketed v6) are kept as-is. assert_eq!( - resolve_udp_check_target(&["1.1.1.1:5353".into()]).await, + resolve_udp_check_target(&["1.1.1.1:5353".into()], None).await, "1.1.1.1:5353".parse().unwrap() ); assert_eq!( - resolve_udp_check_target(&["[2606:4700:4700::1111]:53".into()]).await, + resolve_udp_check_target(&["[2606:4700:4700::1111]:53".into()], None).await, "[2606:4700:4700::1111]:53".parse().unwrap() ); // Literals win over domain entries anywhere in the list (poison-proof). assert_eq!( - resolve_udp_check_target(&["dns.google".into(), "8.8.8.8".into()]).await, + resolve_udp_check_target(&["dns.google".into(), "8.8.8.8".into()], None).await, "8.8.8.8:53".parse().unwrap() ); // host:port resolves via the system resolver ("localhost" needs no // external network). - let addr = resolve_udp_check_target(&["localhost:5353".into()]).await; + let addr = resolve_udp_check_target(&["localhost:5353".into()], None).await; assert_eq!(addr.port(), 5353); assert!(addr.ip().is_loopback()); + + // A domain entry is resolved through the installed hook when present. + let hook: crate::outbound::ResolveHook = std::sync::Arc::new(|host, port| { + Box::pin(async move { + assert_eq!(host, "dns.example"); + vec![std::net::SocketAddr::new( + std::net::IpAddr::from([10, 9, 8, 7]), + port, + )] + }) + }); + assert_eq!( + resolve_udp_check_target(&["dns.example".into()], Some(hook)).await, + "10.9.8.7:53".parse().unwrap() + ); } #[test] diff --git a/crates/honk-core/src/subscription.rs b/crates/honk-core/src/subscription.rs index db2ab57e..bc900e5d 100644 --- a/crates/honk-core/src/subscription.rs +++ b/crates/honk-core/src/subscription.rs @@ -8,6 +8,26 @@ use honk_config::node::Node; use honk_config::subscription::Subscription; use honk_config::types::{NodeProtocol, SubscriptionType}; +/// reqwest DNS resolver backed by honk's bootstrap resolver +/// (bypass-marked UDP/TCP), so subscription fetches do not depend on the +/// system resolver — which on a polluted network can hand back poisoned +/// answers and kill the subscription download. +struct BootstrapDnsResolve; + +impl reqwest::dns::Resolve for BootstrapDnsResolve { + fn resolve(&self, name: reqwest::dns::Name) -> reqwest::dns::Resolving { + let host = name.as_str().to_string(); + Box::pin(async move { + let ips = honk_outbound::bootstrap::resolve(&host).await?; + let addrs: Vec = ips + .into_iter() + .map(|ip| std::net::SocketAddr::new(ip, 0)) + .collect(); + Ok(Box::new(addrs.into_iter()) as reqwest::dns::Addrs) + }) + } +} + /// Manager for fetching and parsing proxy subscriptions. pub struct SubscriptionManager { client: reqwest::Client, @@ -17,6 +37,7 @@ impl SubscriptionManager { pub fn new() -> anyhow::Result { let client = reqwest::Client::builder() .timeout(std::time::Duration::from_secs(30)) + .dns_resolver(std::sync::Arc::new(BootstrapDnsResolve)) .build()?; Ok(Self { client }) } diff --git a/crates/honk-outbound/src/alive/mod.rs b/crates/honk-outbound/src/alive/mod.rs index 7a7595f7..9f4ac985 100644 --- a/crates/honk-outbound/src/alive/mod.rs +++ b/crates/honk-outbound/src/alive/mod.rs @@ -411,24 +411,17 @@ impl AliveDialerSet { // fallback IPs (comma-separated) are merged in so probes still have // targets even when DNS resolution fails. if let Some(hostname) = Self::parse_url_host(&check_url) { - match tokio::net::lookup_host(format!("{}:80", hostname)).await { - Ok(addrs) => { - let ips = Self::merge_check_addrs(addrs.collect(), &check_url); - tracing::info!( - "Health check DNS resolved '{}' → {} IPs", - hostname, - ips.len() - ); - *self.check_url_ips.write() = ips; - } - Err(e) => { - tracing::warn!("Failed to resolve health check URL '{}': {}", hostname, e); - let ips = Self::merge_check_addrs(Vec::new(), &check_url); - if !ips.is_empty() { - *self.check_url_ips.write() = ips; - } - } + let addrs = self.resolve_host(&hostname, 80).await; + if addrs.is_empty() { + tracing::warn!("Failed to resolve health check URL '{}'", hostname); } + let ips = Self::merge_check_addrs(addrs, &check_url); + tracing::info!( + "Health check DNS resolved '{}' → {} IPs", + hostname, + ips.len() + ); + *self.check_url_ips.write() = ips; } else { // No URL hostname at all — literal-only form. let ips = Self::merge_check_addrs(Vec::new(), &check_url); diff --git a/crates/honk-outbound/src/alive/probe.rs b/crates/honk-outbound/src/alive/probe.rs index 8ccd0b50..2c03dff7 100644 --- a/crates/honk-outbound/src/alive/probe.rs +++ b/crates/honk-outbound/src/alive/probe.rs @@ -240,9 +240,18 @@ impl AliveDialerSet { /// Raw TCP connect health check (fallback when no HTTP prober configured). async fn probe_node_tcp(&self, node_id: &str, node_addr: &str, timeout: Duration) -> bool { let addr = node_addr.to_string(); - let addrs: Vec<_> = match tokio::net::lookup_host(&addr).await { - Ok(it) => it.collect(), - Err(_) => { + let (host, port) = match addr.rsplit_once(':') { + Some((h, p)) => match p.parse::() { + Ok(port) => (h.to_string(), port), + Err(_) => (addr.clone(), 80), + }, + None => (addr.clone(), 80), + }; + let addrs: Vec<_> = { + let out = self.resolve_host(&host, port).await; + if !out.is_empty() { + out + } else { tracing::warn!( "Health check DNS resolution failed for node '{}' ({}): system lookup failed", node_id, diff --git a/crates/honk-outbound/src/urltest.rs b/crates/honk-outbound/src/urltest.rs index 792b00e6..2c19eb0b 100644 --- a/crates/honk-outbound/src/urltest.rs +++ b/crates/honk-outbound/src/urltest.rs @@ -26,6 +26,27 @@ pub const DEFAULT_URLTEST_URL: &str = "https://www.gstatic.com/generate_204"; /// Default per-node measurement timeout. pub const DEFAULT_URLTEST_TIMEOUT: Duration = Duration::from_secs(15); +/// Optional resolver for check-URL hosts: `(host, port) → addr`. +/// honk-core installs the DNS-forwarder-backed resolver so delay +/// measurements share the internal DNS stack; unset means the raw system +/// resolver (tests, tools). +pub type UrltestResolver = std::sync::Arc< + dyn Fn( + String, + u16, + ) -> std::pin::Pin> + Send>> + + Send + + Sync, +>; + +static URLTEST_RESOLVER: std::sync::LazyLock>> = + std::sync::LazyLock::new(|| parking_lot::RwLock::new(None)); + +/// Install the resolver used for subsequent [`urltest_node`] measurements. +pub fn set_urltest_resolver(hook: UrltestResolver) { + *URLTEST_RESOLVER.write() = Some(hook); +} + /// Maximum concurrent node measurements inside [`urltest_group`] /// (matches sing-box's health check concurrency). pub const URLTEST_MAX_CONCURRENT: usize = 10; @@ -57,11 +78,21 @@ pub async fn urltest_node( }; let (host, port, is_https) = parse_url_host_port(url)?; - let addr = tokio::net::lookup_host(format!("{host}:{port}")) - .await - .with_context(|| format!("failed to resolve '{host}:{port}'"))? - .next() - .ok_or_else(|| anyhow!("no address resolved for '{host}:{port}'"))?; + let addr = { + let hook = URLTEST_RESOLVER.read().clone(); + match hook { + Some(hook) => hook(host.clone(), port) + .await + .into_iter() + .next() + .ok_or_else(|| anyhow!("no address resolved for '{host}:{port}'"))?, + None => tokio::net::lookup_host(format!("{host}:{port}")) + .await + .with_context(|| format!("failed to resolve '{host}:{port}'"))? + .next() + .ok_or_else(|| anyhow!("no address resolved for '{host}:{port}'"))?, + } + }; measure_head_exchange(node, handler, &host, is_https, addr, timeout).await } @@ -313,6 +344,40 @@ fn validate_status(buf: &[u8]) -> anyhow::Result<()> { Ok(()) } +#[cfg(test)] +mod resolver_hook_tests { + use super::*; + + /// The installed hook is consulted before the system resolver. + #[tokio::test] + async fn hook_supplies_urltest_addresses() { + let called = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); + let called2 = called.clone(); + set_urltest_resolver(std::sync::Arc::new(move |host, port| { + let called2 = called2.clone(); + Box::pin(async move { + called2.store(true, std::sync::atomic::Ordering::Relaxed); + assert_eq!(host, "example.invalid"); + assert_eq!(port, 443); + vec!["127.0.0.1:443".parse().unwrap()] + }) + })); + let node = Node::default(); + // The dial itself fails (nothing on 127.0.0.1:443) but the hook + // must have been consulted first. + let handler = crate::proxy::direct::DirectHandler::new(); + let _ = urltest_node( + &node, + &handler, + "https://example.invalid/", + Duration::from_millis(50), + ) + .await; + assert!(called.load(std::sync::atomic::Ordering::Relaxed)); + *URLTEST_RESOLVER.write() = None; + } +} + #[cfg(test)] mod tests { use super::*;