diff --git a/pr/4036/docs/iroh/dns/trait.Resolver.html b/pr/4036/docs/iroh/dns/trait.Resolver.html index 0dbf7e9bf4..9528be6f13 100644 --- a/pr/4036/docs/iroh/dns/trait.Resolver.html +++ b/pr/4036/docs/iroh/dns/trait.Resolver.html @@ -38,13 +38,13 @@ atomic swap. Build a new instance with re-bound sockets and re-read nameserver configuration rather than mutating in place. Must not perform IO: defer DNS queries and socket binds until the new resolver is first used. May be called concurrently, in which case all but one allocated replacement is dropped unused.

-

Implementations on Foreign Types§

Source§

impl Resolver for Arc<SimpleDnsResolver>

Source§

fn lookup_ipv4( +

Implementations on Foreign Types§

Source§

impl Resolver for Arc<SimpleDnsResolver>

Source§

fn lookup_ipv4( &self, host: String, -) -> Pin<Box<dyn Future<Output = Result<Box<dyn Iterator<Item = Ipv4Addr> + Send>, DnsError>> + Send>>

Source§

fn lookup_ipv6( +) -> Pin<Box<dyn Future<Output = Result<Box<dyn Iterator<Item = Ipv4Addr> + Send>, DnsError>> + Send>>

Source§

fn lookup_ipv6( &self, host: String, -) -> Pin<Box<dyn Future<Output = Result<Box<dyn Iterator<Item = Ipv6Addr> + Send>, DnsError>> + Send>>

Source§

fn lookup_txt( +) -> Pin<Box<dyn Future<Output = Result<Box<dyn Iterator<Item = Ipv6Addr> + Send>, DnsError>> + Send>>

Source§

fn lookup_txt( &self, host: String, -) -> Pin<Box<dyn Future<Output = Result<Box<dyn Iterator<Item = TxtRecordData> + Send>, DnsError>> + Send>>

Source§

fn clear_cache(&self)

Source§

fn reset(&self) -> Box<dyn Resolver>

Implementors§

\ No newline at end of file +) -> Pin<Box<dyn Future<Output = Result<Box<dyn Iterator<Item = TxtRecordData> + Send>, DnsError>> + Send>>
Source§

fn clear_cache(&self)

Source§

fn reset(&self) -> Box<dyn Resolver>

Implementors§

\ No newline at end of file diff --git a/pr/4036/docs/iroh_dns/dns/trait.Resolver.html b/pr/4036/docs/iroh_dns/dns/trait.Resolver.html index 8ec3e1fbdb..ba8a3b657f 100644 --- a/pr/4036/docs/iroh_dns/dns/trait.Resolver.html +++ b/pr/4036/docs/iroh_dns/dns/trait.Resolver.html @@ -38,13 +38,13 @@ atomic swap. Build a new instance with re-bound sockets and re-read nameserver configuration rather than mutating in place. Must not perform IO: defer DNS queries and socket binds until the new resolver is first used. May be called concurrently, in which case all but one allocated replacement is dropped unused.

-

Implementations on Foreign Types§

Source§

impl Resolver for Arc<SimpleDnsResolver>

Source§

fn lookup_ipv4( +

Implementations on Foreign Types§

Source§

impl Resolver for Arc<SimpleDnsResolver>

Source§

fn lookup_ipv4( &self, host: String, -) -> BoxFuture<Result<BoxIter<Ipv4Addr>, DnsError>>

Source§

fn lookup_ipv6( +) -> BoxFuture<Result<BoxIter<Ipv4Addr>, DnsError>>

Source§

fn lookup_ipv6( &self, host: String, -) -> BoxFuture<Result<BoxIter<Ipv6Addr>, DnsError>>

Source§

fn lookup_txt( +) -> BoxFuture<Result<BoxIter<Ipv6Addr>, DnsError>>

Source§

fn lookup_txt( &self, host: String, -) -> BoxFuture<Result<BoxIter<TxtRecordData>, DnsError>>

Source§

fn clear_cache(&self)

Source§

fn reset(&self) -> Box<dyn Resolver>

Implementors§

\ No newline at end of file +) -> BoxFuture<Result<BoxIter<TxtRecordData>, DnsError>>
Source§

fn clear_cache(&self)

Source§

fn reset(&self) -> Box<dyn Resolver>

Implementors§

\ No newline at end of file diff --git a/pr/4036/docs/src/iroh_dns/dns/resolver.rs.html b/pr/4036/docs/src/iroh_dns/dns/resolver.rs.html index 5b6b938e12..1238861263 100644 --- a/pr/4036/docs/src/iroh_dns/dns/resolver.rs.html +++ b/pr/4036/docs/src/iroh_dns/dns/resolver.rs.html @@ -390,562 +390,563 @@ 390 // nameserver may still resolve the name. 391 if let Some(rcode) = query::server_failure_rcode(&resp) { 392 self.rtt_map.record_failure(idx); -393 last_err = Some(e!(DnsError::ServerError { rcode: rcode.to_string() })); -394 // Fail fast: start the next attempt now rather than waiting. -395 next_attempt.as_mut().set_none(); -396 } else { -397 self.rtt_map.record_success(idx, start.elapsed()); -398 return Ok(resp); -399 } -400 } -401 Err(e) => { -402 self.rtt_map.record_failure(idx); -403 last_err = Some(e); -404 // Fail fast: start the next attempt now rather than waiting. -405 next_attempt.as_mut().set_none(); -406 } -407 }, -408 // The next attempt is due. -409 () = &mut next_attempt, if next_attempt.is_some() => { -410 next_attempt.as_mut().set_none(); -411 } -412 } -413 } -414 } -415 -416 /// Send a query and follow CNAME chains recursively if the response contains -417 /// a CNAME but no records of the requested type. -418 async fn send_query_following_cnames( -419 &self, -420 host: String, -421 qtype: TYPE, -422 ) -> Result<Vec<u8>, DnsError> { -423 let mut current_host = host; -424 for _ in 0..MAX_CNAME_DEPTH { -425 let name = simple_dns::Name::new(&current_host) -426 .map_err(|e| e!(DnsError::InvalidQuery, AnyError::from_std(e)))?; -427 let (id, query_bytes) = query::build_query(&current_host, qtype)?; -428 let response = self.send_query(&query_bytes).await?; -429 let packet = -430 simple_dns::Packet::parse(&response).map_err(|_| e!(DnsError::InvalidResponse))?; -431 -432 // Validate the id, QR bit, question, and RCODE before trusting the -433 // packet to decide the answer or the next CNAME target. This is the -434 // only check of the response against the name we actually asked for. -435 query::check_response(&packet, id, &name, qtype)?; -436 -437 let has_answer = packet -438 .answers -439 .iter() -440 .any(|rr| rr.rdata.type_code() == qtype); -441 -442 if has_answer { -443 return Ok(response); -444 } -445 -446 // No records of the requested type -- follow CNAME if present. -447 let Some(target) = query::cname_target(&packet, &current_host) else { -448 return Ok(response); -449 }; -450 debug!(from = %current_host, to = %target, "following CNAME"); -451 current_host = target; -452 } -453 Err(e!(DnsError::InvalidResponse)) -454 } -455 -456 /// Shared lookup logic: check cache, try search names, parse response, cache result. -457 #[allow(clippy::type_complexity)] -458 async fn lookup<T: Clone + std::fmt::Debug>( -459 &self, -460 host: &str, -461 qtype: QueryType, -462 dns_type: TYPE, -463 from_cache: fn(CachedRecord) -> Option<Vec<T>>, -464 parse: fn(&[u8]) -> Result<(Vec<T>, u32), QueryError>, -465 to_cache: fn(Vec<T>) -> CachedRecord, -466 ) -> Result<Vec<T>, DnsError> { -467 if let Some(cached) = self.cache.get(host, qtype).and_then(from_cache) { -468 trace!(%host, records = cached.len(), ?qtype, "cache hit"); -469 return Ok(cached); -470 } -471 -472 let mut last_err = None; -473 let names = self.search_names(host); -474 let total = names.len(); -475 for (i, name) in names.into_iter().enumerate() { -476 trace!(%name, ?qtype, "resolving"); -477 let res = match self -478 .send_query_following_cnames(name.clone(), dns_type) -479 .await -480 { -481 Ok(response) => parse(&response).map_err(DnsError::from), -482 Err(e) => Err(e), -483 }; -484 match res { -485 Ok((results, ttl)) if !results.is_empty() => { -486 debug!(%host, ?qtype, ?results, ttl, "resolved"); -487 self.cache -488 .insert(host, qtype, to_cache(results.clone()), ttl); -489 return Ok(results); -490 } -491 Ok(_) => {} -492 Err(ref e @ DnsError::NxDomain { .. }) -493 | Err(ref e @ DnsError::ServerError { .. }) => { -494 let remaining = total - i - 1; -495 trace!(%name, ?qtype, remaining, reason = %e, "lookup failed"); -496 last_err = Some(e!(DnsError::NxDomain)); -497 } -498 Err(e) => { -499 debug!(%name, ?qtype, reason = %e, "lookup failed"); -500 return Err(e); -501 } -502 } -503 } -504 let err = last_err.unwrap_or_else(|| e!(DnsError::NoResponse)); -505 debug!(%host, ?qtype, reason = %err, "resolve failed"); -506 Err(err) -507 } -508 -509 pub(super) async fn lookup_ipv4( -510 &self, -511 host: String, -512 ) -> Result<impl Iterator<Item = Ipv4Addr> + use<>, DnsError> { -513 // RFC 6761: localhost always resolves to loopback. -514 if is_localhost(&host) { -515 return Ok(vec![Ipv4Addr::LOCALHOST].into_iter()); -516 } -517 // A hosts-file entry overrides DNS, so check it ahead of the cache. -518 if let Some(addrs) = self -519 .search_names(&host) -520 .iter() -521 .find_map(|name| self.hosts.lookup_ipv4(name)) -522 { -523 trace!(%host, ?addrs, "resolved from hosts file"); -524 return Ok(addrs.into_iter()); -525 } -526 let addrs = self -527 .lookup( -528 &host, -529 QueryType::A, -530 TYPE::A, -531 CachedRecord::into_a, -532 query::parse_a_response, -533 CachedRecord::A, -534 ) -535 .await?; -536 Ok(addrs.into_iter()) -537 } -538 -539 pub(super) async fn lookup_ipv6( -540 &self, -541 host: String, -542 ) -> Result<impl Iterator<Item = Ipv6Addr> + use<>, DnsError> { -543 // RFC 6761: localhost always resolves to loopback. -544 if is_localhost(&host) { -545 return Ok(vec![Ipv6Addr::LOCALHOST].into_iter()); -546 } -547 // A hosts-file entry overrides DNS, so check it ahead of the cache. -548 if let Some(addrs) = self -549 .search_names(&host) -550 .iter() -551 .find_map(|name| self.hosts.lookup_ipv6(name)) -552 { -553 trace!(%host, ?addrs, "resolved from hosts file"); -554 return Ok(addrs.into_iter()); -555 } -556 let addrs = self -557 .lookup( -558 &host, -559 QueryType::AAAA, -560 TYPE::AAAA, -561 CachedRecord::into_aaaa, -562 query::parse_aaaa_response, -563 CachedRecord::Aaaa, -564 ) -565 .await?; -566 Ok(addrs.into_iter()) -567 } -568 -569 pub(super) async fn lookup_txt( -570 &self, -571 host: String, -572 ) -> Result<impl Iterator<Item = TxtRecordData> + use<>, DnsError> { -573 let records = self -574 .lookup( -575 &host, -576 QueryType::TXT, -577 TYPE::TXT, -578 CachedRecord::into_txt, -579 query::parse_txt_response, -580 CachedRecord::Txt, -581 ) -582 .await?; -583 Ok(records.into_iter()) -584 } -585 -586 pub(super) fn clear_cache(&self) { -587 self.cache.clear(); -588 } -589 -590 pub(super) fn reset(&self) -> Self { -591 // Carry the cache across so a network change does not start DNS cold, -592 // which would strand reconnects while the new nameservers settle (#4037). -593 Self::with_cache(self.builder.clone(), self.cache.clone()) -594 } -595} -596 -597impl Resolver for Arc<SimpleDnsResolver> { -598 fn lookup_ipv4(&self, host: String) -> BoxFuture<Result<BoxIter<Ipv4Addr>, DnsError>> { -599 let this = self.clone(); -600 Box::pin(async move { -601 let iter = (*this).lookup_ipv4(host).await?; -602 let iter: BoxIter<_> = Box::new(iter); -603 Ok(iter) -604 }) -605 } -606 -607 fn lookup_ipv6(&self, host: String) -> BoxFuture<Result<BoxIter<Ipv6Addr>, DnsError>> { -608 let this = self.clone(); -609 Box::pin(async move { -610 let iter = (*this).lookup_ipv6(host).await?; -611 let iter: BoxIter<_> = Box::new(iter); -612 Ok(iter) -613 }) -614 } -615 -616 fn lookup_txt(&self, host: String) -> BoxFuture<Result<BoxIter<TxtRecordData>, DnsError>> { -617 let this = self.clone(); -618 Box::pin(async move { -619 let iter = (*this).lookup_txt(host).await?; -620 let iter: BoxIter<_> = Box::new(iter); -621 Ok(iter) -622 }) -623 } -624 -625 fn clear_cache(&self) { -626 SimpleDnsResolver::clear_cache(self); -627 } -628 -629 fn reset(&self) -> Box<dyn Resolver> { -630 Box::new(Arc::new(SimpleDnsResolver::reset(self))) -631 } -632} -633 -634#[cfg(test)] -635mod tests { -636 use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; -637 -638 use n0_future::time::Duration; -639 -640 use super::{ -641 super::{DnsProtocol, DnsResolver}, -642 Builder, CachedRecord, Hosts, QueryType, SimpleDnsResolver, -643 }; -644 -645 const TIMEOUT: Duration = Duration::from_secs(5); -646 const GOOGLE_DNS: SocketAddr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(8, 8, 8, 8)), 53); -647 const CLOUDFLARE_DNS: SocketAddr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(1, 1, 1, 1)), 53); -648 #[cfg(with_crypto_provider)] -649 const GOOGLE_DNS_TLS: SocketAddr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(8, 8, 8, 8)), 853); -650 #[cfg(with_crypto_provider)] -651 const CLOUDFLARE_DNS_HTTPS: SocketAddr = -652 SocketAddr::new(IpAddr::V4(Ipv4Addr::new(1, 1, 1, 1)), 443); -653 -654 fn with_proto(addr: SocketAddr, proto: DnsProtocol) -> DnsResolver { -655 #[cfg_attr(not(with_crypto_provider), allow(unused_mut))] -656 let mut builder = DnsResolver::builder().with_nameserver(addr, proto); -657 #[cfg(with_crypto_provider)] -658 if proto == DnsProtocol::Tls { -659 let root_store = -660 rustls::RootCertStore::from_iter(webpki_roots::TLS_SERVER_ROOTS.iter().cloned()); -661 builder = builder.tls_client_config( -662 rustls::ClientConfig::builder() -663 .with_root_certificates(root_store) -664 .with_no_client_auth(), -665 ); -666 } -667 builder.build() -668 } -669 -670 async fn assert_resolves_ipv4(resolver: &DnsResolver, host: &str) { -671 let addrs: Vec<_> = resolver.lookup_ipv4(host, TIMEOUT).await.unwrap().collect(); -672 assert!(!addrs.is_empty(), "{host} should have IPv4 addresses"); -673 } -674 -675 #[tokio::test] -676 #[ignore = "requires network access"] -677 async fn resolve_ipv4_udp() { -678 assert_resolves_ipv4(&with_proto(GOOGLE_DNS, DnsProtocol::Udp), "google.com").await; -679 } -680 -681 #[tokio::test] -682 #[ignore = "requires network access"] -683 async fn resolve_ipv6_udp() { -684 let resolver = with_proto(GOOGLE_DNS, DnsProtocol::Udp); -685 let addrs: Vec<_> = resolver -686 .lookup_ipv6("google.com", TIMEOUT) -687 .await -688 .unwrap() -689 .collect(); -690 assert!(!addrs.is_empty()); -691 } -692 -693 #[tokio::test] -694 #[ignore = "requires network access"] -695 async fn resolve_ipv4_tcp() { -696 assert_resolves_ipv4(&with_proto(CLOUDFLARE_DNS, DnsProtocol::Tcp), "google.com").await; -697 } -698 -699 #[cfg(with_crypto_provider)] -700 #[tokio::test] -701 #[ignore = "requires network access"] -702 async fn resolve_ipv4_tls() { -703 assert_resolves_ipv4(&with_proto(GOOGLE_DNS_TLS, DnsProtocol::Tls), "google.com").await; -704 } -705 -706 #[cfg(with_crypto_provider)] -707 #[tokio::test] -708 #[ignore = "requires network access"] -709 async fn resolve_ipv4_https() { -710 assert_resolves_ipv4( -711 &with_proto(CLOUDFLARE_DNS_HTTPS, DnsProtocol::Https), -712 "google.com", -713 ) -714 .await; -715 } -716 -717 #[tokio::test] -718 #[ignore = "requires network access"] -719 async fn resolve_txt_udp() { -720 let resolver = with_proto(GOOGLE_DNS, DnsProtocol::Udp); -721 let records: Vec<_> = resolver -722 .lookup_txt("google.com", TIMEOUT) -723 .await -724 .unwrap() -725 .collect(); -726 assert!(!records.is_empty()); -727 } -728 -729 #[tokio::test] -730 #[ignore = "requires network access"] -731 async fn resolve_system_defaults() { -732 assert_resolves_ipv4(&DnsResolver::new(), "google.com").await; -733 } -734 -735 #[tokio::test] -736 #[ignore = "requires network access"] -737 async fn resolve_multiple_sites() { -738 let resolver = DnsResolver::new(); -739 for host in ["google.com", "cloudflare.com", "example.com"] { -740 assert_resolves_ipv4(&resolver, host).await; -741 } -742 } -743 -744 /// Run with `cargo test -p iroh-relay resolve_success_and_nxdomain -- --ignored --nocapture` -745 /// and `RUST_LOG=iroh_relay::dns=trace` to see the log output. -746 #[tokio::test] -747 #[ignore = "requires network access"] -748 async fn resolve_success_and_nxdomain() { -749 let _ = tracing_subscriber::fmt::try_init(); -750 let resolver = with_proto(GOOGLE_DNS, DnsProtocol::Udp); -751 -752 tracing::info!("--- resolving example.com (first, expect network query) ---"); -753 let addrs: Vec<_> = resolver -754 .lookup_ipv4("example.com", TIMEOUT) -755 .await -756 .unwrap() -757 .collect(); -758 assert!(!addrs.is_empty()); -759 -760 tracing::info!("--- resolving example.com (second, expect cache hit) ---"); -761 let addrs2: Vec<_> = resolver -762 .lookup_ipv4("example.com", TIMEOUT) -763 .await -764 .unwrap() -765 .collect(); -766 assert_eq!(addrs, addrs2); -767 -768 tracing::info!("--- resolving nonexistent domain (expect NXDOMAIN) ---"); -769 let err = resolver -770 .lookup_ipv4("this-domain-does-not-exist.example.invalid", TIMEOUT) -771 .await -772 .map(|i| i.collect::<Vec<_>>()); -773 assert!(err.is_err(), "expected NXDOMAIN, got {err:?}"); -774 } -775 -776 mod search_names { -777 use super::super::{super::Builder, *}; -778 -779 fn resolver_with_search(domains: &[&str]) -> SimpleDnsResolver { -780 let mut r = SimpleDnsResolver::new(Builder::default()); -781 r.search_domains = domains.iter().map(|s| s.to_string()).collect(); -782 r -783 } -784 -785 #[test] -786 fn no_search_domains() { -787 let r = SimpleDnsResolver::new(Builder::default()); -788 assert_eq!(r.search_names("myhost"), vec!["myhost"]); -789 } -790 -791 #[test] -792 fn fqdn_bypasses_search() { -793 let r = resolver_with_search(&["example.com"]); -794 assert_eq!( -795 r.search_names("myhost.example.com."), -796 vec!["myhost.example.com."] -797 ); -798 } -799 -800 #[test] -801 fn short_name_tries_search_first() { -802 let r = resolver_with_search(&["example.com", "test.local"]); -803 // "myhost" has 0 dots (< ndots=1), so search domains come first. -804 assert_eq!( -805 r.search_names("myhost"), -806 vec!["myhost.example.com", "myhost.test.local", "myhost"] -807 ); -808 } -809 -810 #[test] -811 fn dotted_name_tries_bare_first() { -812 let r = resolver_with_search(&["example.com"]); -813 // "foo.bar" has 1 dot (>= ndots=1), so bare name comes first. -814 assert_eq!( -815 r.search_names("foo.bar"), -816 vec!["foo.bar", "foo.bar.example.com"] -817 ); -818 } -819 -820 #[test] -821 fn multi_dot_name_tries_bare_first() { -822 let r = resolver_with_search(&["example.com"]); -823 assert_eq!(r.search_names("a.b.c"), vec!["a.b.c", "a.b.c.example.com"]); -824 } -825 -826 #[test] -827 fn high_ndots_k8s_style() { -828 let mut r = SimpleDnsResolver::new(Builder::default()); -829 r.search_domains = vec!["ns.svc.cluster.local".into(), "svc.cluster.local".into()]; -830 r.ndots = 5; -831 // 4 dots < ndots=5, so search domains come first (Kubernetes behavior). -832 assert_eq!( -833 r.search_names("my-svc.my-ns.svc.cluster.local"), -834 vec![ -835 "my-svc.my-ns.svc.cluster.local.ns.svc.cluster.local", -836 "my-svc.my-ns.svc.cluster.local.svc.cluster.local", -837 "my-svc.my-ns.svc.cluster.local", -838 ] -839 ); -840 } -841 } -842 -843 /// Spawns a mock UDP nameserver that answers one query with `rcode`, -844 /// echoing the question and adding `answer` as an A record when given. -845 async fn spawn_mock_ns( -846 rcode: simple_dns::RCODE, -847 answer: Option<Ipv4Addr>, -848 ) -> (SocketAddr, tokio::task::JoinHandle<()>) { -849 use simple_dns::{ -850 CLASS, Packet, PacketFlag, ResourceRecord, -851 rdata::{A, RData}, -852 }; -853 -854 let socket = tokio::net::UdpSocket::bind("127.0.0.1:0").await.unwrap(); -855 let addr = socket.local_addr().unwrap(); -856 let handle = tokio::spawn(async move { -857 let mut buf = vec![0u8; 512]; -858 let (len, peer) = socket.recv_from(&mut buf).await.unwrap(); -859 let query = Packet::parse(&buf[..len]).unwrap(); -860 let question = query.questions[0].clone(); -861 let mut reply = Packet::new_reply(query.id()); -862 reply.set_flags(PacketFlag::RECURSION_DESIRED | PacketFlag::RECURSION_AVAILABLE); -863 *reply.rcode_mut() = rcode; -864 if let Some(ip) = answer { -865 reply.answers.push(ResourceRecord::new( -866 question.qname.clone(), -867 CLASS::IN, -868 300, -869 RData::A(A { -870 address: u32::from(ip), -871 }), -872 )); -873 } -874 reply.questions.push(question); -875 socket -876 .send_to(&reply.build_bytes_vec().unwrap(), peer) -877 .await -878 .unwrap(); -879 }); -880 (addr, handle) -881 } -882 -883 /// A SERVFAIL or REFUSED response from the fastest nameserver must not be -884 /// the final answer: the resolver races on to a nameserver that can answer. -885 #[tokio::test] -886 async fn servfail_winner_falls_through_to_next_nameserver() { -887 let (bad, bad_handle) = spawn_mock_ns(simple_dns::RCODE::ServerFailure, None).await; -888 let (good, good_handle) = -889 spawn_mock_ns(simple_dns::RCODE::NoError, Some(Ipv4Addr::new(10, 1, 2, 3))).await; -890 -891 // `bad` is listed first, so it is the fastest by default ordering and -892 // wins the race with a SERVFAIL; the lookup must fall through to `good`. -893 let resolver = DnsResolver::builder() -894 .with_nameserver(bad, DnsProtocol::Udp) -895 .with_nameserver(good, DnsProtocol::Udp) -896 .build(); -897 -898 let addrs: Vec<_> = resolver -899 .lookup_ipv4("test.example", TIMEOUT) -900 .await -901 .unwrap() -902 .collect(); -903 assert_eq!(addrs, [IpAddr::V4(Ipv4Addr::new(10, 1, 2, 3))]); -904 -905 bad_handle.await.unwrap(); -906 good_handle.await.unwrap(); -907 } -908 -909 /// A hosts-file entry must override DNS and resolve without any network -910 /// query, the way the old hickory-backed resolver honored `/etc/hosts`. -911 #[tokio::test] -912 async fn hosts_file_overrides_dns() { -913 let mut resolver = SimpleDnsResolver::new(Builder::default()); -914 resolver.hosts = Hosts::from_content("10.0.1.10 myrelay.test\n::1 myrelay.test\n"); -915 -916 let v4: Vec<_> = resolver -917 .lookup_ipv4("myrelay.test".to_string()) -918 .await -919 .unwrap() -920 .collect(); -921 assert_eq!(v4, [Ipv4Addr::new(10, 0, 1, 10)]); -922 -923 // A trailing dot (FQDN form) still matches the hosts entry. -924 let v6: Vec<_> = resolver -925 .lookup_ipv6("myrelay.test.".to_string()) -926 .await -927 .unwrap() -928 .collect(); -929 assert_eq!(v6, [Ipv6Addr::LOCALHOST]); -930 } -931 -932 /// A major network change rebuilds the resolver via [`SimpleDnsResolver::reset`]; -933 /// the DNS cache must carry across so reconnects keep resolving while the new -934 /// nameservers settle (issue #4037). -935 #[test] -936 fn cache_survives_reset() { -937 let r = SimpleDnsResolver::new(Builder::default()); -938 r.cache.insert( -939 "example.com", -940 QueryType::A, -941 CachedRecord::A(vec![Ipv4Addr::LOCALHOST]), -942 300, -943 ); -944 -945 let reset = r.reset(); -946 -947 let cached = reset.cache.get("example.com", QueryType::A); -948 let survived = matches!(&cached, Some(CachedRecord::A(addrs)) if addrs.as_slice() == [Ipv4Addr::LOCALHOST]); -949 assert!(survived, "cache entry should survive reset, got {cached:?}"); -950 } -951} \ No newline at end of file +393 last_err = +394 Some(e!(DnsError::ServerError { rcode: format!("{rcode:?}") })); +395 // Fail fast: start the next attempt now rather than waiting. +396 next_attempt.as_mut().set_none(); +397 } else { +398 self.rtt_map.record_success(idx, start.elapsed()); +399 return Ok(resp); +400 } +401 } +402 Err(e) => { +403 self.rtt_map.record_failure(idx); +404 last_err = Some(e); +405 // Fail fast: start the next attempt now rather than waiting. +406 next_attempt.as_mut().set_none(); +407 } +408 }, +409 // The next attempt is due. +410 () = &mut next_attempt, if next_attempt.is_some() => { +411 next_attempt.as_mut().set_none(); +412 } +413 } +414 } +415 } +416 +417 /// Send a query and follow CNAME chains recursively if the response contains +418 /// a CNAME but no records of the requested type. +419 async fn send_query_following_cnames( +420 &self, +421 host: String, +422 qtype: TYPE, +423 ) -> Result<Vec<u8>, DnsError> { +424 let mut current_host = host; +425 for _ in 0..MAX_CNAME_DEPTH { +426 let name = simple_dns::Name::new(&current_host) +427 .map_err(|e| e!(DnsError::InvalidQuery, AnyError::from_std(e)))?; +428 let (id, query_bytes) = query::build_query(&current_host, qtype)?; +429 let response = self.send_query(&query_bytes).await?; +430 let packet = +431 simple_dns::Packet::parse(&response).map_err(|_| e!(DnsError::InvalidResponse))?; +432 +433 // Validate the id, QR bit, question, and RCODE before trusting the +434 // packet to decide the answer or the next CNAME target. This is the +435 // only check of the response against the name we actually asked for. +436 query::check_response(&packet, id, &name, qtype)?; +437 +438 let has_answer = packet +439 .answers +440 .iter() +441 .any(|rr| rr.rdata.type_code() == qtype); +442 +443 if has_answer { +444 return Ok(response); +445 } +446 +447 // No records of the requested type -- follow CNAME if present. +448 let Some(target) = query::cname_target(&packet, &current_host) else { +449 return Ok(response); +450 }; +451 debug!(from = %current_host, to = %target, "following CNAME"); +452 current_host = target; +453 } +454 Err(e!(DnsError::InvalidResponse)) +455 } +456 +457 /// Shared lookup logic: check cache, try search names, parse response, cache result. +458 #[allow(clippy::type_complexity)] +459 async fn lookup<T: Clone + std::fmt::Debug>( +460 &self, +461 host: &str, +462 qtype: QueryType, +463 dns_type: TYPE, +464 from_cache: fn(CachedRecord) -> Option<Vec<T>>, +465 parse: fn(&[u8]) -> Result<(Vec<T>, u32), QueryError>, +466 to_cache: fn(Vec<T>) -> CachedRecord, +467 ) -> Result<Vec<T>, DnsError> { +468 if let Some(cached) = self.cache.get(host, qtype).and_then(from_cache) { +469 trace!(%host, records = cached.len(), ?qtype, "cache hit"); +470 return Ok(cached); +471 } +472 +473 let mut last_err = None; +474 let names = self.search_names(host); +475 let total = names.len(); +476 for (i, name) in names.into_iter().enumerate() { +477 trace!(%name, ?qtype, "resolving"); +478 let res = match self +479 .send_query_following_cnames(name.clone(), dns_type) +480 .await +481 { +482 Ok(response) => parse(&response).map_err(DnsError::from), +483 Err(e) => Err(e), +484 }; +485 match res { +486 Ok((results, ttl)) if !results.is_empty() => { +487 debug!(%host, ?qtype, ?results, ttl, "resolved"); +488 self.cache +489 .insert(host, qtype, to_cache(results.clone()), ttl); +490 return Ok(results); +491 } +492 Ok(_) => {} +493 Err(ref e @ DnsError::NxDomain { .. }) +494 | Err(ref e @ DnsError::ServerError { .. }) => { +495 let remaining = total - i - 1; +496 trace!(%name, ?qtype, remaining, reason = %e, "lookup failed"); +497 last_err = Some(e!(DnsError::NxDomain)); +498 } +499 Err(e) => { +500 debug!(%name, ?qtype, reason = %e, "lookup failed"); +501 return Err(e); +502 } +503 } +504 } +505 let err = last_err.unwrap_or_else(|| e!(DnsError::NoResponse)); +506 debug!(%host, ?qtype, reason = %err, "resolve failed"); +507 Err(err) +508 } +509 +510 pub(super) async fn lookup_ipv4( +511 &self, +512 host: String, +513 ) -> Result<impl Iterator<Item = Ipv4Addr> + use<>, DnsError> { +514 // RFC 6761: localhost always resolves to loopback. +515 if is_localhost(&host) { +516 return Ok(vec![Ipv4Addr::LOCALHOST].into_iter()); +517 } +518 // A hosts-file entry overrides DNS, so check it ahead of the cache. +519 if let Some(addrs) = self +520 .search_names(&host) +521 .iter() +522 .find_map(|name| self.hosts.lookup_ipv4(name)) +523 { +524 trace!(%host, ?addrs, "resolved from hosts file"); +525 return Ok(addrs.into_iter()); +526 } +527 let addrs = self +528 .lookup( +529 &host, +530 QueryType::A, +531 TYPE::A, +532 CachedRecord::into_a, +533 query::parse_a_response, +534 CachedRecord::A, +535 ) +536 .await?; +537 Ok(addrs.into_iter()) +538 } +539 +540 pub(super) async fn lookup_ipv6( +541 &self, +542 host: String, +543 ) -> Result<impl Iterator<Item = Ipv6Addr> + use<>, DnsError> { +544 // RFC 6761: localhost always resolves to loopback. +545 if is_localhost(&host) { +546 return Ok(vec![Ipv6Addr::LOCALHOST].into_iter()); +547 } +548 // A hosts-file entry overrides DNS, so check it ahead of the cache. +549 if let Some(addrs) = self +550 .search_names(&host) +551 .iter() +552 .find_map(|name| self.hosts.lookup_ipv6(name)) +553 { +554 trace!(%host, ?addrs, "resolved from hosts file"); +555 return Ok(addrs.into_iter()); +556 } +557 let addrs = self +558 .lookup( +559 &host, +560 QueryType::AAAA, +561 TYPE::AAAA, +562 CachedRecord::into_aaaa, +563 query::parse_aaaa_response, +564 CachedRecord::Aaaa, +565 ) +566 .await?; +567 Ok(addrs.into_iter()) +568 } +569 +570 pub(super) async fn lookup_txt( +571 &self, +572 host: String, +573 ) -> Result<impl Iterator<Item = TxtRecordData> + use<>, DnsError> { +574 let records = self +575 .lookup( +576 &host, +577 QueryType::TXT, +578 TYPE::TXT, +579 CachedRecord::into_txt, +580 query::parse_txt_response, +581 CachedRecord::Txt, +582 ) +583 .await?; +584 Ok(records.into_iter()) +585 } +586 +587 pub(super) fn clear_cache(&self) { +588 self.cache.clear(); +589 } +590 +591 pub(super) fn reset(&self) -> Self { +592 // Carry the cache across so a network change does not start DNS cold, +593 // which would strand reconnects while the new nameservers settle (#4037). +594 Self::with_cache(self.builder.clone(), self.cache.clone()) +595 } +596} +597 +598impl Resolver for Arc<SimpleDnsResolver> { +599 fn lookup_ipv4(&self, host: String) -> BoxFuture<Result<BoxIter<Ipv4Addr>, DnsError>> { +600 let this = self.clone(); +601 Box::pin(async move { +602 let iter = (*this).lookup_ipv4(host).await?; +603 let iter: BoxIter<_> = Box::new(iter); +604 Ok(iter) +605 }) +606 } +607 +608 fn lookup_ipv6(&self, host: String) -> BoxFuture<Result<BoxIter<Ipv6Addr>, DnsError>> { +609 let this = self.clone(); +610 Box::pin(async move { +611 let iter = (*this).lookup_ipv6(host).await?; +612 let iter: BoxIter<_> = Box::new(iter); +613 Ok(iter) +614 }) +615 } +616 +617 fn lookup_txt(&self, host: String) -> BoxFuture<Result<BoxIter<TxtRecordData>, DnsError>> { +618 let this = self.clone(); +619 Box::pin(async move { +620 let iter = (*this).lookup_txt(host).await?; +621 let iter: BoxIter<_> = Box::new(iter); +622 Ok(iter) +623 }) +624 } +625 +626 fn clear_cache(&self) { +627 SimpleDnsResolver::clear_cache(self); +628 } +629 +630 fn reset(&self) -> Box<dyn Resolver> { +631 Box::new(Arc::new(SimpleDnsResolver::reset(self))) +632 } +633} +634 +635#[cfg(test)] +636mod tests { +637 use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; +638 +639 use n0_future::time::Duration; +640 +641 use super::{ +642 super::{DnsProtocol, DnsResolver}, +643 Builder, CachedRecord, Hosts, QueryType, SimpleDnsResolver, +644 }; +645 +646 const TIMEOUT: Duration = Duration::from_secs(5); +647 const GOOGLE_DNS: SocketAddr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(8, 8, 8, 8)), 53); +648 const CLOUDFLARE_DNS: SocketAddr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(1, 1, 1, 1)), 53); +649 #[cfg(with_crypto_provider)] +650 const GOOGLE_DNS_TLS: SocketAddr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(8, 8, 8, 8)), 853); +651 #[cfg(with_crypto_provider)] +652 const CLOUDFLARE_DNS_HTTPS: SocketAddr = +653 SocketAddr::new(IpAddr::V4(Ipv4Addr::new(1, 1, 1, 1)), 443); +654 +655 fn with_proto(addr: SocketAddr, proto: DnsProtocol) -> DnsResolver { +656 #[cfg_attr(not(with_crypto_provider), allow(unused_mut))] +657 let mut builder = DnsResolver::builder().with_nameserver(addr, proto); +658 #[cfg(with_crypto_provider)] +659 if proto == DnsProtocol::Tls { +660 let root_store = +661 rustls::RootCertStore::from_iter(webpki_roots::TLS_SERVER_ROOTS.iter().cloned()); +662 builder = builder.tls_client_config( +663 rustls::ClientConfig::builder() +664 .with_root_certificates(root_store) +665 .with_no_client_auth(), +666 ); +667 } +668 builder.build() +669 } +670 +671 async fn assert_resolves_ipv4(resolver: &DnsResolver, host: &str) { +672 let addrs: Vec<_> = resolver.lookup_ipv4(host, TIMEOUT).await.unwrap().collect(); +673 assert!(!addrs.is_empty(), "{host} should have IPv4 addresses"); +674 } +675 +676 #[tokio::test] +677 #[ignore = "requires network access"] +678 async fn resolve_ipv4_udp() { +679 assert_resolves_ipv4(&with_proto(GOOGLE_DNS, DnsProtocol::Udp), "google.com").await; +680 } +681 +682 #[tokio::test] +683 #[ignore = "requires network access"] +684 async fn resolve_ipv6_udp() { +685 let resolver = with_proto(GOOGLE_DNS, DnsProtocol::Udp); +686 let addrs: Vec<_> = resolver +687 .lookup_ipv6("google.com", TIMEOUT) +688 .await +689 .unwrap() +690 .collect(); +691 assert!(!addrs.is_empty()); +692 } +693 +694 #[tokio::test] +695 #[ignore = "requires network access"] +696 async fn resolve_ipv4_tcp() { +697 assert_resolves_ipv4(&with_proto(CLOUDFLARE_DNS, DnsProtocol::Tcp), "google.com").await; +698 } +699 +700 #[cfg(with_crypto_provider)] +701 #[tokio::test] +702 #[ignore = "requires network access"] +703 async fn resolve_ipv4_tls() { +704 assert_resolves_ipv4(&with_proto(GOOGLE_DNS_TLS, DnsProtocol::Tls), "google.com").await; +705 } +706 +707 #[cfg(with_crypto_provider)] +708 #[tokio::test] +709 #[ignore = "requires network access"] +710 async fn resolve_ipv4_https() { +711 assert_resolves_ipv4( +712 &with_proto(CLOUDFLARE_DNS_HTTPS, DnsProtocol::Https), +713 "google.com", +714 ) +715 .await; +716 } +717 +718 #[tokio::test] +719 #[ignore = "requires network access"] +720 async fn resolve_txt_udp() { +721 let resolver = with_proto(GOOGLE_DNS, DnsProtocol::Udp); +722 let records: Vec<_> = resolver +723 .lookup_txt("google.com", TIMEOUT) +724 .await +725 .unwrap() +726 .collect(); +727 assert!(!records.is_empty()); +728 } +729 +730 #[tokio::test] +731 #[ignore = "requires network access"] +732 async fn resolve_system_defaults() { +733 assert_resolves_ipv4(&DnsResolver::new(), "google.com").await; +734 } +735 +736 #[tokio::test] +737 #[ignore = "requires network access"] +738 async fn resolve_multiple_sites() { +739 let resolver = DnsResolver::new(); +740 for host in ["google.com", "cloudflare.com", "example.com"] { +741 assert_resolves_ipv4(&resolver, host).await; +742 } +743 } +744 +745 /// Run with `cargo test -p iroh-relay resolve_success_and_nxdomain -- --ignored --nocapture` +746 /// and `RUST_LOG=iroh_relay::dns=trace` to see the log output. +747 #[tokio::test] +748 #[ignore = "requires network access"] +749 async fn resolve_success_and_nxdomain() { +750 let _ = tracing_subscriber::fmt::try_init(); +751 let resolver = with_proto(GOOGLE_DNS, DnsProtocol::Udp); +752 +753 tracing::info!("--- resolving example.com (first, expect network query) ---"); +754 let addrs: Vec<_> = resolver +755 .lookup_ipv4("example.com", TIMEOUT) +756 .await +757 .unwrap() +758 .collect(); +759 assert!(!addrs.is_empty()); +760 +761 tracing::info!("--- resolving example.com (second, expect cache hit) ---"); +762 let addrs2: Vec<_> = resolver +763 .lookup_ipv4("example.com", TIMEOUT) +764 .await +765 .unwrap() +766 .collect(); +767 assert_eq!(addrs, addrs2); +768 +769 tracing::info!("--- resolving nonexistent domain (expect NXDOMAIN) ---"); +770 let err = resolver +771 .lookup_ipv4("this-domain-does-not-exist.example.invalid", TIMEOUT) +772 .await +773 .map(|i| i.collect::<Vec<_>>()); +774 assert!(err.is_err(), "expected NXDOMAIN, got {err:?}"); +775 } +776 +777 mod search_names { +778 use super::super::{super::Builder, *}; +779 +780 fn resolver_with_search(domains: &[&str]) -> SimpleDnsResolver { +781 let mut r = SimpleDnsResolver::new(Builder::default()); +782 r.search_domains = domains.iter().map(|s| s.to_string()).collect(); +783 r +784 } +785 +786 #[test] +787 fn no_search_domains() { +788 let r = SimpleDnsResolver::new(Builder::default()); +789 assert_eq!(r.search_names("myhost"), vec!["myhost"]); +790 } +791 +792 #[test] +793 fn fqdn_bypasses_search() { +794 let r = resolver_with_search(&["example.com"]); +795 assert_eq!( +796 r.search_names("myhost.example.com."), +797 vec!["myhost.example.com."] +798 ); +799 } +800 +801 #[test] +802 fn short_name_tries_search_first() { +803 let r = resolver_with_search(&["example.com", "test.local"]); +804 // "myhost" has 0 dots (< ndots=1), so search domains come first. +805 assert_eq!( +806 r.search_names("myhost"), +807 vec!["myhost.example.com", "myhost.test.local", "myhost"] +808 ); +809 } +810 +811 #[test] +812 fn dotted_name_tries_bare_first() { +813 let r = resolver_with_search(&["example.com"]); +814 // "foo.bar" has 1 dot (>= ndots=1), so bare name comes first. +815 assert_eq!( +816 r.search_names("foo.bar"), +817 vec!["foo.bar", "foo.bar.example.com"] +818 ); +819 } +820 +821 #[test] +822 fn multi_dot_name_tries_bare_first() { +823 let r = resolver_with_search(&["example.com"]); +824 assert_eq!(r.search_names("a.b.c"), vec!["a.b.c", "a.b.c.example.com"]); +825 } +826 +827 #[test] +828 fn high_ndots_k8s_style() { +829 let mut r = SimpleDnsResolver::new(Builder::default()); +830 r.search_domains = vec!["ns.svc.cluster.local".into(), "svc.cluster.local".into()]; +831 r.ndots = 5; +832 // 4 dots < ndots=5, so search domains come first (Kubernetes behavior). +833 assert_eq!( +834 r.search_names("my-svc.my-ns.svc.cluster.local"), +835 vec![ +836 "my-svc.my-ns.svc.cluster.local.ns.svc.cluster.local", +837 "my-svc.my-ns.svc.cluster.local.svc.cluster.local", +838 "my-svc.my-ns.svc.cluster.local", +839 ] +840 ); +841 } +842 } +843 +844 /// Spawns a mock UDP nameserver that answers one query with `rcode`, +845 /// echoing the question and adding `answer` as an A record when given. +846 async fn spawn_mock_ns( +847 rcode: simple_dns::RCODE, +848 answer: Option<Ipv4Addr>, +849 ) -> (SocketAddr, tokio::task::JoinHandle<()>) { +850 use simple_dns::{ +851 CLASS, Packet, PacketFlag, ResourceRecord, +852 rdata::{A, RData}, +853 }; +854 +855 let socket = tokio::net::UdpSocket::bind("127.0.0.1:0").await.unwrap(); +856 let addr = socket.local_addr().unwrap(); +857 let handle = tokio::spawn(async move { +858 let mut buf = vec![0u8; 512]; +859 let (len, peer) = socket.recv_from(&mut buf).await.unwrap(); +860 let query = Packet::parse(&buf[..len]).unwrap(); +861 let question = query.questions[0].clone(); +862 let mut reply = Packet::new_reply(query.id()); +863 reply.set_flags(PacketFlag::RECURSION_DESIRED | PacketFlag::RECURSION_AVAILABLE); +864 *reply.rcode_mut() = rcode; +865 if let Some(ip) = answer { +866 reply.answers.push(ResourceRecord::new( +867 question.qname.clone(), +868 CLASS::IN, +869 300, +870 RData::A(A { +871 address: u32::from(ip), +872 }), +873 )); +874 } +875 reply.questions.push(question); +876 socket +877 .send_to(&reply.build_bytes_vec().unwrap(), peer) +878 .await +879 .unwrap(); +880 }); +881 (addr, handle) +882 } +883 +884 /// A SERVFAIL or REFUSED response from the fastest nameserver must not be +885 /// the final answer: the resolver races on to a nameserver that can answer. +886 #[tokio::test] +887 async fn servfail_winner_falls_through_to_next_nameserver() { +888 let (bad, bad_handle) = spawn_mock_ns(simple_dns::RCODE::ServerFailure, None).await; +889 let (good, good_handle) = +890 spawn_mock_ns(simple_dns::RCODE::NoError, Some(Ipv4Addr::new(10, 1, 2, 3))).await; +891 +892 // `bad` is listed first, so it is the fastest by default ordering and +893 // wins the race with a SERVFAIL; the lookup must fall through to `good`. +894 let resolver = DnsResolver::builder() +895 .with_nameserver(bad, DnsProtocol::Udp) +896 .with_nameserver(good, DnsProtocol::Udp) +897 .build(); +898 +899 let addrs: Vec<_> = resolver +900 .lookup_ipv4("test.example", TIMEOUT) +901 .await +902 .unwrap() +903 .collect(); +904 assert_eq!(addrs, [IpAddr::V4(Ipv4Addr::new(10, 1, 2, 3))]); +905 +906 bad_handle.await.unwrap(); +907 good_handle.await.unwrap(); +908 } +909 +910 /// A hosts-file entry must override DNS and resolve without any network +911 /// query, the way the old hickory-backed resolver honored `/etc/hosts`. +912 #[tokio::test] +913 async fn hosts_file_overrides_dns() { +914 let mut resolver = SimpleDnsResolver::new(Builder::default()); +915 resolver.hosts = Hosts::from_content("10.0.1.10 myrelay.test\n::1 myrelay.test\n"); +916 +917 let v4: Vec<_> = resolver +918 .lookup_ipv4("myrelay.test".to_string()) +919 .await +920 .unwrap() +921 .collect(); +922 assert_eq!(v4, [Ipv4Addr::new(10, 0, 1, 10)]); +923 +924 // A trailing dot (FQDN form) still matches the hosts entry. +925 let v6: Vec<_> = resolver +926 .lookup_ipv6("myrelay.test.".to_string()) +927 .await +928 .unwrap() +929 .collect(); +930 assert_eq!(v6, [Ipv6Addr::LOCALHOST]); +931 } +932 +933 /// A major network change rebuilds the resolver via [`SimpleDnsResolver::reset`]; +934 /// the DNS cache must carry across so reconnects keep resolving while the new +935 /// nameservers settle (issue #4037). +936 #[test] +937 fn cache_survives_reset() { +938 let r = SimpleDnsResolver::new(Builder::default()); +939 r.cache.insert( +940 "example.com", +941 QueryType::A, +942 CachedRecord::A(vec![Ipv4Addr::LOCALHOST]), +943 300, +944 ); +945 +946 let reset = r.reset(); +947 +948 let cached = reset.cache.get("example.com", QueryType::A); +949 let survived = matches!(&cached, Some(CachedRecord::A(addrs)) if addrs.as_slice() == [Ipv4Addr::LOCALHOST]); +950 assert!(survived, "cache entry should survive reset, got {cached:?}"); +951 } +952} \ No newline at end of file diff --git a/pr/4036/docs/src/iroh_dns/dns/resolver/query.rs.html b/pr/4036/docs/src/iroh_dns/dns/resolver/query.rs.html index b474d34674..f6be8d215b 100644 --- a/pr/4036/docs/src/iroh_dns/dns/resolver/query.rs.html +++ b/pr/4036/docs/src/iroh_dns/dns/resolver/query.rs.html @@ -4,7 +4,7 @@ 4 5use n0_error::{AnyError, e, stack_error}; 6use simple_dns::{ -7 CLASS, Name, Packet, PacketFlag, QCLASS, QTYPE, Question, RCODE, TYPE, +7 CLASS, Name, Packet, PacketFlag, QCLASS, QTYPE, Question, RCODE, TYPE, header_buffer, 8 rdata::{A, AAAA, RData}, 9}; 10 @@ -64,425 +64,424 @@ 64 Ok((id, bytes)) 65} 66 -67/// Returns the RCODE name if `data` is a server failure that warrants trying -68/// another nameserver (SERVFAIL or REFUSED), otherwise `None`. +67/// Returns the RCODE if `data` is a server failure that warrants trying another +68/// nameserver (SERVFAIL or REFUSED), otherwise `None`. 69/// -70/// Reads the RCODE nibble straight from the header (RFC 1035 Section 4.1.1) so -71/// it works on the raw response before the packet is fully parsed or validated. -72/// A spoofed RCODE here is harmless: at worst it makes the race try another -73/// server, and the eventual response is still validated by [`check_response`]. -74pub(super) fn server_failure_rcode(data: &[u8]) -> Option<&'static str> { -75 match data.get(3).map(|byte| byte & 0x0f) { -76 Some(2) => Some("ServerFailure"), -77 Some(5) => Some("Refused"), -78 _ => None, -79 } -80} -81 -82/// Maximum CNAME chain depth to prevent infinite loops. -83pub(super) const MAX_CNAME_DEPTH: usize = 8; -84 -85/// Resolve the CNAME chain in the answer section starting from `start_name`. -86/// -87/// Returns the final canonical name after following all CNAMEs, or the -88/// original name if no CNAME records are present. -89fn resolve_cname_chain<'a>(packet: &'a Packet<'a>, start_name: &Name<'a>) -> Name<'a> { -90 let mut current = start_name.clone(); -91 for _ in 0..MAX_CNAME_DEPTH { -92 let Some(RData::CNAME(cname)) = packet -93 .answers -94 .iter() -95 .find(|rr| rr.name == current) -96 .map(|rr| &rr.rdata) -97 else { -98 break; -99 }; -100 current = cname.0.clone(); -101 } -102 current -103} -104 -105/// Returns the CNAME target for a query name, if the response contains a CNAME -106/// but no final records of the requested type for that name. -107/// -108/// This is used for recursive CNAME following: when the server returns only a -109/// CNAME without the final record, the caller issues a new query for the target. -110pub(super) fn cname_target(packet: &Packet<'_>, qname: &str) -> Option<String> { -111 let name = Name::new(qname).ok()?; -112 let canonical = resolve_cname_chain(packet, &name); -113 (canonical != name).then(|| canonical.to_string()) -114} -115 -116/// Validate a response against the query that produced it, then surface its RCODE. -117/// -118/// Per RFC 5452 a response is only trustworthy if it echoes the query: the QR -119/// flag must be set, the transaction ID must match, and the response must carry -120/// exactly the one question we asked, by name, type, and class. Without the -121/// question check an off-path attacker who guesses the 16-bit ID could supply -122/// its own question and have its answers accepted for an arbitrary name. A -123/// `NameError` RCODE maps to [`QueryError::NxDomain`] and any other non-`NoError` -124/// RCODE to [`QueryError::ServerFailure`]. -125pub(super) fn check_response( -126 packet: &Packet, -127 expected_id: u16, -128 expected_name: &Name<'_>, -129 expected_type: TYPE, -130) -> Result<(), QueryError> { -131 if !packet.has_flags(PacketFlag::RESPONSE) { -132 return Err(e!(QueryError::Unexpected)); -133 } -134 if packet.id() != expected_id { -135 return Err(e!(QueryError::Unexpected)); -136 } -137 // The response must echo exactly the question we sent (RFC 1035 4.1.2). -138 match packet.questions.as_slice() { -139 [question] -140 if &question.qname == expected_name -141 && question.qtype == QTYPE::TYPE(expected_type) -142 && question.qclass == QCLASS::CLASS(CLASS::IN) => {} -143 _ => return Err(e!(QueryError::Unexpected)), -144 } -145 match packet.rcode() { -146 RCODE::NoError => Ok(()), -147 RCODE::NameError => Err(e!(QueryError::NxDomain)), -148 rcode => Err(e!(QueryError::ServerFailure { -149 rcode: format!("{rcode:?}"), -150 })), -151 } -152} -153 -154/// Check whether a resource record's name matches the queried name or its -155/// CNAME-resolved canonical name. -156/// -157/// `qname` is `None` only for a response with no question section, which -158/// [`check_response`] already rejects, so the `None` arm is unreachable for -159/// validated responses and conservatively matches nothing. -160fn name_matches( -161 rr_name: &Name<'_>, -162 qname: Option<&Name<'_>>, -163 canonical: Option<&Name<'_>>, -164) -> bool { -165 match qname { -166 Some(q) => rr_name == q || canonical.is_some_and(|c| rr_name == c), -167 None => false, -168 } -169} -170 -171/// Extract matching records from a validated DNS response, following CNAME chains. -172/// -173/// The caller must already have validated the response with [`check_response`]; -174/// this resolves the CNAME chain anchored on the question and extracts records -175/// of the requested type using `extract`. Returns the records and the minimum -176/// TTL across them. -177fn parse_response<T>( -178 data: &[u8], -179 extract: impl Fn(&RData<'_>) -> Option<T>, -180) -> Result<(Vec<T>, u32), QueryError> { -181 let packet = -182 Packet::parse(data).map_err(|e| e!(QueryError::Malformed, AnyError::from_std(e)))?; -183 -184 let qname = packet.questions.first().map(|q| q.qname.clone()); -185 let canonical = qname.as_ref().map(|q| resolve_cname_chain(&packet, q)); -186 -187 let mut results = Vec::new(); -188 let mut min_ttl = u32::MAX; -189 for rr in &packet.answers { -190 if name_matches(&rr.name, qname.as_ref(), canonical.as_ref()) -191 && let Some(val) = extract(&rr.rdata) -192 { -193 results.push(val); -194 min_ttl = min_ttl.min(rr.ttl); -195 } -196 } -197 if min_ttl == u32::MAX { -198 min_ttl = 0; -199 } -200 Ok((results, min_ttl)) -201} -202 -203/// Parse A (IPv4) records from a DNS response, following CNAME chains. -204pub(super) fn parse_a_response(data: &[u8]) -> Result<(Vec<Ipv4Addr>, u32), QueryError> { -205 parse_response(data, |rdata| match rdata { -206 RData::A(A { address }) => Some(Ipv4Addr::from(*address)), -207 _ => None, -208 }) -209} -210 -211/// Parse AAAA (IPv6) records from a DNS response, following CNAME chains. -212pub(super) fn parse_aaaa_response(data: &[u8]) -> Result<(Vec<Ipv6Addr>, u32), QueryError> { -213 parse_response(data, |rdata| match rdata { -214 RData::AAAA(AAAA { address }) => Some(Ipv6Addr::from(*address)), -215 _ => None, -216 }) -217} -218 -219/// Parse TXT records from a DNS response, following CNAME chains. -220pub(super) fn parse_txt_response(data: &[u8]) -> Result<(Vec<TxtRecordData>, u32), QueryError> { -221 parse_response(data, |rdata| match rdata { -222 RData::TXT(txt) => Some(extract_txt_record_data(txt)), -223 _ => None, -224 }) -225} -226 -227/// Extract the raw content of a TXT record into `TxtRecordData`. -228/// -229/// Converts the TXT record's character strings into raw bytes. In iroh's -230/// DNS encoding, each TXT record typically contains a single character -231/// string (one `key=value` attribute), and each attribute is published as -232/// a separate TXT ResourceRecord. -233/// -234/// We use `String::try_from` which concatenates all character strings in -235/// the record into one byte sequence. This preserves the raw content -236/// without the destructive key=value parsing that `TXT::attributes()` does -237/// (which uses a HashMap and would lose ordering and deduplicate keys). -238fn extract_txt_record_data(txt: &simple_dns::rdata::TXT<'_>) -> TxtRecordData { -239 match String::try_from(txt.clone()) { -240 Ok(s) if !s.is_empty() => TxtRecordData::from(vec![s.into_bytes().into_boxed_slice()]), -241 _ => TxtRecordData::from(Vec::<Box<[u8]>>::new()), -242 } -243} -244 -245/// Returns true if the response has the TC (truncation) flag set. -246/// -247/// Checks the raw header byte directly instead of parsing the full packet, -248/// since a truncated packet may fail to parse entirely. +70/// Reads just the RCODE from the header so it works on the raw response before +71/// the packet is fully parsed or validated. A spoofed RCODE here is harmless: +72/// at worst it makes the race try another server, and the eventual response is +73/// still validated by [`check_response`]. +74pub(super) fn server_failure_rcode(data: &[u8]) -> Option<RCODE> { +75 match header_buffer::rcode(data) { +76 Ok(rcode @ (RCODE::ServerFailure | RCODE::Refused)) => Some(rcode), +77 _ => None, +78 } +79} +80 +81/// Maximum CNAME chain depth to prevent infinite loops. +82pub(super) const MAX_CNAME_DEPTH: usize = 8; +83 +84/// Resolve the CNAME chain in the answer section starting from `start_name`. +85/// +86/// Returns the final canonical name after following all CNAMEs, or the +87/// original name if no CNAME records are present. +88fn resolve_cname_chain<'a>(packet: &'a Packet<'a>, start_name: &Name<'a>) -> Name<'a> { +89 let mut current = start_name.clone(); +90 for _ in 0..MAX_CNAME_DEPTH { +91 let Some(RData::CNAME(cname)) = packet +92 .answers +93 .iter() +94 .find(|rr| rr.name == current) +95 .map(|rr| &rr.rdata) +96 else { +97 break; +98 }; +99 current = cname.0.clone(); +100 } +101 current +102} +103 +104/// Returns the CNAME target for a query name, if the response contains a CNAME +105/// but no final records of the requested type for that name. +106/// +107/// This is used for recursive CNAME following: when the server returns only a +108/// CNAME without the final record, the caller issues a new query for the target. +109pub(super) fn cname_target(packet: &Packet<'_>, qname: &str) -> Option<String> { +110 let name = Name::new(qname).ok()?; +111 let canonical = resolve_cname_chain(packet, &name); +112 (canonical != name).then(|| canonical.to_string()) +113} +114 +115/// Validate a response against the query that produced it, then surface its RCODE. +116/// +117/// Per RFC 5452 a response is only trustworthy if it echoes the query: the QR +118/// flag must be set, the transaction ID must match, and the response must carry +119/// exactly the one question we asked, by name, type, and class. Without the +120/// question check an off-path attacker who guesses the 16-bit ID could supply +121/// its own question and have its answers accepted for an arbitrary name. A +122/// `NameError` RCODE maps to [`QueryError::NxDomain`] and any other non-`NoError` +123/// RCODE to [`QueryError::ServerFailure`]. +124pub(super) fn check_response( +125 packet: &Packet, +126 expected_id: u16, +127 expected_name: &Name<'_>, +128 expected_type: TYPE, +129) -> Result<(), QueryError> { +130 if !packet.has_flags(PacketFlag::RESPONSE) { +131 return Err(e!(QueryError::Unexpected)); +132 } +133 if packet.id() != expected_id { +134 return Err(e!(QueryError::Unexpected)); +135 } +136 // The response must echo exactly the question we sent (RFC 1035 4.1.2). +137 match packet.questions.as_slice() { +138 [question] +139 if &question.qname == expected_name +140 && question.qtype == QTYPE::TYPE(expected_type) +141 && question.qclass == QCLASS::CLASS(CLASS::IN) => {} +142 _ => return Err(e!(QueryError::Unexpected)), +143 } +144 match packet.rcode() { +145 RCODE::NoError => Ok(()), +146 RCODE::NameError => Err(e!(QueryError::NxDomain)), +147 rcode => Err(e!(QueryError::ServerFailure { +148 rcode: format!("{rcode:?}"), +149 })), +150 } +151} +152 +153/// Check whether a resource record's name matches the queried name or its +154/// CNAME-resolved canonical name. +155/// +156/// `qname` is `None` only for a response with no question section, which +157/// [`check_response`] already rejects, so the `None` arm is unreachable for +158/// validated responses and conservatively matches nothing. +159fn name_matches( +160 rr_name: &Name<'_>, +161 qname: Option<&Name<'_>>, +162 canonical: Option<&Name<'_>>, +163) -> bool { +164 match qname { +165 Some(q) => rr_name == q || canonical.is_some_and(|c| rr_name == c), +166 None => false, +167 } +168} +169 +170/// Extract matching records from a validated DNS response, following CNAME chains. +171/// +172/// The caller must already have validated the response with [`check_response`]; +173/// this resolves the CNAME chain anchored on the question and extracts records +174/// of the requested type using `extract`. Returns the records and the minimum +175/// TTL across them. +176fn parse_response<T>( +177 data: &[u8], +178 extract: impl Fn(&RData<'_>) -> Option<T>, +179) -> Result<(Vec<T>, u32), QueryError> { +180 let packet = +181 Packet::parse(data).map_err(|e| e!(QueryError::Malformed, AnyError::from_std(e)))?; +182 +183 let qname = packet.questions.first().map(|q| q.qname.clone()); +184 let canonical = qname.as_ref().map(|q| resolve_cname_chain(&packet, q)); +185 +186 let mut results = Vec::new(); +187 let mut min_ttl = u32::MAX; +188 for rr in &packet.answers { +189 if name_matches(&rr.name, qname.as_ref(), canonical.as_ref()) +190 && let Some(val) = extract(&rr.rdata) +191 { +192 results.push(val); +193 min_ttl = min_ttl.min(rr.ttl); +194 } +195 } +196 if min_ttl == u32::MAX { +197 min_ttl = 0; +198 } +199 Ok((results, min_ttl)) +200} +201 +202/// Parse A (IPv4) records from a DNS response, following CNAME chains. +203pub(super) fn parse_a_response(data: &[u8]) -> Result<(Vec<Ipv4Addr>, u32), QueryError> { +204 parse_response(data, |rdata| match rdata { +205 RData::A(A { address }) => Some(Ipv4Addr::from(*address)), +206 _ => None, +207 }) +208} +209 +210/// Parse AAAA (IPv6) records from a DNS response, following CNAME chains. +211pub(super) fn parse_aaaa_response(data: &[u8]) -> Result<(Vec<Ipv6Addr>, u32), QueryError> { +212 parse_response(data, |rdata| match rdata { +213 RData::AAAA(AAAA { address }) => Some(Ipv6Addr::from(*address)), +214 _ => None, +215 }) +216} +217 +218/// Parse TXT records from a DNS response, following CNAME chains. +219pub(super) fn parse_txt_response(data: &[u8]) -> Result<(Vec<TxtRecordData>, u32), QueryError> { +220 parse_response(data, |rdata| match rdata { +221 RData::TXT(txt) => Some(extract_txt_record_data(txt)), +222 _ => None, +223 }) +224} +225 +226/// Extract the raw content of a TXT record into `TxtRecordData`. +227/// +228/// Converts the TXT record's character strings into raw bytes. In iroh's +229/// DNS encoding, each TXT record typically contains a single character +230/// string (one `key=value` attribute), and each attribute is published as +231/// a separate TXT ResourceRecord. +232/// +233/// We use `String::try_from` which concatenates all character strings in +234/// the record into one byte sequence. This preserves the raw content +235/// without the destructive key=value parsing that `TXT::attributes()` does +236/// (which uses a HashMap and would lose ordering and deduplicate keys). +237fn extract_txt_record_data(txt: &simple_dns::rdata::TXT<'_>) -> TxtRecordData { +238 match String::try_from(txt.clone()) { +239 Ok(s) if !s.is_empty() => TxtRecordData::from(vec![s.into_bytes().into_boxed_slice()]), +240 _ => TxtRecordData::from(Vec::<Box<[u8]>>::new()), +241 } +242} +243 +244/// Returns true if the response has the TC (truncation) flag set. +245/// +246/// Reads only the header flags, so it works even on a truncated packet whose +247/// body fails to parse. A buffer too short to hold a header is treated as not +248/// truncated; it will fail to parse downstream. 249pub(super) fn is_truncated(data: &[u8]) -> bool { -250 // TC bit is bit 1 of the third byte in the DNS header (RFC 1035 Section 4.1.1). -251 data.len() >= 3 && (data[2] & 0x02) != 0 -252} -253 -254#[cfg(test)] -255mod tests { -256 use std::net::Ipv4Addr; -257 -258 use simple_dns::{ -259 CLASS, Name, Packet, PacketFlag, QCLASS, QTYPE, Question, ResourceRecord, -260 rdata::{A, CNAME, RData}, -261 }; -262 -263 use super::*; -264 -265 /// Build a query packet for `host` with type A, return (id, bytes). -266 fn make_query(host: &str) -> (u16, Vec<u8>) { -267 build_query(host, TYPE::A).unwrap() -268 } -269 -270 /// Build a response with A records for `name`. -271 fn a_response(id: u16, name: &str, addrs: &[Ipv4Addr]) -> Vec<u8> { -272 let mut packet = Packet::new_reply(id); -273 packet.set_flags(PacketFlag::RECURSION_DESIRED | PacketFlag::RECURSION_AVAILABLE); -274 // Echo the question back (needed for CNAME resolution in parse functions). -275 packet.questions.push(Question::new( -276 Name::new_unchecked(name), -277 QTYPE::TYPE(TYPE::A), -278 QCLASS::CLASS(CLASS::IN), -279 false, -280 )); -281 for addr in addrs { -282 packet.answers.push(ResourceRecord::new( -283 Name::new_unchecked(name), -284 CLASS::IN, -285 300, -286 RData::A(A { -287 address: u32::from(*addr), -288 }), -289 )); -290 } -291 packet.build_bytes_vec().unwrap() -292 } -293 -294 /// Build a response containing a CNAME from `alias` -> `canonical`, plus -295 /// A records under the canonical name (the common "both in one response" case). -296 fn cname_with_a_response(id: u16, alias: &str, canonical: &str, addrs: &[Ipv4Addr]) -> Vec<u8> { -297 let mut packet = Packet::new_reply(id); -298 packet.set_flags(PacketFlag::RECURSION_DESIRED | PacketFlag::RECURSION_AVAILABLE); -299 packet.questions.push(Question::new( -300 Name::new_unchecked(alias), -301 QTYPE::TYPE(TYPE::A), -302 QCLASS::CLASS(CLASS::IN), -303 false, -304 )); -305 // CNAME record -306 packet.answers.push(ResourceRecord::new( -307 Name::new_unchecked(alias), -308 CLASS::IN, -309 300, -310 RData::CNAME(CNAME(Name::new_unchecked(canonical))), -311 )); -312 // A records for the canonical name -313 for addr in addrs { -314 packet.answers.push(ResourceRecord::new( -315 Name::new_unchecked(canonical), -316 CLASS::IN, -317 300, -318 RData::A(A { -319 address: u32::from(*addr), -320 }), -321 )); -322 } -323 packet.build_bytes_vec().unwrap() -324 } -325 -326 /// Build a response containing only a CNAME (no final A record). -327 fn cname_only_response(id: u16, alias: &str, canonical: &str) -> Vec<u8> { -328 let mut packet = Packet::new_reply(id); -329 packet.set_flags(PacketFlag::RECURSION_DESIRED | PacketFlag::RECURSION_AVAILABLE); -330 packet.questions.push(Question::new( -331 Name::new_unchecked(alias), -332 QTYPE::TYPE(TYPE::A), -333 QCLASS::CLASS(CLASS::IN), -334 false, -335 )); -336 packet.answers.push(ResourceRecord::new( -337 Name::new_unchecked(alias), -338 CLASS::IN, -339 300, -340 RData::CNAME(CNAME(Name::new_unchecked(canonical))), -341 )); -342 packet.build_bytes_vec().unwrap() -343 } -344 -345 #[test] -346 fn build_query_includes_edns_opt() { -347 let (_, bytes) = build_query("example.com", TYPE::A).unwrap(); -348 let packet = Packet::parse(&bytes).unwrap(); -349 let opt = packet.opt().expect("query should include OPT record"); -350 assert_eq!(opt.udp_packet_size, 1232); -351 assert_eq!(opt.version, 0); -352 } -353 -354 #[test] -355 fn parse_a_no_cname() { -356 let (id, _) = make_query("example.com"); -357 let resp = a_response(id, "example.com", &[Ipv4Addr::new(1, 2, 3, 4)]); -358 let (addrs, ttl) = parse_a_response(&resp).unwrap(); -359 assert_eq!(addrs, [Ipv4Addr::new(1, 2, 3, 4)]); -360 assert_eq!(ttl, 300); -361 } -362 -363 #[test] -364 fn parse_a_with_cname_in_response() { -365 let (id, _) = make_query("alias.example.com"); -366 let resp = cname_with_a_response( -367 id, -368 "alias.example.com", -369 "real.example.com", -370 &[Ipv4Addr::new(10, 0, 0, 1), Ipv4Addr::new(10, 0, 0, 2)], -371 ); -372 let (addrs, _) = parse_a_response(&resp).unwrap(); -373 assert_eq!( -374 addrs, -375 [Ipv4Addr::new(10, 0, 0, 1), Ipv4Addr::new(10, 0, 0, 2)] -376 ); -377 } -378 -379 #[test] -380 fn parse_a_with_chained_cname() { -381 // alias -> middle -> real, A records on real -382 let (id, _) = make_query("alias.example.com"); -383 let mut packet = Packet::new_reply(id); -384 packet.set_flags(PacketFlag::RECURSION_DESIRED | PacketFlag::RECURSION_AVAILABLE); -385 packet.questions.push(Question::new( -386 Name::new_unchecked("alias.example.com"), -387 QTYPE::TYPE(TYPE::A), -388 QCLASS::CLASS(CLASS::IN), -389 false, -390 )); -391 packet.answers.push(ResourceRecord::new( -392 Name::new_unchecked("alias.example.com"), -393 CLASS::IN, -394 300, -395 RData::CNAME(CNAME(Name::new_unchecked("middle.example.com"))), -396 )); -397 packet.answers.push(ResourceRecord::new( -398 Name::new_unchecked("middle.example.com"), -399 CLASS::IN, -400 300, -401 RData::CNAME(CNAME(Name::new_unchecked("real.example.com"))), -402 )); -403 packet.answers.push(ResourceRecord::new( -404 Name::new_unchecked("real.example.com"), -405 CLASS::IN, -406 300, -407 RData::A(A { -408 address: u32::from(Ipv4Addr::new(5, 6, 7, 8)), -409 }), -410 )); -411 let resp = packet.build_bytes_vec().unwrap(); -412 let (addrs, _) = parse_a_response(&resp).unwrap(); -413 assert_eq!(addrs, [Ipv4Addr::new(5, 6, 7, 8)]); -414 } -415 -416 #[test] -417 fn cname_target_extracts_target_for_recursive_follow() { -418 let id = 1234; -419 let resp = cname_only_response(id, "alias.example.com", "real.example.com"); -420 let packet = Packet::parse(&resp).unwrap(); -421 let target = cname_target(&packet, "alias.example.com"); -422 assert_eq!(target.as_deref(), Some("real.example.com")); -423 } -424 -425 /// Builds a reply packet echoing one question for `name`/`qtype`, plus an A -426 /// answer, so `check_response` has something to validate. -427 fn reply_with_question(id: u16, name: &str, qtype: TYPE) -> Packet<'static> { -428 let mut packet = Packet::new_reply(id); -429 packet.set_flags(PacketFlag::RECURSION_DESIRED | PacketFlag::RECURSION_AVAILABLE); -430 packet.questions.push(Question::new( -431 Name::new_unchecked(name).into_owned(), -432 QTYPE::TYPE(qtype), -433 QCLASS::CLASS(CLASS::IN), -434 false, -435 )); -436 packet -437 } -438 -439 #[test] -440 fn check_response_accepts_a_matching_reply() { -441 let name = Name::new_unchecked("example.com"); -442 let packet = reply_with_question(42, "example.com", TYPE::A); -443 assert!(check_response(&packet, 42, &name, TYPE::A).is_ok()); -444 } -445 -446 #[test] -447 fn check_response_rejects_mismatches() { -448 let name = Name::new_unchecked("example.com"); -449 -450 // Wrong transaction id. -451 let packet = reply_with_question(42, "example.com", TYPE::A); -452 assert!(matches!( -453 check_response(&packet, 7, &name, TYPE::A), -454 Err(QueryError::Unexpected { .. }) -455 )); -456 -457 // Question name does not echo the query. -458 let packet = reply_with_question(42, "attacker.example", TYPE::A); -459 assert!(matches!( -460 check_response(&packet, 42, &name, TYPE::A), -461 Err(QueryError::Unexpected { .. }) -462 )); -463 -464 // Question type does not match. -465 let packet = reply_with_question(42, "example.com", TYPE::AAAA); -466 assert!(matches!( -467 check_response(&packet, 42, &name, TYPE::A), -468 Err(QueryError::Unexpected { .. }) -469 )); -470 -471 // No question section at all. -472 let mut packet = reply_with_question(42, "example.com", TYPE::A); -473 packet.questions.clear(); -474 assert!(matches!( -475 check_response(&packet, 42, &name, TYPE::A), -476 Err(QueryError::Unexpected { .. }) -477 )); -478 } -479 -480 #[test] -481 fn cname_target_returns_none_when_no_cname() { -482 let id = 1234; -483 let resp = a_response(id, "example.com", &[Ipv4Addr::new(1, 2, 3, 4)]); -484 let packet = Packet::parse(&resp).unwrap(); -485 let target = cname_target(&packet, "example.com"); -486 assert_eq!(target, None); -487 } -488} \ No newline at end of file +250 header_buffer::has_flags(data, PacketFlag::TRUNCATION).unwrap_or(false) +251} +252 +253#[cfg(test)] +254mod tests { +255 use std::net::Ipv4Addr; +256 +257 use simple_dns::{ +258 CLASS, Name, Packet, PacketFlag, QCLASS, QTYPE, Question, ResourceRecord, +259 rdata::{A, CNAME, RData}, +260 }; +261 +262 use super::*; +263 +264 /// Build a query packet for `host` with type A, return (id, bytes). +265 fn make_query(host: &str) -> (u16, Vec<u8>) { +266 build_query(host, TYPE::A).unwrap() +267 } +268 +269 /// Build a response with A records for `name`. +270 fn a_response(id: u16, name: &str, addrs: &[Ipv4Addr]) -> Vec<u8> { +271 let mut packet = Packet::new_reply(id); +272 packet.set_flags(PacketFlag::RECURSION_DESIRED | PacketFlag::RECURSION_AVAILABLE); +273 // Echo the question back (needed for CNAME resolution in parse functions). +274 packet.questions.push(Question::new( +275 Name::new_unchecked(name), +276 QTYPE::TYPE(TYPE::A), +277 QCLASS::CLASS(CLASS::IN), +278 false, +279 )); +280 for addr in addrs { +281 packet.answers.push(ResourceRecord::new( +282 Name::new_unchecked(name), +283 CLASS::IN, +284 300, +285 RData::A(A { +286 address: u32::from(*addr), +287 }), +288 )); +289 } +290 packet.build_bytes_vec().unwrap() +291 } +292 +293 /// Build a response containing a CNAME from `alias` -> `canonical`, plus +294 /// A records under the canonical name (the common "both in one response" case). +295 fn cname_with_a_response(id: u16, alias: &str, canonical: &str, addrs: &[Ipv4Addr]) -> Vec<u8> { +296 let mut packet = Packet::new_reply(id); +297 packet.set_flags(PacketFlag::RECURSION_DESIRED | PacketFlag::RECURSION_AVAILABLE); +298 packet.questions.push(Question::new( +299 Name::new_unchecked(alias), +300 QTYPE::TYPE(TYPE::A), +301 QCLASS::CLASS(CLASS::IN), +302 false, +303 )); +304 // CNAME record +305 packet.answers.push(ResourceRecord::new( +306 Name::new_unchecked(alias), +307 CLASS::IN, +308 300, +309 RData::CNAME(CNAME(Name::new_unchecked(canonical))), +310 )); +311 // A records for the canonical name +312 for addr in addrs { +313 packet.answers.push(ResourceRecord::new( +314 Name::new_unchecked(canonical), +315 CLASS::IN, +316 300, +317 RData::A(A { +318 address: u32::from(*addr), +319 }), +320 )); +321 } +322 packet.build_bytes_vec().unwrap() +323 } +324 +325 /// Build a response containing only a CNAME (no final A record). +326 fn cname_only_response(id: u16, alias: &str, canonical: &str) -> Vec<u8> { +327 let mut packet = Packet::new_reply(id); +328 packet.set_flags(PacketFlag::RECURSION_DESIRED | PacketFlag::RECURSION_AVAILABLE); +329 packet.questions.push(Question::new( +330 Name::new_unchecked(alias), +331 QTYPE::TYPE(TYPE::A), +332 QCLASS::CLASS(CLASS::IN), +333 false, +334 )); +335 packet.answers.push(ResourceRecord::new( +336 Name::new_unchecked(alias), +337 CLASS::IN, +338 300, +339 RData::CNAME(CNAME(Name::new_unchecked(canonical))), +340 )); +341 packet.build_bytes_vec().unwrap() +342 } +343 +344 #[test] +345 fn build_query_includes_edns_opt() { +346 let (_, bytes) = build_query("example.com", TYPE::A).unwrap(); +347 let packet = Packet::parse(&bytes).unwrap(); +348 let opt = packet.opt().expect("query should include OPT record"); +349 assert_eq!(opt.udp_packet_size, 1232); +350 assert_eq!(opt.version, 0); +351 } +352 +353 #[test] +354 fn parse_a_no_cname() { +355 let (id, _) = make_query("example.com"); +356 let resp = a_response(id, "example.com", &[Ipv4Addr::new(1, 2, 3, 4)]); +357 let (addrs, ttl) = parse_a_response(&resp).unwrap(); +358 assert_eq!(addrs, [Ipv4Addr::new(1, 2, 3, 4)]); +359 assert_eq!(ttl, 300); +360 } +361 +362 #[test] +363 fn parse_a_with_cname_in_response() { +364 let (id, _) = make_query("alias.example.com"); +365 let resp = cname_with_a_response( +366 id, +367 "alias.example.com", +368 "real.example.com", +369 &[Ipv4Addr::new(10, 0, 0, 1), Ipv4Addr::new(10, 0, 0, 2)], +370 ); +371 let (addrs, _) = parse_a_response(&resp).unwrap(); +372 assert_eq!( +373 addrs, +374 [Ipv4Addr::new(10, 0, 0, 1), Ipv4Addr::new(10, 0, 0, 2)] +375 ); +376 } +377 +378 #[test] +379 fn parse_a_with_chained_cname() { +380 // alias -> middle -> real, A records on real +381 let (id, _) = make_query("alias.example.com"); +382 let mut packet = Packet::new_reply(id); +383 packet.set_flags(PacketFlag::RECURSION_DESIRED | PacketFlag::RECURSION_AVAILABLE); +384 packet.questions.push(Question::new( +385 Name::new_unchecked("alias.example.com"), +386 QTYPE::TYPE(TYPE::A), +387 QCLASS::CLASS(CLASS::IN), +388 false, +389 )); +390 packet.answers.push(ResourceRecord::new( +391 Name::new_unchecked("alias.example.com"), +392 CLASS::IN, +393 300, +394 RData::CNAME(CNAME(Name::new_unchecked("middle.example.com"))), +395 )); +396 packet.answers.push(ResourceRecord::new( +397 Name::new_unchecked("middle.example.com"), +398 CLASS::IN, +399 300, +400 RData::CNAME(CNAME(Name::new_unchecked("real.example.com"))), +401 )); +402 packet.answers.push(ResourceRecord::new( +403 Name::new_unchecked("real.example.com"), +404 CLASS::IN, +405 300, +406 RData::A(A { +407 address: u32::from(Ipv4Addr::new(5, 6, 7, 8)), +408 }), +409 )); +410 let resp = packet.build_bytes_vec().unwrap(); +411 let (addrs, _) = parse_a_response(&resp).unwrap(); +412 assert_eq!(addrs, [Ipv4Addr::new(5, 6, 7, 8)]); +413 } +414 +415 #[test] +416 fn cname_target_extracts_target_for_recursive_follow() { +417 let id = 1234; +418 let resp = cname_only_response(id, "alias.example.com", "real.example.com"); +419 let packet = Packet::parse(&resp).unwrap(); +420 let target = cname_target(&packet, "alias.example.com"); +421 assert_eq!(target.as_deref(), Some("real.example.com")); +422 } +423 +424 /// Builds a reply packet echoing one question for `name`/`qtype`, plus an A +425 /// answer, so `check_response` has something to validate. +426 fn reply_with_question(id: u16, name: &str, qtype: TYPE) -> Packet<'static> { +427 let mut packet = Packet::new_reply(id); +428 packet.set_flags(PacketFlag::RECURSION_DESIRED | PacketFlag::RECURSION_AVAILABLE); +429 packet.questions.push(Question::new( +430 Name::new_unchecked(name).into_owned(), +431 QTYPE::TYPE(qtype), +432 QCLASS::CLASS(CLASS::IN), +433 false, +434 )); +435 packet +436 } +437 +438 #[test] +439 fn check_response_accepts_a_matching_reply() { +440 let name = Name::new_unchecked("example.com"); +441 let packet = reply_with_question(42, "example.com", TYPE::A); +442 assert!(check_response(&packet, 42, &name, TYPE::A).is_ok()); +443 } +444 +445 #[test] +446 fn check_response_rejects_mismatches() { +447 let name = Name::new_unchecked("example.com"); +448 +449 // Wrong transaction id. +450 let packet = reply_with_question(42, "example.com", TYPE::A); +451 assert!(matches!( +452 check_response(&packet, 7, &name, TYPE::A), +453 Err(QueryError::Unexpected { .. }) +454 )); +455 +456 // Question name does not echo the query. +457 let packet = reply_with_question(42, "attacker.example", TYPE::A); +458 assert!(matches!( +459 check_response(&packet, 42, &name, TYPE::A), +460 Err(QueryError::Unexpected { .. }) +461 )); +462 +463 // Question type does not match. +464 let packet = reply_with_question(42, "example.com", TYPE::AAAA); +465 assert!(matches!( +466 check_response(&packet, 42, &name, TYPE::A), +467 Err(QueryError::Unexpected { .. }) +468 )); +469 +470 // No question section at all. +471 let mut packet = reply_with_question(42, "example.com", TYPE::A); +472 packet.questions.clear(); +473 assert!(matches!( +474 check_response(&packet, 42, &name, TYPE::A), +475 Err(QueryError::Unexpected { .. }) +476 )); +477 } +478 +479 #[test] +480 fn cname_target_returns_none_when_no_cname() { +481 let id = 1234; +482 let resp = a_response(id, "example.com", &[Ipv4Addr::new(1, 2, 3, 4)]); +483 let packet = Packet::parse(&resp).unwrap(); +484 let target = cname_target(&packet, "example.com"); +485 assert_eq!(target, None); +486 } +487} \ No newline at end of file