Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 14 additions & 14 deletions src/resolver.rs
Original file line number Diff line number Diff line change
Expand Up @@ -289,19 +289,17 @@ fn is_localhost(host: &str) -> bool {
/// Returns `name` without the trailing dot that marks it absolute, if it has one.
///
/// The dot in `foo\.` is escaped and belongs to the last label.
fn strip_root_dot(name: &str) -> Option<&str> {
pub(crate) fn strip_root_dot(name: &str) -> Option<&str> {
let stripped = name.strip_suffix('.')?;
let backslashes = stripped.bytes().rev().take_while(|&b| b == b'\\').count();
(backslashes % 2 == 0).then_some(stripped)
}

/// Returns the key the cache and the hosts file store `name` under.
/// Returns `name` lowercased, borrowed if it has no uppercase letter.
///
/// The key is lowercase without the root dot, so `Example.COM.` and
/// `example.com` share one. A name already in that form is borrowed, as almost
/// every query name is.
pub(crate) fn name_key(name: &str) -> Cow<'_, str> {
let name = strip_root_dot(name).unwrap_or(name);
/// DNS names are case-insensitive. Almost every query name is lowercase
/// already, so this rarely copies.
pub(crate) fn lowercase(name: &str) -> Cow<'_, str> {
match name.bytes().any(|byte| byte.is_ascii_uppercase()) {
true => Cow::Owned(name.to_ascii_lowercase()),
false => Cow::Borrowed(name),
Expand Down Expand Up @@ -1189,8 +1187,8 @@ impl DnsResolver {
let mut saw_transient = false;
let names = self.search_names(&name);
let total = names.len();
for (i, name) in names.into_iter().enumerate() {
trace!(%name, ?kind, "resolving");
for (i, candidate) in names.into_iter().enumerate() {
trace!(%candidate, ?kind, "resolving");
let read_answer = |packet: &Packet<'_>| {
let parsed = query::parse_records(packet, kind).map_err(Error::from);
// RFC 2308 TTL of a NODATA answer. An NXDOMAIN comes back from
Expand All @@ -1202,7 +1200,7 @@ impl DnsResolver {
(parsed, soa)
};
let (res, soa_negative_ttl) = match self
.send_query_following_cnames(name.clone(), kind.dns_type(), read_answer)
.send_query_following_cnames(candidate.clone(), kind.dns_type(), read_answer)
.await
{
Ok(answer) => answer,
Expand All @@ -1211,7 +1209,9 @@ impl DnsResolver {
match res {
Ok((results, ttl)) if !results.is_empty() => {
let ttl = ttl.max(self.cache_min_ttl_secs());
debug!(%name, ?kind, ?results, ttl, "resolved");
debug!(%candidate, ?kind, ?results, ttl, "resolved");
// Under the caller's name, which the next lookup probes, as
// the negative answers below are.
self.cache
.insert(&name, kind, CachedResult::Positive(results.clone()), ttl);
return Ok(results);
Expand All @@ -1226,7 +1226,7 @@ impl DnsResolver {
}
Err(e @ Error::NxDomain { .. }) => {
let remaining = total - i - 1;
trace!(%name, ?kind, remaining, reason = %e, "lookup failed");
trace!(%candidate, ?kind, remaining, reason = %e, "lookup failed");
if first_negative.is_none() {
first_negative = Some(CachedResult::NxDomain);
negative_ttl_secs = self.negative_cache_ttl_secs(soa_negative_ttl);
Expand All @@ -1245,7 +1245,7 @@ impl DnsResolver {
| Error::InvalidResponse { .. }),
) => {
let remaining = total - i - 1;
trace!(%name, ?kind, remaining, reason = %e, "lookup failed");
trace!(%candidate, ?kind, remaining, reason = %e, "lookup failed");
saw_transient = true;
last_err = Some(e);
}
Expand All @@ -1254,7 +1254,7 @@ impl DnsResolver {
// candidate identically, so there is nothing to gain by trying
// the rest.
Err(e) => {
debug!(%name, ?kind, reason = %e, "lookup failed");
debug!(%candidate, ?kind, reason = %e, "lookup failed");
return Err(e);
}
}
Expand Down
31 changes: 20 additions & 11 deletions src/resolver/cache.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use std::{
use lru::LruCache;
use n0_future::time::Instant;

use super::name_key;
use super::lowercase;
use crate::{Record, RecordKind};

/// Maximum number of entries in the DNS cache.
Expand Down Expand Up @@ -92,8 +92,10 @@ impl CachedResult {
/// The hasher has random keys per cache, so its collisions cannot be computed
/// in advance.
///
/// `host` is expected to be in [`name_key`] form, so that names differing only
/// in case or a trailing dot hash to the same key.
/// `host` is expected to be [`lowercase`], so that names differing only in case
/// hash to the same key. The root dot stays in the key. The search list expands
/// the relative `foo` but not the absolute `foo.`, so the two can resolve to
/// different nodes.
///
/// A pre-hashed `u64` key is used rather than a `Hash`-deriving key struct on
/// purpose: the latter would allocate a `String` for the key on every `get`,
Expand All @@ -105,7 +107,7 @@ fn cache_key(hasher: &RandomState, host: &str, kind: RecordKind) -> u64 {
/// A cache entry with TTL expiry tracking.
#[derive(Debug, Clone)]
struct CacheEntry {
/// The host this entry is for, in [`name_key`] form.
/// The host this entry is for, lowercased.
///
/// Verified against the query on lookup, together with `kind`, so that a
/// `u64` key collision returns a miss rather than another entry's records.
Expand Down Expand Up @@ -213,7 +215,7 @@ impl DnsCache {
/// can still serve it as a last resort; it is overwritten on the next
/// successful insert or evicted by LRU pressure.
pub(super) fn get(&self, host: &str, kind: RecordKind) -> Option<CachedResult> {
let host = name_key(host);
let host = lowercase(host);
let key = cache_key(&self.hasher, &host, kind);
let mut inner = self.inner.lock().expect("poisoned");
let entry = inner.entries.get(&key)?;
Expand All @@ -239,7 +241,7 @@ impl DnsCache {
kind: RecordKind,
max_stale: Duration,
) -> Option<Vec<Record>> {
let host = name_key(host);
let host = lowercase(host);
let key = cache_key(&self.hasher, &host, kind);
let mut inner = self.inner.lock().expect("poisoned");
let entry = inner.entries.get(&key)?;
Expand Down Expand Up @@ -269,7 +271,7 @@ impl DnsCache {
if ttl == 0 {
return;
}
let host = name_key(host);
let host = lowercase(host);
let bytes = result.approx_bytes();
let key = cache_key(&self.hasher, &host, kind);
let mut inner = self.inner.lock().expect("poisoned");
Expand Down Expand Up @@ -306,7 +308,7 @@ impl DnsCache {
ttl: Duration,
expired_ago: Duration,
) {
let host = name_key(host);
let host = lowercase(host);
let entry = CacheEntry {
host: host.to_string(),
kind,
Expand All @@ -324,7 +326,7 @@ impl DnsCache {
/// Returns the stored TTL for `host`/`kind`, for tests that assert clamping.
#[cfg(test)]
fn stored_ttl(&self, host: &str, kind: RecordKind) -> Option<Duration> {
let host = name_key(host);
let host = lowercase(host);
let mut inner = self.inner.lock().expect("poisoned");
inner
.entries
Expand Down Expand Up @@ -405,10 +407,17 @@ mod tests {
}

#[test]
fn lookup_is_case_and_trailing_dot_insensitive() {
fn lookup_is_case_insensitive() {
let cache = DnsCache::new();
cache.insert("example.com", RecordKind::A, positive(), 300);
assert_single_a(cache.get("Example.COM.", RecordKind::A), ADDR);
assert_single_a(cache.get("Example.COM", RecordKind::A), ADDR);
}

#[test]
fn trailing_dot_keeps_a_separate_entry() {
let cache = DnsCache::new();
cache.insert("example.com", RecordKind::A, positive(), 300);
assert!(cache.get("example.com.", RecordKind::A).is_none());
}

#[test]
Expand Down
17 changes: 13 additions & 4 deletions src/system_config/hosts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,15 @@
//! way the old hickory-backed resolver did via its `use_hosts_file` default.

use std::{
borrow::Cow,
collections::HashMap,
net::{IpAddr, Ipv4Addr, Ipv6Addr},
};

use rustc_hash::FxBuildHasher;
use tracing::warn;

use crate::resolver::name_key;
use crate::resolver::{lowercase, strip_root_dot};

/// A hosts-file map, keyed by name.
///
Expand Down Expand Up @@ -126,7 +127,7 @@ impl Hosts {
continue;
};
for name in fields {
let key = name_key(name).into_owned().into_boxed_str();
let key = Self::key(name).into_owned().into_boxed_str();
match addr {
IpAddr::V4(ip) => a.entry(key).or_default().push(ip),
IpAddr::V6(ip) => aaaa.entry(key).or_default().push(ip),
Expand All @@ -136,14 +137,22 @@ impl Hosts {
Self { a, aaaa }
}

/// Returns the key the hosts file stores `name` under.
///
/// The key is lowercase without the root dot, so `Example.COM.` and
/// `example.com` share one.
fn key(name: &str) -> Cow<'_, str> {
lowercase(strip_root_dot(name).unwrap_or(name))
}

/// Returns the mapped IPv4 addresses for `name`, if any.
pub(crate) fn lookup_ipv4(&self, name: &str) -> Option<Vec<Ipv4Addr>> {
self.a.get(name_key(name).as_ref())?.to_vec()
self.a.get(Self::key(name).as_ref())?.to_vec()
}

/// Returns the mapped IPv6 addresses for `name`, if any.
pub(crate) fn lookup_ipv6(&self, name: &str) -> Option<Vec<Ipv6Addr>> {
self.aaaa.get(name_key(name).as_ref())?.to_vec()
self.aaaa.get(Self::key(name).as_ref())?.to_vec()
}

/// Builds a hosts map directly from file content, for tests.
Expand Down
89 changes: 89 additions & 0 deletions src/tests/resolver.rs
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,95 @@ async fn search_list_expansion_reaches_bare_name() {
assert_eq!(addrs, [Ipv4Addr::new(10, 1, 1, 1)]);
}

/// An answer for an absolute name does not answer the relative name.
///
/// The absolute `foo.` resolves first and fills the cache. The relative `foo`
/// must still try its search domain, which resolves to another address.
#[tokio::test]
async fn absolute_answer_does_not_answer_relative_lookup() {
let server = spawn_mock(|query| {
let name = qname(query)?;
let answers = match name.as_str() {
"foo" => vec![a("foo", Ipv4Addr::new(10, 0, 0, 1))],
"foo.corp.example" => vec![a("foo.corp.example", Ipv4Addr::new(10, 0, 0, 2))],
_ => return Some(reply(query, RCODE::NameError, vec![])),
};
Some(reply(query, RCODE::NoError, answers))
})
.await;

let mut resolver = resolver_for(server.addr());
resolver.set_search(vec!["corp.example".to_string()], 1);

let absolute = resolver.lookup_ipv4("foo.").await.expect("foo. resolves");
assert_eq!(absolute, [Ipv4Addr::new(10, 0, 0, 1)]);
let relative = resolver.lookup_ipv4("foo").await.expect("foo resolves");
assert_eq!(
relative,
[Ipv4Addr::new(10, 0, 0, 2)],
"the relative name must resolve via the search domain, not the cached foo."
);
}

/// A relative name answered through a search domain hits the cache next time.
///
/// The answer is cached under the name the caller asked for, not under the
/// expanded `foo.corp.example` that the lookup probes never use.
#[tokio::test]
async fn search_domain_answer_is_cached_for_the_relative_name() {
let server = spawn_mock(|query| {
let answers = match qname(query)?.as_str() {
"foo.corp.example" => vec![a("foo.corp.example", Ipv4Addr::new(10, 0, 0, 2))],
_ => return Some(reply(query, RCODE::NameError, vec![])),
};
Some(reply(query, RCODE::NoError, answers))
})
.await;

let mut resolver = resolver_for(server.addr());
resolver.set_search(vec!["corp.example".to_string()], 1);

for _ in 0..2 {
let addrs = resolver.lookup_ipv4("foo").await.expect("foo resolves");
assert_eq!(addrs, [Ipv4Addr::new(10, 0, 0, 2)]);
}
assert_eq!(
server.query_count(),
1,
"the second lookup should hit the cache"
);
}

/// A search-domain answer for a relative name does not answer the absolute name.
///
/// The search domain holds `foo` with no A records (NODATA), and the absolute
/// `foo.` does not exist. The cached NODATA for `foo` must not answer `foo.`.
#[tokio::test]
async fn relative_answer_does_not_answer_absolute_lookup() {
let server = spawn_mock(|query| {
let rcode = match qname(query)?.as_str() {
"foo.corp.example" => RCODE::NoError,
_ => RCODE::NameError,
};
Some(reply(query, rcode, vec![]))
})
.await;

let mut resolver = DnsResolver::builder()
.negative_max_ttl(Duration::from_secs(30))
.nameserver(Nameserver::new(server.addr(), DnsProtocol::Udp))
.build();
resolver.set_search(vec!["corp.example".to_string()], 1);

let relative = resolver.lookup_record("foo", RecordKind::A).await;
assert!(matches!(relative, Ok(ref records) if records.is_empty()));
let absolute = resolver.lookup_record("foo.", RecordKind::A).await;
assert!(
matches!(absolute, Err(crate::Error::NxDomain { .. })),
"foo. must not be answered with the search domain's NODATA, got {absolute:?}",
);
}

/// A bare name's NXDOMAIN wins over an appended candidate's NODATA.
///
/// The first authoritative negative in search order is the answer, so an
Expand Down