rustnet_core/network/
dns.rs1use 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#[derive(Debug, Clone, PartialEq)]
18pub enum ResolutionState {
19 Pending,
21 Resolved,
23 Failed,
25}
26
27#[derive(Debug, Clone)]
29pub struct CachedHostname {
30 pub hostname: Option<String>,
32 pub resolved_at: Instant,
34 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#[derive(Debug, Clone)]
66pub struct DnsResolverConfig {
67 pub cache_ttl: Duration,
69 pub negative_cache_ttl: Duration,
71 pub max_cache_size: usize,
73 pub resolver_threads: usize,
75}
76
77impl Default for DnsResolverConfig {
78 fn default() -> Self {
79 Self {
80 cache_ttl: Duration::from_secs(300), negative_cache_ttl: Duration::from_secs(60), max_cache_size: 10000,
83 resolver_threads: 4,
84 }
85 }
86}
87
88pub struct DnsResolver {
90 cache: Arc<DashMap<IpAddr, CachedHostname>>,
92 request_tx: Sender<IpAddr>,
94 should_stop: Arc<AtomicBool>,
96 config: DnsResolverConfig,
98}
99
100impl DnsResolver {
101 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 resolver.start_resolver_threads(request_rx, &config);
116
117 resolver.start_cache_cleanup_thread();
119
120 resolver
121 }
122
123 pub fn with_defaults() -> Self {
125 Self::new(DnsResolverConfig::default())
126 }
127
128 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 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 _ => {} }
158 }
159
160 cache.insert(ip, CachedHostname::pending());
162
163 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 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)); if should_stop.load(Ordering::Relaxed) {
203 break;
204 }
205
206 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), }
214 });
215
216 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 pub fn request_resolution(&self, ip: IpAddr) {
238 if ip.is_loopback() || is_link_local(&ip) {
240 return;
241 }
242
243 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 _ => {} }
252 }
253
254 let _ = self.request_tx.send(ip);
256 }
257
258 pub fn get_hostname(&self, ip: &IpAddr) -> Option<String> {
260 self.request_resolution(*ip);
262
263 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 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
285fn is_link_local(ip: &IpAddr) -> bool {
287 match ip {
288 IpAddr::V4(v4) => v4.is_link_local(),
289 IpAddr::V6(v6) => {
290 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 assert!(is_link_local(&"169.254.1.1".parse().unwrap()));
320 assert!(!is_link_local(&"192.168.1.1".parse().unwrap()));
321
322 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 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}