v0.1.0
This commit is contained in:
commit
fa432bebda
189 files changed
+26219
No files matched your search
@@ -0,0 +1,130 @@
|
||||
[package]
|
||||
name = "dns-tools"
|
||||
description = "EasyDNS Tools: ed/easydig, eh/easyhost, ens/easynslookup, etrace, ednssec, eptr, ezone, econf, ebench, ewhois, edoh, edot, ediff"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[[bin]]
|
||||
name = "ed"
|
||||
path = "src/bin/ed.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "easydig"
|
||||
path = "src/bin/easydig.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "eh"
|
||||
path = "src/bin/eh.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "easyhost"
|
||||
path = "src/bin/easyhost.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "ens"
|
||||
path = "src/bin/ens.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "easynslookup"
|
||||
path = "src/bin/easynslookup.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "etrace"
|
||||
path = "src/bin/etrace.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "easytrace"
|
||||
path = "src/bin/easytrace.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "ednssec"
|
||||
path = "src/bin/ednssec.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "easydnssec"
|
||||
path = "src/bin/easydnssec.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "eptr"
|
||||
path = "src/bin/eptr.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "easyptr"
|
||||
path = "src/bin/easyptr.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "ezone"
|
||||
path = "src/bin/ezone.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "easyzone"
|
||||
path = "src/bin/easyzone.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "econf"
|
||||
path = "src/bin/econf.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "easyconf"
|
||||
path = "src/bin/easyconf.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "ebench"
|
||||
path = "src/bin/ebench.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "easybench"
|
||||
path = "src/bin/easybench.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "ewhois"
|
||||
path = "src/bin/ewhois.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "easywhois"
|
||||
path = "src/bin/easywhois.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "edoh"
|
||||
path = "src/bin/edoh.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "easydoh"
|
||||
path = "src/bin/easydoh.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "edot"
|
||||
path = "src/bin/edot.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "easydot"
|
||||
path = "src/bin/easydot.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "ediff"
|
||||
path = "src/bin/ediff.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "easydiff"
|
||||
path = "src/bin/easydiff.rs"
|
||||
|
||||
[dependencies]
|
||||
dns-core.workspace = true
|
||||
dns-config.workspace = true
|
||||
dns-recursive.workspace = true
|
||||
dns-cache.workspace = true
|
||||
dns-server.workspace = true
|
||||
tokio.workspace = true
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
serde_norway.workspace = true
|
||||
clap.workspace = true
|
||||
data-encoding.workspace = true
|
||||
rand.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
dns-server.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -0,0 +1,228 @@
|
||||
//! `ebench` / `easybench` – DNS load testing (dnsperf-like).
|
||||
//!
|
||||
//! Only use against servers you operate or are authorised to test. Safe defaults:
|
||||
//! 100 QPS for 10 s, 10 concurrent workers; `--qps` above 5000 requires `--i-own-this-server`.
|
||||
use std::net::SocketAddr;
|
||||
use std::process::ExitCode;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use clap::Parser;
|
||||
use dns_core::client::{QueryOptions, query};
|
||||
use dns_core::proto::rr::{Name, RecordType};
|
||||
use serde_json::json;
|
||||
|
||||
use crate::common::*;
|
||||
|
||||
#[derive(Parser, Debug)]
|
||||
#[command(name = "ebench", version = VERSION, about = "EasyBench – DNS load testing for servers you are authorised to test")]
|
||||
pub struct Args {
|
||||
/// Target server (@IP or IP[:port])
|
||||
pub server: String,
|
||||
/// Query names file (`name type` per line); default: example.com A
|
||||
#[arg(short = 'd', long)]
|
||||
pub datafile: Option<std::path::PathBuf>,
|
||||
#[arg(short, long)]
|
||||
pub name: Option<String>,
|
||||
#[arg(short, long, default_value = "A")]
|
||||
pub rtype: String,
|
||||
/// Target queries per second (0 = as fast as possible within concurrency)
|
||||
#[arg(long, default_value_t = 100)]
|
||||
pub qps: u32,
|
||||
#[arg(long, default_value = "10s")]
|
||||
pub duration: String,
|
||||
#[arg(short, long, default_value_t = 10)]
|
||||
pub concurrency: usize,
|
||||
#[arg(long, default_value = "2s")]
|
||||
pub timeout: String,
|
||||
#[arg(long)]
|
||||
pub tcp: bool,
|
||||
/// Required for --qps above 5000 or --qps 0
|
||||
#[arg(long)]
|
||||
pub i_own_this_server: bool,
|
||||
#[arg(long)]
|
||||
pub json: bool,
|
||||
}
|
||||
|
||||
pub struct Report {
|
||||
pub sent: u64,
|
||||
pub ok: u64,
|
||||
pub errors: u64,
|
||||
pub timeouts: u64,
|
||||
pub elapsed: Duration,
|
||||
pub lat_ms: Vec<f64>,
|
||||
}
|
||||
|
||||
impl Report {
|
||||
pub fn print(&self, json_out: bool) {
|
||||
let mut l = self.lat_ms.clone();
|
||||
l.sort_by(f64::total_cmp);
|
||||
let qps = self.ok as f64 / self.elapsed.as_secs_f64().max(0.001);
|
||||
let lost = if self.sent > 0 { 100.0 * (self.timeouts as f64) / self.sent as f64 } else { 0.0 };
|
||||
if json_out {
|
||||
print_structured(
|
||||
&json!({ "sent": self.sent, "completed": self.ok, "errors": self.errors, "timeouts": self.timeouts, "lost_percent": lost,
|
||||
"duration_s": self.elapsed.as_secs_f64(), "qps": qps,
|
||||
"latency_ms": { "p50": percentile(&l, 0.5), "p95": percentile(&l, 0.95), "p99": percentile(&l, 0.99), "max": l.last().copied().unwrap_or(0.0) } }),
|
||||
false,
|
||||
);
|
||||
} else {
|
||||
println!("Statistics:\n");
|
||||
println!(" Queries sent: {}", self.sent);
|
||||
println!(" Queries completed: {} ({:.2}%)", self.ok, 100.0 * self.ok as f64 / self.sent.max(1) as f64);
|
||||
println!(" Queries lost: {} ({lost:.2}%)", self.timeouts);
|
||||
println!(" Errors (non-timeout): {}", self.errors);
|
||||
println!(" Run time (s): {:.3}", self.elapsed.as_secs_f64());
|
||||
println!(" Queries per second: {qps:.1}");
|
||||
println!(
|
||||
" Latency p50/p95/p99: {:.2} / {:.2} / {:.2} ms (max {:.2})",
|
||||
percentile(&l, 0.5),
|
||||
percentile(&l, 0.95),
|
||||
percentile(&l, 0.99),
|
||||
l.last().copied().unwrap_or(0.0)
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Run a load test. `qps = 0` means unthrottled.
|
||||
pub async fn load(
|
||||
server: SocketAddr,
|
||||
queries: Arc<Vec<(Name, RecordType)>>,
|
||||
qps: u32,
|
||||
duration: Duration,
|
||||
total: Option<u64>,
|
||||
concurrency: usize,
|
||||
opts: QueryOptions,
|
||||
) -> Report {
|
||||
let sent = Arc::new(AtomicU64::new(0));
|
||||
let ok = Arc::new(AtomicU64::new(0));
|
||||
let errors = Arc::new(AtomicU64::new(0));
|
||||
let timeouts = Arc::new(AtomicU64::new(0));
|
||||
let lat = Arc::new(std::sync::Mutex::new(Vec::new()));
|
||||
let start = Instant::now();
|
||||
let deadline = start + duration;
|
||||
let per_worker_interval = if qps > 0 { Some(Duration::from_secs_f64(concurrency as f64 / f64::from(qps))) } else { None };
|
||||
let mut handles = Vec::new();
|
||||
for w in 0..concurrency.max(1) {
|
||||
let (sent, ok, errors, timeouts, lat, queries, opts) =
|
||||
(sent.clone(), ok.clone(), errors.clone(), timeouts.clone(), lat.clone(), queries.clone(), opts.clone());
|
||||
handles.push(tokio::spawn(async move {
|
||||
let mut i = w;
|
||||
let mut next = Instant::now();
|
||||
loop {
|
||||
if Instant::now() >= deadline {
|
||||
break;
|
||||
}
|
||||
if let Some(t) = total {
|
||||
if sent.fetch_add(1, Ordering::Relaxed) >= t {
|
||||
sent.fetch_sub(1, Ordering::Relaxed);
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
sent.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
let (n, t) = &queries[i % queries.len()];
|
||||
i += concurrency;
|
||||
let s = Instant::now();
|
||||
match query(server, n, *t, &opts).await {
|
||||
Ok(_) => {
|
||||
ok.fetch_add(1, Ordering::Relaxed);
|
||||
if let Ok(mut l) = lat.lock() {
|
||||
l.push(s.elapsed().as_secs_f64() * 1000.0);
|
||||
}
|
||||
}
|
||||
Err(dns_core::CoreError::Timeout(_)) => {
|
||||
timeouts.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
Err(_) => {
|
||||
errors.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
if let Some(iv) = per_worker_interval {
|
||||
next += iv;
|
||||
let now = Instant::now();
|
||||
if next > now {
|
||||
tokio::time::sleep(next - now).await;
|
||||
} else {
|
||||
next = now;
|
||||
}
|
||||
}
|
||||
}
|
||||
}));
|
||||
}
|
||||
for h in handles {
|
||||
let _ = h.await;
|
||||
}
|
||||
let lat_ms = lat.lock().map(|l| l.clone()).unwrap_or_default();
|
||||
Report {
|
||||
sent: sent.load(Ordering::Relaxed),
|
||||
ok: ok.load(Ordering::Relaxed),
|
||||
errors: errors.load(Ordering::Relaxed),
|
||||
timeouts: timeouts.load(Ordering::Relaxed),
|
||||
elapsed: start.elapsed(),
|
||||
lat_ms,
|
||||
}
|
||||
}
|
||||
|
||||
/// Used by `ed --benchmark N`.
|
||||
pub async fn run_simple(server: SocketAddr, name: &Name, t: RecordType, n: usize, concurrency: usize, timeout: Duration) -> ExitCode {
|
||||
let q = Arc::new(vec![(name.clone(), t)]);
|
||||
let opts = QueryOptions { timeout, retries: 0, ..Default::default() };
|
||||
let r = load(server, q, 0, Duration::from_secs(3600), Some(n as u64), concurrency, opts).await;
|
||||
r.print(false);
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
|
||||
pub fn main() -> ExitCode {
|
||||
block_on(run(Args::parse()))
|
||||
}
|
||||
|
||||
pub async fn run(a: Args) -> ExitCode {
|
||||
if (a.qps == 0 || a.qps > 5000 || a.concurrency > 500) && !a.i_own_this_server {
|
||||
return fail(
|
||||
"ebench",
|
||||
EXIT_USAGE,
|
||||
"high load requested: pass --i-own-this-server to confirm you are authorised to test this server",
|
||||
);
|
||||
}
|
||||
let server = match server_addr(&a.server, 53).await {
|
||||
Ok(s) => s,
|
||||
Err(e) => return fail("ebench", EXIT_USAGE, e),
|
||||
};
|
||||
let (duration, timeout) = match (parse_duration(&a.duration), parse_duration(&a.timeout)) {
|
||||
(Ok(d), Ok(t)) => (d, t),
|
||||
(Err(e), _) | (_, Err(e)) => return fail("ebench", EXIT_USAGE, e),
|
||||
};
|
||||
let mut qs = Vec::new();
|
||||
if let Some(f) = &a.datafile {
|
||||
let text = match std::fs::read_to_string(f) {
|
||||
Ok(t) => t,
|
||||
Err(e) => return fail("ebench", EXIT_USAGE, format!("{}: {e}", f.display())),
|
||||
};
|
||||
for l in text.lines().map(str::trim).filter(|l| !l.is_empty() && !l.starts_with('#')) {
|
||||
let mut p = l.split_whitespace();
|
||||
let (Some(n), t) = (p.next(), p.next().unwrap_or("A")) else { continue };
|
||||
if let (Ok(n), Some(t)) = (name_arg(n), parse_type(t)) {
|
||||
qs.push((n, t));
|
||||
}
|
||||
}
|
||||
} else {
|
||||
let n = a.name.clone().unwrap_or_else(|| "example.com".into());
|
||||
match (name_arg(&n), parse_type(&a.rtype)) {
|
||||
(Ok(n), Some(t)) => qs.push((n, t)),
|
||||
_ => return fail("ebench", EXIT_USAGE, "invalid name or type"),
|
||||
}
|
||||
}
|
||||
if qs.is_empty() {
|
||||
return fail("ebench", EXIT_USAGE, "no queries");
|
||||
}
|
||||
if !a.json {
|
||||
println!("[Status] Sending queries to {server} for {:?} at {} QPS (concurrency {})", duration, a.qps, a.concurrency);
|
||||
}
|
||||
let opts = QueryOptions { timeout, retries: 0, tcp_only: a.tcp, ..Default::default() };
|
||||
let r = load(server, Arc::new(qs), a.qps, duration, None, a.concurrency, opts).await;
|
||||
r.print(a.json);
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fn main() -> std::process::ExitCode {
|
||||
dns_tools::bench::main()
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fn main() -> std::process::ExitCode {
|
||||
dns_tools::conf::main()
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fn main() -> std::process::ExitCode {
|
||||
dns_tools::diff::main()
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fn main() -> std::process::ExitCode {
|
||||
dns_tools::dig::main()
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fn main() -> std::process::ExitCode {
|
||||
dns_tools::dnssec::main()
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fn main() -> std::process::ExitCode {
|
||||
dns_tools::doh::main()
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fn main() -> std::process::ExitCode {
|
||||
dns_tools::dot::main()
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fn main() -> std::process::ExitCode {
|
||||
dns_tools::host::main()
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fn main() -> std::process::ExitCode {
|
||||
dns_tools::nslookup::main()
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fn main() -> std::process::ExitCode {
|
||||
dns_tools::ptr::main()
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fn main() -> std::process::ExitCode {
|
||||
dns_tools::trace::main()
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fn main() -> std::process::ExitCode {
|
||||
dns_tools::whois::main()
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fn main() -> std::process::ExitCode {
|
||||
dns_tools::zone::main()
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fn main() -> std::process::ExitCode {
|
||||
dns_tools::bench::main()
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fn main() -> std::process::ExitCode {
|
||||
dns_tools::conf::main()
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fn main() -> std::process::ExitCode {
|
||||
dns_tools::dig::main()
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fn main() -> std::process::ExitCode {
|
||||
dns_tools::diff::main()
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fn main() -> std::process::ExitCode {
|
||||
dns_tools::dnssec::main()
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fn main() -> std::process::ExitCode {
|
||||
dns_tools::doh::main()
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fn main() -> std::process::ExitCode {
|
||||
dns_tools::dot::main()
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fn main() -> std::process::ExitCode {
|
||||
dns_tools::host::main()
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fn main() -> std::process::ExitCode {
|
||||
dns_tools::nslookup::main()
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fn main() -> std::process::ExitCode {
|
||||
dns_tools::ptr::main()
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fn main() -> std::process::ExitCode {
|
||||
dns_tools::trace::main()
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fn main() -> std::process::ExitCode {
|
||||
dns_tools::whois::main()
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
fn main() -> std::process::ExitCode {
|
||||
dns_tools::zone::main()
|
||||
}
|
||||
@@ -0,0 +1,239 @@
|
||||
//! Shared helpers: resolver discovery, argument helpers, formatting, colours, JSON.
|
||||
use std::io::IsTerminal;
|
||||
use std::net::{IpAddr, SocketAddr};
|
||||
use std::process::ExitCode;
|
||||
use std::time::Duration;
|
||||
|
||||
use dns_core::client::Exchange;
|
||||
use dns_core::proto::op::{Message, ResponseCode};
|
||||
use dns_core::proto::rr::{Name, Record, RecordType};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
pub const VERSION: &str = env!("CARGO_PKG_VERSION");
|
||||
|
||||
pub const EXIT_OK: u8 = 0;
|
||||
pub const EXIT_USAGE: u8 = 1;
|
||||
pub const EXIT_NO_REPLY: u8 = 9;
|
||||
pub const EXIT_INTERNAL: u8 = 10;
|
||||
|
||||
/// Build a current-thread Tokio runtime and run `f`.
|
||||
pub fn block_on<F: std::future::Future<Output = ExitCode>>(f: F) -> ExitCode {
|
||||
dns_core::quiet_broken_pipe();
|
||||
match tokio::runtime::Builder::new_multi_thread().worker_threads(2).enable_all().build() {
|
||||
Ok(rt) => rt.block_on(f),
|
||||
Err(e) => {
|
||||
eprintln!("cannot start runtime: {e}");
|
||||
ExitCode::from(EXIT_INTERNAL)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// First nameserver from /etc/resolv.conf (or 127.0.0.1).
|
||||
pub fn system_resolver() -> IpAddr {
|
||||
std::fs::read_to_string("/etc/resolv.conf")
|
||||
.ok()
|
||||
.and_then(|t| {
|
||||
t.lines()
|
||||
.filter_map(|l| l.trim().strip_prefix("nameserver"))
|
||||
.filter_map(|v| v.trim().split('%').next().and_then(|a| a.parse().ok()))
|
||||
.next()
|
||||
})
|
||||
.unwrap_or(IpAddr::from([127, 0, 0, 1]))
|
||||
}
|
||||
|
||||
/// Resolve a server argument (IP, IP:port, [v6]:port, or host name via the system resolver).
|
||||
pub async fn server_addr(s: &str, port: u16) -> Result<SocketAddr, String> {
|
||||
let s = s.trim_start_matches('@');
|
||||
if let Ok(a) = s.parse::<SocketAddr>() {
|
||||
return Ok(a);
|
||||
}
|
||||
if let Ok(ip) = s.trim_matches(['[', ']']).parse::<IpAddr>() {
|
||||
return Ok(SocketAddr::new(ip, port));
|
||||
}
|
||||
// dig syntax 1.2.3.4#5353
|
||||
if let Some((h, p)) = s.split_once('#')
|
||||
&& let (Ok(ip), Ok(p)) = (h.parse::<IpAddr>(), p.parse::<u16>())
|
||||
{
|
||||
return Ok(SocketAddr::new(ip, p));
|
||||
}
|
||||
tokio::net::lookup_host((s, port))
|
||||
.await
|
||||
.map_err(|e| format!("cannot resolve server '{s}': {e}"))?
|
||||
.next()
|
||||
.ok_or_else(|| format!("cannot resolve server '{s}'"))
|
||||
}
|
||||
|
||||
/// Parse a record type name or TYPEnnn.
|
||||
pub fn parse_type(s: &str) -> Option<RecordType> {
|
||||
let u = s.to_ascii_uppercase();
|
||||
if let Some(n) = u.strip_prefix("TYPE") {
|
||||
return n.parse::<u16>().ok().map(RecordType::from);
|
||||
}
|
||||
u.parse::<RecordType>().ok().filter(|t| !matches!(t, RecordType::Unknown(_)))
|
||||
}
|
||||
|
||||
/// Parse durations like `2s`, `500ms`, `5` (seconds).
|
||||
pub fn parse_duration(s: &str) -> Result<Duration, String> {
|
||||
dns_config::duration::parse(s)
|
||||
}
|
||||
|
||||
/// ANSI colours only on a TTY and when not disabled.
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct Colors {
|
||||
pub on: bool,
|
||||
}
|
||||
|
||||
impl Colors {
|
||||
pub fn detect(no_color: bool) -> Self {
|
||||
Self { on: !no_color && std::env::var_os("NO_COLOR").is_none() && std::io::stdout().is_terminal() }
|
||||
}
|
||||
pub fn paint(&self, code: &str, s: &str) -> String {
|
||||
if self.on { format!("\x1b[{code}m{s}\x1b[0m") } else { s.to_string() }
|
||||
}
|
||||
pub fn bold(&self, s: &str) -> String {
|
||||
self.paint("1", s)
|
||||
}
|
||||
pub fn rcode(&self, r: ResponseCode) -> String {
|
||||
let code = match r {
|
||||
ResponseCode::NoError => "32",
|
||||
ResponseCode::NXDomain => "33",
|
||||
_ => "31",
|
||||
};
|
||||
self.paint(code, &rcode_str(r))
|
||||
}
|
||||
}
|
||||
|
||||
pub fn rcode_str(r: ResponseCode) -> String {
|
||||
match r {
|
||||
ResponseCode::NoError => "NOERROR".into(),
|
||||
ResponseCode::FormErr => "FORMERR".into(),
|
||||
ResponseCode::ServFail => "SERVFAIL".into(),
|
||||
ResponseCode::NXDomain => "NXDOMAIN".into(),
|
||||
ResponseCode::NotImp => "NOTIMP".into(),
|
||||
ResponseCode::Refused => "REFUSED".into(),
|
||||
ResponseCode::YXDomain => "YXDOMAIN".into(),
|
||||
ResponseCode::NotAuth => "NOTAUTH".into(),
|
||||
ResponseCode::NotZone => "NOTZONE".into(),
|
||||
ResponseCode::BADVERS => "BADVERS".into(),
|
||||
other => format!("RCODE{}", u16::from(other)),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn flags_str(m: &Message) -> String {
|
||||
let md = &m.metadata;
|
||||
let mut f = Vec::new();
|
||||
if md.message_type == dns_core::proto::op::MessageType::Response {
|
||||
f.push("qr");
|
||||
}
|
||||
for (on, n) in [
|
||||
(md.authoritative, "aa"),
|
||||
(md.truncation, "tc"),
|
||||
(md.recursion_desired, "rd"),
|
||||
(md.recursion_available, "ra"),
|
||||
(md.authentic_data, "ad"),
|
||||
(md.checking_disabled, "cd"),
|
||||
] {
|
||||
if on {
|
||||
f.push(n);
|
||||
}
|
||||
}
|
||||
f.join(" ")
|
||||
}
|
||||
|
||||
/// Zone-file style line for a record (dig formatting).
|
||||
pub fn rr_line(r: &Record) -> String {
|
||||
let name = r.name.to_string();
|
||||
let pad = if name.len() < 24 { 24 - name.len() } else { 1 };
|
||||
format!("{name}{}{}\t{}\t{}\t{}", " ".repeat(pad), r.ttl, r.dns_class, r.record_type(), r.data)
|
||||
}
|
||||
|
||||
pub fn rr_json(r: &Record) -> Value {
|
||||
json!({ "name": r.name.to_string(), "ttl": r.ttl, "class": r.dns_class.to_string(), "type": r.record_type().to_string(), "data": r.data.to_string() })
|
||||
}
|
||||
|
||||
/// Structured representation of an exchange (for --json / --yaml).
|
||||
pub fn exchange_json(ex: &Exchange) -> Value {
|
||||
let m = &ex.message;
|
||||
json!({
|
||||
"server": ex.server.to_string(),
|
||||
"transport": ex.transport,
|
||||
"query_time_ms": (ex.elapsed.as_secs_f64() * 1000.0 * 100.0).round() / 100.0,
|
||||
"message_size": ex.size,
|
||||
"tsig_verified": ex.tsig_verified,
|
||||
"header": {
|
||||
"id": m.metadata.id,
|
||||
"opcode": format!("{:?}", m.metadata.op_code).to_uppercase(),
|
||||
"status": rcode_str(m.metadata.response_code),
|
||||
"flags": flags_str(m).split(' ').filter(|s| !s.is_empty()).collect::<Vec<_>>(),
|
||||
},
|
||||
"edns": m.edns.as_ref().map(|e| json!({ "version": e.version(), "udp_size": e.max_payload(), "do": e.flags().dnssec_ok })),
|
||||
"question": m.queries.iter().map(|q| json!({ "name": q.name.to_string(), "class": q.query_class.to_string(), "type": q.query_type.to_string() })).collect::<Vec<_>>(),
|
||||
"answer": m.answers.iter().map(rr_json).collect::<Vec<_>>(),
|
||||
"authority": m.authorities.iter().map(rr_json).collect::<Vec<_>>(),
|
||||
"additional": m.additionals.iter().map(rr_json).collect::<Vec<_>>(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Print JSON or YAML.
|
||||
pub fn print_structured(v: &Value, yaml: bool) {
|
||||
if yaml {
|
||||
print!("{}", serde_norway::to_string(v).unwrap_or_default());
|
||||
} else {
|
||||
println!("{}", serde_json::to_string_pretty(v).unwrap_or_default());
|
||||
}
|
||||
}
|
||||
|
||||
/// Parse a name, accepting IDN input.
|
||||
pub fn name_arg(s: &str) -> Result<Name, String> {
|
||||
dns_core::names::parse_name(s).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
/// Error helper.
|
||||
pub fn fail(tool: &str, code: u8, msg: impl std::fmt::Display) -> ExitCode {
|
||||
eprintln!("{tool}: {msg}");
|
||||
ExitCode::from(code)
|
||||
}
|
||||
|
||||
/// Exit code for a transport error.
|
||||
pub fn net_error(tool: &str, e: &dns_core::CoreError) -> ExitCode {
|
||||
match e {
|
||||
dns_core::CoreError::Timeout(_) | dns_core::CoreError::Io(_) => fail(tool, EXIT_NO_REPLY, format!("communications error: {e}")),
|
||||
_ => fail(tool, EXIT_INTERNAL, e),
|
||||
}
|
||||
}
|
||||
|
||||
/// Order-insensitive set of (type, data) for comparisons.
|
||||
pub fn rrset_key(records: &[Record]) -> Vec<String> {
|
||||
let mut v: Vec<String> = records.iter().map(|r| format!("{} {} {}", r.name.to_lowercase(), r.record_type(), r.data)).collect();
|
||||
v.sort();
|
||||
v.dedup();
|
||||
v
|
||||
}
|
||||
|
||||
/// Percentile of sorted samples.
|
||||
pub fn percentile(sorted: &[f64], p: f64) -> f64 {
|
||||
if sorted.is_empty() {
|
||||
return 0.0;
|
||||
}
|
||||
let idx = ((sorted.len() as f64 - 1.0) * p).round() as usize;
|
||||
sorted[idx.min(sorted.len() - 1)]
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn helpers() {
|
||||
assert_eq!(parse_type("mx"), Some(RecordType::MX));
|
||||
assert_eq!(parse_type("TYPE65"), Some(RecordType::HTTPS));
|
||||
assert_eq!(parse_type("bogus"), None);
|
||||
assert_eq!(percentile(&[1.0, 2.0, 3.0, 4.0], 0.5), 3.0);
|
||||
assert_eq!(parse_duration("2s").unwrap().as_secs(), 2);
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn server_parsing() {
|
||||
assert_eq!(server_addr("@1.1.1.1", 53).await.unwrap().port(), 53);
|
||||
assert_eq!(server_addr("127.0.0.1#5353", 53).await.unwrap().port(), 5353);
|
||||
assert_eq!(server_addr("[::1]:54", 53).await.unwrap().port(), 54);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
//! `econf` / `easyconf` – configuration validation (named-checkconf).
|
||||
use std::path::PathBuf;
|
||||
use std::process::ExitCode;
|
||||
|
||||
use clap::{Parser, Subcommand};
|
||||
|
||||
use crate::common::*;
|
||||
|
||||
#[derive(Parser, Debug)]
|
||||
#[command(name = "econf", version = VERSION, about = "EasyConf – validate EasyDNS configuration")]
|
||||
pub struct Args {
|
||||
#[command(subcommand)]
|
||||
pub cmd: Cmd,
|
||||
#[arg(long, global = true)]
|
||||
pub json: bool,
|
||||
}
|
||||
|
||||
#[derive(Subcommand, Debug)]
|
||||
pub enum Cmd {
|
||||
/// Validate a configuration file (and the zone files it references)
|
||||
Check { file: PathBuf },
|
||||
/// Print the effective configuration
|
||||
Print { file: PathBuf },
|
||||
}
|
||||
|
||||
pub fn main() -> ExitCode {
|
||||
let a = Args::parse();
|
||||
match a.cmd {
|
||||
Cmd::Check { file } => match dns_config::Config::load(&file) {
|
||||
Ok(cfg) => {
|
||||
let f = dns_server::check::check_config(&cfg);
|
||||
let errors = f.iter().filter(|x| x.severity == "error").count();
|
||||
if a.json {
|
||||
print_structured(&serde_json::to_value(&f).unwrap_or_default(), false);
|
||||
} else {
|
||||
for x in &f {
|
||||
println!("{x}");
|
||||
}
|
||||
println!("{}: {}", file.display(), if errors == 0 { "OK" } else { "FAILED" });
|
||||
}
|
||||
if errors == 0 { ExitCode::SUCCESS } else { ExitCode::from(1) }
|
||||
}
|
||||
Err(e) => fail("econf", 1, e),
|
||||
},
|
||||
Cmd::Print { file } => match dns_config::Config::load(&file) {
|
||||
Ok(cfg) => {
|
||||
print!("{}", serde_norway::to_string(&cfg).unwrap_or_default());
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Err(e) => fail("econf", 1, e),
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
//! `ediff` / `easydiff` – compare answers from several resolvers.
|
||||
//! RRset order is ignored; TTL differences are reported separately and do not
|
||||
//! count as a mismatch (TTLs decrease in caches).
|
||||
use std::process::ExitCode;
|
||||
|
||||
use clap::Parser;
|
||||
use dns_core::client::{QueryOptions, query};
|
||||
use dns_core::proto::rr::{Name, RecordType};
|
||||
use serde_json::json;
|
||||
|
||||
use crate::common::*;
|
||||
|
||||
#[derive(Parser, Debug)]
|
||||
#[command(name = "ediff", version = VERSION, about = "EasyDiff – compare DNS answers from several servers")]
|
||||
pub struct Args {
|
||||
pub name: String,
|
||||
/// Record type and servers (@1.1.1.1 @8.8.8.8 ...); type defaults to A
|
||||
pub rest: Vec<String>,
|
||||
#[arg(short, long, default_value_t = 53)]
|
||||
pub port: u16,
|
||||
#[arg(long)]
|
||||
pub json: bool,
|
||||
/// Treat TTL differences as mismatches
|
||||
#[arg(long)]
|
||||
pub strict_ttl: bool,
|
||||
}
|
||||
|
||||
pub fn main() -> ExitCode {
|
||||
let a = Args::parse();
|
||||
let name = match name_arg(&a.name) {
|
||||
Ok(n) => n,
|
||||
Err(e) => return fail("ediff", EXIT_USAGE, e),
|
||||
};
|
||||
let mut t = RecordType::A;
|
||||
let mut servers = Vec::new();
|
||||
for r in &a.rest {
|
||||
if let Some(s) = r.strip_prefix('@') {
|
||||
servers.push(s.to_string());
|
||||
} else if let Some(x) = parse_type(r) {
|
||||
t = x;
|
||||
} else {
|
||||
servers.push(r.clone());
|
||||
}
|
||||
}
|
||||
if servers.is_empty() {
|
||||
servers.push(system_resolver().to_string());
|
||||
}
|
||||
let _ = a.strict_ttl;
|
||||
block_on(run_compare(&name, t, &servers, a.port, a.json, QueryOptions::default()))
|
||||
}
|
||||
|
||||
/// Compare and print; exit 0 when all agree, 1 on differences, 9 when a server fails.
|
||||
pub async fn run_compare(name: &Name, t: RecordType, servers: &[String], port: u16, json_out: bool, opts: QueryOptions) -> ExitCode {
|
||||
let mut rows = Vec::new();
|
||||
for s in servers {
|
||||
let addr = match server_addr(s, port).await {
|
||||
Ok(a) => a,
|
||||
Err(e) => return fail("ediff", EXIT_USAGE, e),
|
||||
};
|
||||
let res = query(addr, name, t, &opts).await;
|
||||
rows.push((s.clone(), res));
|
||||
}
|
||||
let mut sets = Vec::new();
|
||||
let mut failed = false;
|
||||
let mut out = Vec::new();
|
||||
for (s, r) in &rows {
|
||||
match r {
|
||||
Ok(ex) => {
|
||||
let m = &ex.message;
|
||||
let key = rrset_key(&m.answers);
|
||||
let ttls: Vec<u32> = m.answers.iter().map(|r| r.ttl).collect();
|
||||
out.push(json!({ "server": s, "status": rcode_str(m.metadata.response_code), "flags": flags_str(m), "answers": key, "ttls": ttls, "ms": ex.elapsed.as_secs_f64() * 1000.0 }));
|
||||
sets.push((rcode_str(m.metadata.response_code), key));
|
||||
}
|
||||
Err(e) => {
|
||||
failed = true;
|
||||
out.push(json!({ "server": s, "error": e.to_string() }));
|
||||
}
|
||||
}
|
||||
}
|
||||
let consistent = sets.windows(2).all(|w| w[0] == w[1]);
|
||||
if json_out {
|
||||
print_structured(
|
||||
&json!({ "name": name.to_string(), "type": t.to_string(), "consistent": consistent && !failed, "results": out }),
|
||||
false,
|
||||
);
|
||||
} else {
|
||||
println!(";; {name} {t}");
|
||||
for r in &out {
|
||||
if let Some(e) = r.get("error") {
|
||||
println!("{:<22} ERROR {}", r["server"].as_str().unwrap_or(""), e);
|
||||
continue;
|
||||
}
|
||||
println!(
|
||||
"{:<22} {:<9} [{}] {:>7.1} ms ttl {:?}",
|
||||
r["server"].as_str().unwrap_or(""),
|
||||
r["status"].as_str().unwrap_or(""),
|
||||
r["flags"].as_str().unwrap_or(""),
|
||||
r["ms"].as_f64().unwrap_or(0.0),
|
||||
r["ttls"].as_array().map(|a| a.iter().filter_map(|x| x.as_u64()).collect::<Vec<_>>()).unwrap_or_default()
|
||||
);
|
||||
for a in r["answers"].as_array().into_iter().flatten() {
|
||||
println!(" {}", a.as_str().unwrap_or(""));
|
||||
}
|
||||
}
|
||||
println!(
|
||||
";; {}",
|
||||
if failed {
|
||||
"some servers failed"
|
||||
} else if consistent {
|
||||
"all servers agree"
|
||||
} else {
|
||||
"DIFFERENCES FOUND"
|
||||
}
|
||||
);
|
||||
}
|
||||
if failed {
|
||||
ExitCode::from(EXIT_NO_REPLY)
|
||||
} else if consistent {
|
||||
ExitCode::SUCCESS
|
||||
} else {
|
||||
ExitCode::from(1)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,498 @@
|
||||
//! `ed` / `easydig` – dig replacement.
|
||||
//!
|
||||
//! Supports the common dig syntax: `@server`, `-p`, `-t`, `-c`, `-q`, `-x`, `-y`, `-4/-6`,
|
||||
//! `+short`, `+trace`, `+dnssec`, `+tcp`, `+[no]recurse`, `+cd`, `+time=`, `+tries=`,
|
||||
//! `+bufsize=`, `+[no]edns`, `+[no]all`, `+[no]question|answer|authority|additional|stats|cmd`,
|
||||
//! plus `--json`, `--yaml`, `--watch`, `--compare`, `--benchmark`, `--timeout`, `--server`,
|
||||
//! `--port`, `--no-color`.
|
||||
use std::net::IpAddr;
|
||||
use std::process::ExitCode;
|
||||
use std::time::Duration;
|
||||
|
||||
use dns_core::client::{QueryOptions, build_query, exchange};
|
||||
use dns_core::proto::rr::{DNSClass, Name, RecordType};
|
||||
use dns_core::tsig::TsigKey;
|
||||
|
||||
use crate::common::*;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct DigOpts {
|
||||
pub server: Option<String>,
|
||||
pub port: u16,
|
||||
pub name: Option<Name>,
|
||||
pub rtype: Option<RecordType>,
|
||||
pub class: DNSClass,
|
||||
pub short: bool,
|
||||
pub trace: bool,
|
||||
pub dnssec: bool,
|
||||
pub tcp: bool,
|
||||
pub recurse: bool,
|
||||
pub cd: bool,
|
||||
pub ignore_tc: bool,
|
||||
pub json: bool,
|
||||
pub yaml: bool,
|
||||
pub watch: Option<Duration>,
|
||||
pub compare: Vec<String>,
|
||||
pub benchmark: Option<usize>,
|
||||
pub timeout: Duration,
|
||||
pub tries: u32,
|
||||
pub bufsize: u16,
|
||||
pub edns: bool,
|
||||
pub show: Sections,
|
||||
pub no_color: bool,
|
||||
pub v4_only: bool,
|
||||
pub v6_only: bool,
|
||||
pub tsig: Option<TsigKey>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct Sections {
|
||||
pub cmd: bool,
|
||||
pub question: bool,
|
||||
pub answer: bool,
|
||||
pub authority: bool,
|
||||
pub additional: bool,
|
||||
pub stats: bool,
|
||||
pub comments: bool,
|
||||
}
|
||||
|
||||
impl Sections {
|
||||
fn all(v: bool) -> Self {
|
||||
Self { cmd: v, question: v, answer: v, authority: v, additional: v, stats: v, comments: v }
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for DigOpts {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
server: None,
|
||||
port: 53,
|
||||
name: None,
|
||||
rtype: None,
|
||||
class: DNSClass::IN,
|
||||
short: false,
|
||||
trace: false,
|
||||
dnssec: false,
|
||||
tcp: false,
|
||||
recurse: true,
|
||||
cd: false,
|
||||
ignore_tc: false,
|
||||
json: false,
|
||||
yaml: false,
|
||||
watch: None,
|
||||
compare: Vec::new(),
|
||||
benchmark: None,
|
||||
timeout: Duration::from_secs(5),
|
||||
tries: 3,
|
||||
bufsize: 1232,
|
||||
edns: true,
|
||||
show: Sections::all(true),
|
||||
no_color: false,
|
||||
v4_only: false,
|
||||
v6_only: false,
|
||||
tsig: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub const USAGE: &str = "Usage: ed [@server] [-p port] [-t type] [-x addr] [-y [alg:]name:key] name [type] [class] [+opts] [--json|--yaml] [--watch DUR] [--compare S1,S2] [--benchmark N] [--timeout DUR]";
|
||||
|
||||
/// Parse dig-style arguments.
|
||||
pub fn parse_args(args: &[String]) -> Result<DigOpts, String> {
|
||||
let mut o = DigOpts::default();
|
||||
let mut it = args.iter().peekable();
|
||||
let need = |it: &mut std::iter::Peekable<std::slice::Iter<'_, String>>, flag: &str| -> Result<String, String> {
|
||||
it.next().cloned().ok_or_else(|| format!("option {flag} requires an argument"))
|
||||
};
|
||||
while let Some(a) = it.next() {
|
||||
let a = a.as_str();
|
||||
if let Some(s) = a.strip_prefix('@') {
|
||||
o.server = Some(s.to_string());
|
||||
} else if let Some(p) = a.strip_prefix('+') {
|
||||
let (neg, p) = match p.strip_prefix("no") {
|
||||
Some(rest) => (true, rest),
|
||||
None => (false, p),
|
||||
};
|
||||
let (key, val) = p.split_once('=').map(|(k, v)| (k, Some(v))).unwrap_or((p, None));
|
||||
match key {
|
||||
"short" => o.short = !neg,
|
||||
"trace" => o.trace = !neg,
|
||||
"dnssec" | "do" => o.dnssec = !neg,
|
||||
"tcp" | "vc" => o.tcp = !neg,
|
||||
"recurse" | "rec" => o.recurse = !neg,
|
||||
"cd" | "cdflag" => o.cd = !neg,
|
||||
"ignore" => o.ignore_tc = !neg,
|
||||
"edns" => o.edns = !neg,
|
||||
"all" => o.show = Sections::all(!neg),
|
||||
"cmd" => o.show.cmd = !neg,
|
||||
"question" => o.show.question = !neg,
|
||||
"answer" => o.show.answer = !neg,
|
||||
"authority" => o.show.authority = !neg,
|
||||
"additional" => o.show.additional = !neg,
|
||||
"stats" => o.show.stats = !neg,
|
||||
"comments" => o.show.comments = !neg,
|
||||
"time" | "timeout" => o.timeout = Duration::from_secs(val.and_then(|v| v.parse().ok()).ok_or("+time=N")?),
|
||||
"tries" => o.tries = val.and_then(|v| v.parse().ok()).ok_or("+tries=N")?,
|
||||
"retry" => o.tries = val.and_then(|v| v.parse::<u32>().ok()).ok_or("+retry=N")? + 1,
|
||||
"bufsize" => o.bufsize = val.and_then(|v| v.parse().ok()).ok_or("+bufsize=N")?,
|
||||
"json" => o.json = !neg,
|
||||
"yaml" => o.yaml = !neg,
|
||||
"multiline" | "cookie" | "nsid" | "identify" | "ttlid" | "class" | "ttlunits" => {}
|
||||
other => return Err(format!("unknown option +{other}")),
|
||||
}
|
||||
} else if a == "-x" {
|
||||
let ip: IpAddr = need(&mut it, "-x")?.parse().map_err(|_| "invalid address for -x")?;
|
||||
o.name = Some(dns_core::names::reverse_name(ip));
|
||||
o.rtype = Some(RecordType::PTR);
|
||||
} else if a == "-p" || a == "--port" {
|
||||
o.port = need(&mut it, a)?.parse().map_err(|_| "invalid port")?;
|
||||
} else if a == "-t" {
|
||||
let v = need(&mut it, "-t")?;
|
||||
o.rtype = Some(parse_type(&v).ok_or_else(|| format!("unknown type {v}"))?);
|
||||
} else if a == "-c" {
|
||||
let v = need(&mut it, "-c")?;
|
||||
o.class = v.to_ascii_uppercase().parse().map_err(|_| format!("unknown class {v}"))?;
|
||||
} else if a == "-q" {
|
||||
o.name = Some(name_arg(&need(&mut it, "-q")?)?);
|
||||
} else if a == "-y" {
|
||||
let v = need(&mut it, "-y")?;
|
||||
let parts: Vec<&str> = v.split(':').collect();
|
||||
let (alg, name, secret) = match parts.as_slice() {
|
||||
[n, s] => ("hmac-sha256", *n, *s),
|
||||
[a, n, s] => (*a, *n, *s),
|
||||
_ => return Err("-y expects [alg:]name:base64secret".into()),
|
||||
};
|
||||
o.tsig = Some(TsigKey::new(name, alg, secret).map_err(|e| e.to_string())?);
|
||||
} else if a == "-4" {
|
||||
o.v4_only = true;
|
||||
} else if a == "-6" {
|
||||
o.v6_only = true;
|
||||
} else if a == "--json" {
|
||||
o.json = true;
|
||||
} else if a == "--yaml" {
|
||||
o.yaml = true;
|
||||
} else if a == "--no-color" {
|
||||
o.no_color = true;
|
||||
} else if a == "--server" {
|
||||
o.server = Some(need(&mut it, a)?);
|
||||
} else if a == "--timeout" {
|
||||
o.timeout = parse_duration(&need(&mut it, a)?)?;
|
||||
} else if a == "--watch" {
|
||||
o.watch = Some(parse_duration(&need(&mut it, a)?)?);
|
||||
} else if a == "--compare" {
|
||||
o.compare = need(&mut it, a)?.split(',').map(|s| s.trim().to_string()).filter(|s| !s.is_empty()).collect();
|
||||
} else if a == "--benchmark" {
|
||||
o.benchmark = Some(need(&mut it, a)?.parse().map_err(|_| "--benchmark N")?);
|
||||
} else if a.starts_with('-') && a.len() > 1 {
|
||||
return Err(format!("unknown option {a}"));
|
||||
} else if o.name.is_some() && o.rtype.is_none() && parse_type(a).is_some() {
|
||||
o.rtype = parse_type(a);
|
||||
} else if o.name.is_some() && matches!(a.to_ascii_uppercase().as_str(), "IN" | "CH" | "HS" | "ANY") {
|
||||
o.class = a.to_ascii_uppercase().parse().map_err(|_| "class")?;
|
||||
} else if o.name.is_none() {
|
||||
o.name = Some(name_arg(a)?);
|
||||
} else if o.rtype.is_none() {
|
||||
return Err(format!("unknown type '{a}'"));
|
||||
} else {
|
||||
return Err(format!("unexpected argument '{a}'"));
|
||||
}
|
||||
}
|
||||
if o.name.is_none() {
|
||||
o.name = Some(Name::root());
|
||||
o.rtype.get_or_insert(RecordType::NS);
|
||||
}
|
||||
Ok(o)
|
||||
}
|
||||
|
||||
pub fn query_options(o: &DigOpts) -> QueryOptions {
|
||||
QueryOptions {
|
||||
timeout: o.timeout,
|
||||
retries: o.tries.saturating_sub(1),
|
||||
tcp_only: o.tcp || matches!(o.rtype, Some(RecordType::AXFR | RecordType::IXFR)),
|
||||
ignore_tc: o.ignore_tc,
|
||||
edns: o.edns,
|
||||
edns_payload: o.bufsize,
|
||||
dnssec_ok: o.dnssec,
|
||||
recursion_desired: o.recurse,
|
||||
checking_disabled: o.cd,
|
||||
tsig: o.tsig.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Print a full exchange in dig format.
|
||||
pub fn print_dig(ex: &dns_core::client::Exchange, o: &DigOpts, c: Colors, cmdline: &str) {
|
||||
let m = &ex.message;
|
||||
let s = &o.show;
|
||||
if s.cmd {
|
||||
println!("\n; <<>> EasyDig {VERSION} <<>> {cmdline}");
|
||||
println!(";; global options: +cmd");
|
||||
}
|
||||
if s.comments {
|
||||
println!(";; Got answer:");
|
||||
println!(
|
||||
";; ->>HEADER<<- opcode: {}, status: {}, id: {}",
|
||||
format!("{:?}", m.metadata.op_code).to_uppercase(),
|
||||
c.rcode(m.metadata.response_code),
|
||||
m.metadata.id
|
||||
);
|
||||
println!(
|
||||
";; flags: {}; QUERY: {}, ANSWER: {}, AUTHORITY: {}, ADDITIONAL: {}",
|
||||
flags_str(m),
|
||||
m.queries.len(),
|
||||
m.answers.len(),
|
||||
m.authorities.len(),
|
||||
m.additionals.len() + usize::from(m.edns.is_some())
|
||||
);
|
||||
if !o.recurse && !m.metadata.recursion_available {
|
||||
} else if o.recurse && !m.metadata.recursion_available {
|
||||
println!(";; WARNING: recursion requested but not available");
|
||||
}
|
||||
if let Some(e) = &m.edns {
|
||||
println!("\n;; OPT PSEUDOSECTION:");
|
||||
println!("; EDNS: version: {}, flags:{}; udp: {}", e.version(), if e.flags().dnssec_ok { " do" } else { "" }, e.max_payload());
|
||||
}
|
||||
}
|
||||
if s.question {
|
||||
println!("\n{}", c.bold(";; QUESTION SECTION:"));
|
||||
for q in &m.queries {
|
||||
println!(";{}\t\t{}\t{}", q.name, q.query_class, q.query_type);
|
||||
}
|
||||
}
|
||||
for (show, title, recs) in [
|
||||
(s.answer, ";; ANSWER SECTION:", &m.answers),
|
||||
(s.authority, ";; AUTHORITY SECTION:", &m.authorities),
|
||||
(s.additional, ";; ADDITIONAL SECTION:", &m.additionals),
|
||||
] {
|
||||
if show && !recs.is_empty() {
|
||||
println!("\n{}", c.bold(title));
|
||||
for r in recs {
|
||||
println!("{}", rr_line(r));
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(sig) = &m.signature
|
||||
&& s.additional
|
||||
{
|
||||
println!(";; TSIG: key {} ({}){}", sig.name, sig.data.algorithm, if ex.tsig_verified { " verified" } else { "" });
|
||||
}
|
||||
if s.stats {
|
||||
println!("\n;; Query time: {} msec", ex.elapsed.as_millis());
|
||||
println!(
|
||||
";; SERVER: {}#{}({}) ({})",
|
||||
ex.server.ip(),
|
||||
ex.server.port(),
|
||||
ex.server.ip(),
|
||||
format!("{:?}", ex.transport).to_uppercase()
|
||||
);
|
||||
println!(";; WHEN: {}", now_string());
|
||||
println!(";; MSG SIZE rcvd: {}\n", ex.size);
|
||||
}
|
||||
}
|
||||
|
||||
/// UTC timestamp (RFC 3339-ish) without extra dependencies.
|
||||
pub fn now_string() -> String {
|
||||
let t = dns_core::tsig::now();
|
||||
let (d, s) = (t / 86400, t % 86400);
|
||||
let (y, m, dd) = civil(d as i64);
|
||||
format!("{y:04}-{m:02}-{dd:02} {:02}:{:02}:{:02} UTC", s / 3600, (s / 60) % 60, s % 60)
|
||||
}
|
||||
|
||||
fn civil(z: i64) -> (i64, u32, u32) {
|
||||
let z = z + 719_468;
|
||||
let era = z.div_euclid(146_097);
|
||||
let doe = (z - era * 146_097) as u64;
|
||||
let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
|
||||
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
|
||||
let mp = (5 * doy + 2) / 153;
|
||||
let d = (doy - (153 * mp + 2) / 5 + 1) as u32;
|
||||
let m = if mp < 10 { mp + 3 } else { mp - 9 } as u32;
|
||||
let y = yoe as i64 + era * 400;
|
||||
(if m <= 2 { y + 1 } else { y }, m, d)
|
||||
}
|
||||
|
||||
pub fn print_short(m: &dns_core::proto::op::Message) {
|
||||
for r in &m.answers {
|
||||
println!("{}", r.data);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn main() -> ExitCode {
|
||||
let args: Vec<String> = std::env::args().skip(1).collect();
|
||||
if args.iter().any(|a| a == "-h" || a == "--help") {
|
||||
println!("{USAGE}\n\nSee `man ed` or docs/cli-tools.md for all options.");
|
||||
return ExitCode::SUCCESS;
|
||||
}
|
||||
if args.iter().any(|a| a == "-v" || a == "--version") {
|
||||
println!("EasyDig {VERSION}");
|
||||
return ExitCode::SUCCESS;
|
||||
}
|
||||
let o = match parse_args(&args) {
|
||||
Ok(o) => o,
|
||||
Err(e) => return fail("ed", EXIT_USAGE, format!("{e}\n{USAGE}")),
|
||||
};
|
||||
let cmdline = args.join(" ");
|
||||
block_on(run(o, cmdline))
|
||||
}
|
||||
|
||||
pub async fn run(o: DigOpts, cmdline: String) -> ExitCode {
|
||||
let c = Colors::detect(o.no_color);
|
||||
let name = o.name.clone().unwrap_or_else(Name::root);
|
||||
let rtype = o.rtype.unwrap_or(RecordType::A);
|
||||
if o.trace {
|
||||
return crate::trace::run_trace(&name, rtype, o.json || o.yaml, o.yaml, o.dnssec, c).await;
|
||||
}
|
||||
if !o.compare.is_empty() {
|
||||
return crate::diff::run_compare(&name, rtype, &o.compare, o.port, o.json, query_options(&o)).await;
|
||||
}
|
||||
let server = match &o.server {
|
||||
Some(s) => match server_addr(s, o.port).await {
|
||||
Ok(a) => a,
|
||||
Err(e) => return fail("ed", EXIT_USAGE, e),
|
||||
},
|
||||
None => std::net::SocketAddr::new(system_resolver(), o.port),
|
||||
};
|
||||
if (o.v4_only && server.is_ipv6()) || (o.v6_only && server.is_ipv4()) {
|
||||
return fail("ed", EXIT_USAGE, "server address family does not match -4/-6");
|
||||
}
|
||||
if let Some(n) = o.benchmark {
|
||||
return crate::bench::run_simple(server, &name, rtype, n, 10, o.timeout).await;
|
||||
}
|
||||
if matches!(rtype, RecordType::AXFR | RecordType::IXFR) {
|
||||
return axfr(server, &name, rtype, &o, c).await;
|
||||
}
|
||||
let opts = query_options(&o);
|
||||
let mut previous: Option<Vec<String>> = None;
|
||||
loop {
|
||||
let mut msg = build_query(&name, rtype, &opts);
|
||||
if let Some(q) = msg.queries.first_mut() {
|
||||
q.set_query_class(o.class);
|
||||
}
|
||||
match exchange(server, msg, &opts).await {
|
||||
Ok(ex) => {
|
||||
if let Some(iv) = o.watch {
|
||||
let now = rrset_key(&ex.message.answers);
|
||||
let changed = previous.as_ref().is_some_and(|p| *p != now);
|
||||
let tag = if previous.is_none() {
|
||||
"initial"
|
||||
} else if changed {
|
||||
"CHANGED"
|
||||
} else {
|
||||
"same"
|
||||
};
|
||||
println!(
|
||||
"{} [{tag}] {} {} {} ms",
|
||||
now_string(),
|
||||
rcode_str(ex.message.metadata.response_code),
|
||||
ex.message.answers.len(),
|
||||
ex.elapsed.as_millis()
|
||||
);
|
||||
if previous.is_none() || changed {
|
||||
for r in &ex.message.answers {
|
||||
println!(" {}", rr_line(r));
|
||||
}
|
||||
}
|
||||
previous = Some(now);
|
||||
tokio::select! {
|
||||
_ = tokio::time::sleep(iv) => continue,
|
||||
_ = tokio::signal::ctrl_c() => return ExitCode::SUCCESS,
|
||||
}
|
||||
}
|
||||
if o.json || o.yaml {
|
||||
print_structured(&exchange_json(&ex), o.yaml);
|
||||
} else if o.short {
|
||||
print_short(&ex.message);
|
||||
} else {
|
||||
print_dig(&ex, &o, c, &cmdline);
|
||||
}
|
||||
return ExitCode::SUCCESS;
|
||||
}
|
||||
Err(e) => {
|
||||
if o.watch.is_some() {
|
||||
println!("{} [error] {e}", now_string());
|
||||
tokio::time::sleep(o.watch.unwrap_or(Duration::from_secs(5))).await;
|
||||
continue;
|
||||
}
|
||||
if !o.short && !o.json {
|
||||
println!(";; communications error to {server}: {e}");
|
||||
println!(";; no servers could be reached");
|
||||
}
|
||||
return net_error("ed", &e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn axfr(server: std::net::SocketAddr, name: &Name, rtype: RecordType, o: &DigOpts, c: Colors) -> ExitCode {
|
||||
let kind = if rtype == RecordType::IXFR {
|
||||
// dig syntax ixfr=SERIAL is not supported; request IXFR from serial 0 (full)
|
||||
let soa = dns_core::proto::rr::Record::from_rdata(
|
||||
name.clone(),
|
||||
0,
|
||||
dns_core::proto::rr::RData::SOA(dns_core::proto::rr::rdata::SOA::new(name.clone(), name.clone(), 0, 0, 0, 0, 0)),
|
||||
);
|
||||
dns_core::client::TransferKind::Ixfr { current_soa: Box::new(soa) }
|
||||
} else {
|
||||
dns_core::client::TransferKind::Axfr
|
||||
};
|
||||
let lim = dns_core::client::TransferLimits { timeout: o.timeout.max(Duration::from_secs(30)), ..Default::default() };
|
||||
match dns_core::client::transfer(server, name, &kind, o.tsig.as_ref(), lim).await {
|
||||
Ok(st) => {
|
||||
if o.json || o.yaml {
|
||||
print_structured(
|
||||
&serde_json::json!({ "records": st.records.iter().map(rr_json).collect::<Vec<_>>(), "messages": st.messages, "bytes": st.bytes, "tsig_verified": st.tsig_verified }),
|
||||
o.yaml,
|
||||
);
|
||||
} else {
|
||||
println!("\n; <<>> EasyDig {VERSION} <<>> {} {name} @{server}", rtype);
|
||||
for r in &st.records {
|
||||
println!("{}", rr_line(r));
|
||||
}
|
||||
println!(
|
||||
"{}",
|
||||
c.bold(&format!(
|
||||
";; XFR size: {} records (messages {}, bytes {}){}",
|
||||
st.records.len(),
|
||||
st.messages,
|
||||
st.bytes,
|
||||
if st.tsig_verified { ", TSIG verified" } else { "" }
|
||||
))
|
||||
);
|
||||
println!(";; Query time: {} msec\n;; SERVER: {server}", st.elapsed.as_millis());
|
||||
}
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Err(e) => {
|
||||
println!("; Transfer failed: {e}");
|
||||
net_error("ed", &e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
fn p(s: &str) -> DigOpts {
|
||||
parse_args(&s.split_whitespace().map(String::from).collect::<Vec<_>>()).unwrap()
|
||||
}
|
||||
#[test]
|
||||
fn dig_syntax() {
|
||||
let o = p("@1.1.1.1 example.com MX +short +tcp");
|
||||
assert_eq!(o.server.as_deref(), Some("1.1.1.1"));
|
||||
assert_eq!(o.rtype, Some(RecordType::MX));
|
||||
assert!(o.short && o.tcp);
|
||||
let o = p("-x 192.0.2.1");
|
||||
assert_eq!(o.name.unwrap().to_string(), "1.2.0.192.in-addr.arpa.");
|
||||
assert_eq!(o.rtype, Some(RecordType::PTR));
|
||||
let o = p("example.com --server 127.0.0.1 --port 5353 --timeout 2s +norecurse +noall +answer");
|
||||
assert_eq!(o.port, 5353);
|
||||
assert!(!o.recurse && o.show.answer && !o.show.question);
|
||||
let o = p("");
|
||||
assert_eq!(o.rtype, Some(RecordType::NS));
|
||||
assert!(parse_args(&["+bogus".into()]).is_err());
|
||||
let o = p("example.com --compare 1.1.1.1,8.8.8.8 --json");
|
||||
assert_eq!(o.compare.len(), 2);
|
||||
assert!(o.json);
|
||||
let o = p("-t aaaa example.com CH");
|
||||
assert_eq!((o.rtype, o.class), (Some(RecordType::AAAA), DNSClass::CH));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
//! `ednssec` / `easydnssec` – DNSSEC chain-of-trust diagnostics (delv-like).
|
||||
//!
|
||||
//! Resolves iteratively from the root with validation and reports, for every zone cut on
|
||||
//! the way to the name, its DS/DNSKEY key tags and key state, then the validation result
|
||||
//! of the answer: secure, insecure, bogus (with the reason) or indeterminate.
|
||||
use std::process::ExitCode;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use clap::Parser;
|
||||
use dns_core::answer::Security;
|
||||
use dns_core::proto::rr::{Name, RecordType};
|
||||
use dns_recursive::validator::KeyState;
|
||||
use serde_json::json;
|
||||
|
||||
use crate::common::*;
|
||||
|
||||
#[derive(Parser, Debug)]
|
||||
#[command(name = "ednssec", version = VERSION, about = "EasyDNSSEC – validate a name and show the chain of trust")]
|
||||
pub struct Args {
|
||||
pub name: String,
|
||||
#[arg(default_value = "A")]
|
||||
pub rtype: String,
|
||||
/// Trust anchor file (DS/DNSKEY records); default: built-in IANA root KSKs
|
||||
#[arg(long)]
|
||||
pub anchors: Option<std::path::PathBuf>,
|
||||
#[arg(long)]
|
||||
pub root_hints: Option<std::path::PathBuf>,
|
||||
#[arg(long, default_value_t = 53, hide = true)]
|
||||
pub port: u16,
|
||||
#[arg(short, long)]
|
||||
pub verbose: bool,
|
||||
#[arg(long)]
|
||||
pub json: bool,
|
||||
#[arg(long)]
|
||||
pub no_color: bool,
|
||||
}
|
||||
|
||||
pub fn main() -> ExitCode {
|
||||
block_on(run(Args::parse()))
|
||||
}
|
||||
|
||||
fn state_str(s: &KeyState) -> (&'static str, String) {
|
||||
match s {
|
||||
KeyState::Secure(k) => (
|
||||
"secure",
|
||||
format!(
|
||||
"{} DNSKEY(s): {}",
|
||||
k.len(),
|
||||
k.iter().filter_map(|k| k.calculate_key_tag().ok()).map(|t| t.to_string()).collect::<Vec<_>>().join(", ")
|
||||
),
|
||||
),
|
||||
KeyState::Insecure => ("insecure", "no DS in parent (provably unsigned) or unsupported algorithm".into()),
|
||||
KeyState::Bogus(e) => ("bogus", e.clone()),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn run(a: Args) -> ExitCode {
|
||||
let c = Colors::detect(a.no_color);
|
||||
let (Ok(name), Some(t)) = (name_arg(&a.name), parse_type(&a.rtype)) else { return fail("ednssec", EXIT_USAGE, "invalid name or type") };
|
||||
let hints = match dns_recursive::hints::load(a.root_hints.as_deref()) {
|
||||
Ok(h) => h,
|
||||
Err(e) => return fail("ednssec", EXIT_USAGE, e),
|
||||
};
|
||||
let cache = Arc::new(dns_cache::Cache::new(&dns_config::CacheConfig { max_entries: 20_000, ..Default::default() }));
|
||||
let settings = dns_recursive::Settings {
|
||||
max_depth: 30,
|
||||
max_queries: 300,
|
||||
max_cname: 8,
|
||||
query_timeout: Duration::from_secs(2),
|
||||
total_timeout: Duration::from_secs(30),
|
||||
port: a.port,
|
||||
qname_minimization: true,
|
||||
ipv6: false,
|
||||
max_subqueries_depth: 4,
|
||||
dnssec: true,
|
||||
};
|
||||
let mut r = match dns_recursive::Resolver::new(settings, hints, cache, 0) {
|
||||
Ok(r) => r,
|
||||
Err(e) => return fail("ednssec", EXIT_INTERNAL, e),
|
||||
};
|
||||
if let Some(p) = &a.anchors {
|
||||
let recs = match dns_core::zonefile::parse_file(p, &Name::root()) {
|
||||
Ok(r) => r,
|
||||
Err(e) => return fail("ednssec", EXIT_USAGE, e),
|
||||
};
|
||||
if let Err(e) = r.set_trust_anchors(&recs) {
|
||||
return fail("ednssec", EXIT_USAGE, e);
|
||||
}
|
||||
}
|
||||
let ans = r.resolve(&name, t).await;
|
||||
// zone cuts on the path (ancestors that have an SOA at their apex)
|
||||
let mut zones: Vec<Name> = Vec::new();
|
||||
let mut anc: Vec<Name> = dns_core::names::ancestors(&name).collect();
|
||||
anc.reverse();
|
||||
for z in anc {
|
||||
let soa = r.resolve(&z, RecordType::SOA).await;
|
||||
if soa.answers.iter().any(|x| x.record_type() == RecordType::SOA && x.name.eq_ignore_root_case(&z)) {
|
||||
zones.push(z);
|
||||
}
|
||||
}
|
||||
let mut chain = Vec::new();
|
||||
for z in &zones {
|
||||
let st = r.zone_key_state(z).await;
|
||||
let ds = if z.is_root() {
|
||||
Vec::new()
|
||||
} else {
|
||||
r.resolve(z, RecordType::DS).await.answers.iter().filter_map(dns_core::dnssec::ds_of).map(|d| d.key_tag()).collect()
|
||||
};
|
||||
let (s, detail) = state_str(&st);
|
||||
chain.push((z.to_string(), s, detail, ds));
|
||||
}
|
||||
let sec = ans.security;
|
||||
let label = match sec {
|
||||
Security::Secure => "secure",
|
||||
Security::Insecure => "insecure",
|
||||
Security::Bogus => "bogus",
|
||||
Security::Indeterminate => "indeterminate",
|
||||
};
|
||||
if a.json {
|
||||
print_structured(
|
||||
&json!({
|
||||
"name": name.to_string(), "type": t.to_string(), "status": rcode_str(ans.rcode), "validation": label, "reason": ans.note,
|
||||
"chain": chain.iter().map(|(z, s, d, ds)| json!({"zone": z, "state": s, "detail": d, "ds_key_tags": ds})).collect::<Vec<_>>(),
|
||||
"answer": ans.answers.iter().filter(|r| a.verbose || r.record_type() != RecordType::RRSIG).map(rr_json).collect::<Vec<_>>(),
|
||||
}),
|
||||
false,
|
||||
);
|
||||
} else {
|
||||
println!("; EasyDNSSEC {VERSION} {name} {t}\n");
|
||||
println!("{}", c.bold(";; chain of trust"));
|
||||
for (z, s, d, ds) in &chain {
|
||||
let col = match *s {
|
||||
"secure" => c.paint("32", s),
|
||||
"insecure" => c.paint("33", s),
|
||||
_ => c.paint("31", s),
|
||||
};
|
||||
let ds_s = if z == "." {
|
||||
"trust anchor".to_string()
|
||||
} else if ds.is_empty() {
|
||||
"no DS".into()
|
||||
} else {
|
||||
format!("DS {ds:?}")
|
||||
};
|
||||
println!(";; {z:<32} {col:<10} {ds_s:<22} {d}");
|
||||
}
|
||||
println!();
|
||||
let verdict = match sec {
|
||||
Security::Secure => c.paint("32", "; fully validated"),
|
||||
Security::Insecure => c.paint("33", "; unsigned answer (insecure)"),
|
||||
Security::Bogus => c.paint("31", &format!("; validation FAILED: {}", ans.note.clone().unwrap_or_default())),
|
||||
Security::Indeterminate => c.paint("31", &format!("; could not validate: {}", ans.note.clone().unwrap_or_default())),
|
||||
};
|
||||
println!("{verdict}");
|
||||
println!(";; status {}", rcode_str(ans.rcode));
|
||||
for rr in ans.answers.iter().filter(|r| a.verbose || r.record_type() != RecordType::RRSIG) {
|
||||
println!("{}", rr_line(rr));
|
||||
}
|
||||
}
|
||||
match sec {
|
||||
Security::Secure | Security::Insecure => ExitCode::SUCCESS,
|
||||
Security::Bogus => ExitCode::from(2),
|
||||
Security::Indeterminate => ExitCode::from(EXIT_NO_REPLY),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
//! `edoh` / `easydoh` – DNS-over-HTTPS diagnostics (RFC 8484 GET/POST).
|
||||
use std::process::ExitCode;
|
||||
use std::time::Duration;
|
||||
|
||||
use clap::Parser;
|
||||
use dns_core::client::{QueryOptions, build_query};
|
||||
use dns_core::proto::op::Message;
|
||||
use dns_core::tls::DohMethod;
|
||||
use serde_json::json;
|
||||
|
||||
use crate::common::*;
|
||||
|
||||
#[derive(Parser, Debug)]
|
||||
#[command(name = "edoh", version = VERSION, about = "EasyDoH – test a DNS-over-HTTPS endpoint")]
|
||||
pub struct Args {
|
||||
/// URL, e.g. https://1.1.1.1/dns-query or https://127.0.0.1:8443/dns-query
|
||||
pub url: String,
|
||||
pub name: String,
|
||||
#[arg(default_value = "A")]
|
||||
pub rtype: String,
|
||||
/// HTTP method
|
||||
#[arg(long, default_value = "post", value_parser = ["get", "post"])]
|
||||
pub method: String,
|
||||
/// TLS server name (default: URL host)
|
||||
#[arg(long)]
|
||||
pub tls_name: Option<String>,
|
||||
#[arg(long)]
|
||||
pub ca: Option<std::path::PathBuf>,
|
||||
#[arg(long)]
|
||||
pub insecure: bool,
|
||||
#[arg(long, default_value = "5s")]
|
||||
pub timeout: String,
|
||||
#[arg(long)]
|
||||
pub json: bool,
|
||||
/// Use HTTP/2 (as browsers do) instead of HTTP/1.1; reports whether h2 was negotiated
|
||||
#[arg(long)]
|
||||
pub http2: bool,
|
||||
}
|
||||
|
||||
pub fn main() -> ExitCode {
|
||||
block_on(run(Args::parse()))
|
||||
}
|
||||
|
||||
pub async fn run(a: Args) -> ExitCode {
|
||||
let Some(rest) = a.url.strip_prefix("https://") else { return fail("edoh", EXIT_USAGE, "URL must start with https://") };
|
||||
let (hostport, path) = rest.split_at(rest.find('/').unwrap_or(rest.len()));
|
||||
let path = if path.is_empty() { "/dns-query" } else { path };
|
||||
let host = hostport
|
||||
.rsplit_once(':')
|
||||
.filter(|(h, _)| !h.ends_with(']') || h.starts_with('['))
|
||||
.map(|(h, _)| h)
|
||||
.unwrap_or(hostport)
|
||||
.trim_matches(['[', ']']);
|
||||
let addr = match server_addr(hostport, 443).await {
|
||||
Ok(x) => x,
|
||||
Err(e) => return fail("edoh", EXIT_USAGE, e),
|
||||
};
|
||||
let (Ok(name), Some(t)) = (name_arg(&a.name), parse_type(&a.rtype)) else { return fail("edoh", EXIT_USAGE, "invalid name or type") };
|
||||
let ca = match &a.ca {
|
||||
Some(p) => match std::fs::read(p) {
|
||||
Ok(b) => Some(b),
|
||||
Err(e) => return fail("edoh", EXIT_USAGE, format!("{}: {e}", p.display())),
|
||||
},
|
||||
None => None,
|
||||
};
|
||||
let cfg = match dns_core::tls::client_config(ca.as_deref(), a.insecure, &[b"http/1.1"]) {
|
||||
Ok(c) => c,
|
||||
Err(e) => return fail("edoh", EXIT_USAGE, e),
|
||||
};
|
||||
let sni = a.tls_name.clone().unwrap_or_else(|| host.to_string());
|
||||
let q = build_query(&name, t, &QueryOptions::default());
|
||||
let Ok(bytes) = q.to_vec() else { return fail("edoh", EXIT_INTERNAL, "encode") };
|
||||
let method = if a.method == "get" { DohMethod::Get } else { DohMethod::Post };
|
||||
let timeout = parse_duration(&a.timeout).unwrap_or(Duration::from_secs(5));
|
||||
if a.http2 {
|
||||
let base = match dns_core::tls::client_config(ca.as_deref(), a.insecure, &[]) {
|
||||
Ok(c) => c,
|
||||
Err(e) => return fail("edoh", EXIT_USAGE, e),
|
||||
};
|
||||
let c = dns_core::tls_pool::DohClient::new(addr, &sni, path, &base);
|
||||
let start = std::time::Instant::now();
|
||||
return match c.exchange(&bytes, method, timeout).await {
|
||||
Ok((status, body)) => {
|
||||
let total = start.elapsed().as_secs_f64() * 1000.0;
|
||||
let proto = if c.uses_http2() { "HTTP/2" } else { "HTTP/1.1 (server did not offer h2)" };
|
||||
let m = Message::from_vec(&body).ok();
|
||||
if a.json {
|
||||
print_structured(
|
||||
&json!({ "url": a.url, "http_status": status, "protocol": proto, "total_ms": total,
|
||||
"status": m.as_ref().map(|m| rcode_str(m.metadata.response_code)),
|
||||
"answer": m.as_ref().map(|m| m.answers.iter().map(rr_json).collect::<Vec<_>>()) }),
|
||||
false,
|
||||
);
|
||||
} else {
|
||||
println!(";; DoH {} {} over {proto} -> HTTP {status}, total {total:.1} ms", a.method.to_uppercase(), a.url);
|
||||
if let Some(m) = &m {
|
||||
println!(";; status {} flags: {}", rcode_str(m.metadata.response_code), flags_str(m));
|
||||
for r in &m.answers {
|
||||
println!("{}", rr_line(r));
|
||||
}
|
||||
}
|
||||
}
|
||||
if status == 200 && m.is_some() { ExitCode::SUCCESS } else { ExitCode::from(1) }
|
||||
}
|
||||
Err(e) => net_error("edoh", &e),
|
||||
};
|
||||
}
|
||||
let start = std::time::Instant::now();
|
||||
match dns_core::tls::doh_exchange(addr, &sni, path, &bytes, method, timeout, cfg).await {
|
||||
Ok((status, body, info)) => {
|
||||
let total = start.elapsed().as_secs_f64() * 1000.0;
|
||||
let m = Message::from_vec(&body).ok();
|
||||
if a.json {
|
||||
print_structured(
|
||||
&json!({ "url": a.url, "http_status": status, "method": a.method.to_uppercase(), "tls": info, "total_ms": total,
|
||||
"status": m.as_ref().map(|m| rcode_str(m.metadata.response_code)),
|
||||
"answer": m.as_ref().map(|m| m.answers.iter().map(rr_json).collect::<Vec<_>>()) }),
|
||||
false,
|
||||
);
|
||||
} else {
|
||||
println!(";; DoH {} {} -> HTTP {status}", a.method.to_uppercase(), a.url);
|
||||
println!(
|
||||
";; TLS {} {} ALPN {:?}{}",
|
||||
info.protocol,
|
||||
info.cipher_suite,
|
||||
info.alpn,
|
||||
if a.insecure { " — NOT VERIFIED" } else { ", certificate verified" }
|
||||
);
|
||||
println!(";; connect {:.1} ms, handshake {:.1} ms, total {total:.1} ms", info.connect_ms, info.handshake_ms);
|
||||
match &m {
|
||||
Some(m) => {
|
||||
println!(";; status {} flags: {}", rcode_str(m.metadata.response_code), flags_str(m));
|
||||
for r in &m.answers {
|
||||
println!("{}", rr_line(r));
|
||||
}
|
||||
}
|
||||
None => println!(
|
||||
";; body is not a DNS message ({} bytes): {}",
|
||||
body.len(),
|
||||
String::from_utf8_lossy(&body[..body.len().min(200)])
|
||||
),
|
||||
}
|
||||
}
|
||||
if status == 200 && m.is_some() { ExitCode::SUCCESS } else { ExitCode::from(1) }
|
||||
}
|
||||
Err(e) => net_error("edoh", &e),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
//! `edot` / `easydot` – DNS-over-TLS diagnostics.
|
||||
use std::process::ExitCode;
|
||||
use std::time::Duration;
|
||||
|
||||
use clap::Parser;
|
||||
use dns_core::client::{QueryOptions, build_query};
|
||||
use dns_core::proto::op::Message;
|
||||
use serde_json::json;
|
||||
|
||||
use crate::common::*;
|
||||
|
||||
#[derive(Parser, Debug)]
|
||||
#[command(name = "edot", version = VERSION, about = "EasyDoT – test a DNS-over-TLS server")]
|
||||
pub struct Args {
|
||||
/// Server IP[:port] (default port 853)
|
||||
pub server: String,
|
||||
pub name: String,
|
||||
#[arg(default_value = "A")]
|
||||
pub rtype: String,
|
||||
/// TLS server name (SNI and certificate check); defaults to the server argument
|
||||
#[arg(long)]
|
||||
pub tls_name: Option<String>,
|
||||
/// Extra CA certificate (PEM) to trust
|
||||
#[arg(long)]
|
||||
pub ca: Option<std::path::PathBuf>,
|
||||
/// Skip certificate verification (diagnostics only!)
|
||||
#[arg(long)]
|
||||
pub insecure: bool,
|
||||
#[arg(long, default_value = "5s")]
|
||||
pub timeout: String,
|
||||
#[arg(long)]
|
||||
pub json: bool,
|
||||
}
|
||||
|
||||
pub fn main() -> ExitCode {
|
||||
block_on(run(Args::parse()))
|
||||
}
|
||||
|
||||
pub async fn run(a: Args) -> ExitCode {
|
||||
let addr = match server_addr(&a.server, 853).await {
|
||||
Ok(x) => x,
|
||||
Err(e) => return fail("edot", EXIT_USAGE, e),
|
||||
};
|
||||
let (Ok(name), Some(t)) = (name_arg(&a.name), parse_type(&a.rtype)) else { return fail("edot", EXIT_USAGE, "invalid name or type") };
|
||||
let timeout = parse_duration(&a.timeout).unwrap_or(Duration::from_secs(5));
|
||||
let ca = match &a.ca {
|
||||
Some(p) => match std::fs::read(p) {
|
||||
Ok(b) => Some(b),
|
||||
Err(e) => return fail("edot", EXIT_USAGE, format!("{}: {e}", p.display())),
|
||||
},
|
||||
None => None,
|
||||
};
|
||||
let cfg = match dns_core::tls::client_config(ca.as_deref(), a.insecure, &[b"dot"]) {
|
||||
Ok(c) => c,
|
||||
Err(e) => return fail("edot", EXIT_USAGE, e),
|
||||
};
|
||||
let sni = a.tls_name.clone().unwrap_or_else(|| addr.ip().to_string());
|
||||
let q = build_query(&name, t, &QueryOptions::default());
|
||||
let bytes = match q.to_vec() {
|
||||
Ok(b) => b,
|
||||
Err(e) => return fail("edot", EXIT_INTERNAL, e),
|
||||
};
|
||||
let start = std::time::Instant::now();
|
||||
match dns_core::tls::dot_exchange(addr, &sni, &bytes, timeout, cfg).await {
|
||||
Ok((raw, info)) => {
|
||||
let total = start.elapsed().as_secs_f64() * 1000.0;
|
||||
let m = match Message::from_vec(&raw) {
|
||||
Ok(m) => m,
|
||||
Err(e) => return fail("edot", EXIT_INTERNAL, format!("invalid DNS response: {e}")),
|
||||
};
|
||||
if a.json {
|
||||
print_structured(
|
||||
&json!({ "server": addr.to_string(), "tls_name": sni, "tls": info, "total_ms": total, "status": rcode_str(m.metadata.response_code),
|
||||
"answer": m.answers.iter().map(rr_json).collect::<Vec<_>>(), "certificate_verified": !a.insecure }),
|
||||
false,
|
||||
);
|
||||
} else {
|
||||
println!(";; DoT {addr} (SNI {sni})");
|
||||
println!(
|
||||
";; TLS {} {} ALPN {:?}, {} peer certificate(s){}",
|
||||
info.protocol,
|
||||
info.cipher_suite,
|
||||
info.alpn,
|
||||
info.peer_certificates,
|
||||
if a.insecure { " — NOT VERIFIED" } else { ", verified" }
|
||||
);
|
||||
println!(";; connect {:.1} ms, handshake {:.1} ms, total {total:.1} ms", info.connect_ms, info.handshake_ms);
|
||||
println!(";; status {} flags: {}", rcode_str(m.metadata.response_code), flags_str(&m));
|
||||
for r in &m.answers {
|
||||
println!("{}", rr_line(r));
|
||||
}
|
||||
}
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Err(e) => net_error("edot", &e),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
//! `eh` / `easyhost` – host replacement.
|
||||
use std::net::IpAddr;
|
||||
use std::process::ExitCode;
|
||||
|
||||
use clap::Parser;
|
||||
use dns_core::client::{QueryOptions, query};
|
||||
use dns_core::proto::op::ResponseCode;
|
||||
use dns_core::proto::rr::{RData, RecordType};
|
||||
use serde_json::json;
|
||||
|
||||
use crate::common::*;
|
||||
|
||||
#[derive(Parser, Debug)]
|
||||
#[command(name = "eh", version = VERSION, about = "EasyHost – simple DNS lookups (host replacement)")]
|
||||
pub struct Args {
|
||||
/// Name or IP address (IP → reverse lookup)
|
||||
pub target: String,
|
||||
/// Server to query
|
||||
pub server: Option<String>,
|
||||
/// Query type
|
||||
#[arg(short = 't', long = "type")]
|
||||
pub rtype: Option<String>,
|
||||
/// Query common types (A, AAAA, MX, NS, TXT, SOA, CAA)
|
||||
#[arg(short = 'a', long = "all")]
|
||||
pub all: bool,
|
||||
/// Use TCP
|
||||
#[arg(short = 'T', long)]
|
||||
pub tcp: bool,
|
||||
/// Port
|
||||
#[arg(short, long, default_value_t = 53)]
|
||||
pub port: u16,
|
||||
/// Timeout (e.g. 2s)
|
||||
#[arg(short = 'W', long, default_value = "5s")]
|
||||
pub timeout: String,
|
||||
/// Retries
|
||||
#[arg(short = 'R', long, default_value_t = 1)]
|
||||
pub retries: u32,
|
||||
/// Verbose (dig-like) output
|
||||
#[arg(short, long)]
|
||||
pub verbose: bool,
|
||||
#[arg(long)]
|
||||
pub json: bool,
|
||||
}
|
||||
|
||||
fn describe(r: &dns_core::proto::rr::Record) -> String {
|
||||
let owner = r.name.to_string();
|
||||
let n = owner.trim_end_matches('.');
|
||||
match &r.data {
|
||||
RData::A(a) => format!("{n} has address {a}"),
|
||||
RData::AAAA(a) => format!("{n} has IPv6 address {a}"),
|
||||
RData::MX(mx) => format!("{n} mail is handled by {} {}", mx.preference, mx.exchange),
|
||||
RData::CNAME(c) => format!("{n} is an alias for {}", c.0),
|
||||
RData::PTR(p) => format!("{n} domain name pointer {}", p.0),
|
||||
RData::NS(ns) => format!("{n} name server {}", ns.0),
|
||||
RData::TXT(_) => format!("{n} descriptive text {}", r.data),
|
||||
RData::SOA(_) => format!("{n} has SOA record {}", r.data),
|
||||
RData::SRV(_) => format!("{n} has SRV record {}", r.data),
|
||||
RData::CAA(_) => format!("{n} has CAA record {}", r.data),
|
||||
other => format!("{n} has {} record {other}", r.record_type()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn main() -> ExitCode {
|
||||
let a = Args::parse();
|
||||
block_on(run(a))
|
||||
}
|
||||
|
||||
pub async fn run(a: Args) -> ExitCode {
|
||||
let timeout = match parse_duration(&a.timeout) {
|
||||
Ok(t) => t,
|
||||
Err(e) => return fail("eh", EXIT_USAGE, e),
|
||||
};
|
||||
let server = match &a.server {
|
||||
Some(s) => match server_addr(s, a.port).await {
|
||||
Ok(x) => x,
|
||||
Err(e) => return fail("eh", EXIT_USAGE, e),
|
||||
},
|
||||
None => std::net::SocketAddr::new(system_resolver(), a.port),
|
||||
};
|
||||
let (name, types): (_, Vec<RecordType>) = if let Ok(ip) = a.target.parse::<IpAddr>() {
|
||||
(dns_core::names::reverse_name(ip), vec![RecordType::PTR])
|
||||
} else {
|
||||
let n = match name_arg(&a.target) {
|
||||
Ok(n) => n,
|
||||
Err(e) => return fail("eh", EXIT_USAGE, e),
|
||||
};
|
||||
let t = if let Some(t) = &a.rtype {
|
||||
match parse_type(t) {
|
||||
Some(t) => vec![t],
|
||||
None => return fail("eh", EXIT_USAGE, format!("invalid type: {t}")),
|
||||
}
|
||||
} else if a.all {
|
||||
vec![RecordType::A, RecordType::AAAA, RecordType::MX, RecordType::NS, RecordType::TXT, RecordType::SOA, RecordType::CAA]
|
||||
} else {
|
||||
vec![RecordType::A, RecordType::AAAA, RecordType::MX]
|
||||
};
|
||||
(n, t)
|
||||
};
|
||||
let opts = QueryOptions { timeout, retries: a.retries, tcp_only: a.tcp, ..Default::default() };
|
||||
let mut out = Vec::new();
|
||||
let mut code = ExitCode::SUCCESS;
|
||||
let mut seen_cname = std::collections::HashSet::new();
|
||||
if a.server.is_some() && !a.json {
|
||||
println!(
|
||||
"Using domain server:\nName: {}\nAddress: {}#{}\nAliases: \n",
|
||||
a.server.as_deref().unwrap_or(""),
|
||||
server.ip(),
|
||||
server.port()
|
||||
);
|
||||
}
|
||||
for t in &types {
|
||||
let ex = match query(server, &name, *t, &opts).await {
|
||||
Ok(ex) => ex,
|
||||
Err(e) => {
|
||||
if !a.json {
|
||||
println!(";; connection timed out; no servers could be reached ({e})");
|
||||
}
|
||||
return net_error("eh", &e);
|
||||
}
|
||||
};
|
||||
let m = &ex.message;
|
||||
match m.metadata.response_code {
|
||||
ResponseCode::NoError => {}
|
||||
rc => {
|
||||
if a.json {
|
||||
out.push(json!({ "type": t.to_string(), "status": rcode_str(rc) }));
|
||||
} else {
|
||||
println!("Host {} not found: {}({})", a.target, u16::from(rc), rcode_str(rc));
|
||||
}
|
||||
code = ExitCode::from(1);
|
||||
break;
|
||||
}
|
||||
}
|
||||
if a.verbose && !a.json {
|
||||
println!("Trying \"{name}\" ({t})");
|
||||
for r in &m.answers {
|
||||
println!("{}", rr_line(r));
|
||||
}
|
||||
println!("Received {} bytes from {} in {} ms\n", ex.size, ex.server, ex.elapsed.as_millis());
|
||||
continue;
|
||||
}
|
||||
for r in &m.answers {
|
||||
if r.record_type() == RecordType::CNAME && !seen_cname.insert(r.data.to_string()) {
|
||||
continue;
|
||||
}
|
||||
if a.json {
|
||||
out.push(rr_json(r));
|
||||
} else {
|
||||
println!("{}", describe(r));
|
||||
}
|
||||
}
|
||||
if m.answers.is_empty() && a.rtype.is_some() && !a.json {
|
||||
println!("{} has no {} record", name.to_string().trim_end_matches('.'), t);
|
||||
}
|
||||
}
|
||||
if a.json {
|
||||
print_structured(&json!({ "name": name.to_string(), "server": server.to_string(), "records": out }), false);
|
||||
}
|
||||
code
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
//! EasyDNS Tools – practical replacements for common BIND utilities, built on the
|
||||
//! shared EasyDNS engine. Each tool lives in its own module and is exposed as two
|
||||
//! binaries (short and long name, e.g. `ed` and `easydig`).
|
||||
//!
|
||||
//! Common exit codes: 0 success (a valid DNS answer, including NXDOMAIN, unless the
|
||||
//! tool documents otherwise), 1 usage error, 9 no reply / timeout, 10 internal error.
|
||||
#![cfg_attr(test, allow(clippy::unwrap_used, clippy::expect_used))]
|
||||
|
||||
pub mod bench;
|
||||
pub mod common;
|
||||
pub mod conf;
|
||||
pub mod diff;
|
||||
pub mod dig;
|
||||
pub mod dnssec;
|
||||
pub mod doh;
|
||||
pub mod dot;
|
||||
pub mod host;
|
||||
pub mod nslookup;
|
||||
pub mod ptr;
|
||||
pub mod trace;
|
||||
pub mod whois;
|
||||
pub mod zone;
|
||||
@@ -0,0 +1,207 @@
|
||||
//! `ens` / `easynslookup` – nslookup replacement with interactive mode.
|
||||
use std::io::{BufRead, Write};
|
||||
use std::net::{IpAddr, SocketAddr};
|
||||
use std::process::ExitCode;
|
||||
use std::time::Duration;
|
||||
|
||||
use dns_core::client::{QueryOptions, query};
|
||||
use dns_core::proto::op::ResponseCode;
|
||||
use dns_core::proto::rr::{RData, RecordType};
|
||||
|
||||
use crate::common::*;
|
||||
|
||||
struct State {
|
||||
server: SocketAddr,
|
||||
rtype: RecordType,
|
||||
port: u16,
|
||||
timeout: Duration,
|
||||
recurse: bool,
|
||||
tcp: bool,
|
||||
}
|
||||
|
||||
fn usage() -> &'static str {
|
||||
"Usage: ens [-type=T] [-port=N] [-timeout=S] [-norecurse] [-vc] [name] [server]\n ens --interactive"
|
||||
}
|
||||
|
||||
async fn lookup(st: &State, target: &str) -> bool {
|
||||
let (name, t) = match target.parse::<IpAddr>() {
|
||||
Ok(ip) => (dns_core::names::reverse_name(ip), RecordType::PTR),
|
||||
Err(_) => match name_arg(target) {
|
||||
Ok(n) => (n, st.rtype),
|
||||
Err(e) => {
|
||||
println!("*** invalid name {target}: {e}");
|
||||
return false;
|
||||
}
|
||||
},
|
||||
};
|
||||
let opts = QueryOptions { timeout: st.timeout, retries: 1, recursion_desired: st.recurse, tcp_only: st.tcp, ..Default::default() };
|
||||
println!("Server:\t\t{}\nAddress:\t{}#{}\n", st.server.ip(), st.server.ip(), st.server.port());
|
||||
let types = if t == RecordType::A && st.rtype == RecordType::A { vec![RecordType::A, RecordType::AAAA] } else { vec![t] };
|
||||
let mut ok = true;
|
||||
let mut printed_header = false;
|
||||
for t in types {
|
||||
match query(st.server, &name, t, &opts).await {
|
||||
Ok(ex) => {
|
||||
let m = &ex.message;
|
||||
if m.metadata.response_code != ResponseCode::NoError {
|
||||
println!("** server can't find {}: {}", name.to_string().trim_end_matches('.'), rcode_str(m.metadata.response_code));
|
||||
ok = false;
|
||||
break;
|
||||
}
|
||||
if !m.metadata.authoritative && !printed_header && !m.answers.is_empty() {
|
||||
println!("Non-authoritative answer:");
|
||||
printed_header = true;
|
||||
}
|
||||
for r in &m.answers {
|
||||
let n = r.name.to_string();
|
||||
let n = n.trim_end_matches('.');
|
||||
match &r.data {
|
||||
RData::A(a) => println!("Name:\t{n}\nAddress: {a}"),
|
||||
RData::AAAA(a) => println!("Name:\t{n}\nAddress: {a}"),
|
||||
RData::CNAME(c) => println!("{n}\tcanonical name = {}", c.0),
|
||||
RData::PTR(p) => println!("{n}\tname = {}", p.0),
|
||||
RData::MX(mx) => println!("{n}\tmail exchanger = {} {}", mx.preference, mx.exchange),
|
||||
RData::NS(ns) => println!("{n}\tnameserver = {}", ns.0),
|
||||
RData::TXT(_) => println!("{n}\ttext = {}", r.data),
|
||||
RData::SOA(s) => println!(
|
||||
"{n}\n\torigin = {}\n\tmail addr = {}\n\tserial = {}\n\trefresh = {}\n\tretry = {}\n\texpire = {}\n\tminimum = {}",
|
||||
s.mname, s.rname, s.serial, s.refresh, s.retry, s.expire, s.minimum
|
||||
),
|
||||
other => println!("{n}\t{} = {other}", r.record_type()),
|
||||
}
|
||||
}
|
||||
if m.answers.is_empty() && t == st.rtype {
|
||||
println!("*** No {t} records available for {}", name.to_string().trim_end_matches('.'));
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
println!(";; connection timed out; no servers could be reached ({e})");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
println!();
|
||||
ok
|
||||
}
|
||||
|
||||
fn apply_set(st: &mut State, arg: &str) -> Result<(), String> {
|
||||
let a = arg.trim_start_matches('-');
|
||||
let (k, v) = a.split_once('=').map(|(k, v)| (k.to_ascii_lowercase(), Some(v))).unwrap_or((a.to_ascii_lowercase(), None));
|
||||
match (k.as_str(), v) {
|
||||
("type" | "querytype" | "q" | "ty", Some(v)) => st.rtype = parse_type(v).ok_or_else(|| format!("unknown type {v}"))?,
|
||||
("port" | "po", Some(v)) => st.port = v.parse().map_err(|_| "invalid port")?,
|
||||
("timeout" | "ti", Some(v)) => st.timeout = Duration::from_secs(v.parse().map_err(|_| "invalid timeout")?),
|
||||
("norecurse" | "norec", None) => st.recurse = false,
|
||||
("recurse" | "rec", None) => st.recurse = true,
|
||||
("vc", None) => st.tcp = true,
|
||||
("novc", None) => st.tcp = false,
|
||||
_ => return Err(format!("unknown option {arg}")),
|
||||
}
|
||||
st.server.set_port(st.port);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn main() -> ExitCode {
|
||||
block_on(run(std::env::args().skip(1).collect()))
|
||||
}
|
||||
|
||||
pub async fn run(args: Vec<String>) -> ExitCode {
|
||||
let mut st = State {
|
||||
server: SocketAddr::new(system_resolver(), 53),
|
||||
rtype: RecordType::A,
|
||||
port: 53,
|
||||
timeout: Duration::from_secs(5),
|
||||
recurse: true,
|
||||
tcp: false,
|
||||
};
|
||||
let mut interactive = false;
|
||||
let mut pos = Vec::new();
|
||||
for a in &args {
|
||||
match a.as_str() {
|
||||
"-h" | "--help" => {
|
||||
println!("{}", usage());
|
||||
return ExitCode::SUCCESS;
|
||||
}
|
||||
"--version" => {
|
||||
println!("EasyNSLookup {VERSION}");
|
||||
return ExitCode::SUCCESS;
|
||||
}
|
||||
"--interactive" | "-i" => interactive = true,
|
||||
s if s.starts_with('-') && s.len() > 1 => {
|
||||
if let Err(e) = apply_set(&mut st, s) {
|
||||
return fail("ens", EXIT_USAGE, format!("{e}\n{}", usage()));
|
||||
}
|
||||
}
|
||||
s => pos.push(s.to_string()),
|
||||
}
|
||||
}
|
||||
if pos.len() > 1 {
|
||||
match server_addr(&pos[1], st.port).await {
|
||||
Ok(a) => st.server = a,
|
||||
Err(e) => return fail("ens", EXIT_USAGE, e),
|
||||
}
|
||||
}
|
||||
if pos.is_empty() {
|
||||
interactive = true;
|
||||
}
|
||||
if !interactive {
|
||||
return if lookup(&st, &pos[0]).await { ExitCode::SUCCESS } else { ExitCode::from(1) };
|
||||
}
|
||||
let stdin = std::io::stdin();
|
||||
loop {
|
||||
print!("> ");
|
||||
let _ = std::io::stdout().flush();
|
||||
let mut line = String::new();
|
||||
if stdin.lock().read_line(&mut line).unwrap_or(0) == 0 {
|
||||
return ExitCode::SUCCESS;
|
||||
}
|
||||
let line = line.trim();
|
||||
let mut parts = line.split_whitespace();
|
||||
match parts.next() {
|
||||
None => continue,
|
||||
Some("exit" | "quit") => return ExitCode::SUCCESS,
|
||||
Some("server" | "lserver") => match parts.next() {
|
||||
Some(s) => match server_addr(s, st.port).await {
|
||||
Ok(a) => {
|
||||
st.server = a;
|
||||
println!("Default server: {s}\nAddress: {}#{}", a.ip(), a.port());
|
||||
}
|
||||
Err(e) => println!("*** {e}"),
|
||||
},
|
||||
None => println!("Default server: {}", st.server),
|
||||
},
|
||||
Some("set") => match parts.next() {
|
||||
Some("all") => println!(
|
||||
"Default server: {}\n type = {}\n port = {}\n timeout = {:?}\n {}recurse\n {}vc",
|
||||
st.server,
|
||||
st.rtype,
|
||||
st.port,
|
||||
st.timeout,
|
||||
if st.recurse { "" } else { "no" },
|
||||
if st.tcp { "" } else { "no" }
|
||||
),
|
||||
Some(opt) => {
|
||||
if let Err(e) = apply_set(&mut st, opt) {
|
||||
println!("*** {e}");
|
||||
}
|
||||
}
|
||||
None => println!("*** set requires an option"),
|
||||
},
|
||||
Some("help" | "?") => {
|
||||
println!("Commands: NAME, server IP, set type=T, set port=N, set timeout=S, set [no]recurse, set [no]vc, set all, exit")
|
||||
}
|
||||
Some(name) => {
|
||||
if let Some(srv) = parts.next() {
|
||||
let mut tmp =
|
||||
State { server: st.server, rtype: st.rtype, port: st.port, timeout: st.timeout, recurse: st.recurse, tcp: st.tcp };
|
||||
if let Ok(a) = server_addr(srv, st.port).await {
|
||||
tmp.server = a;
|
||||
}
|
||||
lookup(&tmp, name).await;
|
||||
} else {
|
||||
lookup(&st, name).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
//! `eptr` / `easyptr` – reverse DNS for IPv4/IPv6 (several addresses at once).
|
||||
use std::net::IpAddr;
|
||||
use std::process::ExitCode;
|
||||
|
||||
use clap::Parser;
|
||||
use dns_core::client::{QueryOptions, query};
|
||||
use dns_core::proto::op::ResponseCode;
|
||||
use dns_core::proto::rr::{RData, RecordType};
|
||||
use serde_json::json;
|
||||
|
||||
use crate::common::*;
|
||||
|
||||
#[derive(Parser, Debug)]
|
||||
#[command(name = "eptr", version = VERSION, about = "EasyPTR – reverse DNS lookups")]
|
||||
pub struct Args {
|
||||
/// IPv4/IPv6 addresses
|
||||
#[arg(required = true)]
|
||||
pub addresses: Vec<String>,
|
||||
/// Server (default: system resolver)
|
||||
#[arg(short, long)]
|
||||
pub server: Option<String>,
|
||||
#[arg(short, long, default_value_t = 53)]
|
||||
pub port: u16,
|
||||
/// Also verify forward-confirmed reverse DNS (PTR → A/AAAA matches)
|
||||
#[arg(long)]
|
||||
pub verify: bool,
|
||||
#[arg(long)]
|
||||
pub json: bool,
|
||||
}
|
||||
|
||||
pub fn main() -> ExitCode {
|
||||
block_on(run(Args::parse()))
|
||||
}
|
||||
|
||||
pub async fn run(a: Args) -> ExitCode {
|
||||
let server = match &a.server {
|
||||
Some(s) => match server_addr(s, a.port).await {
|
||||
Ok(x) => x,
|
||||
Err(e) => return fail("eptr", EXIT_USAGE, e),
|
||||
},
|
||||
None => std::net::SocketAddr::new(system_resolver(), a.port),
|
||||
};
|
||||
let opts = QueryOptions::default();
|
||||
let mut results = Vec::new();
|
||||
let mut code = ExitCode::SUCCESS;
|
||||
for addr in &a.addresses {
|
||||
let Ok(ip) = addr.parse::<IpAddr>() else {
|
||||
return fail("eptr", EXIT_USAGE, format!("not an IP address: {addr}"));
|
||||
};
|
||||
let rname = dns_core::names::reverse_name(ip);
|
||||
let res = match query(server, &rname, RecordType::PTR, &opts).await {
|
||||
Ok(ex) => ex,
|
||||
Err(e) => return net_error("eptr", &e),
|
||||
};
|
||||
let ptrs: Vec<String> = res
|
||||
.message
|
||||
.answers
|
||||
.iter()
|
||||
.filter_map(|r| match &r.data {
|
||||
RData::PTR(p) => Some(p.0.to_string()),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
let mut fcrdns = None;
|
||||
if a.verify {
|
||||
let mut ok = false;
|
||||
for p in &ptrs {
|
||||
let Ok(n) = name_arg(p) else { continue };
|
||||
let t = if ip.is_ipv4() { RecordType::A } else { RecordType::AAAA };
|
||||
if let Ok(ex) = query(server, &n, t, &opts).await {
|
||||
ok |= ex.message.answers.iter().any(|r| r.data.ip_addr() == Some(ip));
|
||||
}
|
||||
}
|
||||
fcrdns = Some(ok);
|
||||
}
|
||||
let rc = res.message.metadata.response_code;
|
||||
if rc != ResponseCode::NoError || ptrs.is_empty() {
|
||||
code = ExitCode::from(1);
|
||||
}
|
||||
if a.json {
|
||||
results.push(
|
||||
json!({ "address": addr, "reverse_name": rname.to_string(), "status": rcode_str(rc), "ptr": ptrs, "fcrdns": fcrdns }),
|
||||
);
|
||||
} else if ptrs.is_empty() {
|
||||
println!("{addr}\t{} ({})", rcode_str(rc), rname);
|
||||
} else {
|
||||
for p in &ptrs {
|
||||
let v = match fcrdns {
|
||||
Some(true) => " [forward-confirmed]",
|
||||
Some(false) => " [NOT forward-confirmed]",
|
||||
None => "",
|
||||
};
|
||||
println!("{addr}\t{p}{v}");
|
||||
}
|
||||
}
|
||||
}
|
||||
if a.json {
|
||||
print_structured(&json!(results), false);
|
||||
}
|
||||
code
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
//! `etrace` / `easytrace` – follow delegations from the root (dig +trace).
|
||||
use std::process::ExitCode;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use clap::Parser;
|
||||
use dns_core::proto::rr::{Name, RecordType};
|
||||
use serde_json::json;
|
||||
|
||||
use crate::common::*;
|
||||
|
||||
#[derive(Parser, Debug)]
|
||||
#[command(name = "etrace", version = VERSION, about = "EasyTrace – trace the delegation path root → TLD → authoritative")]
|
||||
pub struct Args {
|
||||
pub name: String,
|
||||
#[arg(default_value = "A")]
|
||||
pub rtype: String,
|
||||
/// Also show DS/DNSKEY presence for each zone cut
|
||||
#[arg(long)]
|
||||
pub dnssec: bool,
|
||||
/// Root hints file (default: built-in)
|
||||
#[arg(long)]
|
||||
pub root_hints: Option<std::path::PathBuf>,
|
||||
/// Port of authoritative servers (testing)
|
||||
#[arg(long, default_value_t = 53, hide = true)]
|
||||
pub port: u16,
|
||||
/// Maximum referrals to follow
|
||||
#[arg(long, default_value_t = 30)]
|
||||
pub max_depth: u32,
|
||||
/// Use IPv6 transport too
|
||||
#[arg(short = '6', long)]
|
||||
pub ipv6: bool,
|
||||
#[arg(long)]
|
||||
pub json: bool,
|
||||
#[arg(long)]
|
||||
pub no_color: bool,
|
||||
}
|
||||
|
||||
pub fn main() -> ExitCode {
|
||||
let a = Args::parse();
|
||||
let Some(t) = parse_type(&a.rtype) else { return fail("etrace", EXIT_USAGE, format!("unknown type {}", a.rtype)) };
|
||||
let name = match name_arg(&a.name) {
|
||||
Ok(n) => n,
|
||||
Err(e) => return fail("etrace", EXIT_USAGE, e),
|
||||
};
|
||||
block_on(trace_with(
|
||||
&name,
|
||||
t,
|
||||
a.json,
|
||||
false,
|
||||
a.dnssec,
|
||||
Colors::detect(a.no_color),
|
||||
a.root_hints.as_deref(),
|
||||
a.port,
|
||||
a.max_depth,
|
||||
a.ipv6,
|
||||
))
|
||||
}
|
||||
|
||||
/// Entry used by `ed +trace`.
|
||||
pub async fn run_trace(name: &Name, t: RecordType, json_out: bool, yaml: bool, dnssec: bool, c: Colors) -> ExitCode {
|
||||
trace_with(name, t, json_out, yaml, dnssec, c, None, 53, 30, false).await
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub async fn trace_with(
|
||||
name: &Name,
|
||||
t: RecordType,
|
||||
json_out: bool,
|
||||
yaml: bool,
|
||||
dnssec: bool,
|
||||
c: Colors,
|
||||
hints: Option<&std::path::Path>,
|
||||
port: u16,
|
||||
max_depth: u32,
|
||||
ipv6: bool,
|
||||
) -> ExitCode {
|
||||
let hints = match dns_recursive::hints::load(hints) {
|
||||
Ok(h) => h,
|
||||
Err(e) => return fail("etrace", EXIT_USAGE, e),
|
||||
};
|
||||
let cache = Arc::new(dns_cache::Cache::new(&dns_config::CacheConfig { max_entries: 10_000, ..Default::default() }));
|
||||
let settings = dns_recursive::Settings {
|
||||
max_depth,
|
||||
max_queries: 200,
|
||||
max_cname: 8,
|
||||
query_timeout: Duration::from_secs(2),
|
||||
total_timeout: Duration::from_secs(30),
|
||||
port,
|
||||
qname_minimization: false,
|
||||
ipv6,
|
||||
max_subqueries_depth: 4,
|
||||
dnssec,
|
||||
};
|
||||
let r = match dns_recursive::Resolver::new(settings, hints, cache, 0) {
|
||||
Ok(r) => r,
|
||||
Err(e) => return fail("etrace", EXIT_INTERNAL, e),
|
||||
};
|
||||
let (ans, steps) = r.resolve_traced(name, t).await;
|
||||
let mut ds_info = Vec::new();
|
||||
if dnssec {
|
||||
let mut zones: Vec<String> = steps.iter().map(|s| s.zone.clone()).collect();
|
||||
zones.dedup();
|
||||
for z in zones {
|
||||
let zn = name_arg(&z).unwrap_or_else(|_| Name::root());
|
||||
let dnskey = r.resolve(&zn, RecordType::DNSKEY).await;
|
||||
let ds = if zn.is_root() { None } else { Some(r.resolve(&zn, RecordType::DS).await) };
|
||||
ds_info.push((
|
||||
z,
|
||||
dnskey.answers.iter().filter(|x| x.record_type() == RecordType::DNSKEY).count(),
|
||||
ds.map(|d| d.answers.iter().filter(|x| x.record_type() == RecordType::DS).count()),
|
||||
));
|
||||
}
|
||||
}
|
||||
if json_out {
|
||||
print_structured(
|
||||
&json!({
|
||||
"name": name.to_string(), "type": t.to_string(), "status": rcode_str(ans.rcode),
|
||||
"steps": steps,
|
||||
"answer": ans.answers.iter().map(rr_json).collect::<Vec<_>>(),
|
||||
"note": ans.note,
|
||||
"dnssec": ds_info.iter().map(|(z, k, d)| json!({"zone": z, "dnskeys": k, "ds": d})).collect::<Vec<_>>(),
|
||||
}),
|
||||
yaml,
|
||||
);
|
||||
} else {
|
||||
println!("\n; <<>> EasyTrace {VERSION} <<>> {name} {t}");
|
||||
let mut last_zone = String::new();
|
||||
for s in &steps {
|
||||
if s.zone != last_zone {
|
||||
println!("\n{}", c.bold(&format!(";; zone {}", s.zone)));
|
||||
last_zone = s.zone.clone();
|
||||
}
|
||||
println!(
|
||||
";; {:<40} {:<22} {:>7.1} ms {:<9} {}",
|
||||
format!("{} ({})", s.server_name.as_deref().unwrap_or("?"), s.server),
|
||||
format!("{} {}", s.qname, s.qtype),
|
||||
s.elapsed_ms,
|
||||
s.rcode,
|
||||
s.outcome
|
||||
);
|
||||
}
|
||||
if !ds_info.is_empty() {
|
||||
println!("\n{}", c.bold(";; DNSSEC"));
|
||||
for (z, k, d) in &ds_info {
|
||||
println!(
|
||||
";; {z:<30} DNSKEY: {k:<3} DS in parent: {}",
|
||||
d.map(|x| x.to_string()).unwrap_or_else(|| "(trust anchor)".into())
|
||||
);
|
||||
}
|
||||
}
|
||||
println!("\n;; status: {} queries: {}", c.rcode(ans.rcode), steps.len());
|
||||
for rr in &ans.answers {
|
||||
println!("{}", rr_line(rr));
|
||||
}
|
||||
if let Some(n) = &ans.note {
|
||||
println!(";; note: {n}");
|
||||
}
|
||||
}
|
||||
if ans.rcode == dns_core::proto::op::ResponseCode::ServFail { ExitCode::from(EXIT_NO_REPLY) } else { ExitCode::SUCCESS }
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
//! `ewhois` / `easywhois` – RDAP (preferred) and WHOIS lookups.
|
||||
//!
|
||||
//! This is a separate component from the DNS engine: RDAP uses the IANA bootstrap
|
||||
//! registry over HTTPS; classic WHOIS (TCP/43) is used with `--whois` or as fallback.
|
||||
use std::net::IpAddr;
|
||||
use std::process::ExitCode;
|
||||
use std::time::Duration;
|
||||
|
||||
use clap::Parser;
|
||||
use serde_json::Value;
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
|
||||
use crate::common::*;
|
||||
|
||||
#[derive(Parser, Debug)]
|
||||
#[command(name = "ewhois", version = VERSION, about = "EasyWhois – RDAP/WHOIS lookups for domains and IP addresses")]
|
||||
pub struct Args {
|
||||
pub query: String,
|
||||
/// Use classic WHOIS (port 43) instead of RDAP
|
||||
#[arg(long)]
|
||||
pub whois: bool,
|
||||
/// WHOIS server (default: whois.iana.org with referral)
|
||||
#[arg(long)]
|
||||
pub server: Option<String>,
|
||||
#[arg(long, default_value = "15s")]
|
||||
pub timeout: String,
|
||||
#[arg(long)]
|
||||
pub json: bool,
|
||||
}
|
||||
|
||||
async fn rdap(q: &str, timeout: Duration) -> Result<Value, String> {
|
||||
let (registry, key) = match q.parse::<IpAddr>() {
|
||||
Ok(IpAddr::V4(_)) => ("https://data.iana.org/rdap/ipv4.json", q.to_string()),
|
||||
Ok(IpAddr::V6(_)) => ("https://data.iana.org/rdap/ipv6.json", q.to_string()),
|
||||
Err(_) => ("https://data.iana.org/rdap/dns.json", q.trim_end_matches('.').rsplit('.').next().unwrap_or("").to_ascii_lowercase()),
|
||||
};
|
||||
let (st, body) = dns_core::tls::https_get(registry, timeout, 4 * 1024 * 1024).await.map_err(|e| format!("RDAP bootstrap: {e}"))?;
|
||||
if st != 200 {
|
||||
return Err(format!("RDAP bootstrap HTTP {st}"));
|
||||
}
|
||||
let boot: Value = serde_json::from_slice(&body).map_err(|e| e.to_string())?;
|
||||
let mut base = None;
|
||||
for svc in boot["services"].as_array().into_iter().flatten() {
|
||||
let keys = svc[0].as_array().cloned().unwrap_or_default();
|
||||
let hit = keys.iter().filter_map(Value::as_str).any(|k| match q.parse::<IpAddr>() {
|
||||
Ok(ip) => k.parse::<ipnet_lite::Net>().map(|n| n.contains(ip)).unwrap_or(false),
|
||||
Err(_) => k.eq_ignore_ascii_case(&key),
|
||||
});
|
||||
if hit {
|
||||
base = svc[1].as_array().and_then(|u| u.iter().filter_map(Value::as_str).find(|u| u.starts_with("https://"))).map(String::from);
|
||||
break;
|
||||
}
|
||||
}
|
||||
let base = base.ok_or("no RDAP service found for this query")?;
|
||||
let kind = if q.parse::<IpAddr>().is_ok() { "ip" } else { "domain" };
|
||||
let url = format!("{}/{kind}/{}", base.trim_end_matches('/'), q.trim_end_matches('.'));
|
||||
let (st, body) = dns_core::tls::https_get(&url, timeout, 4 * 1024 * 1024).await.map_err(|e| format!("{url}: {e}"))?;
|
||||
if st == 404 {
|
||||
return Err("not found".into());
|
||||
}
|
||||
if st != 200 {
|
||||
return Err(format!("{url}: HTTP {st}"));
|
||||
}
|
||||
serde_json::from_slice(&body).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
mod ipnet_lite {
|
||||
use std::net::IpAddr;
|
||||
pub struct Net(IpAddr, u8);
|
||||
impl std::str::FromStr for Net {
|
||||
type Err = ();
|
||||
fn from_str(s: &str) -> Result<Self, ()> {
|
||||
let (a, p) = s.split_once('/').ok_or(())?;
|
||||
Ok(Net(a.parse().map_err(|_| ())?, p.parse().map_err(|_| ())?))
|
||||
}
|
||||
}
|
||||
impl Net {
|
||||
pub fn contains(&self, ip: IpAddr) -> bool {
|
||||
match (self.0, ip) {
|
||||
(IpAddr::V4(n), IpAddr::V4(i)) => self.1 <= 32 && (self.1 == 0 || (u32::from(n) ^ u32::from(i)) >> (32 - self.1) == 0),
|
||||
(IpAddr::V6(n), IpAddr::V6(i)) => self.1 <= 128 && (self.1 == 0 || (u128::from(n) ^ u128::from(i)) >> (128 - self.1) == 0),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn whois43(server: &str, q: &str, timeout: Duration) -> Result<String, String> {
|
||||
let fut = async {
|
||||
let mut s = tokio::net::TcpStream::connect((server, 43)).await.map_err(|e| format!("{server}: {e}"))?;
|
||||
s.write_all(format!("{q}\r\n").as_bytes()).await.map_err(|e| e.to_string())?;
|
||||
let mut buf = Vec::new();
|
||||
s.take(1024 * 1024).read_to_end(&mut buf).await.map_err(|e| e.to_string())?;
|
||||
Ok(String::from_utf8_lossy(&buf).to_string())
|
||||
};
|
||||
tokio::time::timeout(timeout, fut).await.map_err(|_| format!("{server}: timeout"))?
|
||||
}
|
||||
|
||||
fn summarise(v: &Value) {
|
||||
let s = |p: &str| v.pointer(p).and_then(Value::as_str).unwrap_or("-").to_string();
|
||||
println!("Handle: {}", s("/handle"));
|
||||
if let Some(n) = v.get("ldhName").and_then(Value::as_str) {
|
||||
println!("Domain: {n}");
|
||||
}
|
||||
if let (Some(a), Some(b)) = (v.get("startAddress").and_then(Value::as_str), v.get("endAddress").and_then(Value::as_str)) {
|
||||
println!("Range: {a} - {b}");
|
||||
}
|
||||
if let Some(n) = v.get("name").and_then(Value::as_str) {
|
||||
println!("Name: {n}");
|
||||
}
|
||||
for st in v["status"].as_array().into_iter().flatten().filter_map(Value::as_str) {
|
||||
println!("Status: {st}");
|
||||
}
|
||||
for ev in v["events"].as_array().into_iter().flatten() {
|
||||
println!("Event: {:<20} {}", ev["eventAction"].as_str().unwrap_or(""), ev["eventDate"].as_str().unwrap_or(""));
|
||||
}
|
||||
for ns in v["nameservers"].as_array().into_iter().flatten() {
|
||||
println!("NS: {}", ns["ldhName"].as_str().unwrap_or(""));
|
||||
}
|
||||
for e in v["entities"].as_array().into_iter().flatten() {
|
||||
let roles: Vec<&str> = e["roles"].as_array().into_iter().flatten().filter_map(Value::as_str).collect();
|
||||
let fname = e
|
||||
.pointer("/vcardArray/1")
|
||||
.and_then(Value::as_array)
|
||||
.and_then(|a| a.iter().find(|x| x[0] == "fn"))
|
||||
.and_then(|x| x[3].as_str())
|
||||
.unwrap_or("-");
|
||||
println!("Entity: {:<30} {}", fname, roles.join(","));
|
||||
}
|
||||
}
|
||||
|
||||
pub fn main() -> ExitCode {
|
||||
block_on(run(Args::parse()))
|
||||
}
|
||||
|
||||
pub async fn run(a: Args) -> ExitCode {
|
||||
let timeout = parse_duration(&a.timeout).unwrap_or(Duration::from_secs(15));
|
||||
if !a.whois {
|
||||
match rdap(&a.query, timeout).await {
|
||||
Ok(v) => {
|
||||
if a.json {
|
||||
print_structured(&v, false);
|
||||
} else {
|
||||
summarise(&v);
|
||||
}
|
||||
return ExitCode::SUCCESS;
|
||||
}
|
||||
Err(e) if e == "not found" => return fail("ewhois", 1, "no match"),
|
||||
Err(e) => eprintln!("ewhois: RDAP failed ({e}); falling back to WHOIS"),
|
||||
}
|
||||
}
|
||||
let first = a.server.clone().unwrap_or_else(|| "whois.iana.org".into());
|
||||
let mut text = match whois43(&first, &a.query, timeout).await {
|
||||
Ok(t) => t,
|
||||
Err(e) => return fail("ewhois", EXIT_NO_REPLY, e),
|
||||
};
|
||||
if a.server.is_none()
|
||||
&& let Some(refer) =
|
||||
text.lines().find_map(|l| l.strip_prefix("refer:").or_else(|| l.strip_prefix("whois:")).map(|s| s.trim().to_string()))
|
||||
&& let Ok(t) = whois43(&refer, &a.query, timeout).await
|
||||
{
|
||||
text = t;
|
||||
}
|
||||
if a.json {
|
||||
print_structured(&serde_json::json!({ "query": a.query, "whois": text }), false);
|
||||
} else {
|
||||
print!("{text}");
|
||||
}
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
//! `ezone` / `easyzone` – zone file validation (named-checkzone).
|
||||
use std::path::PathBuf;
|
||||
use std::process::ExitCode;
|
||||
|
||||
use clap::{Parser, Subcommand};
|
||||
|
||||
use crate::common::*;
|
||||
|
||||
#[derive(Parser, Debug)]
|
||||
#[command(name = "ezone", version = VERSION, about = "EasyZone – validate zone files")]
|
||||
pub struct Args {
|
||||
#[command(subcommand)]
|
||||
pub cmd: Cmd,
|
||||
#[arg(long, global = true)]
|
||||
pub json: bool,
|
||||
}
|
||||
|
||||
#[derive(Subcommand, Debug)]
|
||||
pub enum Cmd {
|
||||
/// Check one zone file
|
||||
Check {
|
||||
file: PathBuf,
|
||||
#[arg(short, long)]
|
||||
origin: String,
|
||||
},
|
||||
/// Check all primary zones of a configuration
|
||||
Validate {
|
||||
#[arg(long)]
|
||||
all: bool,
|
||||
#[arg(short, long, default_value = "/etc/easydns/config.yaml")]
|
||||
config: PathBuf,
|
||||
},
|
||||
/// Print a zone in canonical sorted form
|
||||
Canonical {
|
||||
file: PathBuf,
|
||||
#[arg(short, long)]
|
||||
origin: String,
|
||||
},
|
||||
}
|
||||
|
||||
fn report(findings: &[dns_server::check::Finding], json: bool) -> ExitCode {
|
||||
let errors = findings.iter().filter(|f| f.severity == "error").count();
|
||||
if json {
|
||||
print_structured(&serde_json::to_value(findings).unwrap_or_default(), false);
|
||||
} else {
|
||||
for f in findings {
|
||||
println!("{f}");
|
||||
}
|
||||
println!("{}", if errors == 0 { "OK" } else { "FAILED" });
|
||||
}
|
||||
if errors == 0 { ExitCode::SUCCESS } else { ExitCode::from(1) }
|
||||
}
|
||||
|
||||
pub fn main() -> ExitCode {
|
||||
let a = Args::parse();
|
||||
match a.cmd {
|
||||
Cmd::Check { file, origin } => report(&dns_server::check::check_zone_file(&file, &origin), a.json),
|
||||
Cmd::Validate { config, .. } => match dns_config::Config::load(&config) {
|
||||
Ok(cfg) => {
|
||||
let mut f = Vec::new();
|
||||
for z in cfg.zones.iter().filter(|z| z.zone_type == dns_config::ZoneType::Primary) {
|
||||
if let Some(file) = &z.file {
|
||||
f.extend(dns_server::check::check_zone_file(&cfg.resolve_path(file), &z.name));
|
||||
}
|
||||
}
|
||||
report(&f, a.json)
|
||||
}
|
||||
Err(e) => fail("ezone", EXIT_USAGE, e),
|
||||
},
|
||||
Cmd::Canonical { file, origin } => {
|
||||
let o = match name_arg(&origin) {
|
||||
Ok(o) => o,
|
||||
Err(e) => return fail("ezone", EXIT_USAGE, e),
|
||||
};
|
||||
match dns_core::zonefile::parse_file(&file, &o) {
|
||||
Ok(r) => {
|
||||
print!("{}", dns_core::zonefile::emit(&o, &r));
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Err(e) => fail("ezone", 1, e),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
//! Run the tool binaries against a local EasyDNS server and check output + exit codes.
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used)]
|
||||
|
||||
use std::process::Command;
|
||||
|
||||
fn run(bin: &str, args: &[&str]) -> (i32, String) {
|
||||
let out = Command::new(bin).args(args).env("NO_COLOR", "1").output().unwrap();
|
||||
(out.status.code().unwrap_or(-1), String::from_utf8_lossy(&out.stdout).to_string() + &String::from_utf8_lossy(&out.stderr))
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn tools_against_local_server() {
|
||||
let dir = std::env::temp_dir().join(format!("easydns-tools-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
std::fs::write(
|
||||
dir.join("z.zone"),
|
||||
"$TTL 60\n@ IN SOA ns hm 1 3600 600 86400 60\n@ IN NS ns\n@ IN MX 10 mail\nns IN A 127.0.0.1\nmail IN A 192.0.2.25\nwww IN A 192.0.2.10\nwww IN AAAA 2001:db8::10\n",
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::write(
|
||||
dir.join("r.zone"),
|
||||
"$TTL 60\n@ IN SOA ns.example.test. hm 1 3600 600 86400 60\n@ IN NS ns.example.test.\n10 IN PTR www.example.test.\n",
|
||||
)
|
||||
.unwrap();
|
||||
let yaml = "server: { listen: [\"127.0.0.1:0\"], data_dir: data }\napi: { enabled: false }\nzones:\n - { name: example.test, type: primary, file: z.zone, transfer_acl: [\"127.0.0.1/32\"] }\n - { name: 2.0.192.in-addr.arpa, type: primary, file: r.zone }\n";
|
||||
std::fs::write(dir.join("config.yaml"), yaml).unwrap();
|
||||
let cfg = dns_config::Config::load(&dir.join("config.yaml")).unwrap();
|
||||
let h = dns_server::Server::start(cfg, None, Default::default()).await.unwrap();
|
||||
let port = h.bound.dns[0].port().to_string();
|
||||
let srv = "@127.0.0.1".to_string();
|
||||
let ed = env!("CARGO_BIN_EXE_ed");
|
||||
|
||||
let p = port.clone();
|
||||
let (s, ed_out, short, json, nx, ax, eh_out, ens, eptr, ezone, econf, ediff, bad) = tokio::task::spawn_blocking({
|
||||
let srv = srv.clone();
|
||||
let dir = dir.clone();
|
||||
move || {
|
||||
(
|
||||
0,
|
||||
run(ed, &[&srv, "-p", &p, "www.example.test", "A"]),
|
||||
run(ed, &[&srv, "-p", &p, "www.example.test", "AAAA", "+short"]),
|
||||
run(ed, &[&srv, "-p", &p, "example.test", "MX", "--json"]),
|
||||
run(ed, &[&srv, "-p", &p, "nope.example.test"]),
|
||||
run(ed, &[&srv, "-p", &p, "example.test", "AXFR"]),
|
||||
run(env!("CARGO_BIN_EXE_eh"), &["-p", &p, "www.example.test", "127.0.0.1"]),
|
||||
run(env!("CARGO_BIN_EXE_ens"), &[&format!("-port={p}"), "www.example.test", "127.0.0.1"]),
|
||||
run(env!("CARGO_BIN_EXE_eptr"), &["-s", "127.0.0.1", "-p", &p, "192.0.2.10", "--json"]),
|
||||
run(env!("CARGO_BIN_EXE_ezone"), &["check", dir.join("z.zone").to_str().unwrap(), "--origin", "example.test"]),
|
||||
run(env!("CARGO_BIN_EXE_econf"), &["check", dir.join("config.yaml").to_str().unwrap()]),
|
||||
run(env!("CARGO_BIN_EXE_ediff"), &["www.example.test", "A", &format!("127.0.0.1:{p}"), &format!("127.0.0.1:{p}")]),
|
||||
run(ed, &["+nonsense"]),
|
||||
)
|
||||
}
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
let _ = s;
|
||||
assert_eq!(ed_out.0, 0, "{}", ed_out.1);
|
||||
assert!(
|
||||
ed_out.1.contains("status: NOERROR") && ed_out.1.contains("192.0.2.10") && ed_out.1.contains("flags: qr aa rd"),
|
||||
"{}",
|
||||
ed_out.1
|
||||
);
|
||||
assert_eq!(short.1.trim(), "2001:db8::10");
|
||||
let v: serde_json::Value = serde_json::from_str(&json.1).unwrap();
|
||||
assert_eq!(v["header"]["status"], "NOERROR");
|
||||
assert_eq!(v["answer"][0]["data"], "10 mail.example.test.");
|
||||
assert!(nx.0 == 0 && nx.1.contains("NXDOMAIN"), "dig semantics: NXDOMAIN is still exit 0");
|
||||
assert!(ax.1.contains("XFR size") && ax.0 == 0, "{}", ax.1);
|
||||
assert!(
|
||||
eh_out.1.contains("www.example.test has address 192.0.2.10") && eh_out.1.contains("has IPv6 address 2001:db8::10"),
|
||||
"{}",
|
||||
eh_out.1
|
||||
);
|
||||
assert!(ens.1.contains("Address: 192.0.2.10"), "{}", ens.1);
|
||||
let v: serde_json::Value = serde_json::from_str(&eptr.1).unwrap();
|
||||
assert_eq!(v[0]["ptr"][0], "www.example.test.");
|
||||
assert_eq!(ezone.0, 0, "{}", ezone.1);
|
||||
assert!(ezone.1.contains("serial 1"));
|
||||
assert_eq!(econf.0, 0, "{}", econf.1);
|
||||
assert_eq!(ediff.0, 0, "{}", ediff.1);
|
||||
assert!(ediff.1.contains("all servers agree"));
|
||||
assert_eq!(bad.0, 1, "usage error exit code");
|
||||
|
||||
// a broken zone file fails validation with exit 1
|
||||
std::fs::write(dir.join("bad.zone"), "@ IN SOA ns hm 1 2 3 4 5\nx IN CNAME y\nx IN A 192.0.2.1\n").unwrap();
|
||||
let (code, out) = run(env!("CARGO_BIN_EXE_ezone"), &["check", dir.join("bad.zone").to_str().unwrap(), "-o", "example.test"]);
|
||||
assert_eq!(code, 1, "{out}");
|
||||
// timeout -> exit 9
|
||||
let (code, _) = run(ed, &["@127.0.0.1", "-p", "9", "example.test", "--timeout", "300ms", "+tries=1"]);
|
||||
assert_eq!(code, 9);
|
||||
h.shutdown().await;
|
||||
}
|
||||
Reference in new issue
Block a user