use std::time::Duration;
use hickory_resolver::config::{ResolverConfig, ResolverOpts};
use hickory_resolver::Resolver;
use super::cache::{DnsCache, SharedDnsCache};
use super::{DnsConfig, RecordType};
use crate::{NetworkError, Result};
#[derive(Debug, Clone)]
pub struct DnsResolver {
config: DnsConfig,
cache: Option<SharedDnsCache>,
timeout: Duration,
attempts: u32,
}
impl Default for DnsResolver {
fn default() -> Self {
Self::new()
}
}
impl DnsResolver {
#[must_use]
pub fn new() -> Self {
Self {
config: DnsConfig::default(),
cache: None,
timeout: Duration::from_secs(5),
attempts: 3,
}
}
#[must_use]
pub fn builder() -> DnsResolverBuilder {
DnsResolverBuilder::new()
}
pub fn system() -> Result<Self> {
let config = DnsConfig::get()?;
Ok(Self {
config,
cache: None,
timeout: Duration::from_secs(5),
attempts: 3,
})
}
#[must_use]
pub fn nameservers(&self) -> &[std::net::IpAddr] {
&self.config.nameservers
}
#[must_use]
pub fn search_domains(&self) -> &[String] {
&self.config.search_domains
}
pub fn lookup(&self, name: &str, record_type: RecordType) -> Result<Vec<String>> {
if let Some(cache) = &self.cache {
if let Some(value) = cache.get(name, record_type) {
return Ok(vec![value]);
}
}
let records = Self::do_lookup(name, record_type)?;
if let Some(cache) = &self.cache {
for record in &records {
cache.add(name, record_type, record.clone(), Duration::from_secs(300));
}
}
Ok(records)
}
pub fn get_cache_ttl(&self, name: &str, record_type: RecordType) -> Result<Option<Duration>> {
Ok(self
.cache
.as_ref()
.and_then(|cache| cache.get_ttl(name, record_type)))
}
pub fn refresh_cache(&self, name: &str, record_type: RecordType) -> Result<()> {
if let Some(cache) = &self.cache {
cache.remove(name, record_type);
let _ = self.lookup(name, record_type)?;
}
Ok(())
}
fn do_lookup(name: &str, record_type: RecordType) -> Result<Vec<String>> {
let resolver = Resolver::new(ResolverConfig::default(), ResolverOpts::default())
.map_err(|e| NetworkError::Dns(format!("Failed to create resolver: {e}")))?;
match record_type {
RecordType::A => {
let response = resolver
.ipv4_lookup(name)
.map_err(|e| NetworkError::Dns(format!("A lookup failed: {e}")))?;
Ok(response
.iter()
.map(std::string::ToString::to_string)
.collect())
}
RecordType::AAAA => {
let response = resolver
.ipv6_lookup(name)
.map_err(|e| NetworkError::Dns(format!("AAAA lookup failed: {e}")))?;
Ok(response
.iter()
.map(std::string::ToString::to_string)
.collect())
}
RecordType::MX => {
let response = resolver
.mx_lookup(name)
.map_err(|e| NetworkError::Dns(format!("MX lookup failed: {e}")))?;
Ok(response
.iter()
.map(|mx| format!("{} {}", mx.preference(), mx.exchange()))
.collect())
}
RecordType::TXT => {
let response = resolver
.txt_lookup(name)
.map_err(|e| NetworkError::Dns(format!("TXT lookup failed: {e}")))?;
Ok(response
.iter()
.map(std::string::ToString::to_string)
.collect())
}
RecordType::CNAME
| RecordType::NS
| RecordType::PTR
| RecordType::SRV
| RecordType::SOA => Err(NetworkError::NotImplemented(format!(
"DNS record type {record_type} not yet supported"
))
.into()),
}
}
}
pub struct DnsResolverBuilder {
resolver: DnsResolver,
}
impl DnsResolverBuilder {
#[must_use]
pub fn new() -> Self {
Self {
resolver: DnsResolver::new(),
}
}
#[must_use]
pub fn cache(mut self, _cache: DnsCache) -> Self {
self.resolver.cache = Some(SharedDnsCache::new());
self
}
#[must_use]
pub const fn timeout(mut self, timeout: Duration) -> Self {
self.resolver.timeout = timeout;
self
}
#[must_use]
pub const fn attempts(mut self, attempts: u32) -> Self {
self.resolver.attempts = attempts;
self
}
pub fn build(self) -> Result<DnsResolver> {
Ok(self.resolver)
}
}
impl Default for DnsResolverBuilder {
fn default() -> Self {
Self::new()
}
}