sagittarius 0.1.0

A fast, self-hosted DNS sinkhole in a single Rust binary
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
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
913
914
915
916
917
918
919
920
921
//! DNS domain name type, QNAME codec, and RR name-skip helper.
//!
//! # Design
//!
//! ## [`Name`]
//!
//! A normalized, validated domain name.  Normalization is:
//! - ASCII letters are lowercased (DNS names are case-insensitive, RFC 4343).
//! - A trailing dot (root label) is always present in the canonical form.
//!
//! So `"Example.COM"` and `"example.com."` both normalize to `"example.com."`.
//! The [`Display`] representation is the fully-qualified form with trailing dot.
//! [`PartialEq`], [`Eq`], and [`Hash`] all operate on the normalized string, so
//! `"A.B"` and `"a.b."` compare equal and hash identically.
//!
//! ## QNAME reader (`Name::read_question`)
//!
//! Reads a wire-format name from the **question** section.  The question name
//! is always the first name in the message and therefore **can never be
//! compressed** in a well-formed packet (SPEC §2.1).  The reader enforces this
//! by rejecting any label byte with the top two bits set (`0xC0` pattern) —
//! returning [`Error::CompressionPointerInQuestion`] — rather than implementing
//! general decompression logic.
//!
//! ## QNAME writer (`Name::write`)
//!
//! Serializes a [`Name`] into a [`Writer`] as the standard length-prefixed
//! label sequence terminated by a zero byte.  Round-trips cleanly with
//! `read_question`.
//!
//! ## RR name-skip (`Name::skip_rr`)
//!
//! Advances a [`Reader`]'s cursor past a name in an **RR section**
//! (answer/authority/additional).  This is the **only** place in the codec that
//! handles compression pointers, and it does so defensively:
//!
//! - Pointers are followed only for *skipping*, never materialized.
//! - A hard cap of [`MAX_SKIP_HOPS`] pointer hops and [`MAX_SKIP_LABELS`] total
//!   label bytes processed is enforced.  A crafted pointer loop therefore always
//!   terminates with [`Error::NameSkipLimitExceeded`] rather than hanging.
//! - Forward pointers and out-of-range targets are rejected with
//!   [`Error::InvalidPointerTarget`].
//! - After a successful skip the caller's [`Reader`] cursor sits immediately
//!   after the name in the RR stream (after the 2-byte pointer if the name
//!   ended in a pointer, after the zero terminator otherwise) — ready for the
//!   next field in the sequential RR walk.

use std::{
    fmt,
    hash::{Hash, Hasher},
    str::FromStr,
};

use crate::codec::{Error, reader::Reader, writer::Writer};

// ── Limits ────────────────────────────────────────────────────────────────────

/// Maximum length of a single DNS label in bytes (RFC 1035 §2.3.4).
const MAX_LABEL_LEN: usize = 63;

/// Maximum total wire-format length of a DNS name in bytes (RFC 1035 §2.3.4).
/// This includes all length bytes and the terminating zero but excludes any
/// 2-byte compression pointer.
const MAX_NAME_WIRE_LEN: usize = 255;

/// Maximum number of compression-pointer hops allowed during [`Name::skip_rr`].
/// This caps the work done when following pointer chains, bounding loop
/// detection to a constant regardless of message size.
const MAX_SKIP_HOPS: usize = 16;

/// Maximum total number of label-content bytes visited (across all
/// pointer-followed segments) during a single [`Name::skip_rr`] call.
/// Combined with [`MAX_SKIP_HOPS`] this gives two independent caps, either of
/// which alone is sufficient to prevent unbounded work.
const MAX_SKIP_BYTES: usize = 512;

// ── Name ─────────────────────────────────────────────────────────────────────

/// A validated, normalized DNS domain name.
///
/// The name is stored in its canonical (fully-qualified, lowercase) string
/// form, e.g. `"example.com."`.  The root zone is represented as `"."`.
///
/// # Normalization
///
/// - All ASCII letters are lowercased.
/// - A trailing dot is always present.
///
/// Therefore `"Example.COM"`, `"example.com"`, and `"example.com."` are all
/// equivalent and compare/hash identically.
///
/// # Limits (RFC 1035 §2.3.4)
///
/// - Each label must be at most 63 bytes.
/// - The total wire-format encoded length must be at most 255 bytes (including
///   length bytes and the root terminator).
#[derive(Clone, Debug)]
pub struct Name {
    /// Normalized (lowercase, trailing dot) fully-qualified name string.
    /// Invariant: always ends with `'.'`; always valid per RFC 1035 limits.
    inner: Box<str>,
}

impl Name {
    /// Return the normalized string representation (always ends with `'.'`).
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.inner
    }

    // ── Internal constructor ──────────────────────────────────────────────────

    /// Construct from a pre-validated, already-normalized string.
    ///
    /// # Safety
    ///
    /// The caller must ensure:
    /// - `s` is lowercase and ends with `'.'`.
    /// - All label and total-length invariants hold.
    fn from_normalized(s: String) -> Self {
        Self {
            inner: s.into_boxed_str(),
        }
    }

    // ── Wire-format I/O ───────────────────────────────────────────────────────

    /// Read a wire-format name from the **question section** of a DNS message.
    ///
    /// Reads length-prefixed labels terminated by a zero label from `reader`.
    /// Enforces RFC 1035 label (≤ 63 bytes) and total-name (≤ 255 wire bytes)
    /// limits, and **rejects any compression pointer** (`0xC0` high-bits pattern)
    /// with [`Error::CompressionPointerInQuestion`] — the question name is never
    /// compressed (SPEC §2.1).
    ///
    /// Returns a fully normalized [`Name`] (lowercase, trailing dot).
    ///
    /// # Errors
    ///
    /// - [`Error::CompressionPointerInQuestion`] — a label length byte has its
    ///   top two bits set, indicating a compression pointer.
    /// - [`Error::LabelTooLong`] — a label length byte exceeds 63.
    /// - [`Error::NameTooLong`] — the cumulative wire length exceeds 255 bytes.
    /// - [`Error::UnexpectedEof`] — the buffer is truncated mid-name.
    pub fn read_question(reader: &mut Reader) -> Result<Self, Error> {
        let mut normalized = String::with_capacity(64);
        // wire_len tracks the cumulative wire-format size:
        // each label contributes 1 (length byte) + label bytes, plus the
        // final 0x00 root terminator.  Start at 1 to account for the root.
        let mut wire_len: usize = 1;

        loop {
            let len_byte = reader.read_u8()?;

            // Compression pointer detection: top two bits 0b11 → reject.
            // RFC 1035 §4.1.4: a label length byte with top two bits both set
            // is a compression pointer.  The question name must never be
            // compressed (SPEC §2.1).
            if len_byte & 0xC0 == 0xC0 {
                return Err(Error::CompressionPointerInQuestion);
            }

            let label_len = len_byte as usize;

            if label_len == 0 {
                // Root label — end of name.
                break;
            }

            // Enforce label length limit.
            if label_len > MAX_LABEL_LEN {
                return Err(Error::LabelTooLong(label_len));
            }

            // Accumulate wire length: 1 (length byte already counted above as
            // part of the constant `wire_len` increment below) + label bytes.
            // wire_len was pre-set to 1 for the root; here we add 1 (length
            // byte for this label) + label_len.
            wire_len = wire_len
                .checked_add(1 + label_len)
                .ok_or(Error::NameTooLong(usize::MAX))?;
            if wire_len > MAX_NAME_WIRE_LEN {
                return Err(Error::NameTooLong(wire_len));
            }

            // Read the label bytes and append to the normalized string.
            let label_bytes = reader.read_slice(label_len)?;
            for &b in label_bytes.iter() {
                normalized.push(b.to_ascii_lowercase() as char);
            }
            normalized.push('.');
        }

        // Root-only: just the trailing dot.
        if normalized.is_empty() {
            normalized.push('.');
        }

        Ok(Self::from_normalized(normalized))
    }

    /// Encode this name into `writer` in wire format.
    ///
    /// Writes length-prefixed labels terminated by a zero root label, suitable
    /// for the question section of a DNS message.  Round-trips cleanly with
    /// [`Name::read_question`].
    pub fn write(&self, writer: &mut Writer) {
        // self.inner always ends with '.'; split on '.' to get labels.
        // The trailing '.' produces a final empty string after split — skip it.
        for label in self.inner.split('.') {
            if label.is_empty() {
                // Trailing dot produces an empty final segment; root label.
                continue;
            }
            // label_len is always ≤ 63 (enforced on construction).
            writer.write_u8(label.len() as u8);
            writer.write_slice(label.as_bytes());
        }
        // Root terminator.
        writer.write_u8(0);
    }

    // ── RR name-skip ─────────────────────────────────────────────────────────

    /// Skip past a name in an **RR section** (answer/authority/additional),
    /// following compression pointers defensively.
    ///
    /// After a successful call the caller's `reader` cursor is positioned
    /// immediately **after** the name in the original stream — either after the
    /// 2-byte compression pointer (if the name ended in a pointer) or after the
    /// zero root label (if no trailing pointer).  This is the position needed
    /// for a sequential RR walk.
    ///
    /// # Pointer safety
    ///
    /// - Pointer targets must point *strictly before* the current read offset
    ///   in the message, and within the message bounds.  Forward and
    ///   out-of-range pointers are rejected with [`Error::InvalidPointerTarget`].
    /// - At most [`MAX_SKIP_HOPS`] pointer hops are followed.
    /// - At most [`MAX_SKIP_BYTES`] total label-content bytes are visited.
    ///
    /// Either cap alone is sufficient to defeat pointer loops; both are enforced
    /// as independent defence-in-depth guards.
    ///
    /// # Errors
    ///
    /// - [`Error::NameSkipLimitExceeded`] — hop or byte cap exceeded.
    /// - [`Error::InvalidPointerTarget`] — pointer target is forward or OOB.
    /// - [`Error::LabelTooLong`] — a label length byte exceeds 63.
    /// - [`Error::NameTooLong`] — total label bytes processed exceed 255.
    /// - [`Error::UnexpectedEof`] — the buffer is truncated.
    pub fn skip_rr(reader: &mut Reader) -> Result<(), Error> {
        // We maintain two cursors:
        //  - `reader` — the original stream cursor; advanced to just after the
        //    name (after pointer or after zero label).  This is what the caller
        //    sees.
        //  - `follow_pos` — used when following pointer chains.  Once we take
        //    the first pointer, the original stream cursor has already been set
        //    (to after the 2-byte pointer), and we track the followed position
        //    separately so the original cursor is not disturbed.
        //
        // The `following` flag records whether we have already fixed the
        // original cursor's post-skip position (i.e. taken the first pointer).

        let msg = reader.as_bytes().clone();
        let msg_len = msg.len();

        // Current read position within the name (may diverge from reader.pos
        // once we follow a pointer).
        let mut cur_pos = reader.position();

        // Set to true once we consume the first pointer from the original stream
        // (reader cursor already advanced past the 2-byte pointer at that point).
        let mut fixed_reader = false;

        let mut hops: usize = 0;
        let mut total_label_bytes: usize = 0;

        loop {
            // Read length byte at cur_pos.
            let len_byte = msg.get(cur_pos).copied().ok_or(Error::UnexpectedEof {
                offset: cur_pos,
                needed: 1,
                available: msg_len.saturating_sub(cur_pos),
            })?;
            cur_pos += 1;

            if len_byte & 0xC0 == 0xC0 {
                // Compression pointer: high two bits are 0b11.
                // Need one more byte for the full 14-bit offset.
                let low_byte = msg.get(cur_pos).copied().ok_or(Error::UnexpectedEof {
                    offset: cur_pos,
                    needed: 1,
                    available: msg_len.saturating_sub(cur_pos),
                })?;
                cur_pos += 1;

                // If this is the first pointer we encounter, fix the original
                // stream cursor to just after these 2 bytes.
                if !fixed_reader {
                    reader.read_slice(cur_pos - reader.position())?;
                    fixed_reader = true;
                }

                let target = u16::from_be_bytes([len_byte & 0x3F, low_byte]) as usize;

                // Pointer must point strictly backwards and within message.
                // "Strictly before cur_pos" prevents same-position loops and
                // forward pointers.  We check against the position *after*
                // consuming the 2-byte pointer word, but since the pointer
                // target must be before the pointer itself we use cur_pos
                // (which now points one-past the second byte of the pointer).
                // A valid pointer target must be < (cur_pos - 2) is too strict
                // (it could legitimately point to the byte just before the
                // pointer), so we allow target < cur_pos to catch forward
                // pointers, combined with a target-within-message check.
                if target >= msg_len {
                    return Err(Error::InvalidPointerTarget {
                        target: target as u16,
                        msg_len,
                    });
                }
                // Reject forward pointers: target must be strictly before the
                // start of this pointer word (cur_pos - 2 is where the pointer
                // started).  This prevents a pointer pointing to itself or
                // forward.
                let pointer_start = cur_pos - 2;
                if target >= pointer_start {
                    return Err(Error::InvalidPointerTarget {
                        target: target as u16,
                        msg_len,
                    });
                }

                hops += 1;
                if hops > MAX_SKIP_HOPS {
                    return Err(Error::NameSkipLimitExceeded);
                }

                // Jump: continue from the pointer target.
                cur_pos = target;
                continue;
            }

            // Reserved high-bits patterns (0b10, 0b01) — reject.
            if len_byte & 0xC0 != 0 {
                return Err(Error::LabelTooLong(len_byte as usize));
            }

            let label_len = len_byte as usize;

            if label_len == 0 {
                // Root label: end of name.
                if !fixed_reader {
                    // No pointer was encountered; advance the original cursor
                    // to include this zero byte (cur_pos already past it).
                    reader.read_slice(cur_pos - reader.position())?;
                }
                return Ok(());
            }

            // Enforce limits.
            if label_len > MAX_LABEL_LEN {
                return Err(Error::LabelTooLong(label_len));
            }

            total_label_bytes = total_label_bytes.saturating_add(label_len);
            if total_label_bytes > MAX_SKIP_BYTES {
                return Err(Error::NameSkipLimitExceeded);
            }

            // Also enforce overall name wire-length limit (not strictly required
            // for skipping but prevents accepting names that would be invalid
            // to materialize later).
            // wire length = all (1 + label_len) segments + 1 root byte.
            // We track label bytes only; add generous headroom.
            if total_label_bytes > MAX_NAME_WIRE_LEN {
                return Err(Error::NameTooLong(total_label_bytes));
            }

            // Skip the label bytes.
            cur_pos = cur_pos
                .checked_add(label_len)
                .ok_or(Error::NameSkipLimitExceeded)?;
            if cur_pos > msg_len {
                return Err(Error::UnexpectedEof {
                    offset: cur_pos - label_len,
                    needed: label_len,
                    available: msg_len.saturating_sub(cur_pos - label_len),
                });
            }

            // If we are still in the original (non-pointer-followed) stream,
            // advance the reader cursor to keep it in sync until we hit a
            // pointer or the root label.
            if !fixed_reader {
                reader.read_slice(1 + label_len)?;
            }
        }
    }
}

// ── Standard trait implementations ───────────────────────────────────────────

impl PartialEq for Name {
    fn eq(&self, other: &Self) -> bool {
        self.inner == other.inner
    }
}

impl Eq for Name {}

impl Hash for Name {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.inner.hash(state);
    }
}

impl fmt::Display for Name {
    /// Format the name in its normalized, fully-qualified form (trailing dot).
    ///
    /// # Example
    ///
    /// ```
    /// use sagittarius::codec::name::Name;
    /// let n: Name = "Example.COM".parse().unwrap();
    /// assert_eq!(n.to_string(), "example.com.");
    /// ```
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.inner)
    }
}

impl FromStr for Name {
    type Err = Error;

    /// Parse and normalize a domain name string.
    ///
    /// Accepts names with or without a trailing dot.  The root zone may be
    /// given as `"."` or `""` (empty string).
    ///
    /// # Normalization
    ///
    /// ASCII letters are lowercased; a trailing dot is appended if absent.
    ///
    /// # Errors
    ///
    /// - [`Error::LabelTooLong`] — a label exceeds 63 bytes.
    /// - [`Error::NameTooLong`] — the total wire length exceeds 255 bytes.
    /// - [`Error::EmptyLabel`] — an empty label appears in a non-root position
    ///   (e.g. `"foo..bar"`).
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        // Normalize trailing dot: strip it for parsing, re-add it at the end.
        // Special case: "." is the root.
        if s == "." || s.is_empty() {
            return Ok(Self::from_normalized(".".to_string()));
        }

        // Strip optional trailing dot for label iteration.
        let s_stripped = s.strip_suffix('.').unwrap_or(s);

        let mut normalized = String::with_capacity(s.len() + 1);
        // wire_len: 1 for root terminator, plus for each label: 1 + len.
        let mut wire_len: usize = 1;

        for label in s_stripped.split('.') {
            // Empty label in a non-terminal position.
            if label.is_empty() {
                return Err(Error::EmptyLabel);
            }

            let label_len = label.len();
            if label_len > MAX_LABEL_LEN {
                return Err(Error::LabelTooLong(label_len));
            }

            wire_len = wire_len
                .checked_add(1 + label_len)
                .ok_or(Error::NameTooLong(usize::MAX))?;
            if wire_len > MAX_NAME_WIRE_LEN {
                return Err(Error::NameTooLong(wire_len));
            }

            for c in label.chars() {
                normalized.push(c.to_ascii_lowercase());
            }
            normalized.push('.');
        }

        Ok(Self::from_normalized(normalized))
    }
}

// ── Tests ─────────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use std::collections::HashSet;

    use bytes::Bytes;

    use super::*;
    use crate::codec::{reader::Reader, writer::Writer};

    // ── Helper: encode a name to wire bytes ───────────────────────────────────

    fn wire_encode(name: &Name) -> Bytes {
        let mut w = Writer::new();
        name.write(&mut w);
        w.finish()
    }

    fn reader_from(bytes: &'static [u8]) -> Reader {
        Reader::new(Bytes::from_static(bytes))
    }

    // ── FromStr / Display ─────────────────────────────────────────────────────

    #[test]
    fn parse_simple() {
        let n: Name = "example.com".parse().unwrap();
        assert_eq!(n.to_string(), "example.com.");
    }

    #[test]
    fn parse_with_trailing_dot() {
        let n: Name = "example.com.".parse().unwrap();
        assert_eq!(n.to_string(), "example.com.");
    }

    #[test]
    fn parse_root_dot() {
        let n: Name = ".".parse().unwrap();
        assert_eq!(n.to_string(), ".");
    }

    #[test]
    fn parse_root_empty_str() {
        let n: Name = "".parse().unwrap();
        assert_eq!(n.to_string(), ".");
    }

    #[test]
    fn parse_single_label() {
        let n: Name = "localhost".parse().unwrap();
        assert_eq!(n.to_string(), "localhost.");
    }

    #[test]
    fn normalization_mixed_case() {
        let n: Name = "Example.COM".parse().unwrap();
        assert_eq!(n.to_string(), "example.com.");
    }

    #[test]
    fn normalization_uppercase_all() {
        let n: Name = "UPPER.CASE.LABELS".parse().unwrap();
        assert_eq!(n.to_string(), "upper.case.labels.");
    }

    // ── Equality / Hash on normalized form ────────────────────────────────────

    #[test]
    fn eq_case_insensitive() {
        let a: Name = "Example.COM".parse().unwrap();
        let b: Name = "example.com".parse().unwrap();
        let c: Name = "example.com.".parse().unwrap();
        assert_eq!(a, b);
        assert_eq!(b, c);
        assert_eq!(a, c);
    }

    #[test]
    fn hash_consistent_with_eq() {
        let a: Name = "Example.COM".parse().unwrap();
        let b: Name = "example.com.".parse().unwrap();
        let mut set = HashSet::new();
        set.insert(a.clone());
        // b is equal to a; inserting should not grow the set.
        assert!(!set.insert(b));
        assert_eq!(set.len(), 1);
    }

    #[test]
    fn hashset_lookup_case_insensitive() {
        let mut set: HashSet<Name> = HashSet::new();
        set.insert("blocked.example.com.".parse().unwrap());
        // Lookup with different casing should find the entry.
        let query: Name = "BLOCKED.EXAMPLE.COM".parse().unwrap();
        assert!(set.contains(&query));
    }

    // ── Label / name length limits ────────────────────────────────────────────

    #[test]
    fn label_too_long_from_str() {
        let long_label = "a".repeat(64);
        let err = Name::from_str(&long_label).unwrap_err();
        assert!(
            matches!(err, Error::LabelTooLong(64)),
            "unexpected error: {err}"
        );
    }

    #[test]
    fn label_exactly_63_ok() {
        let label = "a".repeat(63);
        let n = Name::from_str(&label).unwrap();
        assert!(n.to_string().starts_with(&label));
    }

    #[test]
    fn name_too_long_from_str() {
        // Build a name that exceeds 255 wire bytes.
        // Each label of 63 chars costs 1+63 = 64 wire bytes.
        // 4 such labels = 256 wire bytes + 1 root = 257 > 255.
        let label = "a".repeat(63);
        let long_name = format!("{label}.{label}.{label}.{label}");
        let err = Name::from_str(&long_name).unwrap_err();
        assert!(
            matches!(err, Error::NameTooLong(_)),
            "unexpected error: {err}"
        );
    }

    #[test]
    fn name_max_length_ok() {
        // 3 labels of 63 bytes = 3*(1+63) = 192, plus root = 193 — fits.
        let label = "a".repeat(63);
        let name = format!("{label}.{label}.{label}");
        assert!(Name::from_str(&name).is_ok());
    }

    #[test]
    fn empty_label_in_middle_is_error() {
        let err = Name::from_str("foo..bar").unwrap_err();
        assert!(matches!(err, Error::EmptyLabel), "unexpected error: {err}");
    }

    // ── Wire round-trip ───────────────────────────────────────────────────────

    #[test]
    fn wire_round_trip_simple() {
        let original: Name = "example.com".parse().unwrap();
        let wire = wire_encode(&original);
        let mut r = Reader::new(wire);
        let decoded = Name::read_question(&mut r).unwrap();
        assert_eq!(original, decoded);
    }

    #[test]
    fn wire_round_trip_root() {
        let original: Name = ".".parse().unwrap();
        let wire = wire_encode(&original);
        // Root encodes as a single zero byte.
        assert_eq!(&wire[..], &[0x00]);
        let mut r = Reader::new(wire);
        let decoded = Name::read_question(&mut r).unwrap();
        assert_eq!(original, decoded);
    }

    #[test]
    fn wire_round_trip_single_label() {
        let original: Name = "localhost".parse().unwrap();
        let wire = wire_encode(&original);
        // \x09 localhost \x00
        assert_eq!(wire[0], 9);
        assert_eq!(&wire[1..10], b"localhost");
        assert_eq!(wire[10], 0);
        let mut r = Reader::new(wire);
        let decoded = Name::read_question(&mut r).unwrap();
        assert_eq!(original, decoded);
    }

    #[test]
    fn wire_round_trip_multi_label() {
        let original: Name = "a.b.c.d".parse().unwrap();
        let wire = wire_encode(&original);
        let mut r = Reader::new(wire);
        let decoded = Name::read_question(&mut r).unwrap();
        assert_eq!(original, decoded);
    }

    #[test]
    fn wire_round_trip_mixed_case_normalizes() {
        let original: Name = "UPPER.CASE".parse().unwrap();
        let wire = wire_encode(&original);
        let mut r = Reader::new(wire);
        let decoded = Name::read_question(&mut r).unwrap();
        assert_eq!(decoded.to_string(), "upper.case.");
    }

    // ── Compression pointer in question → error ───────────────────────────────

    #[test]
    fn compression_pointer_in_question_rejected() {
        // Wire bytes: 0xC0 0x0C = compression pointer to offset 12.
        let mut r = reader_from(&[0xC0, 0x0C]);
        let err = Name::read_question(&mut r).unwrap_err();
        assert!(
            matches!(err, Error::CompressionPointerInQuestion),
            "unexpected error: {err}"
        );
    }

    #[test]
    fn compression_pointer_mid_question_rejected() {
        // \x03 "foo" then pointer → pointer rejected.
        let mut r = reader_from(&[0x03, b'f', b'o', b'o', 0xC0, 0x0C]);
        let err = Name::read_question(&mut r).unwrap_err();
        assert!(
            matches!(err, Error::CompressionPointerInQuestion),
            "unexpected error: {err}"
        );
    }

    // ── Wire reader: label/name too long ──────────────────────────────────────

    #[test]
    fn wire_label_too_long_rejected() {
        // Label length byte = 64 (> 63).
        let mut data = vec![64u8];
        data.extend_from_slice(&[b'a'; 64]);
        data.push(0);
        let mut r = Reader::new(Bytes::from(data));
        let err = Name::read_question(&mut r).unwrap_err();
        assert!(
            matches!(err, Error::LabelTooLong(64)),
            "unexpected error: {err}"
        );
    }

    // ── skip_rr: normal names ─────────────────────────────────────────────────

    #[test]
    fn skip_rr_simple_name_no_pointer() {
        // \x03 "www" \x07 "example" \x03 "com" \x00
        let wire: &[u8] = &[
            0x03, b'w', b'w', b'w', 0x07, b'e', b'x', b'a', b'm', b'p', b'l', b'e', 0x03, b'c',
            b'o', b'm', 0x00, // sentinel byte at position 17
            0xFF,
        ];
        let mut r = Reader::new(Bytes::from_static(wire));
        Name::skip_rr(&mut r).unwrap();
        // Cursor should be at 17 (past the 0x00, before 0xFF).
        assert_eq!(r.position(), 17);
    }

    #[test]
    fn skip_rr_root_name() {
        // Just the zero byte.
        let wire: &[u8] = &[0x00, 0xFF];
        let mut r = Reader::new(Bytes::from_static(wire));
        Name::skip_rr(&mut r).unwrap();
        assert_eq!(r.position(), 1);
    }

    #[test]
    fn skip_rr_name_ending_in_pointer() {
        // Simulate a message where the name at position 20 ends with a pointer
        // to position 12.
        //
        // Layout:
        //   bytes 0..12  : padding (e.g. a DNS header)
        //   bytes 12..16 : \x03 "com" \x00  (the pointer target)
        //   bytes 16..20 : padding
        //   bytes 20..   : \x07 "example" \xC0 \x0C  (name with trailing pointer)
        //
        // We craft a flat byte array and position the reader at offset 20.
        let mut msg = vec![0u8; 12]; // header padding
        // offset 12: \x03 "com" \x00
        msg.extend_from_slice(&[0x03, b'c', b'o', b'm', 0x00]);
        // offset 17..20: padding
        msg.extend_from_slice(&[0x00, 0x00, 0x00]);
        // offset 20: \x07 "example" \xC0 \x0C
        msg.extend_from_slice(&[0x07, b'e', b'x', b'a', b'm', b'p', b'l', b'e', 0xC0, 0x0C]);
        // sentinel
        msg.push(0xAB);

        let mut r = Reader::new(Bytes::from(msg));
        // Advance to offset 20 manually (the RR name start).
        r.read_slice(20).unwrap();
        assert_eq!(r.position(), 20);

        Name::skip_rr(&mut r).unwrap();
        // After skip: cursor should be at 30 (20 + 7 + 1 (len) + 2 (pointer) = 30).
        // 20 + [1 (len_byte) + 7 (example) + 2 (pointer)] = 30
        assert_eq!(r.position(), 30);
    }

    // ── skip_rr: pointer loop → error ─────────────────────────────────────────

    #[test]
    fn skip_rr_pointer_loop_self_terminates() {
        // Build a message where offset 12 contains a pointer to itself: \xC0\x0C.
        let mut msg = vec![0u8; 12]; // header
        msg.extend_from_slice(&[0xC0, 0x0C]); // pointer at offset 12 → 12 (self-loop)

        let mut r = Reader::new(Bytes::from(msg));
        r.read_slice(12).unwrap(); // position at 12

        let err = Name::skip_rr(&mut r).unwrap_err();
        assert!(
            matches!(
                err,
                Error::InvalidPointerTarget { .. } | Error::NameSkipLimitExceeded
            ),
            "expected pointer loop to return an error, got: {err}"
        );
    }

    #[test]
    fn skip_rr_pointer_two_cycle_terminates() {
        // Pointer at offset 12 → 14, pointer at offset 14 → 12.
        // offset 12: \xC0 \x0E  (pointer to 14)
        // offset 14: \xC0 \x0C  (pointer to 12)
        let mut msg = vec![0u8; 12];
        msg.extend_from_slice(&[0xC0, 0x0E]); // offset 12: → 14
        msg.extend_from_slice(&[0xC0, 0x0C]); // offset 14: → 12

        let mut r = Reader::new(Bytes::from(msg));
        r.read_slice(12).unwrap();

        let err = Name::skip_rr(&mut r).unwrap_err();
        assert!(
            matches!(
                err,
                Error::InvalidPointerTarget { .. } | Error::NameSkipLimitExceeded
            ),
            "expected two-cycle loop to error, got: {err}"
        );
    }

    #[test]
    fn skip_rr_forward_pointer_rejected() {
        // Pointer at offset 12 pointing to offset 20 (forward).
        let mut msg = vec![0u8; 12];
        msg.extend_from_slice(&[0xC0, 0x14]); // pointer to 20

        let mut r = Reader::new(Bytes::from(msg));
        r.read_slice(12).unwrap();

        let err = Name::skip_rr(&mut r).unwrap_err();
        assert!(
            matches!(err, Error::InvalidPointerTarget { target: 20, .. }),
            "unexpected error: {err}"
        );
    }

    #[test]
    fn skip_rr_out_of_bounds_pointer_rejected() {
        // Pointer at offset 12 pointing to offset 9999 (beyond message).
        let mut msg = vec![0u8; 12];
        msg.extend_from_slice(&[0xC0 | 0x27, 0x0F]); // 0x270F = 9999
        let mut r = Reader::new(Bytes::from(msg));
        r.read_slice(12).unwrap();

        let err = Name::skip_rr(&mut r).unwrap_err();
        assert!(
            matches!(err, Error::InvalidPointerTarget { .. }),
            "unexpected error: {err}"
        );
    }

    // ── skip_rr: truncated input ───────────────────────────────────────────────

    #[test]
    fn skip_rr_truncated_label_content() {
        // Says label is 5 bytes but only 2 bytes follow.
        let wire: &[u8] = &[0x05, b'a', b'b'];
        let mut r = Reader::new(Bytes::from_static(wire));
        let err = Name::skip_rr(&mut r).unwrap_err();
        assert!(
            matches!(err, Error::UnexpectedEof { .. }),
            "unexpected error: {err}"
        );
    }

    #[test]
    fn skip_rr_truncated_pointer() {
        // 0xC0 with no second byte.
        let wire: &[u8] = &[0xC0];
        let mut r = Reader::new(Bytes::from_static(wire));
        let err = Name::skip_rr(&mut r).unwrap_err();
        assert!(
            matches!(err, Error::UnexpectedEof { .. }),
            "unexpected error: {err}"
        );
    }

    // ── No panic on any malformed input ──────────────────────────────────────

    #[test]
    fn no_panic_empty_buffer() {
        let mut r = reader_from(&[]);
        assert!(Name::read_question(&mut r).is_err());
    }

    #[test]
    fn no_panic_skip_empty_buffer() {
        let mut r = reader_from(&[]);
        assert!(Name::skip_rr(&mut r).is_err());
    }

    #[test]
    fn no_panic_all_ones() {
        let data = vec![0xFFu8; 512];
        let mut r = Reader::new(Bytes::from(data));
        // Should error cleanly (label too long or pointer rejection), never panic.
        let _ = Name::read_question(&mut r);
    }

    #[test]
    fn no_panic_skip_all_ones() {
        // All-0xFF: first byte 0xFF has top two bits set → compression pointer
        // pattern, but the target will be out of bounds.
        let data = vec![0xFFu8; 512];
        let mut r = Reader::new(Bytes::from(data));
        let _ = Name::skip_rr(&mut r);
    }
}