Skip to main content

rustnet_core/network/
dns.rs

1//! DNS resolver with background async resolution and caching.
2//!
3//! Provides non-blocking reverse DNS lookups with an LRU cache to avoid
4//! repeated lookups for the same IP address.
5
6use crossbeam::channel::{self, Receiver, Sender};
7use dashmap::DashMap;
8use dns_lookup::lookup_addr;
9use log::debug;
10use std::net::IpAddr;
11use std::sync::Arc;
12use std::sync::atomic::{AtomicBool, Ordering};
13use std::thread;
14use std::time::{Duration, Instant};
15
16/// Resolution state for a cached entry
17#[derive(Debug, Clone, PartialEq)]
18pub enum ResolutionState {
19    /// Resolution is in progress
20    Pending,
21    /// Resolution succeeded
22    Resolved,
23    /// Resolution failed
24    Failed,
25}
26
27/// Cached hostname entry
28#[derive(Debug, Clone)]
29pub struct CachedHostname {
30    /// The resolved hostname, if successful
31    pub hostname: Option<String>,
32    /// When this entry was resolved
33    pub resolved_at: Instant,
34    /// Current resolution state
35    pub state: ResolutionState,
36}
37
38impl CachedHostname {
39    fn pending() -> Self {
40        Self {
41            hostname: None,
42            resolved_at: Instant::now(),
43            state: ResolutionState::Pending,
44        }
45    }
46
47    fn resolved(hostname: String) -> Self {
48        Self {
49            hostname: Some(hostname),
50            resolved_at: Instant::now(),
51            state: ResolutionState::Resolved,
52        }
53    }
54
55    fn failed() -> Self {
56        Self {
57            hostname: None,
58            resolved_at: Instant::now(),
59            state: ResolutionState::Failed,
60        }
61    }
62}
63
64/// Configuration for DNS resolver
65#[derive(Debug, Clone)]
66pub struct DnsResolverConfig {
67    /// Cache TTL for resolved hostnames (default: 5 minutes)
68    pub cache_ttl: Duration,
69    /// Cache TTL for failed lookups (default: 1 minute)
70    pub negative_cache_ttl: Duration,
71    /// Maximum cache size (default: 10000 entries)
72    pub max_cache_size: usize,
73    /// Number of resolver threads (default: 4)
74    pub resolver_threads: usize,
75}
76
77impl Default for DnsResolverConfig {
78    fn default() -> Self {
79        Self {
80            cache_ttl: Duration::from_secs(300),         // 5 minutes
81            negative_cache_ttl: Duration::from_secs(60), // 1 minute
82            max_cache_size: 10000,
83            resolver_threads: 4,
84        }
85    }
86}
87
88/// Background DNS resolver with caching
89pub struct DnsResolver {
90    /// Hostname cache: IP -> CachedHostname
91    cache: Arc<DashMap<IpAddr, CachedHostname>>,
92    /// Channel to send IPs for resolution
93    request_tx: Sender<IpAddr>,
94    /// Control flag for shutdown
95    should_stop: Arc<AtomicBool>,
96    /// Configuration
97    config: DnsResolverConfig,
98}
99
100impl DnsResolver {
101    /// Create a new DNS resolver with the given configuration
102    pub fn new(config: DnsResolverConfig) -> Self {
103        let cache = Arc::new(DashMap::new());
104        let (request_tx, request_rx) = channel::unbounded();
105        let should_stop = Arc::new(AtomicBool::new(false));
106
107        let resolver = Self {
108            cache: Arc::clone(&cache),
109            request_tx,
110            should_stop: Arc::clone(&should_stop),
111            config: config.clone(),
112        };
113
114        // Start resolver threads
115        resolver.start_resolver_threads(request_rx, &config);
116
117        // Start cache cleanup thread
118        resolver.start_cache_cleanup_thread();
119
120        resolver
121    }
122
123    /// Create a new DNS resolver with default configuration
124    pub fn with_defaults() -> Self {
125        Self::new(DnsResolverConfig::default())
126    }
127
128    /// Start background resolver threads
129    fn start_resolver_threads(&self, request_rx: Receiver<IpAddr>, config: &DnsResolverConfig) {
130        let num_threads = config.resolver_threads;
131
132        for i in 0..num_threads {
133            let rx = request_rx.clone();
134            let cache = Arc::clone(&self.cache);
135            let should_stop = Arc::clone(&self.should_stop);
136            let cache_ttl = config.cache_ttl;
137            let negative_cache_ttl = config.negative_cache_ttl;
138
139            thread::Builder::new()
140                .name(format!("dns-resolver-{}", i))
141                .spawn(move || {
142                    debug!("DNS resolver thread {} started", i);
143
144                    while !should_stop.load(Ordering::Relaxed) {
145                        match rx.recv_timeout(Duration::from_millis(100)) {
146                            Ok(ip) => {
147                                // Skip if already resolved or pending
148                                if let Some(entry) = cache.get(&ip) {
149                                    let age = entry.resolved_at.elapsed();
150                                    match entry.state {
151                                        ResolutionState::Pending => continue,
152                                        ResolutionState::Resolved if age < cache_ttl => continue,
153                                        ResolutionState::Failed if age < negative_cache_ttl => {
154                                            continue;
155                                        }
156                                        _ => {} // Expired, re-resolve
157                                    }
158                                }
159
160                                // Mark as pending
161                                cache.insert(ip, CachedHostname::pending());
162
163                                // Perform DNS lookup
164                                match lookup_addr(&ip) {
165                                    Ok(hostname) => {
166                                        debug!("Resolved {} -> {}", ip, hostname);
167                                        cache.insert(ip, CachedHostname::resolved(hostname));
168                                    }
169                                    Err(e) => {
170                                        debug!("Failed to resolve {}: {}", ip, e);
171                                        cache.insert(ip, CachedHostname::failed());
172                                    }
173                                }
174                            }
175                            Err(crossbeam::channel::RecvTimeoutError::Timeout) => continue,
176                            Err(crossbeam::channel::RecvTimeoutError::Disconnected) => break,
177                        }
178                    }
179
180                    debug!("DNS resolver thread {} stopping", i);
181                })
182                .expect("Failed to spawn DNS resolver thread");
183        }
184    }
185
186    /// Start cache cleanup thread to evict expired entries
187    fn start_cache_cleanup_thread(&self) {
188        let cache = Arc::clone(&self.cache);
189        let should_stop = Arc::clone(&self.should_stop);
190        let cache_ttl = self.config.cache_ttl;
191        let negative_cache_ttl = self.config.negative_cache_ttl;
192        let max_cache_size = self.config.max_cache_size;
193
194        thread::Builder::new()
195            .name("dns-cache-cleanup".to_string())
196            .spawn(move || {
197                debug!("DNS cache cleanup thread started");
198
199                while !should_stop.load(Ordering::Relaxed) {
200                    thread::sleep(Duration::from_secs(30)); // Cleanup every 30 seconds
201
202                    if should_stop.load(Ordering::Relaxed) {
203                        break;
204                    }
205
206                    // Remove expired entries
207                    cache.retain(|_, entry| {
208                        let age = entry.resolved_at.elapsed();
209                        match entry.state {
210                            ResolutionState::Resolved => age < cache_ttl,
211                            ResolutionState::Failed => age < negative_cache_ttl,
212                            ResolutionState::Pending => age < Duration::from_secs(30), // Timeout pending
213                        }
214                    });
215
216                    // If cache is too large, remove oldest entries
217                    if cache.len() > max_cache_size {
218                        let mut entries: Vec<_> =
219                            cache.iter().map(|e| (*e.key(), e.resolved_at)).collect();
220                        entries.sort_by_key(|(_, time)| *time);
221
222                        let to_remove = cache.len() - max_cache_size;
223                        for (ip, _) in entries.into_iter().take(to_remove) {
224                            cache.remove(&ip);
225                        }
226                    }
227
228                    debug!("DNS cache size: {}", cache.len());
229                }
230
231                debug!("DNS cache cleanup thread stopping");
232            })
233            .expect("Failed to spawn DNS cache cleanup thread");
234    }
235
236    /// Request resolution for an IP address (non-blocking)
237    pub fn request_resolution(&self, ip: IpAddr) {
238        // Don't resolve localhost or link-local
239        if ip.is_loopback() || is_link_local(&ip) {
240            return;
241        }
242
243        // Check if already in cache and not expired
244        if let Some(entry) = self.cache.get(&ip) {
245            let age = entry.resolved_at.elapsed();
246            match entry.state {
247                ResolutionState::Pending => return,
248                ResolutionState::Resolved if age < self.config.cache_ttl => return,
249                ResolutionState::Failed if age < self.config.negative_cache_ttl => return,
250                _ => {} // Expired
251            }
252        }
253
254        // Queue for resolution (ignore send errors - channel is unbounded)
255        let _ = self.request_tx.send(ip);
256    }
257
258    /// Get hostname for IP if resolved, otherwise return None
259    pub fn get_hostname(&self, ip: &IpAddr) -> Option<String> {
260        // Request resolution if not in cache
261        self.request_resolution(*ip);
262
263        // Return cached hostname if available
264        self.cache.get(ip).and_then(|entry| {
265            if entry.state == ResolutionState::Resolved {
266                entry.hostname.clone()
267            } else {
268                None
269            }
270        })
271    }
272
273    /// Stop the resolver
274    pub fn stop(&self) {
275        self.should_stop.store(true, Ordering::Relaxed);
276    }
277}
278
279impl Drop for DnsResolver {
280    fn drop(&mut self) {
281        self.stop();
282    }
283}
284
285/// Check if IP is link-local
286fn is_link_local(ip: &IpAddr) -> bool {
287    match ip {
288        IpAddr::V4(v4) => v4.is_link_local(),
289        IpAddr::V6(v6) => {
290            // fe80::/10
291            let segments = v6.segments();
292            (segments[0] & 0xffc0) == 0xfe80
293        }
294    }
295}
296
297#[cfg(test)]
298mod tests {
299    use super::*;
300
301    #[test]
302    fn test_cached_hostname_states() {
303        let pending = CachedHostname::pending();
304        assert_eq!(pending.state, ResolutionState::Pending);
305        assert!(pending.hostname.is_none());
306
307        let resolved = CachedHostname::resolved("example.com".to_string());
308        assert_eq!(resolved.state, ResolutionState::Resolved);
309        assert_eq!(resolved.hostname, Some("example.com".to_string()));
310
311        let failed = CachedHostname::failed();
312        assert_eq!(failed.state, ResolutionState::Failed);
313        assert!(failed.hostname.is_none());
314    }
315
316    #[test]
317    fn test_link_local_detection() {
318        // IPv4 link-local
319        assert!(is_link_local(&"169.254.1.1".parse().unwrap()));
320        assert!(!is_link_local(&"192.168.1.1".parse().unwrap()));
321
322        // IPv6 link-local
323        assert!(is_link_local(&"fe80::1".parse().unwrap()));
324        assert!(!is_link_local(&"2001:db8::1".parse().unwrap()));
325    }
326
327    #[test]
328    fn test_loopback_skip() {
329        let config = DnsResolverConfig {
330            resolver_threads: 1,
331            ..Default::default()
332        };
333        let resolver = DnsResolver::new(config);
334
335        // Loopback should not be queued
336        resolver.request_resolution("127.0.0.1".parse().unwrap());
337        assert!(
338            resolver
339                .get_hostname(&"127.0.0.1".parse().unwrap())
340                .is_none()
341        );
342
343        resolver.stop();
344    }
345
346    #[test]
347    fn test_default_config() {
348        let config = DnsResolverConfig::default();
349        assert_eq!(config.cache_ttl, Duration::from_secs(300));
350        assert_eq!(config.negative_cache_ttl, Duration::from_secs(60));
351        assert_eq!(config.max_cache_size, 10000);
352        assert_eq!(config.resolver_threads, 4);
353    }
354}