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

+18
View File
@@ -0,0 +1,18 @@
[package]
name = "dns-forwarder"
description = "EasyDNS forwarder: upstream pools, strategies, health checks, circuit breaker"
version.workspace = true
edition.workspace = true
license.workspace = true
[dependencies]
dns-core.workspace = true
dns-config.workspace = true
tokio.workspace = true
tracing.workspace = true
rand.workspace = true
serde.workspace = true
rustls.workspace = true
[lints]
workspace = true
+329
View File
@@ -0,0 +1,329 @@
//! Upstream pools used by the forwarder role.
//!
//! * strategies: round-robin, fastest (EWMA RTT), failover, random, priority,
//! * circuit breaker: after 3 consecutive failures an upstream is skipped for an
//! exponentially growing period (30 s … 5 min); health checks close it again,
//! * SERVFAIL/REFUSED/timeouts count as failures and the next upstream is tried,
//! * transports: UDP (TCP fallback), TCP, DoT (pooled persistent connections),
//! DoH (POST over a persistent, multiplexed HTTP/2 connection; HTTP/1.1 fallback).
#![cfg_attr(test, allow(clippy::unwrap_used, clippy::expect_used))]
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use dns_config::Strategy;
use dns_config::upstream::{UpstreamAddr, UpstreamProto};
use dns_core::client::{QueryOptions, build_query, exchange};
use dns_core::proto::op::{Message, ResponseCode};
use dns_core::proto::rr::{Name, RecordType};
use dns_core::wire::response_matches;
use serde::Serialize;
const FAILS_TO_OPEN: u32 = 3;
#[derive(Debug, Clone, Default, Serialize)]
pub struct UpstreamStats {
pub queries: u64,
pub failures: u64,
pub consecutive_failures: u32,
pub ewma_rtt_ms: Option<f64>,
pub circuit_open_for_ms: Option<u64>,
pub last_error: Option<String>,
pub healthy: bool,
}
#[derive(Debug)]
struct State {
stats: UpstreamStats,
open_until: Option<Instant>,
opens: u32,
}
/// Persistent encrypted transport of an upstream.
#[derive(Debug)]
enum Encrypted {
Dot(dns_core::tls_pool::DotPool),
Doh(dns_core::tls_pool::DohClient),
}
/// Idle DoT connections kept per upstream.
const DOT_POOL_SIZE: usize = 8;
/// One upstream server.
#[derive(Debug)]
pub struct Upstream {
pub addr: UpstreamAddr,
pub priority: usize,
state: Mutex<State>,
enc: Option<Encrypted>,
}
impl Upstream {
fn new(addr: UpstreamAddr, priority: usize, tls: Option<&Arc<rustls::ClientConfig>>) -> Self {
let name = addr.tls_name.clone().unwrap_or_default();
let enc = match (addr.proto, tls) {
(UpstreamProto::Tls, Some(c)) => Some(Encrypted::Dot(dns_core::tls_pool::DotPool::new(addr.addr, &name, c, DOT_POOL_SIZE))),
(UpstreamProto::Https, Some(c)) => Some(Encrypted::Doh(dns_core::tls_pool::DohClient::new(addr.addr, &name, &addr.path, c))),
_ => None,
};
Self {
addr,
priority,
state: Mutex::new(State { stats: UpstreamStats { healthy: true, ..Default::default() }, open_until: None, opens: 0 }),
enc,
}
}
fn lock(&self) -> std::sync::MutexGuard<'_, State> {
self.state.lock().unwrap_or_else(|e| e.into_inner())
}
fn is_open(&self) -> bool {
self.lock().open_until.is_some_and(|t| t > Instant::now())
}
fn rtt(&self) -> f64 {
self.lock().stats.ewma_rtt_ms.unwrap_or(50.0)
}
fn success(&self, rtt: Duration) {
let mut s = self.lock();
let ms = rtt.as_secs_f64() * 1000.0;
s.stats.ewma_rtt_ms = Some(match s.stats.ewma_rtt_ms {
Some(o) => o * 0.7 + ms * 0.3,
None => ms,
});
s.stats.queries += 1;
s.stats.consecutive_failures = 0;
s.stats.healthy = true;
s.open_until = None;
s.opens = 0;
}
fn failure(&self, err: &str) {
let mut s = self.lock();
s.stats.queries += 1;
s.stats.failures += 1;
s.stats.consecutive_failures += 1;
s.stats.last_error = Some(err.to_string());
// penalise RTT so `fastest` moves away
s.stats.ewma_rtt_ms = Some(s.stats.ewma_rtt_ms.unwrap_or(50.0) * 1.5 + 100.0);
if s.stats.consecutive_failures >= FAILS_TO_OPEN {
let secs = (30u64 << s.opens.min(4)).min(300);
s.open_until = Some(Instant::now() + Duration::from_secs(secs));
s.opens += 1;
s.stats.healthy = false;
tracing::warn!(upstream = %self.addr.original, secs, "circuit opened for upstream");
}
}
pub fn stats(&self) -> UpstreamStats {
let s = self.lock();
let mut st = s.stats.clone();
st.circuit_open_for_ms = s.open_until.and_then(|t| t.checked_duration_since(Instant::now())).map(|d| d.as_millis() as u64);
st
}
}
/// Result of a forwarded query.
#[derive(Debug)]
pub struct Forwarded {
pub message: Message,
pub upstream: String,
pub elapsed: Duration,
pub reason: &'static str,
}
/// A group of upstreams with a selection strategy.
#[derive(Debug)]
pub struct Pool {
pub name: String,
pub strategy: Strategy,
pub upstreams: Vec<Arc<Upstream>>,
pub timeout: Duration,
rr: AtomicUsize,
}
impl Pool {
pub fn new(name: &str, servers: &[String], strategy: Strategy, timeout: Duration) -> Result<Self, String> {
Self::with_tls_roots(name, servers, strategy, timeout, None)
}
/// Like [`Pool::new`], with extra trusted CA certificates (PEM) for DoT/DoH upstreams.
pub fn with_tls_roots(
name: &str,
servers: &[String],
strategy: Strategy,
timeout: Duration,
extra_roots_pem: Option<&[u8]>,
) -> Result<Self, String> {
let addrs = servers.iter().map(|s| UpstreamAddr::parse(s)).collect::<Result<Vec<_>, _>>()?;
if addrs.is_empty() {
return Err(format!("pool {name}: no upstreams"));
}
let needs_tls = addrs.iter().any(|a| matches!(a.proto, UpstreamProto::Tls | UpstreamProto::Https));
let tls =
if needs_tls { Some(dns_core::tls::client_config(extra_roots_pem, false, &[]).map_err(|e| e.to_string())?) } else { None };
let ups: Vec<Arc<Upstream>> = addrs.into_iter().enumerate().map(|(i, a)| Arc::new(Upstream::new(a, i, tls.as_ref()))).collect();
Ok(Self { name: name.into(), strategy, upstreams: ups, timeout, rr: AtomicUsize::new(0) })
}
/// Order upstreams for one query according to the strategy; open circuits go last.
pub fn order(&self) -> (Vec<Arc<Upstream>>, &'static str) {
let mut v: Vec<Arc<Upstream>> = self.upstreams.clone();
let reason = match self.strategy {
Strategy::Failover | Strategy::Priority => {
v.sort_by_key(|u| u.priority);
"priority order"
}
Strategy::RoundRobin => {
let n = v.len();
let k = self.rr.fetch_add(1, Ordering::Relaxed) % n;
v.rotate_left(k);
"round-robin"
}
Strategy::Random => {
use rand::seq::SliceRandom;
v.shuffle(&mut rand::rng());
"random"
}
Strategy::Fastest => {
v.sort_by(|a, b| a.rtt().total_cmp(&b.rtt()));
// explore: occasionally try the second-fastest to refresh its RTT estimate
if v.len() > 1 && rand::random::<u8>() < 13 {
v.swap(0, 1);
}
"lowest RTT"
}
};
let (closed, open): (Vec<_>, Vec<_>) = v.into_iter().partition(|u| !u.is_open());
let mut out = closed;
out.extend(open);
(out, reason)
}
async fn send(&self, u: &Upstream, msg: &Message, opts: &QueryOptions) -> Result<Message, String> {
match u.addr.proto {
UpstreamProto::Udp | UpstreamProto::Tcp => {
let mut o = opts.clone();
o.tcp_only = u.addr.proto == UpstreamProto::Tcp;
o.retries = 0;
exchange(u.addr.addr, msg.clone(), &o).await.map(|e| e.message).map_err(|e| e.to_string())
}
UpstreamProto::Tls | UpstreamProto::Https => {
let bytes = msg.to_vec().map_err(|e| e.to_string())?;
let raw = match &u.enc {
Some(Encrypted::Dot(p)) => p.exchange(&bytes, self.timeout).await,
Some(Encrypted::Doh(c)) => {
c.exchange(&bytes, dns_core::tls::DohMethod::Post, self.timeout).await.and_then(|(st, body)| {
if st == 200 { Ok(body) } else { Err(dns_core::CoreError::Proto(format!("HTTP status {st}"))) }
})
}
None => return Err("TLS not configured".into()),
}
.map_err(|e| e.to_string())?;
let m = Message::from_vec(&raw).map_err(|e| e.to_string())?;
if !response_matches(msg, &m) {
return Err("response does not match query".into());
}
Ok(m)
}
}
}
/// Forward a query; tries upstreams in strategy order until one gives a usable answer.
pub async fn query(&self, name: &Name, qtype: RecordType, dnssec_ok: bool, cd: bool) -> Result<Forwarded, String> {
let opts = QueryOptions {
timeout: self.timeout,
retries: 0,
dnssec_ok,
checking_disabled: cd,
recursion_desired: true,
..Default::default()
};
let (order, reason) = self.order();
let mut errors = Vec::new();
for u in order.iter().take(3) {
let msg = build_query(name, qtype, &opts);
let start = Instant::now();
match self.send(u, &msg, &opts).await {
Ok(m)
if matches!(
m.metadata.response_code,
ResponseCode::ServFail | ResponseCode::Refused | ResponseCode::NotImp | ResponseCode::FormErr
) =>
{
let e = format!("{} answered {}", u.addr.original, m.metadata.response_code);
u.failure(&e);
errors.push(e);
}
Ok(m) => {
let el = start.elapsed();
u.success(el);
return Ok(Forwarded { message: m, upstream: u.addr.original.clone(), elapsed: el, reason });
}
Err(e) => {
u.failure(&e);
errors.push(format!("{}: {e}", u.addr.original));
}
}
}
Err(errors.join("; "))
}
/// Probe every upstream once (root NS query); used by the periodic health checker.
pub async fn health_check(&self) {
for u in &self.upstreams {
let opts = QueryOptions { timeout: self.timeout, retries: 0, ..Default::default() };
let msg = build_query(&Name::root(), RecordType::NS, &opts);
let start = Instant::now();
match self.send(u, &msg, &opts).await {
Ok(m) if m.metadata.response_code == ResponseCode::NoError => u.success(start.elapsed()),
Ok(m) => u.failure(&format!("health check: {}", m.metadata.response_code)),
Err(e) => u.failure(&format!("health check: {e}")),
}
}
}
pub fn stats(&self) -> Vec<(String, UpstreamStats)> {
self.upstreams.iter().map(|u| (u.addr.original.clone(), u.stats())).collect()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn ordering_strategies() {
let s: Vec<String> = vec!["192.0.2.1".into(), "192.0.2.2".into(), "192.0.2.3".into()];
let p = Pool::new("t", &s, Strategy::Failover, Duration::from_millis(100)).unwrap();
let (o, _) = p.order();
assert_eq!(o[0].addr.original, "192.0.2.1");
for _ in 0..3 {
p.upstreams[0].failure("x");
}
let (o, _) = p.order();
assert_eq!(o[0].addr.original, "192.0.2.2", "open circuit goes last");
assert!(p.upstreams[0].stats().circuit_open_for_ms.is_some());
p.upstreams[0].success(Duration::from_millis(1));
assert_eq!(p.order().0[0].addr.original, "192.0.2.1");
let rr = Pool::new("t", &s, Strategy::RoundRobin, Duration::from_millis(100)).unwrap();
let a = rr.order().0[0].addr.original.clone();
let b = rr.order().0[0].addr.original.clone();
assert_ne!(a, b);
let f = Pool::new("t", &s, Strategy::Fastest, Duration::from_millis(100)).unwrap();
f.upstreams[2].success(Duration::from_millis(1));
f.upstreams[0].success(Duration::from_millis(80));
f.upstreams[1].success(Duration::from_millis(90));
let firsts: Vec<String> = (0..50).map(|_| f.order().0[0].addr.original.clone()).collect();
assert!(firsts.iter().filter(|x| *x == "192.0.2.3").count() > 35);
}
#[tokio::test]
async fn failover_on_dead_upstream() {
// Nothing listens on these ports: both fail fast/timeout -> error with both reasons.
let s: Vec<String> = vec!["127.0.0.1:9".into(), "127.0.0.1:19".into()];
let p = Pool::new("t", &s, Strategy::Failover, Duration::from_millis(200)).unwrap();
let r = p.query(&Name::from_ascii("example.com.").unwrap(), RecordType::A, false, false).await;
let e = r.unwrap_err();
assert!(e.contains("127.0.0.1:9") && e.contains("127.0.0.1:19"), "{e}");
}
}