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

No files matched your search

+498
View File
@@ -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));
}
}