rdns-server 1.17.21

A high-performance, security-focused DNS server written in Rust
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
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
use crate::cache::entry::{CacheEntry, CacheKey};
use crate::cache::CacheStore;
use crate::config::ForwardZoneConfig;
use crate::dnssec::DnssecValidator;
use crate::protocol::message::Message;
use crate::protocol::name::DnsName;
use crate::protocol::rcode::Rcode;
use crate::protocol::record::{RecordClass, RecordType};
use crate::resolver::forwarder::ForwarderPool;
use std::net::SocketAddr;
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::OnceCell;

/// A parsed forward zone: domain suffix → upstream servers.
struct ForwardZone {
    /// Domain suffix to match (lowercase, with trailing dot).
    suffix: String,
    /// Upstream DNS servers for this zone.
    servers: Vec<SocketAddr>,
}

/// The main recursive resolver.
#[derive(Clone)]
pub struct Resolver {
    inner: Arc<ResolverInner>,
}

struct ResolverInner {
    cache: CacheStore,
    forwarders: Vec<SocketAddr>,
    root_hints: Vec<SocketAddr>,
    max_depth: u8,
    query_timeout: Duration,
    dnssec_validator: DnssecValidator,
    qname_minimization: bool,
    /// TTL sent to clients when we return a stale answer (RFC 8767 §5
    /// recommends a small value — default 30 s — so clients re-query
    /// soon and pick up fresh data once upstream recovers).
    stale_answer_ttl: u32,
    /// Lazily initialized forwarder pool (one per first forwarder)
    forwarder_pool: OnceCell<ForwarderPool>,
    /// Per-domain forwarding rules (longest suffix match wins).
    forward_zones: Vec<ForwardZone>,
    /// DNS64 (RFC 6147) synthesis prefix; `None` disables synthesis.
    dns64_prefix: Option<std::net::Ipv6Addr>,
}

impl Resolver {
    pub fn new(
        cache: CacheStore,
        forwarders: Vec<SocketAddr>,
        max_depth: u8,
        dnssec_validator: DnssecValidator,
        qname_minimization: bool,
        stale_answer_ttl: u32,
    ) -> Self {
        Self {
            inner: Arc::new(ResolverInner {
                cache,
                forwarders,
                root_hints: super::iterator::root_hints(),
                max_depth,
                query_timeout: Duration::from_secs(5),
                dnssec_validator,
                qname_minimization,
                stale_answer_ttl,
                forwarder_pool: OnceCell::new(),
                forward_zones: Vec::new(),
                dns64_prefix: None,
            }),
        }
    }

    /// Create a resolver with per-domain forward zones.
    pub fn with_forward_zones(
        cache: CacheStore,
        forwarders: Vec<SocketAddr>,
        max_depth: u8,
        dnssec_validator: DnssecValidator,
        qname_minimization: bool,
        stale_answer_ttl: u32,
        zones: &[ForwardZoneConfig],
    ) -> Self {
        let forward_zones: Vec<ForwardZone> = zones
            .iter()
            .filter_map(|z| {
                let servers: Vec<SocketAddr> = z
                    .forwarders
                    .iter()
                    .filter_map(|s| {
                        if s.contains(':') {
                            s.parse().ok()
                        } else {
                            format!("{}:53", s).parse().ok()
                        }
                    })
                    .collect();
                if servers.is_empty() {
                    return None;
                }
                let mut suffix = z.name.to_lowercase();
                if !suffix.ends_with('.') {
                    suffix.push('.');
                }
                Some(ForwardZone { suffix, servers })
            })
            .collect();

        if !forward_zones.is_empty() {
            tracing::info!(count = forward_zones.len(), "Forward zones configured");
        }

        Self {
            inner: Arc::new(ResolverInner {
                cache,
                forwarders,
                root_hints: super::iterator::root_hints(),
                max_depth,
                query_timeout: Duration::from_secs(5),
                dnssec_validator,
                qname_minimization,
                stale_answer_ttl,
                forwarder_pool: OnceCell::new(),
                forward_zones,
                dns64_prefix: None,
            }),
        }
    }

    /// Resolve the A records for `name` and synthesize AAAA answers from
    /// them. `None` when the A lookup fails or yields no addresses — the
    /// caller then returns the original (empty) AAAA answer unchanged.
    ///
    /// Follows CNAME chains itself (bounded): a forwarded upstream that
    /// doesn't chase — e.g. a plain authoritative server — returns just
    /// the CNAME, and synthesis must still reach the terminal A records.
    /// Each hop goes through `resolve`, so it benefits from (and
    /// populates) the per-name A cache; re-entry into synthesis is
    /// impossible because the inner queries have `rtype == A`.
    async fn dns64_synthesize(
        &self,
        name: &DnsName,
        rclass: RecordClass,
        prefix: std::net::Ipv6Addr,
    ) -> Option<Vec<crate::protocol::record::ResourceRecord>> {
        use crate::protocol::rdata::RData;

        const MAX_CNAME_HOPS: usize = 8;
        let mut chain: Vec<crate::protocol::record::ResourceRecord> = Vec::new();
        let mut qname = name.clone();

        for _ in 0..MAX_CNAME_HOPS {
            let a_resp = Box::pin(self.resolve(&qname, RecordType::A, rclass)).await;
            if a_resp.header.rcode != Rcode::NoError {
                return None;
            }
            let records = synthesize_aaaa_records(&a_resp.answers, prefix);
            if records.iter().any(|r| r.rtype == RecordType::AAAA) {
                chain.extend(records);
                return Some(chain);
            }
            // No A records in this hop — follow the terminal CNAME, if any.
            let target = a_resp.answers.iter().rev().find_map(|rr| match &rr.rdata {
                RData::CNAME(t) => Some(t.clone()),
                _ => None,
            })?;
            // Keep the chain records (CNAMEs) for the final answer section.
            chain.extend(records);
            qname = target;
        }
        None
    }

    /// Enable DNS64 synthesis (RFC 6147) with the given /96 prefix.
    /// Builder-style; call right after construction (before any clone).
    pub fn with_dns64(mut self, prefix: std::net::Ipv6Addr) -> Self {
        if let Some(inner) = Arc::get_mut(&mut self.inner) {
            inner.dns64_prefix = Some(prefix);
            tracing::info!(%prefix, "DNS64 synthesis enabled");
        } else {
            tracing::error!("with_dns64 called after the resolver was shared; DNS64 NOT enabled");
        }
        self
    }

    /// Find the best matching forward zone for a query name (longest suffix wins).
    fn match_forward_zone(&self, name: &DnsName) -> Option<&[SocketAddr]> {
        let qname = name.to_dotted().to_lowercase();
        let mut best: Option<(usize, &[SocketAddr])> = None;
        for fz in &self.inner.forward_zones {
            if qname.ends_with(&fz.suffix) || qname.trim_end_matches('.') == fz.suffix.trim_end_matches('.') {
                let len = fz.suffix.len();
                if best.map_or(true, |(bl, _)| len > bl) {
                    best = Some((len, &fz.servers));
                }
            }
        }
        best.map(|(_, servers)| servers)
    }

    /// Get or create the forwarder pool for the primary forwarder.
    async fn get_forwarder_pool(&self) -> Option<&ForwarderPool> {
        let server = self.inner.forwarders.first()?;
        let server = *server;
        // Try to initialize the pool; if it already failed, return None
        // and let the caller fall back to single-shot forwarding.
        if self.inner.forwarder_pool.get().is_none() {
            match ForwarderPool::new(server).await {
                Ok(pool) => {
                    let _ = self.inner.forwarder_pool.set(pool);
                    tracing::info!(%server, "Forwarder connection pool initialized");
                }
                Err(e) => {
                    tracing::error!(%server, error = %e, "Failed to create forwarder pool, using single-shot");
                    return None;
                }
            }
        }
        self.inner.forwarder_pool.get()
    }

    /// Resolve a DNS query. Checks cache first, then resolves recursively or forwards.
    pub async fn resolve(
        &self,
        name: &DnsName,
        rtype: RecordType,
        rclass: RecordClass,
    ) -> Message {
        // Check cache
        let key = CacheKey::new(name.clone(), rtype, rclass);
        if let Some(entry) = self.inner.cache.lookup(&key) {
            return self.build_cached_response(name, rtype, rclass, &entry);
        }

        // Resolve: check per-domain forward zones first, then global forwarders, then recursive
        let result = if let Some(zone_servers) = self.match_forward_zone(name) {
            tracing::debug!(name = %name, servers = ?zone_servers, "Using forward zone");
            super::forwarder::forward(name, rtype, zone_servers, self.inner.query_timeout).await
        } else if self.inner.forwarders.is_empty() {
            self.resolve_recursive(name, rtype).await
        } else {
            self.resolve_forwarded(name, rtype).await
        };

        match result {
            Ok(mut response) => {
                // DNS64 (RFC 6147): a NoError AAAA answer with no AAAA
                // records is re-resolved as A and synthesized. The gate is
                // "no AAAA present", NOT "answers empty" — a name that
                // CNAMEs to a v4-only target returns the CNAME chain in
                // the answer section (RFC 6147 §5.1.6 still requires
                // synthesis there, and that shape is most CDN-hosted
                // sites). The A re-query follows the same chain, so the
                // synthesized set carries chain + AAAA records. Runs
                // BEFORE cache_response so the synthetic answer is cached
                // positively under the AAAA key — otherwise the negative
                // entry would suppress synthesis on every cache hit.
                // NXDOMAIN is never synthesized.
                // TODO: skip synthesis when the response is DNSSEC-Secure
                // once cryptographic validation lands (the validator never
                // returns Secure today).
                if let Some(prefix) = self.inner.dns64_prefix
                    && rtype == RecordType::AAAA
                    && response.header.rcode == Rcode::NoError
                    && !response
                        .answers
                        .iter()
                        .any(|r| r.rtype == RecordType::AAAA)
                    && let Some(records) = self.dns64_synthesize(name, rclass, prefix).await
                {
                    tracing::debug!(name = %name, count = records.len(), "DNS64 synthesized AAAA");
                    response.answers = records;
                    // Drop the negative-answer SOA — this is a positive
                    // answer now.
                    response.authority.clear();
                }

                // DNSSEC validation
                let status = self.inner.dnssec_validator.validate(&response);
                DnssecValidator::set_ad_bit(&mut response, status);

                // Cache the response
                self.cache_response(&key, &response);
                response
            }
            Err(e) => {
                // Serve-stale fallback (RFC 8767). Only activates if the
                // cache has a non-zero stale window — `lookup_stale`
                // returns None otherwise.
                if let Some(stale) = self.inner.cache.lookup_stale(&key) {
                    tracing::info!(
                        name = %name,
                        rtype = %rtype,
                        error = %e,
                        staleness_secs = stale.staleness_secs(),
                        "Upstream failed; serving stale answer"
                    );
                    return self.build_stale_response(name, rtype, rclass, &stale);
                }
                tracing::warn!(name = %name, rtype = %rtype, error = %e, "Resolution failed");
                self.build_servfail(name, rtype, rclass)
            }
        }
    }

    /// Full recursive resolution from root hints.
    async fn resolve_recursive(
        &self,
        name: &DnsName,
        rtype: RecordType,
    ) -> anyhow::Result<Message> {
        if self.inner.qname_minimization {
            tracing::trace!(name = %name, "QNAME minimization enabled");
        }

        let response = super::iterator::iterate(
            name,
            rtype,
            &self.inner.root_hints,
            self.inner.max_depth,
            self.inner.query_timeout,
        )
        .await?;

        // Handle CNAME chains
        if let Some(cname_target) = super::iterator::follow_cnames(&response, name, rtype) {
            tracing::debug!(
                original = %name,
                cname = %cname_target,
                "Following CNAME"
            );
            let cname_response = super::iterator::iterate(
                &cname_target,
                rtype,
                &self.inner.root_hints,
                self.inner.max_depth,
                self.inner.query_timeout,
            )
            .await?;

            let mut merged = response;
            for answer in cname_response.answers {
                if !merged.answers.contains(&answer) {
                    merged.answers.push(answer);
                }
            }
            merged.header.an_count = merged.answers.len() as u16;
            return Ok(merged);
        }

        Ok(response)
    }

    /// Forward to upstream resolvers using the connection pool.
    async fn resolve_forwarded(
        &self,
        name: &DnsName,
        rtype: RecordType,
    ) -> anyhow::Result<Message> {
        // Try the pooled forwarder first (much faster under concurrency)
        if let Some(pool) = self.get_forwarder_pool().await {
            match pool.query(name, rtype, self.inner.query_timeout).await {
                Ok(resp) => return Ok(resp),
                Err(e) => {
                    tracing::debug!(error = %e, "Pooled forwarder failed, falling back");
                }
            }
        }

        // Fallback to single-shot forwarding
        super::forwarder::forward(
            name,
            rtype,
            &self.inner.forwarders,
            self.inner.query_timeout,
        )
        .await
    }

    /// Cache a successful DNS response with bailiwick validation.
    fn cache_response(&self, key: &CacheKey, response: &Message) {
        let ttl = response
            .answers
            .iter()
            .map(|rr| rr.ttl)
            .min()
            .or_else(|| {
                response.authority.iter().find_map(|rr| {
                    if let crate::protocol::rdata::RData::SOA(soa) = &rr.rdata {
                        Some(soa.minimum)
                    } else {
                        None
                    }
                })
            })
            .unwrap_or(300);

        let negative = response.header.rcode == Rcode::NxDomain
            || (response.header.rcode == Rcode::NoError && response.answers.is_empty());

        let negative_rcode = if response.header.rcode == Rcode::NxDomain {
            Rcode::NxDomain
        } else {
            Rcode::NoError // NODATA or positive
        };

        // Bailiwick validation: only cache records that are in-bailiwick
        // for the queried name's zone OR are part of the legitimate CNAME
        // chain starting from the query name.
        //
        // Without the CNAME-chain allowance the cache would drop the chained
        // A/AAAA record (whose owner is the CNAME's target, not the query
        // name) and only keep the CNAME itself. On the next lookup the
        // resolver returns CNAME-only and clients like pkg(8) / libfetch
        // decide there's no address — the symptom we just chased on the
        // build VM ("Address family for host not supported" from
        // pkg.FreeBSD.org despite a perfectly fine upstream reply).
        let query_name = &key.name;
        let chain_names: std::collections::HashSet<DnsName> = {
            let mut set = std::collections::HashSet::new();
            set.insert(query_name.clone());
            // Walk to a fixed point — answers may be in any order so a single
            // pass isn't enough. Bounded by the answer count, so cheap.
            loop {
                let mut grew = false;
                for rr in &response.answers {
                    if !set.contains(&rr.name) { continue; }
                    if let crate::protocol::rdata::RData::CNAME(target) = &rr.rdata {
                        if set.insert(target.clone()) { grew = true; }
                    }
                }
                if !grew { break; }
            }
            set
        };
        let answers: Vec<_> = response
            .answers
            .iter()
            .filter(|rr| chain_names.contains(&rr.name) || is_in_bailiwick(&rr.name, query_name))
            .cloned()
            .collect();
        let authority: Vec<_> = response
            .authority
            .iter()
            .filter(|rr| is_in_bailiwick_authority(&rr.name, query_name))
            .cloned()
            .collect();
        let additional: Vec<_> = response
            .additional
            .iter()
            .filter(|rr| {
                // Additional records should be glue for NS names in the authority section
                authority.iter().any(|auth| {
                    if let crate::protocol::rdata::RData::NS(ns_name) = &auth.rdata {
                        rr.name == *ns_name
                    } else {
                        false
                    }
                }) || is_in_bailiwick(&rr.name, query_name)
            })
            .cloned()
            .collect();

        let entry = CacheEntry::new(answers, authority, additional, ttl, negative, negative_rcode);

        self.inner.cache.insert(key.clone(), entry);
    }

    fn build_cached_response(
        &self,
        name: &DnsName,
        rtype: RecordType,
        rclass: RecordClass,
        entry: &CacheEntry,
    ) -> Message {
        use crate::protocol::header::Header;
        use crate::protocol::opcode::Opcode;
        use crate::protocol::record::Question;

        Message {
            header: Header {
                id: 0,
                qr: true,
                opcode: Opcode::Query,
                aa: false,
                tc: false,
                rd: true,
                ra: true,
                ad: false,
                cd: false,
                rcode: if entry.negative {
                    entry.negative_rcode
                } else {
                    Rcode::NoError
                },
                qd_count: 1,
                an_count: entry.answers.len() as u16,
                ns_count: entry.authority.len() as u16,
                ar_count: entry.additional.len() as u16,
            },
            questions: vec![Question {
                name: name.clone(),
                qtype: rtype,
                qclass: rclass,
            }],
            answers: entry.answers_with_adjusted_ttl(),
            // minimal-responses: keep authority only when the client needs
            // SOA for negative caching; drop additional unconditionally.
            authority: if crate::listener::minimal_keep_authority(entry.negative) {
                entry.authority_with_adjusted_ttl()
            } else {
                Vec::new()
            },
            additional: Vec::new(),
            edns: None,
        }
    }

    /// Build a response from a stale cache entry (RFC 8767). Same shape as
    /// `build_cached_response` but every record's TTL is clamped to the
    /// configured stale-answer TTL so clients re-query quickly once upstream
    /// recovers instead of latching the stale data for its original TTL.
    fn build_stale_response(
        &self,
        name: &DnsName,
        rtype: RecordType,
        rclass: RecordClass,
        entry: &CacheEntry,
    ) -> Message {
        use crate::protocol::header::Header;
        use crate::protocol::opcode::Opcode;
        use crate::protocol::record::{Question, ResourceRecord};

        let stale_ttl = self.inner.stale_answer_ttl;
        let with_stale_ttl = |records: &[ResourceRecord]| -> Vec<ResourceRecord> {
            records
                .iter()
                .map(|rr| ResourceRecord {
                    name: rr.name.clone(),
                    rtype: rr.rtype,
                    rclass: rr.rclass,
                    ttl: stale_ttl,
                    rdata: rr.rdata.clone(),
                })
                .collect()
        };

        Message {
            header: Header {
                id: 0,
                qr: true,
                opcode: Opcode::Query,
                aa: false,
                tc: false,
                rd: true,
                ra: true,
                ad: false,
                cd: false,
                rcode: if entry.negative {
                    entry.negative_rcode
                } else {
                    Rcode::NoError
                },
                qd_count: 1,
                an_count: entry.answers.len() as u16,
                ns_count: entry.authority.len() as u16,
                ar_count: entry.additional.len() as u16,
            },
            questions: vec![Question {
                name: name.clone(),
                qtype: rtype,
                qclass: rclass,
            }],
            answers: with_stale_ttl(&entry.answers),
            authority: if crate::listener::minimal_keep_authority(entry.negative) {
                with_stale_ttl(&entry.authority)
            } else {
                Vec::new()
            },
            additional: Vec::new(),
            edns: None,
        }
    }

    fn build_servfail(
        &self,
        name: &DnsName,
        rtype: RecordType,
        rclass: RecordClass,
    ) -> Message {
        use crate::protocol::header::Header;
        use crate::protocol::opcode::Opcode;
        use crate::protocol::record::Question;

        Message {
            header: Header {
                id: 0,
                qr: true,
                opcode: Opcode::Query,
                aa: false,
                tc: false,
                rd: true,
                ra: true,
                ad: false,
                cd: false,
                rcode: Rcode::ServFail,
                qd_count: 1,
                an_count: 0,
                ns_count: 0,
                ar_count: 0,
            },
            questions: vec![Question {
                name: name.clone(),
                qtype: rtype,
                qclass: rclass,
            }],
            answers: vec![],
            authority: vec![],
            additional: vec![],
            edns: None,
        }
    }
}

/// Check if a record name is in-bailiwick for the query.
/// A record is in-bailiwick if it's the query name itself, or a parent/ancestor of it.
fn is_in_bailiwick(record_name: &DnsName, query_name: &DnsName) -> bool {
    // Answer records should match the query name (or be in a CNAME chain)
    record_name == query_name || query_name.is_subdomain_of(record_name)
}

/// Check if an authority record name is in-bailiwick.
/// Authority records should be for a parent zone of the query name.
fn is_in_bailiwick_authority(record_name: &DnsName, query_name: &DnsName) -> bool {
    query_name.is_subdomain_of(record_name) || record_name == query_name
}

/// RFC 6052 §2.2: embed an IPv4 address in the low 32 bits of a /96 prefix.
fn dns64_embed(prefix: std::net::Ipv6Addr, v4: std::net::Ipv4Addr) -> std::net::Ipv6Addr {
    let mut octets = prefix.octets();
    octets[12..16].copy_from_slice(&v4.octets());
    std::net::Ipv6Addr::from(octets)
}

/// Transform an A answer set into a DNS64 AAAA answer set (RFC 6147 §5.1):
/// CNAME chain records pass through unchanged, each A becomes a AAAA with
/// the IPv4 embedded in `prefix`, and everything else is dropped. TTLs are
/// preserved per record (the cache applies its usual min/max clamps).
fn synthesize_aaaa_records(
    answers: &[crate::protocol::record::ResourceRecord],
    prefix: std::net::Ipv6Addr,
) -> Vec<crate::protocol::record::ResourceRecord> {
    use crate::protocol::rdata::RData;
    use crate::protocol::record::ResourceRecord;
    answers
        .iter()
        .filter_map(|rr| match &rr.rdata {
            RData::A(v4) => Some(ResourceRecord {
                name: rr.name.clone(),
                rtype: RecordType::AAAA,
                rclass: rr.rclass,
                ttl: rr.ttl,
                rdata: RData::AAAA(dns64_embed(prefix, *v4)),
            }),
            RData::CNAME(_) => Some(rr.clone()),
            _ => None,
        })
        .collect()
}

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

    #[test]
    fn test_dns64_embed_well_known_prefix() {
        let prefix: std::net::Ipv6Addr = "64:ff9b::".parse().unwrap();
        assert_eq!(
            dns64_embed(prefix, "192.0.2.33".parse().unwrap()),
            "64:ff9b::c000:221".parse::<std::net::Ipv6Addr>().unwrap()
        );
        assert_eq!(
            dns64_embed(prefix, "10.99.2.2".parse().unwrap()),
            "64:ff9b::a63:202".parse::<std::net::Ipv6Addr>().unwrap()
        );
        // network-specific prefix keeps its upper 96 bits
        let nsp: std::net::Ipv6Addr = "2001:db8:2::".parse().unwrap();
        assert_eq!(
            dns64_embed(nsp, "10.99.1.1".parse().unwrap()),
            "2001:db8:2::a63:101".parse::<std::net::Ipv6Addr>().unwrap()
        );
    }

    #[test]
    fn test_dns64_synthesize_records() {
        use crate::protocol::rdata::RData;
        use crate::protocol::record::ResourceRecord;

        let prefix: std::net::Ipv6Addr = "64:ff9b::".parse().unwrap();
        let name = DnsName::from_str("v4only.example.com").unwrap();
        let cname_target = DnsName::from_str("origin.example.com").unwrap();
        let answers = vec![
            ResourceRecord {
                name: name.clone(),
                rtype: RecordType::CNAME,
                rclass: RecordClass::IN,
                ttl: 120,
                rdata: RData::CNAME(cname_target.clone()),
            },
            ResourceRecord {
                name: cname_target.clone(),
                rtype: RecordType::A,
                rclass: RecordClass::IN,
                ttl: 60,
                rdata: RData::A("192.0.2.7".parse().unwrap()),
            },
            // Non-address record in the answer set must be dropped, not
            // passed through into a AAAA answer.
            ResourceRecord {
                name: cname_target.clone(),
                rtype: RecordType::TXT,
                rclass: RecordClass::IN,
                ttl: 60,
                rdata: RData::TXT(vec![b"x".to_vec()]),
            },
        ];

        let out = synthesize_aaaa_records(&answers, prefix);
        assert_eq!(out.len(), 2, "CNAME passthrough + one synthesized AAAA");
        assert_eq!(out[0].rtype, RecordType::CNAME);
        assert_eq!(out[1].rtype, RecordType::AAAA);
        assert_eq!(out[1].ttl, 60, "AAAA keeps the A record's TTL");
        match &out[1].rdata {
            RData::AAAA(v6) => assert_eq!(
                *v6,
                "64:ff9b::c000:207".parse::<std::net::Ipv6Addr>().unwrap()
            ),
            other => panic!("expected AAAA rdata, got {other:?}"),
        }

        // A CNAME-only answer set synthesizes nothing usable.
        let cname_only = vec![answers[0].clone()];
        let out = synthesize_aaaa_records(&cname_only, prefix);
        assert!(out.iter().all(|r| r.rtype != RecordType::AAAA));
    }

    #[test]
    fn test_resolver_creation() {
        let cache = CacheStore::new(1000, 60, 86400, 300);
        let validator = DnssecValidator::new(true);
        let resolver = Resolver::new(cache, vec![], 30, validator, true, 30);
        assert!(resolver.inner.forwarders.is_empty());
        assert_eq!(resolver.inner.root_hints.len(), 13);
    }

    /// Regression: cache_response was filtering out CNAME-target records via
    /// the bailiwick check, leaving only the CNAME in cache. Subsequent
    /// lookups returned CNAME-only and clients (pkg(8) / libfetch) treated
    /// the host as having no address.
    #[test]
    fn test_cache_response_keeps_cname_chain() {
        use crate::cache::entry::CacheKey;
        use crate::protocol::header::Header;
        use crate::protocol::message::Message;
        use crate::protocol::opcode::Opcode;
        use crate::protocol::rdata::RData;
        use crate::protocol::record::{Question, RecordClass, RecordType, ResourceRecord};
        use std::net::Ipv4Addr;

        let cache = CacheStore::new(1000, 60, 86400, 300);
        let validator = DnssecValidator::new(false);
        let resolver = Resolver::new(cache.clone(), vec![], 30, validator, true, 30);

        let qname = DnsName::from_str("pkg.freebsd.org").unwrap();
        let target = DnsName::from_str("pkgmir.geo.freebsd.org").unwrap();
        let response = Message {
            header: Header {
                id: 1, qr: true, opcode: Opcode::Query,
                aa: false, tc: false, rd: true, ra: true,
                ad: false, cd: false, rcode: Rcode::NoError,
                qd_count: 1, an_count: 2, ns_count: 0, ar_count: 0,
            },
            questions: vec![Question {
                name: qname.clone(),
                qtype: RecordType::A,
                qclass: RecordClass::IN,
            }],
            answers: vec![
                ResourceRecord {
                    name: qname.clone(),
                    rtype: RecordType::CNAME,
                    rclass: RecordClass::IN,
                    ttl: 300,
                    rdata: RData::CNAME(target.clone()),
                },
                ResourceRecord {
                    name: target.clone(),
                    rtype: RecordType::A,
                    rclass: RecordClass::IN,
                    ttl: 300,
                    rdata: RData::A(Ipv4Addr::new(163, 237, 194, 42)),
                },
            ],
            authority: vec![],
            additional: vec![],
            edns: None,
        };

        let key = CacheKey::new(qname.clone(), RecordType::A, RecordClass::IN);
        resolver.cache_response(&key, &response);

        let entry = cache.lookup(&key).expect("entry should be cached");
        assert_eq!(entry.answers.len(), 2, "both CNAME and chained A must be cached");
        assert!(entry.answers.iter().any(|rr| matches!(rr.rdata, RData::A(_))),
            "chained A record must survive bailiwick filtering");
    }

    /// Cached positive answers should ship without authority/additional —
    /// stubs never use them and carrying NS / glue fills UDP budget for
    /// nothing.
    #[test]
    fn build_cached_response_drops_authority_and_additional_on_positive() {
        use crate::cache::entry::CacheEntry;
        use crate::protocol::rdata::RData;
        use crate::protocol::record::{RecordClass, RecordType, ResourceRecord};
        use std::net::Ipv4Addr;

        let cache = CacheStore::new(1000, 60, 86400, 300);
        let validator = DnssecValidator::new(false);
        let resolver = Resolver::new(cache, vec![], 30, validator, true, 30);

        let qname = DnsName::from_str("www.example.com").unwrap();
        let entry = CacheEntry {
            answers: vec![ResourceRecord {
                name: qname.clone(),
                rtype: RecordType::A,
                rclass: RecordClass::IN,
                ttl: 300,
                rdata: RData::A(Ipv4Addr::new(93, 184, 216, 34)),
            }],
            authority: vec![ResourceRecord {
                name: DnsName::from_str("example.com").unwrap(),
                rtype: RecordType::NS,
                rclass: RecordClass::IN,
                ttl: 300,
                rdata: RData::NS(DnsName::from_str("ns.example.com").unwrap()),
            }],
            additional: vec![ResourceRecord {
                name: DnsName::from_str("ns.example.com").unwrap(),
                rtype: RecordType::A,
                rclass: RecordClass::IN,
                ttl: 300,
                rdata: RData::A(Ipv4Addr::new(1, 2, 3, 4)),
            }],
            negative: false,
            negative_rcode: Rcode::NoError,
            original_ttl: 300,
            inserted_at: std::time::Instant::now(),
            hit_count: 0,
            wire: std::sync::OnceLock::new(),
        };

        let msg = resolver.build_cached_response(&qname, RecordType::A, RecordClass::IN, &entry);
        assert_eq!(msg.answers.len(), 1);
        assert!(msg.authority.is_empty(), "positive response must drop authority");
        assert!(msg.additional.is_empty(), "positive response must drop additional");
    }

    /// Negative cached responses need the SOA in authority so downstream
    /// stubs can do negative caching per RFC 2308. Additional still gets
    /// dropped.
    #[test]
    fn build_cached_response_keeps_authority_on_negative() {
        use crate::cache::entry::CacheEntry;
        use crate::protocol::rdata::{RData, SoaData};
        use crate::protocol::record::{RecordClass, RecordType, ResourceRecord};

        let cache = CacheStore::new(1000, 60, 86400, 300);
        let validator = DnssecValidator::new(false);
        let resolver = Resolver::new(cache, vec![], 30, validator, true, 30);

        let qname = DnsName::from_str("nope.example.com").unwrap();
        let entry = CacheEntry {
            answers: vec![],
            authority: vec![ResourceRecord {
                name: DnsName::from_str("example.com").unwrap(),
                rtype: RecordType::SOA,
                rclass: RecordClass::IN,
                ttl: 300,
                rdata: RData::SOA(SoaData {
                    mname: DnsName::from_str("ns.example.com").unwrap(),
                    rname: DnsName::from_str("admin.example.com").unwrap(),
                    serial: 1, refresh: 3600, retry: 900, expire: 604800, minimum: 300,
                }),
            }],
            additional: vec![],
            negative: true,
            negative_rcode: Rcode::NxDomain,
            original_ttl: 300,
            inserted_at: std::time::Instant::now(),
            hit_count: 0,
            wire: std::sync::OnceLock::new(),
        };

        let msg = resolver.build_cached_response(&qname, RecordType::A, RecordClass::IN, &entry);
        assert!(msg.answers.is_empty());
        assert_eq!(msg.authority.len(), 1, "negative response must keep SOA for RFC 2308");
        assert!(matches!(msg.authority[0].rdata, RData::SOA(_)));
        assert!(msg.additional.is_empty());
    }
}