etchdns 0.2.1

Caching DNS proxy and forwarding server with load balancing, failover, domain filtering, and WebAssembly plugins
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
use bytes::Bytes;
use http_body_util::Full;
use hyper::{Method, Request, Response, StatusCode, server::conn::http1};
use hyper_util::rt::TokioIo;
use log::{debug, error, info, warn};
use serde::{Deserialize, Serialize};
use std::convert::Infallible;
use std::sync::Arc;
use tokio::net::TcpListener;
use tokio::sync::Semaphore;

use crate::cache::SyncDnsCache;
use crate::stats::SharedStats;

/// Response structure for API calls
#[derive(Serialize, Deserialize)]
struct ApiResponse {
    success: bool,
    message: String,
}

/// Cache status response structure
#[derive(Serialize, Deserialize)]
struct CacheStatusResponse {
    success: bool,
    size: usize,
    capacity: usize,
    hit_rate: f64,
    hits: u64,
    misses: u64,
}

/// Check if a domain is within a zone
///
/// For example, if zone is "example.com", then "www.example.com" is within that zone,
/// but "example.org" is not.
fn is_domain_in_zone(domain: &str, zone: &str) -> bool {
    // Normalize both domain and zone (lowercase, no trailing dot)
    let normalized_domain = domain.trim_end_matches('.').to_lowercase();
    let normalized_zone = zone.trim_end_matches('.').to_lowercase();

    // Every name is in the root zone
    if normalized_zone.is_empty() {
        return true;
    }

    // Check if domain equals zone
    if normalized_domain == normalized_zone {
        return true;
    }

    // Check if domain is a subdomain of zone
    // Domain must end with .zone
    normalized_domain.ends_with(&format!(".{normalized_zone}"))
}

/// Handle HTTP requests for the control API
async fn handle_request(
    req: Request<hyper::body::Incoming>,
    control_path: String,
    dns_cache: Option<Arc<SyncDnsCache>>,
    stats: Option<Arc<SharedStats>>,
) -> Result<Response<Full<Bytes>>, Infallible> {
    let path = req.uri().path();
    let method = req.method();

    // Only match the exact control path or descendants beneath it.
    let is_control_path = path == control_path
        || path
            .strip_prefix(&control_path)
            .map(|suffix| control_path.ends_with('/') || suffix.starts_with('/'))
            .unwrap_or(false);
    if !is_control_path {
        let mut response = Response::new(Full::new(Bytes::from("Not Found")));
        *response.status_mut() = StatusCode::NOT_FOUND;
        return Ok(response);
    }

    // Remove the control_path prefix to get the actual endpoint
    let endpoint = path
        .strip_prefix(&control_path)
        .unwrap_or("")
        .trim_start_matches('/');

    match (method, endpoint) {
        // GET /status - Return server status
        (&Method::GET, "status") => {
            let response = ApiResponse {
                success: true,
                message: "Server is running".to_string(),
            };
            let json = serde_json::to_string(&response).unwrap_or_else(|e| {
                error!("Failed to serialize API response: {e}");
                r#"{"success":false,"message":"Internal server error"}"#.to_string()
            });

            let mut response = Response::new(Full::new(Bytes::from(json)));
            response.headers_mut().insert(
                hyper::header::CONTENT_TYPE,
                hyper::header::HeaderValue::from_static("application/json"),
            );
            Ok(response)
        }

        // GET /cache - Return cache status
        (&Method::GET, "cache") => {
            if let Some(cache) = dns_cache {
                // Get cache size and capacity
                let size = cache.len();
                let capacity = cache.capacity();

                // Get cache hit/miss statistics from the stats system
                let (hits, misses, hit_rate) = if let Some(stats_ref) = &stats {
                    let global_stats = stats_ref.get_stats().await;

                    let hits = global_stats.cache_hits;
                    let misses = global_stats.cache_misses;
                    let hit_rate = if hits + misses > 0 {
                        hits as f64 / (hits + misses) as f64
                    } else {
                        0.0
                    };

                    (hits, misses, hit_rate)
                } else {
                    // Fallback to placeholder values if stats not available
                    let hits = 0;
                    let misses = 0;
                    let hit_rate = 0.0;
                    (hits, misses, hit_rate)
                };

                let response = CacheStatusResponse {
                    success: true,
                    size,
                    capacity,
                    hit_rate,
                    hits,
                    misses,
                };
                let json = serde_json::to_string(&response).unwrap_or_else(|e| {
                    error!("Failed to serialize API response: {e}");
                    r#"{"success":false,"message":"Internal server error"}"#.to_string()
                });

                let mut response = Response::new(Full::new(Bytes::from(json)));
                response.headers_mut().insert(
                    hyper::header::CONTENT_TYPE,
                    hyper::header::HeaderValue::from_static("application/json"),
                );
                Ok(response)
            } else {
                // DNS cache not available
                let response = ApiResponse {
                    success: false,
                    message: "DNS cache not available".to_string(),
                };
                let json = serde_json::to_string(&response).unwrap_or_else(|e| {
                    error!("Failed to serialize API response: {e}");
                    r#"{"success":false,"message":"Internal server error"}"#.to_string()
                });

                let mut response = Response::new(Full::new(Bytes::from(json)));
                response.headers_mut().insert(
                    hyper::header::CONTENT_TYPE,
                    hyper::header::HeaderValue::from_static("application/json"),
                );
                *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR;
                Ok(response)
            }
        }

        // DELETE /cache - Clear the DNS cache
        (&Method::DELETE, "cache") => {
            if let Some(cache) = dns_cache {
                // Clear the cache
                cache.clear();

                let cache_size = cache.len();
                info!("DNS cache cleared, current size: {cache_size}");

                let response = ApiResponse {
                    success: true,
                    message: format!("Cache cleared successfully. Current size: {cache_size}"),
                };
                let json = serde_json::to_string(&response).unwrap_or_else(|e| {
                    error!("Failed to serialize API response: {e}");
                    r#"{"success":false,"message":"Internal server error"}"#.to_string()
                });

                let mut response = Response::new(Full::new(Bytes::from(json)));
                response.headers_mut().insert(
                    hyper::header::CONTENT_TYPE,
                    hyper::header::HeaderValue::from_static("application/json"),
                );
                Ok(response)
            } else {
                // DNS cache not available
                let response = ApiResponse {
                    success: false,
                    message: "DNS cache not available".to_string(),
                };
                let json = serde_json::to_string(&response).unwrap_or_else(|e| {
                    error!("Failed to serialize API response: {e}");
                    r#"{"success":false,"message":"Internal server error"}"#.to_string()
                });

                let mut response = Response::new(Full::new(Bytes::from(json)));
                response.headers_mut().insert(
                    hyper::header::CONTENT_TYPE,
                    hyper::header::HeaderValue::from_static("application/json"),
                );
                *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR;
                Ok(response)
            }
        }

        // DELETE /cache/zone/<zone> - Clear entries for a specific zone
        (&Method::DELETE, zone_path) if zone_path.starts_with("cache/zone/") => {
            if let Some(cache) = dns_cache {
                // Extract the zone from the path
                let zone = zone_path.strip_prefix("cache/zone/").unwrap_or("");
                if zone.is_empty() {
                    let response = ApiResponse {
                        success: false,
                        message: "Zone parameter is required".to_string(),
                    };
                    let json = serde_json::to_string(&response).unwrap_or_else(|e| {
                        error!("Failed to serialize API response: {e}");
                        r#"{"success":false,"message":"Internal server error"}"#.to_string()
                    });

                    let mut response = Response::new(Full::new(Bytes::from(json)));
                    response.headers_mut().insert(
                        hyper::header::CONTENT_TYPE,
                        hyper::header::HeaderValue::from_static("application/json"),
                    );
                    *response.status_mut() = StatusCode::BAD_REQUEST;
                    return Ok(response);
                }

                let normalized_zone = match crate::dns_key::DNSKey::normalize_name(zone) {
                    Ok(zone) => zone,
                    Err(e) => {
                        let mut response = Response::new(Full::new(Bytes::from(format!(
                            "Invalid domain name: {e}"
                        ))));
                        *response.status_mut() = StatusCode::BAD_REQUEST;
                        return Ok(response);
                    }
                };
                let (removed_entries, new_size) = cache.with_lock(|inner| {
                    let initial_size = inner.len();
                    inner.retain(|key, _| !is_domain_in_zone(&key.name, &normalized_zone));
                    let new_size = inner.len();
                    (initial_size.saturating_sub(new_size), new_size)
                });

                info!("Cleared {removed_entries} entries for zone {zone} from DNS cache");

                let response = ApiResponse {
                    success: true,
                    message: format!(
                        "Cleared {removed_entries} entries for zone {zone} from DNS cache. New size: {new_size}"
                    ),
                };
                let json = serde_json::to_string(&response).unwrap_or_else(|e| {
                    error!("Failed to serialize API response: {e}");
                    r#"{"success":false,"message":"Internal server error"}"#.to_string()
                });

                let mut response = Response::new(Full::new(Bytes::from(json)));
                response.headers_mut().insert(
                    hyper::header::CONTENT_TYPE,
                    hyper::header::HeaderValue::from_static("application/json"),
                );
                Ok(response)
            } else {
                // DNS cache not available
                let response = ApiResponse {
                    success: false,
                    message: "DNS cache not available".to_string(),
                };
                let json = serde_json::to_string(&response).unwrap_or_else(|e| {
                    error!("Failed to serialize API response: {e}");
                    r#"{"success":false,"message":"Internal server error"}"#.to_string()
                });

                let mut response = Response::new(Full::new(Bytes::from(json)));
                response.headers_mut().insert(
                    hyper::header::CONTENT_TYPE,
                    hyper::header::HeaderValue::from_static("application/json"),
                );
                *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR;
                Ok(response)
            }
        }

        // DELETE /cache/name/<name> - Clear a specific entry
        (&Method::DELETE, name_path) if name_path.starts_with("cache/name/") => {
            if let Some(cache) = dns_cache {
                // Extract the name from the path
                let name = name_path.strip_prefix("cache/name/").unwrap_or("");
                if name.is_empty() {
                    let response = ApiResponse {
                        success: false,
                        message: "Name parameter is required".to_string(),
                    };
                    let json = serde_json::to_string(&response).unwrap_or_else(|e| {
                        error!("Failed to serialize API response: {e}");
                        r#"{"success":false,"message":"Internal server error"}"#.to_string()
                    });

                    let mut response = Response::new(Full::new(Bytes::from(json)));
                    response.headers_mut().insert(
                        hyper::header::CONTENT_TYPE,
                        hyper::header::HeaderValue::from_static("application/json"),
                    );
                    *response.status_mut() = StatusCode::BAD_REQUEST;
                    return Ok(response);
                }

                // Use retain to keep only entries that don't match the specified name
                // We need to normalize the name for comparison
                let normalized_name = match crate::dns_key::DNSKey::normalize_name(name) {
                    Ok(name) => name,
                    Err(e) => {
                        // If name normalization fails, return an error response
                        error!("Failed to normalize domain name: {}", e);
                        let response = ApiResponse {
                            success: false,
                            message: format!("Invalid domain name: {}", e),
                        };
                        let json = serde_json::to_string(&response).unwrap_or_else(|e| {
                            error!("Failed to serialize API response: {}", e);
                            r#"{"success":false,"message":"Internal server error"}"#.to_string()
                        });

                        let mut response = Response::new(Full::new(Bytes::from(json)));
                        response.headers_mut().insert(
                            hyper::header::CONTENT_TYPE,
                            hyper::header::HeaderValue::from_static("application/json"),
                        );
                        *response.status_mut() = StatusCode::BAD_REQUEST;
                        return Ok(response);
                    }
                };
                let (removed_entries, new_size) = cache.with_lock(|inner| {
                    let initial_size = inner.len();
                    inner.retain(|key, _| key.name != normalized_name);
                    let new_size = inner.len();
                    (initial_size.saturating_sub(new_size), new_size)
                });

                info!("Cleared {removed_entries} entries for name {name} from DNS cache");

                let response = ApiResponse {
                    success: true,
                    message: format!(
                        "Cleared {removed_entries} entries for name {name} from DNS cache. New size: {new_size}"
                    ),
                };
                let json = serde_json::to_string(&response).unwrap_or_else(|e| {
                    error!("Failed to serialize API response: {e}");
                    r#"{"success":false,"message":"Internal server error"}"#.to_string()
                });

                let mut response = Response::new(Full::new(Bytes::from(json)));
                response.headers_mut().insert(
                    hyper::header::CONTENT_TYPE,
                    hyper::header::HeaderValue::from_static("application/json"),
                );
                Ok(response)
            } else {
                // DNS cache not available
                let response = ApiResponse {
                    success: false,
                    message: "DNS cache not available".to_string(),
                };
                let json = serde_json::to_string(&response).unwrap_or_else(|e| {
                    error!("Failed to serialize API response: {e}");
                    r#"{"success":false,"message":"Internal server error"}"#.to_string()
                });

                let mut response = Response::new(Full::new(Bytes::from(json)));
                response.headers_mut().insert(
                    hyper::header::CONTENT_TYPE,
                    hyper::header::HeaderValue::from_static("application/json"),
                );
                *response.status_mut() = StatusCode::INTERNAL_SERVER_ERROR;
                Ok(response)
            }
        }

        // Any other endpoint
        _ => {
            let response = ApiResponse {
                success: false,
                message: "Endpoint not found".to_string(),
            };
            let json = serde_json::to_string(&response).unwrap_or_else(|e| {
                error!("Failed to serialize API response: {e}");
                r#"{"success":false,"message":"Internal server error"}"#.to_string()
            });

            let mut response = Response::new(Full::new(Bytes::from(json)));
            response.headers_mut().insert(
                hyper::header::CONTENT_TYPE,
                hyper::header::HeaderValue::from_static("application/json"),
            );
            *response.status_mut() = StatusCode::NOT_FOUND;
            Ok(response)
        }
    }
}

/// Start the HTTP control server
pub async fn start_control_server(
    listener: TcpListener,
    control_path: String,
    max_connections: usize,
    dns_cache: Option<Arc<SyncDnsCache>>,
    stats: Option<Arc<SharedStats>>,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    let addr = listener.local_addr()?;
    info!("Control server listening on {addr}, base path: {control_path}");

    if dns_cache.is_some() {
        info!(
            "DNS cache control API enabled at {control_path}/cache (GET/DELETE), {control_path}/cache/zone/<zone> (DELETE), and {control_path}/cache/name/<name> (DELETE)"
        );
    } else {
        warn!("DNS cache not available for control API");
    }

    // Create a semaphore to limit concurrent connections
    let semaphore = Arc::new(Semaphore::new(max_connections));

    // Accept connections
    loop {
        // Accept a connection
        let (stream, client_addr) = crate::net::accept_with_retry(&listener, "control").await;
        let io = TokioIo::new(stream);

        // Clone the resources for this connection
        let control_path = control_path.clone();
        let semaphore = semaphore.clone();
        let dns_cache = dns_cache.clone();
        let stats = stats.clone();

        // Spawn a task to handle the connection
        tokio::spawn(async move {
            // Try to acquire a permit from the semaphore
            let _permit = match semaphore.try_acquire() {
                Ok(permit) => permit,
                Err(_) => {
                    // Too many connections, reject this one
                    warn!("Too many control connections, rejecting connection from {client_addr}");
                    return;
                }
            };

            debug!("Accepted control connection from {client_addr}");

            // Handle the connection
            let service = hyper::service::service_fn(move |req| {
                let control_path = control_path.clone();
                let dns_cache = dns_cache.clone();
                let stats = stats.clone();
                async move { handle_request(req, control_path, dns_cache, stats).await }
            });

            if let Ok(Err(err)) = tokio::time::timeout(
                std::time::Duration::from_secs(30),
                http1::Builder::new().serve_connection(io, service),
            )
            .await
            {
                // Log any errors
                error!("Error serving control connection from {client_addr}: {err}");
            }

            debug!("Closed control connection from {client_addr}");
        });
    }
}

#[cfg(test)]
mod tests {
    use super::is_domain_in_zone;

    #[test]
    fn zone_matching_normalizes_case_and_trailing_dots() {
        assert!(is_domain_in_zone("WWW.Example.COM.", "example.com."));
        assert!(is_domain_in_zone("example.com", "EXAMPLE.COM."));
        assert!(!is_domain_in_zone("notexample.com", "example.com."));
        assert!(is_domain_in_zone("www.example.com", "."));
    }
}