oscall 0.1.1

Low-level cross-platform interface to operating system services: files, memory mapping, networking and more, with no libc on Linux
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
//! DNS messages (RFC 1035): writing a query, and reading a response that
//! came from the network and may be anything.
//!
//! Nothing here indexes a slice with a number the message gave: every
//! read goes through `get`, every loop has a bound that does not depend on
//! the message telling the truth, and a message that lies about itself is
//! `None`.

use core::net::{IpAddr, Ipv4Addr, Ipv6Addr};

/// The longest name, in the form it travels in: labels, each after its
/// length, and the empty label of the root.
pub(crate) const MAX_NAME: usize = 255;
const MAX_LABEL: usize = 63;
/// The longest message without EDNS, which is not used.
pub(crate) const MAX_UDP: usize = 512;
const HEADER: usize = 12;

pub(crate) const TYPE_A: u16 = 1;
pub(crate) const TYPE_CNAME: u16 = 5;
pub(crate) const TYPE_PTR: u16 = 12;
pub(crate) const TYPE_AAAA: u16 = 28;
const CLASS_IN: u16 = 1;

/// How many aliases are followed inside one response. A response holds
/// fewer records than that many times over, so the bound costs nothing
/// that is not a loop.
const MAX_ALIASES: usize = 16;
/// How many times a name may send its reader elsewhere in the message. A
/// name has at most 127 labels, and a pointer that is not followed by a
/// label is a pointer to a pointer: nobody writes those.
const MAX_JUMPS: usize = 127;

pub(crate) const RCODE_OK: u8 = 0;
pub(crate) const RCODE_NAME_ERROR: u8 = 3;

/// A domain name as it travels, without compression.
#[derive(Clone)]
pub(crate) struct Name {
    bytes: [u8; MAX_NAME],
    len: usize,
}

impl Name {
    const fn root() -> Self {
        let mut bytes = [0; MAX_NAME];
        bytes[0] = 0;
        Self { bytes, len: 1 }
    }

    pub(crate) fn as_bytes(&self) -> &[u8] {
        &self.bytes[..self.len]
    }

    /// Adds a label before the root, which stays the last byte.
    fn push_label(&mut self, label: &[u8]) -> Option<()> {
        if label.is_empty() || label.len() > MAX_LABEL {
            return None;
        }
        let start = self.len - 1;
        let end = start + 1 + label.len();
        // One more byte for the root.
        let slot = self.bytes.get_mut(start..end + 1)?;
        slot[0] = label.len() as u8;
        slot[1..=label.len()].copy_from_slice(label);
        slot[label.len() + 1] = 0;
        self.len = end + 1;
        Some(())
    }

    /// Adds the labels of `text`, a name written with dots, which one dot
    /// may end. `None` for an empty label, a label or a name that is too
    /// long, or a byte no host name has: only letters, digits, `-` and `_`
    /// are taken.
    pub(crate) fn push_text(&mut self, text: &[u8]) -> Option<()> {
        let text = text.strip_suffix(b".").unwrap_or(text);
        if text.is_empty() {
            return None;
        }
        for label in text.split(|&byte| byte == b'.') {
            if !label
                .iter()
                .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_'))
            {
                return None;
            }
            self.push_label(label)?;
        }
        Some(())
    }

    /// The name `text` writes.
    pub(crate) fn from_text(text: &[u8]) -> Option<Self> {
        let mut name = Self::root();
        name.push_text(text)?;
        Some(name)
    }

    /// The name under which the names that point to `addr` are kept:
    /// `4.3.2.1.in-addr.arpa`, or the 32 hexadecimal digits of an IPv6
    /// address under `ip6.arpa`.
    pub(crate) fn reverse(addr: IpAddr) -> Self {
        let mut name = Self::root();
        // The pushes cannot fail: the labels are short, and the longest
        // name of the kind has 74 bytes.
        match addr {
            IpAddr::V4(addr) => {
                for octet in addr.octets().iter().rev() {
                    let digits = [
                        b'0' + octet / 100,
                        b'0' + octet / 10 % 10,
                        b'0' + octet % 10,
                    ];
                    let skip = match *octet {
                        0..10 => 2,
                        10..100 => 1,
                        _ => 0,
                    };
                    let _ = name.push_label(&digits[skip..]);
                }
                let _ = name.push_text(b"in-addr.arpa");
            }
            IpAddr::V6(addr) => {
                const HEX: &[u8; 16] = b"0123456789abcdef";
                for octet in addr.octets().iter().rev() {
                    let _ = name.push_label(&[HEX[usize::from(octet & 15)]]);
                    let _ = name.push_label(&[HEX[usize::from(octet >> 4)]]);
                }
                let _ = name.push_text(b"ip6.arpa");
            }
        }
        name
    }

    /// Names compare without regard to the case of ASCII letters. (A
    /// length is at most 63, below every letter: comparing the bytes that
    /// way compares the labels.)
    pub(crate) fn matches(&self, other: &Self) -> bool {
        self.as_bytes().eq_ignore_ascii_case(other.as_bytes())
    }

    /// Writes the name with dots into `out`, without a last dot, and
    /// returns its length. `None` if it does not fit, is the root, or has
    /// a byte no host name has: what a server says is not printed blindly.
    pub(crate) fn to_text(&self, out: &mut [u8]) -> Option<usize> {
        let mut len = 0;
        let mut rest = self.as_bytes();
        while let [count, tail @ ..] = rest {
            if *count == 0 {
                break;
            }
            let (label, tail) = tail.split_at_checked(usize::from(*count))?;
            if !label
                .iter()
                .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_'))
            {
                return None;
            }
            if len != 0 {
                *out.get_mut(len)? = b'.';
                len += 1;
            }
            out.get_mut(len..len + label.len())?.copy_from_slice(label);
            len += label.len();
            rest = tail;
        }
        (len != 0).then_some(len)
    }

    /// Reads the name that starts at `pos` of `msg`, following the
    /// pointers that compress it, and returns it with the position after
    /// it in the place it started at.
    fn read(msg: &[u8], pos: usize) -> Option<(Self, usize)> {
        let mut name = Self::root();
        let mut at = pos;
        // Where the name ends where it started: after its first pointer.
        let mut after = None;
        let mut jumps = 0;
        loop {
            let count = usize::from(*msg.get(at)?);
            match count {
                0 => return Some((name, after.unwrap_or(at + 1))),
                1..=MAX_LABEL => {
                    let label = msg.get(at + 1..at + 1 + count)?;
                    name.push_label(label)?;
                    at += 1 + count;
                }
                // The two top bits set: the rest, and the next byte, are
                // where the name goes on.
                0xc0.. => {
                    let low = usize::from(*msg.get(at + 1)?);
                    after.get_or_insert(at + 2);
                    jumps += 1;
                    if jumps > MAX_JUMPS {
                        return None;
                    }
                    at = (count & 0x3f) << 8 | low;
                }
                // `01` and `10` are reserved.
                _ => return None,
            }
        }
    }
}

impl core::fmt::Debug for Name {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "Name({:?})", self.as_bytes())
    }
}

/// Writes a query for the records of type `qtype` of `name` to `buf`:
/// one question, recursion desired. Returns its length.
pub(crate) fn write_query(buf: &mut [u8; MAX_UDP], id: u16, name: &Name, qtype: u16) -> usize {
    let name = name.as_bytes();
    let len = HEADER + name.len() + 4;
    buf[..2].copy_from_slice(&id.to_be_bytes());
    // A standard query (`QR` 0, `OPCODE` 0), `RD` set.
    buf[2..4].copy_from_slice(&[0x01, 0x00]);
    // One question, and nothing else.
    buf[4..HEADER].copy_from_slice(&[0, 1, 0, 0, 0, 0, 0, 0]);
    buf[HEADER..HEADER + name.len()].copy_from_slice(name);
    buf[HEADER + name.len()..len - 2].copy_from_slice(&qtype.to_be_bytes());
    buf[len - 2..len].copy_from_slice(&CLASS_IN.to_be_bytes());
    len
}

fn u16_at(msg: &[u8], pos: usize) -> Option<u16> {
    let bytes = msg.get(pos..pos + 2)?;
    Some(u16::from_be_bytes([bytes[0], bytes[1]]))
}

/// What the header and the question of a response say.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct Header {
    pub(crate) rcode: u8,
    /// The message was cut to fit a datagram.
    pub(crate) truncated: bool,
    answers: u16,
    /// Where the answers start.
    start: usize,
}

/// Reads the header of `msg` as the response to the query `id` for the
/// records `qtype` of `name`. `None` if it is not that: another
/// identifier, a query, another question, or not a message at all.
pub(crate) fn parse_header(msg: &[u8], id: u16, name: &Name, qtype: u16) -> Option<Header> {
    if u16_at(msg, 0)? != id {
        return None;
    }
    let flags = u16_at(msg, 2)?;
    // `QR` must say response, and `OPCODE` standard query.
    if flags & 0x8000 == 0 || flags & 0x7800 != 0 {
        return None;
    }
    if u16_at(msg, 4)? != 1 {
        return None;
    }
    let answers = u16_at(msg, 6)?;
    // The other two counts, at 8 and 10, are of sections that are not
    // read; they must be there all the same.
    msg.get(..HEADER)?;
    let (question, pos) = Name::read(msg, HEADER)?;
    if !question.matches(name) || u16_at(msg, pos)? != qtype || u16_at(msg, pos + 2)? != CLASS_IN {
        return None;
    }
    Some(Header {
        rcode: (flags & 0xf) as u8,
        truncated: flags & 0x0200 != 0,
        answers,
        start: pos + 4,
    })
}

/// A record of the answer section.
struct Record<'a> {
    name: Name,
    rtype: u16,
    class: u16,
    /// Where its data starts in the message, for the names in it.
    data_at: usize,
    data: &'a [u8],
}

/// The records of the answer section, until the count or the message runs
/// out. An item is `None` when the message is malformed from there on.
fn records<'a>(msg: &'a [u8], header: &Header) -> impl Iterator<Item = Option<Record<'a>>> {
    let mut pos = header.start;
    let mut left = header.answers;
    let mut broken = false;
    core::iter::from_fn(move || {
        if left == 0 || broken {
            return None;
        }
        left -= 1;
        let record = (|| {
            let (name, at) = Name::read(msg, pos)?;
            let rtype = u16_at(msg, at)?;
            let class = u16_at(msg, at + 2)?;
            // Four bytes of time to live, which is not used.
            let len = usize::from(u16_at(msg, at + 8)?);
            let data_at = at + 10;
            let data = msg.get(data_at..data_at + len)?;
            pos = data_at + len;
            Some(Record {
                name,
                rtype,
                class,
                data_at,
                data,
            })
        })();
        broken = record.is_none();
        Some(record)
    })
}

/// What a response holds for a question.
#[derive(Debug, PartialEq, Eq)]
pub(crate) enum Answer {
    /// Records of the type asked for, as many as this.
    Found(usize),
    /// The name exists, or is an alias, and has no record of the type.
    Nothing,
}

/// Finds in the answers of `msg` the records `qtype` of `name`, following
/// the aliases (`CNAME`) the same message resolves, and gives the data of
/// each to `found`, with where it starts in the message. `None` if the
/// message is malformed.
fn walk(
    msg: &[u8],
    header: &Header,
    name: &Name,
    qtype: u16,
    mut found: impl FnMut(&[u8], usize) -> Option<()>,
) -> Option<Answer> {
    let mut target = name.clone();
    let mut count = 0;
    for _ in 0..MAX_ALIASES {
        let mut alias = None;
        for record in records(msg, header) {
            let record = record?;
            if record.class != CLASS_IN || !record.name.matches(&target) {
                continue;
            }
            if record.rtype == qtype {
                found(record.data, record.data_at)?;
                count += 1;
            } else if record.rtype == TYPE_CNAME && alias.is_none() {
                let (to, end) = Name::read(msg, record.data_at)?;
                // The name must be the whole of the data.
                if end != record.data_at + record.data.len() {
                    return None;
                }
                alias = Some(to);
            }
        }
        match alias {
            Some(to) if count == 0 => target = to,
            _ => break,
        }
    }
    Some(if count == 0 {
        Answer::Nothing
    } else {
        Answer::Found(count)
    })
}

/// Gives `found` the addresses `msg` has for `name`: its `A` records or
/// its `AAAA` records, as `qtype` says. `None` if the message is
/// malformed.
pub(crate) fn addresses(
    msg: &[u8],
    header: &Header,
    name: &Name,
    qtype: u16,
    mut found: impl FnMut(IpAddr),
) -> Option<Answer> {
    walk(msg, header, name, qtype, |data, _| {
        found(match qtype {
            TYPE_A => IpAddr::V4(Ipv4Addr::from(<[u8; 4]>::try_from(data).ok()?)),
            TYPE_AAAA => IpAddr::V6(Ipv6Addr::from(<[u8; 16]>::try_from(data).ok()?)),
            _ => return None,
        });
        Some(())
    })
}

/// The first name `msg` gives as what `name`, a name of
/// [`Name::reverse`], points to. `None` if the message is malformed.
pub(crate) fn pointer(msg: &[u8], header: &Header, name: &Name) -> Option<Option<Name>> {
    let mut first = None;
    walk(msg, header, name, TYPE_PTR, |data, at| {
        let (to, end) = Name::read(msg, at)?;
        if end != at + data.len() {
            return None;
        }
        first.get_or_insert(to);
        Some(())
    })?;
    Some(first)
}

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

    extern crate std;
    use std::vec::Vec;

    pub(crate) fn name(text: &str) -> Name {
        Name::from_text(text.as_bytes()).unwrap()
    }

    /// A response under construction: a header, one question, and what
    /// the test appends.
    pub(crate) struct Builder(pub(crate) Vec<u8>);

    impl Builder {
        pub(crate) fn new(id: u16, flags: u16, question: &Name, qtype: u16, answers: u16) -> Self {
            let mut msg = Vec::new();
            msg.extend_from_slice(&id.to_be_bytes());
            msg.extend_from_slice(&flags.to_be_bytes());
            msg.extend_from_slice(&1u16.to_be_bytes());
            msg.extend_from_slice(&answers.to_be_bytes());
            msg.extend_from_slice(&[0; 4]);
            msg.extend_from_slice(question.as_bytes());
            msg.extend_from_slice(&qtype.to_be_bytes());
            msg.extend_from_slice(&CLASS_IN.to_be_bytes());
            Self(msg)
        }

        /// A record whose name is written out.
        pub(crate) fn record(mut self, name: &Name, rtype: u16, data: &[u8]) -> Self {
            self.0.extend_from_slice(name.as_bytes());
            self.raw_record(rtype, data)
        }

        /// A record whose name is a pointer to `offset`.
        pub(crate) fn pointed(mut self, offset: u16, rtype: u16, data: &[u8]) -> Self {
            self.0.extend_from_slice(&(0xc000 | offset).to_be_bytes());
            self.raw_record(rtype, data)
        }

        fn raw_record(mut self, rtype: u16, data: &[u8]) -> Self {
            self.0.extend_from_slice(&rtype.to_be_bytes());
            self.0.extend_from_slice(&CLASS_IN.to_be_bytes());
            self.0.extend_from_slice(&300u32.to_be_bytes());
            self.0.extend_from_slice(&(data.len() as u16).to_be_bytes());
            self.0.extend_from_slice(data);
            self
        }
    }

    const RESPONSE: u16 = 0x8180;

    fn collect(msg: &[u8], id: u16, question: &Name, qtype: u16) -> Option<(Answer, Vec<IpAddr>)> {
        let header = parse_header(msg, id, question, qtype)?;
        let mut found = Vec::new();
        let answer = addresses(msg, &header, question, qtype, |addr| found.push(addr))?;
        Some((answer, found))
    }

    #[test]
    fn names() {
        let host = name("www.Example.com");
        assert_eq!(host.as_bytes(), b"\x03www\x07Example\x03com\0");
        assert!(host.matches(&name("WWW.example.COM.")));
        assert!(!host.matches(&name("www.example.org")));
        assert!(!host.matches(&name("ww.wexample.com")));
        let mut text = [0u8; 64];
        let len = host.to_text(&mut text).unwrap();
        assert_eq!(&text[..len], b"www.Example.com");
        assert_eq!(host.to_text(&mut text[..14]), None);
        assert_eq!(Name::root().to_text(&mut text), None);

        for bad in [
            "",
            ".",
            "a..b",
            ".a",
            "a b",
            "a/b",
            "h\u{e9}llo",
            "a\0b",
            "a,b",
        ] {
            assert!(Name::from_text(bad.as_bytes()).is_none(), "{bad:?}");
        }
        // 63 bytes are a label, 64 are not; 253 are a name, more are not.
        let label = [b'a'; 64];
        assert!(Name::from_text(&label[..63]).is_some());
        assert!(Name::from_text(&label).is_none());
        let mut long = Vec::new();
        for _ in 0..4 {
            long.extend_from_slice(&label[..62]);
            long.push(b'.');
        }
        // Four labels of 62: 252 bytes with their lengths, and the root.
        assert_eq!(Name::from_text(&long).unwrap().as_bytes().len(), 253);
        long.extend_from_slice(b"a.");
        assert_eq!(Name::from_text(&long).unwrap().as_bytes().len(), 255);
        long.extend_from_slice(b"a.");
        assert!(Name::from_text(&long).is_none());

        assert_eq!(
            Name::reverse("192.0.2.10".parse().unwrap()).as_bytes(),
            name("10.2.0.192.in-addr.arpa").as_bytes()
        );
        assert_eq!(
            Name::reverse("2001:db8::567:89ab".parse().unwrap()).as_bytes(),
            name("b.a.9.8.7.6.5.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.8.b.d.0.1.0.0.2.ip6.arpa")
                .as_bytes()
        );
    }

    #[test]
    fn queries() {
        let mut buf = [0u8; MAX_UDP];
        let host = name("example.com");
        let len = write_query(&mut buf, 0xbeef, &host, TYPE_AAAA);
        assert_eq!(
            buf[..len],
            *b"\xbe\xef\x01\x00\0\x01\0\0\0\0\0\0\x07example\x03com\0\0\x1c\0\x01"
        );
        // The longest name there is fits.
        let label = [b'a'; 63];
        let mut long = Name::root();
        for _ in 0..3 {
            long.push_label(&label).unwrap();
        }
        long.push_label(&label[..61]).unwrap();
        assert_eq!(long.as_bytes().len(), MAX_NAME);
        assert!(long.push_label(b"a").is_none());
        assert_eq!(write_query(&mut buf, 1, &long, TYPE_A), 12 + 255 + 4);
        // A query is not its own response.
        assert_eq!(parse_header(&buf[..len], 0xbeef, &host, TYPE_AAAA), None);
    }

    #[test]
    fn responses() {
        let host = name("www.example.com");
        let msg = Builder::new(7, RESPONSE, &host, TYPE_A, 2)
            .pointed(12, TYPE_A, &[192, 0, 2, 1])
            .record(&name("WWW.EXAMPLE.COM"), TYPE_A, &[192, 0, 2, 2])
            .0;
        let (answer, found) = collect(&msg, 7, &host, TYPE_A).unwrap();
        assert_eq!(answer, Answer::Found(2));
        assert_eq!(
            found,
            [
                "192.0.2.1".parse::<IpAddr>().unwrap(),
                "192.0.2.2".parse().unwrap()
            ]
        );
        // Not the response to another identifier, name or type.
        assert!(collect(&msg, 8, &host, TYPE_A).is_none());
        assert!(collect(&msg, 7, &name("example.com"), TYPE_A).is_none());
        assert!(collect(&msg, 7, &host, TYPE_AAAA).is_none());

        let header = parse_header(&msg, 7, &host, TYPE_A).unwrap();
        assert_eq!((header.rcode, header.truncated), (RCODE_OK, false));
        let cut = Builder::new(7, RESPONSE | 0x0200 | 3, &host, TYPE_A, 0).0;
        let header = parse_header(&cut, 7, &host, TYPE_A).unwrap();
        assert_eq!((header.rcode, header.truncated), (RCODE_NAME_ERROR, true));

        // Records of other names, other types and other classes are not
        // answers.
        let mut msg = Builder::new(7, RESPONSE, &host, TYPE_AAAA, 4)
            .record(&name("other.example.com"), TYPE_AAAA, &[1; 16])
            .pointed(12, TYPE_A, &[192, 0, 2, 1])
            .pointed(12, TYPE_AAAA, &[2; 16])
            .pointed(12, TYPE_AAAA, &[3; 16])
            .0;
        let class = msg.len() - 16 - 8;
        msg[class..class + 2].copy_from_slice(&3u16.to_be_bytes());
        let (answer, found) = collect(&msg, 7, &host, TYPE_AAAA).unwrap();
        assert_eq!(answer, Answer::Found(1));
        assert_eq!(found, [IpAddr::V6(Ipv6Addr::from([2; 16]))]);

        let empty = Builder::new(7, RESPONSE, &host, TYPE_A, 0).0;
        assert_eq!(
            collect(&empty, 7, &host, TYPE_A).unwrap().0,
            Answer::Nothing
        );
    }

    #[test]
    fn aliases() {
        let host = name("www.example.com");
        let (one, two) = (name("one.example.net"), name("two.example.org"));
        // In the order a server sends them, and in the other.
        for reversed in [false, true] {
            let mut records = [
                (host.clone(), TYPE_CNAME, one.as_bytes().to_vec()),
                (one.clone(), TYPE_CNAME, two.as_bytes().to_vec()),
                (two.clone(), TYPE_A, [192, 0, 2, 9].to_vec()),
                (two.clone(), TYPE_A, [192, 0, 2, 8].to_vec()),
                // Of a name nothing leads to.
                (name("three.example.org"), TYPE_A, [192, 0, 2, 7].to_vec()),
            ];
            if reversed {
                records.reverse();
            }
            let mut msg = Builder::new(1, RESPONSE, &host, TYPE_A, 5);
            for (owner, rtype, data) in &records {
                msg = msg.record(owner, *rtype, data);
            }
            let (answer, mut found) = collect(&msg.0, 1, &host, TYPE_A).unwrap();
            assert_eq!(answer, Answer::Found(2));
            found.sort();
            assert_eq!(
                found,
                [
                    "192.0.2.8".parse::<IpAddr>().unwrap(),
                    "192.0.2.9".parse().unwrap()
                ]
            );
        }

        // An alias to a name the message says nothing of.
        let msg = Builder::new(1, RESPONSE, &host, TYPE_A, 1)
            .record(&host, TYPE_CNAME, one.as_bytes())
            .0;
        assert_eq!(collect(&msg, 1, &host, TYPE_A).unwrap().0, Answer::Nothing);

        // Aliases in a circle end.
        let msg = Builder::new(1, RESPONSE, &host, TYPE_A, 2)
            .record(&host, TYPE_CNAME, one.as_bytes())
            .record(&one, TYPE_CNAME, host.as_bytes())
            .0;
        assert_eq!(collect(&msg, 1, &host, TYPE_A).unwrap().0, Answer::Nothing);
        let msg = Builder::new(1, RESPONSE, &host, TYPE_A, 1)
            .record(&host, TYPE_CNAME, host.as_bytes())
            .0;
        assert_eq!(collect(&msg, 1, &host, TYPE_A).unwrap().0, Answer::Nothing);

        // An alias whose data is not exactly a name.
        let mut data = one.as_bytes().to_vec();
        data.push(0);
        let msg = Builder::new(1, RESPONSE, &host, TYPE_A, 1)
            .record(&host, TYPE_CNAME, &data)
            .0;
        assert!(collect(&msg, 1, &host, TYPE_A).is_none());
    }

    #[test]
    fn pointers() {
        let addr = Name::reverse("192.0.2.10".parse().unwrap());
        let host = name("host.example.com");
        let msg = Builder::new(3, RESPONSE, &addr, TYPE_PTR, 2)
            .pointed(12, TYPE_PTR, host.as_bytes())
            .pointed(12, TYPE_PTR, name("other.example.com").as_bytes())
            .0;
        let header = parse_header(&msg, 3, &addr, TYPE_PTR).unwrap();
        let found = pointer(&msg, &header, &addr).unwrap().unwrap();
        assert!(found.matches(&host));

        let msg = Builder::new(3, RESPONSE, &addr, TYPE_PTR, 0).0;
        let header = parse_header(&msg, 3, &addr, TYPE_PTR).unwrap();
        assert!(pointer(&msg, &header, &addr).unwrap().is_none());

        // A name with a byte no host name has is read, and not printed.
        let msg = Builder::new(3, RESPONSE, &addr, TYPE_PTR, 1)
            .pointed(12, TYPE_PTR, b"\x04a b\n\x03com\0")
            .0;
        let header = parse_header(&msg, 3, &addr, TYPE_PTR).unwrap();
        let found = pointer(&msg, &header, &addr).unwrap().unwrap();
        assert_eq!(found.to_text(&mut [0u8; 64]), None);
    }

    /// Messages that lie: none of them is read past its end, loops, or
    /// panics.
    #[test]
    fn malformed() {
        let host = name("www.example.com");
        let good = Builder::new(7, RESPONSE, &host, TYPE_A, 2)
            .pointed(12, TYPE_A, &[192, 0, 2, 1])
            .record(&host, TYPE_A, &[192, 0, 2, 2])
            .0;
        assert!(collect(&good, 7, &host, TYPE_A).is_some());

        // Cut anywhere: either it is not a response, or it is malformed,
        // or (cut between the header and the records) it promises records
        // it does not have.
        for len in 0..good.len() {
            assert!(collect(&good[..len], 7, &host, TYPE_A).is_none(), "{len}");
        }
        // More records promised than there are.
        let mut more = good.clone();
        more[6..8].copy_from_slice(&u16::MAX.to_be_bytes());
        assert!(collect(&more, 7, &host, TYPE_A).is_none());
        // Fewer: the rest is not read.
        let mut fewer = good.clone();
        fewer[6..8].copy_from_slice(&1u16.to_be_bytes());
        assert_eq!(
            collect(&fewer, 7, &host, TYPE_A).unwrap().0,
            Answer::Found(1)
        );

        // An address of the wrong length.
        let msg = Builder::new(7, RESPONSE, &host, TYPE_A, 1)
            .pointed(12, TYPE_A, &[192, 0, 2])
            .0;
        assert!(collect(&msg, 7, &host, TYPE_A).is_none());
        let msg = Builder::new(7, RESPONSE, &host, TYPE_AAAA, 1)
            .pointed(12, TYPE_AAAA, &[0; 4])
            .0;
        assert!(collect(&msg, 7, &host, TYPE_AAAA).is_none());
        // A length of data that runs past the end.
        let mut msg = Builder::new(7, RESPONSE, &host, TYPE_A, 1)
            .pointed(12, TYPE_A, &[192, 0, 2, 1])
            .0;
        let len = msg.len() - 6;
        msg[len..len + 2].copy_from_slice(&500u16.to_be_bytes());
        assert!(collect(&msg, 7, &host, TYPE_A).is_none());

        // Pointers: to itself, to each other, past the end, forward into
        // a loop, and a chain longer than any name.
        for target in [0xc000u16 | 33, 0xc000 | 35, 0xc000 | 0x3fff] {
            let mut msg = Builder::new(7, RESPONSE, &host, TYPE_A, 1).0;
            assert_eq!(msg.len(), 33);
            msg.extend_from_slice(&target.to_be_bytes());
            msg.extend_from_slice(&(0xc000u16 | 33).to_be_bytes());
            msg.extend_from_slice(&[0; 16]);
            assert!(collect(&msg, 7, &host, TYPE_A).is_none(), "{target:#x}");
        }
        let mut msg = Builder::new(7, RESPONSE, &host, TYPE_A, 1).0;
        let start = msg.len() as u16;
        for i in 0..200u16 {
            msg.extend_from_slice(&(0xc000 | (start + 2 * i + 2)).to_be_bytes());
        }
        msg.extend_from_slice(&[0; 16]);
        assert!(collect(&msg, 7, &host, TYPE_A).is_none());
        // A name that loops through a label grows past any name.
        let mut msg = Builder::new(7, RESPONSE, &host, TYPE_A, 1).0;
        let start = msg.len() as u16;
        msg.extend_from_slice(b"\x01a");
        msg.extend_from_slice(&(0xc000 | start).to_be_bytes());
        msg.extend_from_slice(&[0; 16]);
        assert!(collect(&msg, 7, &host, TYPE_A).is_none());
        // The question itself may be the lie.
        let mut msg = good.clone();
        msg[12] = 0xc0;
        msg[13] = 12;
        assert!(collect(&msg, 7, &host, TYPE_A).is_none());
        // Reserved label types.
        for kind in [0x40u8, 0x80] {
            let mut msg = good.clone();
            msg[12] = kind | 3;
            assert!(collect(&msg, 7, &host, TYPE_A).is_none());
        }
        // Two questions, or none.
        for count in [0u16, 2] {
            let mut msg = good.clone();
            msg[4..6].copy_from_slice(&count.to_be_bytes());
            assert!(collect(&msg, 7, &host, TYPE_A).is_none());
        }
    }

    /// Bytes that mean nothing: a generator with a fixed seed, over
    /// messages that start like a response, so that the reader gets past
    /// the header often enough, and over mutations of a good one.
    #[test]
    fn noise() {
        let host = name("www.example.com");
        let good = Builder::new(7, RESPONSE, &host, TYPE_A, 3)
            .pointed(12, TYPE_CNAME, name("a.example.net").as_bytes())
            .record(&name("a.example.net"), TYPE_A, &[192, 0, 2, 1])
            .pointed(12, TYPE_A, &[192, 0, 2, 2])
            .0;
        let mut state = 0x9e37_79b9_7f4a_7c15u64;
        let mut next = move || {
            state ^= state << 13;
            state ^= state >> 7;
            state ^= state << 17;
            state
        };
        let prefix = Builder::new(7, RESPONSE, &host, TYPE_A, 0).0;
        for round in 0..20_000 {
            let mut msg = if round % 2 == 0 {
                let mut msg = prefix.clone();
                let answers = (next() % 40) as u16;
                msg[6..8].copy_from_slice(&answers.to_be_bytes());
                for _ in 0..next() % 120 {
                    // Bytes that are often pointers, lengths and types.
                    msg.push(match next() % 8 {
                        0 => 0xc0,
                        1 => 12,
                        2 => 0,
                        3 => (next() % 64) as u8,
                        4 => 1,
                        5 => 5,
                        _ => next() as u8,
                    });
                }
                msg
            } else {
                good.clone()
            };
            if round % 2 == 1 {
                for _ in 0..1 + next() % 4 {
                    let at = (next() % msg.len() as u64) as usize;
                    msg[at] = next() as u8;
                }
                msg.truncate(msg.len() - (next() % 8) as usize);
            }
            for qtype in [TYPE_A, TYPE_AAAA] {
                let _ = collect(&msg, 7, &host, qtype);
            }
            if let Some(header) = parse_header(&msg, 7, &host, TYPE_PTR) {
                let _ = pointer(&msg, &header, &host);
            }
        }
    }
}