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

+148
View File
@@ -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),
}
}