crafter 0.3.2

Packet-level network interaction for Rust tools and agents.
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
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
//! Domain Name System protocol implementation.

use core::any::Any;
use core::ops::Div;

use crate::endian::{read_u16_be, read_u32_be};
use crate::error::{CrafterError, Result};
use crate::field::Field;
use crate::packet::{IntoPacket, Layer, LayerContext, Packet};

mod constants;
mod dnssec;
mod edns;
mod name;
mod rdata;
mod record;
mod svcb;

use rdata::decode_record_data;

pub use dnssec::DnsTypeBitmaps;
pub use edns::{edns_option_code_name, EdnsOption};
pub use name::{decode_dns_name, decode_dns_name_typed, DnsName};
pub use rdata::DnsRecordData;
pub use record::{DnsQuestion, DnsRecord};
pub use svcb::{svcb_param_key_name, SvcParam, SvcParams};

pub use constants::{
    DNS_CLASS_ANY, DNS_CLASS_CH, DNS_CLASS_HS, DNS_CLASS_IN, DNS_CLASS_NONE,
    DNS_EDNS_DEFAULT_UDP_PAYLOAD_SIZE, DNS_EDNS_FLAG_DO, DNS_EDNS_OPTION_CLIENT_SUBNET,
    DNS_EDNS_OPTION_COOKIE, DNS_EDNS_OPTION_DAU, DNS_EDNS_OPTION_DHU, DNS_EDNS_OPTION_EXPIRE,
    DNS_EDNS_OPTION_EXTENDED_ERROR, DNS_EDNS_OPTION_N3U, DNS_EDNS_OPTION_NSID,
    DNS_EDNS_OPTION_PADDING, DNS_EDNS_OPTION_TCP_KEEPALIVE, DNS_FLAG_AUTHENTIC_DATA,
    DNS_FLAG_AUTHORITATIVE, DNS_FLAG_CHECKING_DISABLED, DNS_FLAG_QR_RESPONSE,
    DNS_FLAG_RECURSION_AVAILABLE, DNS_FLAG_RECURSION_DESIRED, DNS_FLAG_TRUNCATED, DNS_HEADER_LEN,
    DNS_OPCODE_DSO, DNS_OPCODE_IQUERY, DNS_OPCODE_NOTIFY, DNS_OPCODE_QUERY, DNS_OPCODE_STATUS,
    DNS_OPCODE_UPDATE, DNS_PORT, DNS_RCODE_DSOTYPENI, DNS_RCODE_FORMERR, DNS_RCODE_NOERROR,
    DNS_RCODE_NOTAUTH, DNS_RCODE_NOTIMP, DNS_RCODE_NOTZONE, DNS_RCODE_NXDOMAIN, DNS_RCODE_NXRRSET,
    DNS_RCODE_REFUSED, DNS_RCODE_SERVFAIL, DNS_RCODE_YXDOMAIN, DNS_RCODE_YXRRSET,
    DNS_SVCB_KEY_ALPN, DNS_SVCB_KEY_DOHPATH, DNS_SVCB_KEY_ECH, DNS_SVCB_KEY_IPV4HINT,
    DNS_SVCB_KEY_IPV6HINT, DNS_SVCB_KEY_MANDATORY, DNS_SVCB_KEY_NO_DEFAULT_ALPN, DNS_SVCB_KEY_PORT,
    DNS_TYPE_A, DNS_TYPE_AAAA, DNS_TYPE_CNAME, DNS_TYPE_DNSKEY, DNS_TYPE_DS, DNS_TYPE_HTTPS,
    DNS_TYPE_MX, DNS_TYPE_NS, DNS_TYPE_NSEC, DNS_TYPE_NSEC3, DNS_TYPE_NSEC3PARAM, DNS_TYPE_OPT,
    DNS_TYPE_PTR, DNS_TYPE_RRSIG, DNS_TYPE_SOA, DNS_TYPE_SRV, DNS_TYPE_SVCB, DNS_TYPE_TLSA,
    DNS_TYPE_TXT,
};

const DNS_NAME_POINTER_MASK: u8 = 0xc0;
const DNS_NAME_POINTER_TAG: u8 = 0xc0;
const DNS_MAX_LABEL_LEN: usize = 63;
const DNS_MAX_NAME_WIRE_LEN: usize = 255;

/// Mask for the four-bit OPCODE field within the DNS flags word (bits 11-14).
const DNS_OPCODE_MASK: u16 = 0x7800;
/// Bit shift for the OPCODE field within the DNS flags word.
const DNS_OPCODE_SHIFT: u16 = 11;
/// Mask for the four-bit RCODE field within the DNS flags word (bits 0-3).
const DNS_RCODE_MASK: u16 = 0x000f;

/// Bit shift for the EXTENDED-RCODE byte (upper 8 bits) of the OPT TTL field
/// (RFC 6891 Section 6.1.3).
const DNS_EDNS_EXTENDED_RCODE_SHIFT: u32 = 24;
/// Bit shift for the VERSION byte (bits 16-23) of the OPT TTL field
/// (RFC 6891 Section 6.1.3).
const DNS_EDNS_VERSION_SHIFT: u32 = 16;
/// Mask selecting the lower 16-bit DO/Z half of the OPT TTL field.
const DNS_EDNS_FLAGS_MASK: u32 = 0x0000_ffff;

macro_rules! impl_layer_object {
    ($type:ty) => {
        fn clone_layer(&self) -> Box<dyn Layer> {
            Box::new(self.clone())
        }

        fn as_any(&self) -> &dyn Any {
            self
        }

        fn as_any_mut(&mut self) -> &mut dyn Any {
            self
        }

        fn into_any(self: Box<Self>) -> Box<dyn Any> {
            self
        }
    };
}

macro_rules! impl_layer_div {
    ($type:ty) => {
        impl<R> Div<R> for $type
        where
            R: IntoPacket,
        {
            type Output = Packet;

            fn div(self, rhs: R) -> Self::Output {
                Packet::from_layer(self).concat(rhs)
            }
        }
    };
}

/// DNS message layer.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Dns {
    id: Field<u16>,
    flags: Field<u16>,
    questions: Vec<DnsQuestion>,
    answers: Vec<DnsRecord>,
    authorities: Vec<DnsRecord>,
    additionals: Vec<DnsRecord>,
}

impl Dns {
    /// Create an empty DNS query with recursion desired enabled.
    pub fn new() -> Self {
        Self {
            id: Field::defaulted(0),
            flags: Field::defaulted(DNS_FLAG_RECURSION_DESIRED),
            questions: Vec::new(),
            answers: Vec::new(),
            authorities: Vec::new(),
            additionals: Vec::new(),
        }
    }

    /// Create a DNS query for a single name and type.
    pub fn query(name: impl Into<DnsName>, question_type: u16) -> Self {
        Self::new().question(DnsQuestion::new(name, question_type))
    }

    /// Create an A query.
    pub fn a_query(name: impl Into<DnsName>) -> Self {
        Self::query(name, DNS_TYPE_A)
    }

    /// Create an AAAA query.
    pub fn aaaa_query(name: impl Into<DnsName>) -> Self {
        Self::query(name, DNS_TYPE_AAAA)
    }

    /// Set the DNS transaction ID.
    pub fn id(mut self, id: u16) -> Self {
        self.id.set_user(id);
        self
    }

    /// Set the raw DNS flags field.
    pub fn flags(mut self, flags: u16) -> Self {
        self.flags.set_user(flags);
        self
    }

    /// Set or clear the response flag.
    pub fn response(self, enabled: bool) -> Self {
        self.set_flag(DNS_FLAG_QR_RESPONSE, enabled)
    }

    /// Set or clear the authoritative-answer flag.
    pub fn authoritative(self, enabled: bool) -> Self {
        self.set_flag(DNS_FLAG_AUTHORITATIVE, enabled)
    }

    /// Set or clear the recursion-desired flag.
    pub fn recursion_desired(self, enabled: bool) -> Self {
        self.set_flag(DNS_FLAG_RECURSION_DESIRED, enabled)
    }

    /// Compatibility alias for recursion desired.
    pub fn rd(self, enabled: bool) -> Self {
        self.recursion_desired(enabled)
    }

    /// Set or clear the recursion-available flag.
    pub fn recursion_available(self, enabled: bool) -> Self {
        self.set_flag(DNS_FLAG_RECURSION_AVAILABLE, enabled)
    }

    /// Set the four-bit OPCODE field, preserving every other flag bit.
    ///
    /// Only the low four bits of `opcode` are used; the field cannot represent
    /// values above 15. Unrelated header bits are left untouched.
    pub fn opcode(mut self, opcode: u8) -> Self {
        let field = ((opcode as u16) << DNS_OPCODE_SHIFT) & DNS_OPCODE_MASK;
        let flags = (self.flags_value() & !DNS_OPCODE_MASK) | field;
        self.flags.set_user(flags);
        self
    }

    /// Set the four-bit RCODE field, preserving every other flag bit.
    ///
    /// Only the low four bits of `rcode` are used. Extended RCODE bits carried
    /// in an EDNS(0) OPT record are out of scope here.
    pub fn rcode(mut self, rcode: u8) -> Self {
        let flags = (self.flags_value() & !DNS_RCODE_MASK) | ((rcode as u16) & DNS_RCODE_MASK);
        self.flags.set_user(flags);
        self
    }

    /// Append one DNS question.
    pub fn question(mut self, question: DnsQuestion) -> Self {
        self.questions.push(question);
        self
    }

    /// Append one DNS answer record.
    pub fn answer(mut self, answer: DnsRecord) -> Self {
        self.answers.push(answer);
        self
    }

    /// Append one DNS authority record.
    pub fn authority(mut self, authority: DnsRecord) -> Self {
        self.authorities.push(authority);
        self
    }

    /// Append one DNS additional record.
    pub fn additional(mut self, additional: DnsRecord) -> Self {
        self.additionals.push(additional);
        self
    }

    /// DNS transaction ID.
    pub fn id_value(&self) -> u16 {
        value_or_copy(&self.id, 0)
    }

    /// Raw DNS flags.
    pub fn flags_value(&self) -> u16 {
        value_or_copy(&self.flags, DNS_FLAG_RECURSION_DESIRED)
    }

    /// Return true when this message is a response.
    pub fn is_response(&self) -> bool {
        self.flags_value() & DNS_FLAG_QR_RESPONSE != 0
    }

    /// Four-bit OPCODE field extracted from the raw flags word.
    ///
    /// The value is the registry codepoint (for example [`DNS_OPCODE_QUERY`]).
    /// Unknown opcodes are returned verbatim rather than rejected.
    pub fn opcode_value(&self) -> u8 {
        ((self.flags_value() & DNS_OPCODE_MASK) >> DNS_OPCODE_SHIFT) as u8
    }

    /// Four-bit RCODE field extracted from the raw flags word.
    ///
    /// The value is the registry codepoint (for example [`DNS_RCODE_NOERROR`]).
    /// Extended RCODE bits from an EDNS(0) OPT record are not folded in here.
    pub fn rcode_value(&self) -> u8 {
        (self.flags_value() & DNS_RCODE_MASK) as u8
    }

    /// DNS questions.
    pub fn questions(&self) -> &[DnsQuestion] {
        &self.questions
    }

    /// DNS answer records.
    pub fn answers(&self) -> &[DnsRecord] {
        &self.answers
    }

    /// DNS authority records.
    pub fn authorities(&self) -> &[DnsRecord] {
        &self.authorities
    }

    /// DNS additional records.
    pub fn additionals(&self) -> &[DnsRecord] {
        &self.additionals
    }

    fn set_flag(mut self, bit: u16, enabled: bool) -> Self {
        let mut flags = self.flags_value();
        if enabled {
            flags |= bit;
        } else {
            flags &= !bit;
        }
        self.flags.set_user(flags);
        self
    }

    fn encoded_message_len(&self) -> usize {
        DNS_HEADER_LEN
            + self
                .questions
                .iter()
                .map(DnsQuestion::encoded_len)
                .sum::<usize>()
            + self
                .answers
                .iter()
                .map(DnsRecord::encoded_len)
                .sum::<usize>()
            + self
                .authorities
                .iter()
                .map(DnsRecord::encoded_len)
                .sum::<usize>()
            + self
                .additionals
                .iter()
                .map(DnsRecord::encoded_len)
                .sum::<usize>()
    }

    fn encode(&self, out: &mut Vec<u8>) -> Result<()> {
        validate_count("dns.qdcount", self.questions.len())?;
        validate_count("dns.ancount", self.answers.len())?;
        validate_count("dns.nscount", self.authorities.len())?;
        validate_count("dns.arcount", self.additionals.len())?;

        out.extend_from_slice(&self.id_value().to_be_bytes());
        out.extend_from_slice(&self.flags_value().to_be_bytes());
        out.extend_from_slice(&(self.questions.len() as u16).to_be_bytes());
        out.extend_from_slice(&(self.answers.len() as u16).to_be_bytes());
        out.extend_from_slice(&(self.authorities.len() as u16).to_be_bytes());
        out.extend_from_slice(&(self.additionals.len() as u16).to_be_bytes());

        for question in &self.questions {
            question.encode(out)?;
        }
        for answer in &self.answers {
            answer.encode(out)?;
        }
        for authority in &self.authorities {
            authority.encode(out)?;
        }
        for additional in &self.additionals {
            additional.encode(out)?;
        }
        Ok(())
    }
}

impl Default for Dns {
    fn default() -> Self {
        Self::new()
    }
}

impl Layer for Dns {
    fn name(&self) -> &'static str {
        "Dns"
    }

    fn summary(&self) -> String {
        let direction = if self.is_response() {
            "response"
        } else {
            "query"
        };
        let question = self
            .questions
            .first()
            .map(|question| {
                format!(
                    " {} {}",
                    question.name(),
                    record_type_summary(question.question_type())
                )
            })
            .unwrap_or_default();

        format!(
            "Dns(id=0x{:04x}, {direction}{question}, answers={})",
            self.id_value(),
            self.answers.len()
        )
    }

    fn inspection_fields(&self) -> Vec<(&'static str, String)> {
        vec![
            ("id", format!("0x{:04x}", self.id_value())),
            ("flags", format!("0x{:04x}", self.flags_value())),
            ("qdcount", self.questions.len().to_string()),
            ("ancount", self.answers.len().to_string()),
            ("nscount", self.authorities.len().to_string()),
            ("arcount", self.additionals.len().to_string()),
        ]
    }

    fn encoded_len(&self) -> usize {
        self.encoded_message_len()
    }

    fn compile(&self, _ctx: &LayerContext<'_>, out: &mut Vec<u8>) -> Result<()> {
        self.encode(out)
    }

    impl_layer_object!(Dns);
}

impl_layer_div!(Dns);

/// Append a decoded DNS message to an existing packet stack.
pub(crate) fn append_dns_packet(packet: Packet, bytes: &[u8]) -> Result<Packet> {
    Ok(packet.push(decode_dns(bytes)?))
}

fn decode_dns(bytes: &[u8]) -> Result<Dns> {
    if bytes.len() < DNS_HEADER_LEN {
        return Err(CrafterError::buffer_too_short(
            "dns header",
            DNS_HEADER_LEN,
            bytes.len(),
        ));
    }

    let qdcount = read_u16_be(&bytes[4..6])? as usize;
    let ancount = read_u16_be(&bytes[6..8])? as usize;
    let nscount = read_u16_be(&bytes[8..10])? as usize;
    let arcount = read_u16_be(&bytes[10..12])? as usize;

    let mut offset = DNS_HEADER_LEN;
    let mut questions = Vec::with_capacity(qdcount);
    let mut answers = Vec::with_capacity(ancount);
    let mut authorities = Vec::with_capacity(nscount);
    let mut additionals = Vec::with_capacity(arcount);

    for _ in 0..qdcount {
        let (question, next_offset) = decode_question(bytes, offset)?;
        questions.push(question);
        offset = next_offset;
    }
    for _ in 0..ancount {
        let (record, next_offset) = decode_record(bytes, offset)?;
        answers.push(record);
        offset = next_offset;
    }
    for _ in 0..nscount {
        let (record, next_offset) = decode_record(bytes, offset)?;
        authorities.push(record);
        offset = next_offset;
    }
    for _ in 0..arcount {
        let (record, next_offset) = decode_record(bytes, offset)?;
        additionals.push(record);
        offset = next_offset;
    }

    if offset != bytes.len() {
        return Err(CrafterError::invalid_field_value(
            "dns.length",
            "DNS message has trailing bytes after declared records",
        ));
    }

    Ok(Dns {
        id: Field::user(read_u16_be(&bytes[0..2])?),
        flags: Field::user(read_u16_be(&bytes[2..4])?),
        questions,
        answers,
        authorities,
        additionals,
    })
}

fn decode_question(bytes: &[u8], offset: usize) -> Result<(DnsQuestion, usize)> {
    let (name, consumed) = decode_dns_name_typed(bytes, offset)?;
    let fields_offset = offset + consumed;
    if fields_offset + 4 > bytes.len() {
        return Err(CrafterError::buffer_too_short(
            "dns question",
            fields_offset + 4,
            bytes.len(),
        ));
    }

    Ok((
        DnsQuestion {
            name,
            question_type: read_u16_be(&bytes[fields_offset..fields_offset + 2])?,
            question_class: read_u16_be(&bytes[fields_offset + 2..fields_offset + 4])?,
        },
        fields_offset + 4,
    ))
}

fn decode_record(bytes: &[u8], offset: usize) -> Result<(DnsRecord, usize)> {
    let (name, consumed) = decode_dns_name_typed(bytes, offset)?;
    let fields_offset = offset + consumed;
    if fields_offset + 10 > bytes.len() {
        return Err(CrafterError::buffer_too_short(
            "dns record",
            fields_offset + 10,
            bytes.len(),
        ));
    }

    let record_type = read_u16_be(&bytes[fields_offset..fields_offset + 2])?;
    let class = read_u16_be(&bytes[fields_offset + 2..fields_offset + 4])?;
    let ttl = read_u32_be(&bytes[fields_offset + 4..fields_offset + 8])?;
    let rdlength = read_u16_be(&bytes[fields_offset + 8..fields_offset + 10])? as usize;
    let rdata_start = fields_offset + 10;
    let rdata_end = rdata_start + rdlength;
    if rdata_end > bytes.len() {
        return Err(CrafterError::buffer_too_short(
            "dns rdata",
            rdata_end,
            bytes.len(),
        ));
    }

    let data = decode_record_data(record_type, bytes, rdata_start, rdata_end)?;
    Ok((
        DnsRecord {
            name,
            record_type,
            class,
            ttl,
            data,
        },
        rdata_end,
    ))
}

fn validate_count(field: &'static str, count: usize) -> Result<()> {
    if count > u16::MAX as usize {
        return Err(CrafterError::invalid_field_value(
            field,
            "DNS section count exceeds 65535",
        ));
    }
    Ok(())
}

fn value_or_copy<T: Copy>(field: &Field<T>, default: T) -> T {
    field.value().copied().unwrap_or(default)
}

fn record_type_summary(record_type: u16) -> String {
    match dns_type_name(record_type) {
        Some(name) => name.to_string(),
        None => format!("TYPE{record_type}"),
    }
}

/// Return the IANA registry mnemonic for a source-backed DNS RR TYPE, or
/// `None` when the value is unknown to this crate so callers can fall back to
/// a numeric `TYPE<n>` form.
pub fn dns_type_name(record_type: u16) -> Option<&'static str> {
    Some(match record_type {
        DNS_TYPE_A => "A",
        DNS_TYPE_NS => "NS",
        DNS_TYPE_CNAME => "CNAME",
        DNS_TYPE_SOA => "SOA",
        DNS_TYPE_PTR => "PTR",
        DNS_TYPE_MX => "MX",
        DNS_TYPE_TXT => "TXT",
        DNS_TYPE_AAAA => "AAAA",
        DNS_TYPE_SRV => "SRV",
        DNS_TYPE_OPT => "OPT",
        DNS_TYPE_DS => "DS",
        DNS_TYPE_RRSIG => "RRSIG",
        DNS_TYPE_NSEC => "NSEC",
        DNS_TYPE_DNSKEY => "DNSKEY",
        DNS_TYPE_NSEC3 => "NSEC3",
        DNS_TYPE_NSEC3PARAM => "NSEC3PARAM",
        DNS_TYPE_TLSA => "TLSA",
        DNS_TYPE_SVCB => "SVCB",
        DNS_TYPE_HTTPS => "HTTPS",
        _ => return None,
    })
}

#[cfg(test)]
mod dns_tests {
    use super::{
        decode_dns_name, Dns, DnsName, DnsQuestion, DnsRecord, DnsRecordData, DNS_CLASS_IN,
        DNS_FLAG_AUTHORITATIVE, DNS_FLAG_QR_RESPONSE, DNS_FLAG_RECURSION_DESIRED, DNS_TYPE_A,
        DNS_TYPE_AAAA, DNS_TYPE_CNAME, DNS_TYPE_MX, DNS_TYPE_NS, DNS_TYPE_PTR, DNS_TYPE_SRV,
        DNS_TYPE_TXT,
    };
    use crate::{Ipv4, NetworkLayer, Packet, Raw, Udp};
    use core::net::{Ipv4Addr, Ipv6Addr};

    #[test]
    fn dns_a_query_encodes_header_question_and_udp_payload() {
        let dns = Dns::a_query("example.com").id(0xbeef);
        let packet = Udp::new().sport(53001).dport(53) / dns;
        let compiled = packet.compile().unwrap();
        assert_eq!(&compiled.as_bytes()[8..10], &0xbeefu16.to_be_bytes());
        assert_eq!(
            &compiled.as_bytes()[10..12],
            &DNS_FLAG_RECURSION_DESIRED.to_be_bytes()
        );
        assert_eq!(&compiled.as_bytes()[12..14], &1u16.to_be_bytes());
        assert!(compiled.as_bytes().ends_with(&[
            7, b'e', b'x', b'a', b'm', b'p', b'l', b'e', 3, b'c', b'o', b'm', 0, 0, 1, 0, 1,
        ]));
    }

    #[test]
    fn dns_response_records_roundtrip() {
        let original = Dns::new()
            .id(0x1234)
            .response(true)
            .authoritative(true)
            .question(DnsQuestion::a("example.com."))
            .answer(DnsRecord::a(
                "example.com.",
                Ipv4Addr::new(203, 0, 113, 10),
                60,
            ))
            .answer(DnsRecord::aaaa(
                "example.com.",
                Ipv6Addr::from([0x20, 0x01, 0x0d, 0xb8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]),
                60,
            ))
            .answer(DnsRecord::cname("www.example.com.", "example.com.", 60));

        let bytes = (Ipv4::new()
            .src(Ipv4Addr::new(198, 51, 100, 53))
            .dst(Ipv4Addr::new(192, 0, 2, 10))
            / Udp::new().sport(53).dport(53001)
            / original.clone())
        .compile()
        .unwrap();
        let decoded = Packet::decode_from_l3(NetworkLayer::Ipv4, bytes.as_bytes()).unwrap();
        let dns = decoded.layer::<Dns>().unwrap();

        assert_eq!(dns.id_value(), 0x1234);
        assert_eq!(
            dns.flags_value() & (DNS_FLAG_QR_RESPONSE | DNS_FLAG_AUTHORITATIVE),
            DNS_FLAG_QR_RESPONSE | DNS_FLAG_AUTHORITATIVE
        );
        assert_eq!(dns.questions()[0].name(), "example.com.");
        assert_eq!(dns.answers().len(), 3);
        assert_eq!(
            dns.answers()[0].data(),
            &DnsRecordData::A(Ipv4Addr::new(203, 0, 113, 10))
        );
        assert_eq!(decoded.compile().unwrap(), bytes);
    }

    #[test]
    fn dns_decode_uses_udp_port_context() {
        let bytes = (Ipv4::new()
            .src(Ipv4Addr::new(192, 0, 2, 10))
            .dst(Ipv4Addr::new(198, 51, 100, 53))
            / Udp::new().sport(53001).dport(53)
            / Dns::aaaa_query("example.com").id(0x5678))
        .compile()
        .unwrap();
        let decoded = Packet::decode_from_l3(NetworkLayer::Ipv4, bytes.as_bytes()).unwrap();
        let dns = decoded.layer::<Dns>().unwrap();

        assert_eq!(dns.questions()[0].question_type(), DNS_TYPE_AAAA);
        assert_eq!(decoded.compile().unwrap(), bytes);
    }

    #[test]
    fn dns_builders_keep_common_values_visible() {
        let query = Dns::new()
            .id(7)
            .rd(false)
            .question(DnsQuestion::new("example.org", DNS_TYPE_A).qclass(DNS_CLASS_IN));

        assert_eq!(query.id_value(), 7);
        assert_eq!(query.flags_value() & DNS_FLAG_RECURSION_DESIRED, 0);
        assert_eq!(query.questions()[0].name(), "example.org.");
        assert_eq!(query.questions()[0].question_class(), DNS_CLASS_IN);
    }

    #[test]
    fn dns_compressed_name_decode_is_exposed() {
        let message = [
            3, b'w', b'w', b'w', 7, b'e', b'x', b'a', b'm', b'p', b'l', b'e', 3, b'c', b'o', b'm',
            0, 4, b'm', b'a', b'i', b'l', 0xc0, 4,
        ];

        assert_eq!(
            decode_dns_name(&message, 0).unwrap(),
            ("www.example.com.".to_string(), 17)
        );
        assert_eq!(
            decode_dns_name(&message, 17).unwrap(),
            ("mail.example.com.".to_string(), 7)
        );
    }

    #[test]
    fn non_text_owner_name_round_trips_through_a_compiled_packet() {
        // An owner name with a non-UTF-8 label must survive build -> compile ->
        // decode -> recompile with its exact wire bytes intact, exercising the
        // byte-preserving name path end to end through the packet stack.
        let owner = DnsName::from_labels([vec![0x00u8, 0xff], b"example".to_vec()]).unwrap();
        assert!(!owner.is_text());

        let record = DnsRecord::new(
            owner.clone(),
            DNS_TYPE_TXT,
            DNS_CLASS_IN,
            300,
            DnsRecordData::txt(b"v"),
        );
        let original = Dns::new().id(0x4242).response(true).answer(record);

        let bytes = (Ipv4::new()
            .src(Ipv4Addr::new(198, 51, 100, 53))
            .dst(Ipv4Addr::new(192, 0, 2, 10))
            / Udp::new().sport(53).dport(53001)
            / original)
            .compile()
            .unwrap();

        let decoded = Packet::decode_from_l3(NetworkLayer::Ipv4, bytes.as_bytes()).unwrap();
        let dns = decoded.layer::<Dns>().unwrap();
        let answer = &dns.answers()[0];

        // Exact wire-label bytes are preserved, and the presentation string uses
        // the documented \DDD escaping for the non-text octets.
        assert_eq!(answer.name_labels(), owner.labels());
        assert_eq!(answer.dns_name(), &owner);
        // Each label is escaped independently and dot-separated, so the
        // non-text first label and the text second label render as one name.
        assert_eq!(answer.name(), "\\000\\255.example.");
        assert_eq!(decoded.compile().unwrap(), bytes);
    }

    #[test]
    fn dns_compression_decodes_then_recompiles_uncompressed() {
        // A handcrafted DNS response whose owner names and embedded RDATA
        // <domain-name> fields are compression pointers (0xC0 0x0C) back to the
        // question name "example.com." at the fixed 12-octet offset. libcrafter
        // must follow each pointer on decode and then re-emit every name
        // uncompressed on recompile, so the decoded DNS-name model is preserved
        // while the recompiled wire bytes intentionally differ from the
        // compressed input (the deterministic uncompressed encoder owns output
        // form). This mirrors the reference-backed `dns-compressed-names` oracle case.
        let message: &[u8] = &[
            // Header: id=0x1234, flags=0x8180 (response, RD, RA), qd=1, an=3.
            0x12, 0x34, 0x81, 0x80, 0x00, 0x01, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00,
            // Question at offset 12: example.com. A IN.
            7, b'e', b'x', b'a', b'm', b'p', b'l', b'e', 3, b'c', b'o', b'm', 0, //
            0x00, 0x01, 0x00, 0x01, //
            // Answer 1 CNAME: owner = pointer(12); RDATA = "alias" + pointer(12).
            0xc0, 0x0c, 0x00, 0x05, 0x00, 0x01, 0x00, 0x00, 0x01, 0x2c, 0x00, 0x08, //
            5, b'a', b'l', b'i', b'a', b's', 0xc0, 0x0c, //
            // Answer 2 MX: owner = pointer(12); RDATA = pref(10) + "mail" + ptr.
            0xc0, 0x0c, 0x00, 0x0f, 0x00, 0x01, 0x00, 0x00, 0x01, 0x2c, 0x00, 0x09, //
            0x00, 0x0a, 4, b'm', b'a', b'i', b'l', 0xc0, 0x0c, //
            // Answer 3 SRV: owner = "_sip._tcp" + pointer(12); RDATA = prio/
            // weight/port + "sip" + pointer(12).
            4, b'_', b's', b'i', b'p', 4, b'_', b't', b'c', b'p', 0xc0, 0x0c, //
            0x00, 0x21, 0x00, 0x01, 0x00, 0x00, 0x01, 0x2c, 0x00, 0x0c, //
            0x00, 0x0a, 0x00, 0x05, 0x16, 0x2c, 3, b's', b'i', b'p', 0xc0, 0x0c,
        ];

        // Carry the handcrafted compressed DNS payload as a raw UDP body so
        // compile() auto-fills the IPv4/UDP lengths and checksums, then decode it
        // through the packet entrypoint with port-53 context so the DNS layer
        // parses the compressed message.
        let wire = (Ipv4::new()
            .src(Ipv4Addr::new(198, 51, 100, 53))
            .dst(Ipv4Addr::new(192, 0, 2, 10))
            / Udp::new().sport(53).dport(53001)
            / Raw::from_bytes(message))
        .compile()
        .unwrap();
        let decoded = Packet::decode_from_l3(NetworkLayer::Ipv4, wire.as_bytes()).unwrap();
        let dns = decoded.layer::<Dns>().unwrap();

        // Every compressed name decompressed to its full presentation form.
        assert_eq!(dns.questions()[0].name(), "example.com.");
        assert_eq!(dns.answers().len(), 3);
        assert_eq!(dns.answers()[0].name(), "example.com.");
        assert_eq!(dns.answers()[0].record_type(), DNS_TYPE_CNAME);
        match dns.answers()[0].data() {
            DnsRecordData::Name(name) => assert_eq!(name.presentation(), "alias.example.com."),
            other => panic!("expected CNAME name, got {other:?}"),
        }
        assert_eq!(dns.answers()[1].record_type(), DNS_TYPE_MX);
        match dns.answers()[1].data() {
            DnsRecordData::Mx {
                preference,
                exchange,
            } => {
                assert_eq!(*preference, 10);
                assert_eq!(exchange.presentation(), "mail.example.com.");
            }
            other => panic!("expected MX, got {other:?}"),
        }
        assert_eq!(dns.answers()[2].name(), "_sip._tcp.example.com.");
        assert_eq!(dns.answers()[2].record_type(), DNS_TYPE_SRV);
        match dns.answers()[2].data() {
            DnsRecordData::Srv {
                priority,
                weight,
                port,
                target,
            } => {
                assert_eq!((*priority, *weight, *port), (10, 5, 5676));
                assert_eq!(target.presentation(), "sip.example.com.");
            }
            other => panic!("expected SRV, got {other:?}"),
        }

        // Re-encode the decoded DNS model into a fresh datagram. The decoder set
        // the original (compressed) UDP length on the decoded packet, so building
        // a new packet lets compile() auto-fill the larger uncompressed lengths
        // and checksums. The deterministic encoder emits every name uncompressed,
        // so the recompiled DNS payload carries no compression pointer.
        let recompiled = (Ipv4::new()
            .src(Ipv4Addr::new(198, 51, 100, 53))
            .dst(Ipv4Addr::new(192, 0, 2, 10))
            / Udp::new().sport(53).dport(53001)
            / dns.clone())
        .compile()
        .unwrap();
        let dns_payload = &recompiled.as_bytes()[28..];
        // The uncompressed encode is strictly larger than the compressed input.
        assert!(dns_payload.len() > message.len());
        assert!(
            !dns_payload.iter().any(|&b| b & 0xc0 == 0xc0),
            "recompiled DNS payload must not contain a compression pointer",
        );

        // The decoded DNS-name model is stable across the recompile: decoding the
        // uncompressed re-encode yields the same names, so normalization agrees
        // even though the wire bytes changed.
        let redecoded = Packet::decode_from_l3(NetworkLayer::Ipv4, recompiled.as_bytes()).unwrap();
        let redns = redecoded.layer::<Dns>().unwrap();
        assert_eq!(redns.answers().len(), 3);
        assert_eq!(redns.questions()[0].name(), "example.com.");
        assert_eq!(redns.answers()[0].data(), dns.answers()[0].data());
        assert_eq!(redns.answers()[1].data(), dns.answers()[1].data());
        assert_eq!(redns.answers()[2].data(), dns.answers()[2].data());
        assert_eq!(redns.answers()[2].name(), "_sip._tcp.example.com.");
    }

    #[test]
    fn name_records_round_trip_through_a_compiled_packet() {
        // NS, CNAME, and PTR all carry their RDATA as a single nested
        // <domain-name>, so all three map to DnsRecordData::Name. This mirrors
        // the reference-backed `dns-name-records` oracle case: an authoritative
        // response with one NS answer, one CNAME answer, and one PTR answer,
        // plus a root-adjacent target so a one-label-from-root name is
        // exercised. The whole message must survive build -> compile -> decode
        // -> recompile with byte-identical wire bytes because every name is
        // emitted uncompressed.
        let original = Dns::new()
            .id(0x4e43)
            .response(true)
            .authoritative(true)
            .question(DnsQuestion::new("example.com.", DNS_TYPE_NS).qclass(DNS_CLASS_IN))
            .answer(DnsRecord::new(
                "example.com.",
                DNS_TYPE_NS,
                DNS_CLASS_IN,
                3600,
                DnsRecordData::name("ns1.example.com."),
            ))
            // Root-adjacent CNAME target: a single label directly under the root.
            .answer(DnsRecord::cname("www.example.com.", "host.example.", 300))
            .answer(DnsRecord::new(
                "20.113.0.203.in-addr.arpa.",
                DNS_TYPE_PTR,
                DNS_CLASS_IN,
                300,
                DnsRecordData::name("host.example.com."),
            ));

        let bytes = (Ipv4::new()
            .src(Ipv4Addr::new(198, 51, 100, 53))
            .dst(Ipv4Addr::new(192, 0, 2, 10))
            / Udp::new().sport(53).dport(53001)
            / original.clone())
        .compile()
        .unwrap();
        let decoded = Packet::decode_from_l3(NetworkLayer::Ipv4, bytes.as_bytes()).unwrap();
        let dns = decoded.layer::<Dns>().unwrap();

        assert_eq!(dns.questions()[0].name(), "example.com.");
        assert_eq!(dns.questions()[0].question_type(), DNS_TYPE_NS);
        assert_eq!(dns.answers().len(), 3);

        assert_eq!(dns.answers()[0].record_type(), DNS_TYPE_NS);
        match dns.answers()[0].data() {
            DnsRecordData::Name(name) => assert_eq!(name.presentation(), "ns1.example.com."),
            other => panic!("expected NS name, got {other:?}"),
        }

        assert_eq!(dns.answers()[1].record_type(), DNS_TYPE_CNAME);
        assert_eq!(dns.answers()[1].name(), "www.example.com.");
        match dns.answers()[1].data() {
            DnsRecordData::Name(name) => assert_eq!(name.presentation(), "host.example."),
            other => panic!("expected CNAME name, got {other:?}"),
        }

        assert_eq!(dns.answers()[2].record_type(), DNS_TYPE_PTR);
        assert_eq!(dns.answers()[2].name(), "20.113.0.203.in-addr.arpa.");
        match dns.answers()[2].data() {
            DnsRecordData::Name(name) => assert_eq!(name.presentation(), "host.example.com."),
            other => panic!("expected PTR name, got {other:?}"),
        }

        // Uncompressed encode is deterministic, so the recompile is byte-exact.
        assert_eq!(decoded.compile().unwrap(), bytes);
    }

    #[test]
    fn compressed_name_records_normalize_to_uncompressed_model() {
        // A handcrafted DNS response whose NS, CNAME, and PTR owner names and
        // embedded RDATA <domain-name> fields are compression pointers
        // (0xC0 0x0C) back to the question name "example.com." at offset 12.
        // libcrafter follows each pointer on decode, so the decoded
        // DnsRecordData::Name model matches the uncompressed `dns-name-records`
        // case even though the input wire bytes differ. This is the normalized
        // companion to the strict-bytes oracle case.
        let message: &[u8] = &[
            // Header: id=0x4e43, flags=0x8400 (response, AA), qd=1, an=3.
            0x4e, 0x43, 0x84, 0x00, 0x00, 0x01, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00,
            // Question at offset 12: example.com. NS IN.
            7, b'e', b'x', b'a', b'm', b'p', b'l', b'e', 3, b'c', b'o', b'm', 0, //
            0x00, 0x02, 0x00, 0x01, //
            // Answer 1 NS: owner = pointer(12); RDATA = "ns1" + pointer(12).
            0xc0, 0x0c, 0x00, 0x02, 0x00, 0x01, 0x00, 0x00, 0x0e, 0x10, 0x00, 0x06, //
            3, b'n', b's', b'1', 0xc0, 0x0c, //
            // Answer 2 CNAME: owner = "www" + pointer(12); RDATA = "host" + ptr.
            3, b'w', b'w', b'w', 0xc0, 0x0c, //
            0x00, 0x05, 0x00, 0x01, 0x00, 0x00, 0x01, 0x2c, 0x00, 0x07, //
            4, b'h', b'o', b's', b't', 0xc0, 0x0c, //
            // Answer 3 PTR: owner = "ptr" + pointer(12); RDATA = "host" + ptr.
            3, b'p', b't', b'r', 0xc0, 0x0c, //
            0x00, 0x0c, 0x00, 0x01, 0x00, 0x00, 0x01, 0x2c, 0x00, 0x07, //
            4, b'h', b'o', b's', b't', 0xc0, 0x0c,
        ];

        let wire = (Ipv4::new()
            .src(Ipv4Addr::new(198, 51, 100, 53))
            .dst(Ipv4Addr::new(192, 0, 2, 10))
            / Udp::new().sport(53).dport(53001)
            / Raw::from_bytes(message))
        .compile()
        .unwrap();
        let decoded = Packet::decode_from_l3(NetworkLayer::Ipv4, wire.as_bytes()).unwrap();
        let dns = decoded.layer::<Dns>().unwrap();

        assert_eq!(dns.questions()[0].name(), "example.com.");
        assert_eq!(dns.answers().len(), 3);

        assert_eq!(dns.answers()[0].name(), "example.com.");
        assert_eq!(dns.answers()[0].record_type(), DNS_TYPE_NS);
        match dns.answers()[0].data() {
            DnsRecordData::Name(name) => assert_eq!(name.presentation(), "ns1.example.com."),
            other => panic!("expected NS name, got {other:?}"),
        }

        assert_eq!(dns.answers()[1].name(), "www.example.com.");
        assert_eq!(dns.answers()[1].record_type(), DNS_TYPE_CNAME);
        match dns.answers()[1].data() {
            DnsRecordData::Name(name) => assert_eq!(name.presentation(), "host.example.com."),
            other => panic!("expected CNAME name, got {other:?}"),
        }

        assert_eq!(dns.answers()[2].name(), "ptr.example.com.");
        assert_eq!(dns.answers()[2].record_type(), DNS_TYPE_PTR);
        match dns.answers()[2].data() {
            DnsRecordData::Name(name) => assert_eq!(name.presentation(), "host.example.com."),
            other => panic!("expected PTR name, got {other:?}"),
        }

        // The decoded model recompiles uncompressed: every name is emitted in
        // full, so the recompiled DNS payload carries no compression pointer and
        // the decoded name model is stable across the round trip.
        let recompiled = (Ipv4::new()
            .src(Ipv4Addr::new(198, 51, 100, 53))
            .dst(Ipv4Addr::new(192, 0, 2, 10))
            / Udp::new().sport(53).dport(53001)
            / dns.clone())
        .compile()
        .unwrap();
        let dns_payload = &recompiled.as_bytes()[28..];
        assert!(dns_payload.len() > message.len());
        assert!(
            !dns_payload.iter().any(|&b| b & 0xc0 == 0xc0),
            "recompiled DNS payload must not contain a compression pointer",
        );

        let redecoded = Packet::decode_from_l3(NetworkLayer::Ipv4, recompiled.as_bytes()).unwrap();
        let redns = redecoded.layer::<Dns>().unwrap();
        assert_eq!(redns.answers().len(), 3);
        assert_eq!(redns.answers()[0].data(), dns.answers()[0].data());
        assert_eq!(redns.answers()[1].data(), dns.answers()[1].data());
        assert_eq!(redns.answers()[2].data(), dns.answers()[2].data());
    }

    #[test]
    fn dns_type_mismatch_is_rejected() {
        let record = DnsRecord::new(
            "example.com.",
            DNS_TYPE_CNAME,
            DNS_CLASS_IN,
            60,
            DnsRecordData::A(Ipv4Addr::new(203, 0, 113, 1)),
        );
        assert!(Packet::from_layer(Dns::new().answer(record))
            .compile()
            .is_err());
    }
}

#[cfg(test)]
mod dns_header_codepoints {
    use super::{
        dns_type_name, Dns, DnsQuestion, DnsRecord, DnsRecordData, DNS_CLASS_ANY, DNS_CLASS_CH,
        DNS_CLASS_HS, DNS_CLASS_IN, DNS_CLASS_NONE, DNS_FLAG_AUTHENTIC_DATA,
        DNS_FLAG_AUTHORITATIVE, DNS_FLAG_CHECKING_DISABLED, DNS_FLAG_QR_RESPONSE,
        DNS_FLAG_RECURSION_AVAILABLE, DNS_FLAG_RECURSION_DESIRED, DNS_FLAG_TRUNCATED,
        DNS_OPCODE_QUERY, DNS_OPCODE_STATUS, DNS_OPCODE_UPDATE, DNS_RCODE_NOERROR,
        DNS_RCODE_NXDOMAIN, DNS_RCODE_REFUSED, DNS_TYPE_A, DNS_TYPE_AAAA, DNS_TYPE_HTTPS,
        DNS_TYPE_MX, DNS_TYPE_NS, DNS_TYPE_OPT, DNS_TYPE_SOA, DNS_TYPE_SRV, DNS_TYPE_TXT,
    };
    use crate::{Ipv4, NetworkLayer, Packet, Udp};
    use std::net::Ipv4Addr;

    #[test]
    fn existing_flag_helpers_compile_identically() {
        // A response with AA set built through the existing helpers must produce
        // the same flags word it did before opcode/rcode helpers existed.
        let dns = Dns::new()
            .id(0xbeef)
            .response(true)
            .authoritative(true)
            .question(DnsQuestion::a("example.com."));
        let compiled = (Udp::new().sport(53001).dport(53) / dns).compile().unwrap();

        let expected_flags =
            DNS_FLAG_QR_RESPONSE | DNS_FLAG_AUTHORITATIVE | DNS_FLAG_RECURSION_DESIRED;
        assert_eq!(&compiled.as_bytes()[10..12], &expected_flags.to_be_bytes());
    }

    #[test]
    fn opcode_setter_preserves_unrelated_bits() {
        let dns = Dns::new()
            .response(true)
            .authoritative(true)
            .rcode(DNS_RCODE_NXDOMAIN)
            .opcode(DNS_OPCODE_UPDATE);

        // OPCODE is set without disturbing QR, AA, RD, or the RCODE nibble.
        assert_eq!(dns.opcode_value(), DNS_OPCODE_UPDATE);
        assert!(dns.is_response());
        assert_ne!(dns.flags_value() & DNS_FLAG_AUTHORITATIVE, 0);
        assert_ne!(dns.flags_value() & DNS_FLAG_RECURSION_DESIRED, 0);
        assert_eq!(dns.rcode_value(), DNS_RCODE_NXDOMAIN);
    }

    #[test]
    fn rcode_setter_preserves_unrelated_bits() {
        let dns = Dns::new()
            .opcode(DNS_OPCODE_STATUS)
            .response(true)
            .rcode(DNS_RCODE_REFUSED);

        assert_eq!(dns.rcode_value(), DNS_RCODE_REFUSED);
        assert_eq!(dns.opcode_value(), DNS_OPCODE_STATUS);
        assert!(dns.is_response());
    }

    #[test]
    fn opcode_and_rcode_defaults_are_query_noerror() {
        let dns = Dns::new();
        assert_eq!(dns.opcode_value(), DNS_OPCODE_QUERY);
        assert_eq!(dns.rcode_value(), DNS_RCODE_NOERROR);
    }

    #[test]
    fn unknown_opcode_and_rcode_values_round_trip() {
        // Values outside the named registry entries must remain representable.
        let dns = Dns::new().opcode(0xf).rcode(0xf);
        assert_eq!(dns.opcode_value(), 0xf);
        assert_eq!(dns.rcode_value(), 0xf);

        // Only the low four bits of each field are honored; higher bits are
        // masked off rather than corrupting neighbouring fields.
        let truncated = Dns::new().opcode(0xff).rcode(0xff);
        assert_eq!(truncated.opcode_value(), 0xf);
        assert_eq!(truncated.rcode_value(), 0xf);
    }

    #[test]
    fn raw_flags_remain_the_escape_hatch() {
        // flags() sets the whole word verbatim, including unusual combinations,
        // and flags_value() reflects it untouched.
        let dns = Dns::new().flags(0xabcd);
        assert_eq!(dns.flags_value(), 0xabcd);
        // Extracted fields reflect the raw word without rejecting it.
        assert_eq!(dns.opcode_value(), ((0xabcd & 0x7800) >> 11) as u8);
        assert_eq!(dns.rcode_value(), (0xabcd & 0x000f) as u8);
    }

    #[test]
    fn all_named_header_flag_bits_survive_compile_and_decode() {
        // Every named header flag constant set together must round-trip through
        // compile and decode untouched, including the authentic-data and
        // checking-disabled bits that have no dedicated setter.
        let all_named = DNS_FLAG_AUTHORITATIVE
            | DNS_FLAG_TRUNCATED
            | DNS_FLAG_RECURSION_DESIRED
            | DNS_FLAG_RECURSION_AVAILABLE
            | DNS_FLAG_AUTHENTIC_DATA
            | DNS_FLAG_CHECKING_DISABLED;
        let dns = Dns::new()
            .flags(all_named)
            .question(DnsQuestion::a("example.com."));

        let bytes = (Ipv4::new()
            .src(Ipv4Addr::new(203, 0, 113, 1))
            .dst(Ipv4Addr::new(198, 51, 100, 1))
            / Udp::new().sport(53001).dport(53)
            / dns)
            .compile()
            .unwrap();
        let decoded = Packet::decode_from_l3(NetworkLayer::Ipv4, bytes.as_bytes()).unwrap();
        let header = decoded.layer::<Dns>().unwrap();

        assert_eq!(header.flags_value(), all_named);
        assert_ne!(header.flags_value() & DNS_FLAG_AUTHENTIC_DATA, 0);
        assert_ne!(header.flags_value() & DNS_FLAG_CHECKING_DISABLED, 0);
        assert_eq!(decoded.compile().unwrap(), bytes);
    }

    #[test]
    fn recursion_available_setter_sets_only_its_bit() {
        // The recursion-available setter must light its own flag without
        // disturbing the recursion-desired default or other bits.
        let dns = Dns::new().recursion_available(true);
        assert_ne!(dns.flags_value() & DNS_FLAG_RECURSION_AVAILABLE, 0);
        assert_ne!(dns.flags_value() & DNS_FLAG_RECURSION_DESIRED, 0);
        assert_eq!(
            dns.flags_value() & !(DNS_FLAG_RECURSION_AVAILABLE | DNS_FLAG_RECURSION_DESIRED),
            0
        );
    }

    #[test]
    fn section_counts_auto_fill_from_typed_vectors() {
        // Each section's count is derived from the typed vectors at compile
        // time; placing one record in every response section yields counts of
        // one across the header.
        let dns = Dns::new()
            .response(true)
            .question(DnsQuestion::a("example.com."))
            .answer(DnsRecord::a(
                "example.com.",
                Ipv4Addr::new(192, 0, 2, 10),
                60,
            ))
            .authority(DnsRecord::cname("example.com.", "ns1.example.com.", 300))
            .additional(DnsRecord::a(
                "ns1.example.com.",
                Ipv4Addr::new(192, 0, 2, 53),
                300,
            ));

        let bytes = (Ipv4::new()
            .src(Ipv4Addr::new(203, 0, 113, 1))
            .dst(Ipv4Addr::new(198, 51, 100, 1))
            / Udp::new().sport(53).dport(53001)
            / dns)
            .compile()
            .unwrap();
        let decoded = Packet::decode_from_l3(NetworkLayer::Ipv4, bytes.as_bytes()).unwrap();
        let header = decoded.layer::<Dns>().unwrap();

        // QDCOUNT/ANCOUNT/NSCOUNT/ARCOUNT each reflect exactly one vector entry.
        assert_eq!(header.questions().len(), 1);
        assert_eq!(header.answers().len(), 1);
        assert_eq!(header.authorities().len(), 1);
        assert_eq!(header.additionals().len(), 1);
        assert_eq!(decoded.compile().unwrap(), bytes);
    }

    #[test]
    fn section_placement_survives_decode_and_recompile() {
        // A single authoritative response that places a record in every DNS
        // section (RFC 1035 Section 4.1): one A answer, one NS authority record,
        // and two additional records - an EDNS(0) OPT pseudo-record (RFC 6891)
        // plus a non-OPT A glue record. Decode must keep each record in its own
        // section without migration, the OPT must stay in the additional section
        // next to the non-OPT record, and recompile must reproduce the exact wire
        // bytes. This mirrors the dns-section-placement oracle case.
        let dns = Dns::new()
            .id(0x5023)
            .response(true)
            .authoritative(true)
            .question(DnsQuestion::a("example.com."))
            .answer(DnsRecord::a(
                "example.com.",
                Ipv4Addr::new(192, 0, 2, 10),
                3600,
            ))
            .authority(DnsRecord::new(
                "example.com.",
                DNS_TYPE_NS,
                DNS_CLASS_IN,
                3600,
                DnsRecordData::name("ns1.example.com."),
            ))
            .additional(DnsRecord::a(
                "ns1.example.com.",
                Ipv4Addr::new(192, 0, 2, 53),
                3600,
            ))
            .additional(DnsRecord::opt(1232, 0, 0, false, Vec::new()));

        let bytes = (Ipv4::new()
            .src(Ipv4Addr::new(203, 0, 113, 1))
            .dst(Ipv4Addr::new(198, 51, 100, 1))
            / Udp::new().sport(53).dport(53001)
            / dns)
            .compile()
            .unwrap();
        let decoded = Packet::decode_from_l3(NetworkLayer::Ipv4, bytes.as_bytes()).unwrap();
        let header = decoded.layer::<Dns>().unwrap();

        // Each section carries exactly the records it was given, and the counts
        // auto-fill from the typed vectors.
        assert_eq!(header.questions().len(), 1);
        assert_eq!(header.answers().len(), 1);
        assert_eq!(header.authorities().len(), 1);
        assert_eq!(header.additionals().len(), 2);

        // The answer is the A record, never the NS or OPT.
        assert_eq!(header.answers()[0].record_type(), DNS_TYPE_A);
        assert_eq!(header.answers()[0].name(), "example.com.");

        // The NS record stays in the authority section and is not promoted into
        // the answer or additional sections.
        assert_eq!(header.authorities()[0].record_type(), DNS_TYPE_NS);
        assert_eq!(
            header.authorities()[0].data(),
            &DnsRecordData::name("ns1.example.com.")
        );

        // Both additional records stay in the additional section in their given
        // order: the non-OPT A glue record first, then the EDNS(0) OPT record.
        assert_eq!(header.additionals()[0].record_type(), DNS_TYPE_A);
        assert!(!header.additionals()[0].is_opt());
        assert_eq!(header.additionals()[0].name(), "ns1.example.com.");
        assert_eq!(header.additionals()[1].record_type(), DNS_TYPE_OPT);
        assert!(header.additionals()[1].is_opt());

        // Recompiling the decoded packet reproduces the exact bytes, proving no
        // record migrated between sections during decode.
        assert_eq!(decoded.compile().unwrap(), bytes);
    }

    #[test]
    fn multi_question_class_and_type_values_round_trip() {
        // A single query carrying several questions in a deterministic order that
        // spans the QTYPE axis (A, AAAA, MX, TXT, the ANY meta-type, and a
        // private-use unknown numeric QTYPE) and the QCLASS axis (IN, CH, HS,
        // NONE, ANY, and a private-use unknown numeric QCLASS). QDCOUNT must
        // auto-fill from the questions vector and every type/class value -
        // including the unknown numeric codepoints - must survive compile,
        // decode, and recompile unchanged. QTYPE/QCLASS ANY share IANA codepoint
        // 255; the private-use codepoint 65280 has no named type or class.
        const QTYPE_ANY: u16 = 255;
        const PRIVATE_QTYPE: u16 = 65280;
        const PRIVATE_QCLASS: u16 = 65280;
        let questions = [
            (DNS_TYPE_A, DNS_CLASS_IN),
            (DNS_TYPE_AAAA, DNS_CLASS_CH),
            (DNS_TYPE_MX, DNS_CLASS_HS),
            (DNS_TYPE_TXT, DNS_CLASS_NONE),
            (QTYPE_ANY, DNS_CLASS_ANY),
            (PRIVATE_QTYPE, PRIVATE_QCLASS),
        ];

        let mut dns = Dns::new().rd(true);
        for (index, (qtype, qclass)) in questions.iter().enumerate() {
            let name = format!("q{index}.example.com.");
            dns = dns.question(DnsQuestion::new(name, *qtype).qclass(*qclass));
        }

        let bytes = (Ipv4::new()
            .src(Ipv4Addr::new(192, 0, 2, 10))
            .dst(Ipv4Addr::new(198, 51, 100, 53))
            / Udp::new().sport(53001).dport(53)
            / dns)
            .compile()
            .unwrap();
        let decoded = Packet::decode_from_l3(NetworkLayer::Ipv4, bytes.as_bytes()).unwrap();
        let header = decoded.layer::<Dns>().unwrap();

        // QDCOUNT auto-fills from the typed questions vector.
        assert_eq!(header.questions().len(), questions.len());
        for (index, (qtype, qclass)) in questions.iter().enumerate() {
            let question = &header.questions()[index];
            assert_eq!(question.name(), format!("q{index}.example.com."));
            assert_eq!(question.question_type(), *qtype);
            assert_eq!(question.question_class(), *qclass);
        }
        // The unknown numeric QTYPE/QCLASS are preserved verbatim, not remapped.
        assert_eq!(header.questions()[5].question_type(), PRIVATE_QTYPE);
        assert_eq!(header.questions()[5].question_class(), PRIVATE_QCLASS);
        assert_eq!(decoded.compile().unwrap(), bytes);
    }

    #[test]
    fn type_names_cover_source_backed_codepoints() {
        assert_eq!(dns_type_name(DNS_TYPE_A), Some("A"));
        assert_eq!(dns_type_name(DNS_TYPE_SOA), Some("SOA"));
        assert_eq!(dns_type_name(DNS_TYPE_SRV), Some("SRV"));
        assert_eq!(dns_type_name(DNS_TYPE_HTTPS), Some("HTTPS"));
        // Unknown values stay numeric for callers to format.
        assert_eq!(dns_type_name(60000), None);
    }
}

#[cfg(test)]
mod dns_malformed {
    //! Table-driven boundary coverage for the record-data and name parsers.
    //!
    //! These cases live as unit tests (rather than full packet fixtures in the
    //! resilience corpus) because they exercise a single RDATA or name decoder
    //! directly and assert the exact structured error field, which is clearer
    //! than reconstructing an entire DNS message. The resilience corpus carries
    //! the matching end-to-end packet rows.

    use super::{
        decode_dns_name_typed, decode_record_data, DnsRecordData, DNS_MAX_LABEL_LEN, DNS_TYPE_A,
        DNS_TYPE_AAAA, DNS_TYPE_DNSKEY, DNS_TYPE_DS, DNS_TYPE_NSEC, DNS_TYPE_NSEC3, DNS_TYPE_RRSIG,
        DNS_TYPE_SOA, DNS_TYPE_SRV, DNS_TYPE_SVCB,
    };
    use crate::error::CrafterError;

    /// Assert that decoding `rdata` for `record_type` fails with a
    /// `buffer-too-short` error whose context is exactly `field`.
    fn assert_too_short(record_type: u16, rdata: &[u8], field: &str) {
        match decode_record_data(record_type, rdata, 0, rdata.len()) {
            Err(CrafterError::BufferTooShort { context, .. }) => assert_eq!(
                context, field,
                "type {record_type:#x} expected buffer-too-short context {field}"
            ),
            other => {
                panic!("type {record_type:#x} expected buffer-too-short {field}, got {other:?}")
            }
        }
    }

    /// Assert that decoding `rdata` for `record_type` fails with an
    /// `invalid-field-value` error whose field is exactly `field`.
    fn assert_invalid(record_type: u16, rdata: &[u8], field: &str) {
        match decode_record_data(record_type, rdata, 0, rdata.len()) {
            Err(CrafterError::InvalidFieldValue { field: got, .. }) => assert_eq!(
                got, field,
                "type {record_type:#x} expected invalid-field-value {field}"
            ),
            other => {
                panic!("type {record_type:#x} expected invalid-field-value {field}, got {other:?}")
            }
        }
    }

    #[test]
    fn fixed_length_records_reject_wrong_rdlength() {
        // A and AAAA carry an exact fixed-length address; any other length is
        // structurally invalid rather than silently truncated.
        assert_invalid(DNS_TYPE_A, &[192, 0, 2], "dns.a.rdlength");
        assert_invalid(DNS_TYPE_A, &[192, 0, 2, 1, 9], "dns.a.rdlength");
        assert_invalid(DNS_TYPE_AAAA, &[0u8; 15], "dns.aaaa.rdlength");
        assert_invalid(DNS_TYPE_AAAA, &[0u8; 17], "dns.aaaa.rdlength");
    }

    #[test]
    fn dnssec_fixed_headers_reject_truncation() {
        // Each DNSSEC record has a fixed minimum header; fewer bytes must error
        // on the documented field rather than panic on a slice.
        assert_too_short(DNS_TYPE_DS, &[0u8; 3], "dns.ds");
        assert_too_short(DNS_TYPE_DNSKEY, &[0u8; 3], "dns.dnskey");
        assert_too_short(DNS_TYPE_RRSIG, &[0u8; 17], "dns.rrsig");
    }

    #[test]
    fn soa_rejects_wrong_fixed_tail_length() {
        // MNAME "a." + RNAME root, then a fixed tail that is one byte short and
        // one byte long: both are rejected on dns.soa.rdlength.
        let mut short = vec![1u8, b'a', 0, 0];
        short.extend_from_slice(&[0u8; 19]);
        assert_invalid(DNS_TYPE_SOA, &short, "dns.soa.rdlength");

        let mut long = vec![1u8, b'a', 0, 0];
        long.extend_from_slice(&[0u8; 21]);
        assert_invalid(DNS_TYPE_SOA, &long, "dns.soa.rdlength");
    }

    #[test]
    fn srv_rejects_short_header_and_trailing_bytes() {
        // Fewer than the six fixed octets plus a name.
        assert_too_short(DNS_TYPE_SRV, &[0u8; 5], "dns.srv");
        // priority/weight/port + root target + one stray trailing byte.
        assert_invalid(
            DNS_TYPE_SRV,
            &[0, 1, 0, 2, 0x13, 0x88, 0, 0xff],
            "dns.srv.target",
        );
    }

    #[test]
    fn nsec3_rejects_hash_length_overrun() {
        // Salt length 0, then Hash Length 20 with only two bytes present.
        assert_too_short(
            DNS_TYPE_NSEC3,
            &[1, 0, 0, 10, 0, 20, 0x11, 0x22],
            "dns.nsec3.hash",
        );
    }

    #[test]
    fn nsec_rejects_non_minimal_trailing_zero_bitmap() {
        // Next name root, then a window whose bitmap ends in a trailing zero
        // octet (a non-minimal encoding) is rejected on dns.nsec.bitmap.
        let rdata = [0u8, 0x00, 2, 0x40, 0x00];
        assert_invalid(DNS_TYPE_NSEC, &rdata, "dns.nsec.bitmap");
    }

    #[test]
    fn svcb_rejects_out_of_order_and_overrun_params() {
        // priority + root target + port(3) then alpn(1): a decreasing key pair.
        let out_of_order = [0u8, 1, 0, 0, 3, 0, 0, 0, 1, 0, 0];
        assert_invalid(DNS_TYPE_SVCB, &out_of_order, "dns.svcb.params");

        // priority + root target + a SvcParam whose declared length runs past
        // the RDATA.
        let overrun = [0u8, 1, 0, 0, 3, 0, 8, 0, 0];
        assert_too_short(DNS_TYPE_SVCB, &overrun, "dns.svcb.params");
    }

    #[test]
    fn unknown_record_type_decodes_as_raw_not_rejected() {
        // A structurally valid record with a TYPE this crate does not model must
        // surface its RDATA verbatim rather than being rejected for being
        // unknown.
        let rdata = [0xde, 0xad, 0xbe, 0xef];
        let data = decode_record_data(0xfff0, &rdata, 0, rdata.len()).unwrap();
        assert_eq!(data, DnsRecordData::Raw(rdata.to_vec()));

        // Even a zero-length RDATA under an unknown type stays raw and empty.
        let empty = decode_record_data(0xfff0, &[], 0, 0).unwrap();
        assert_eq!(empty, DnsRecordData::Raw(Vec::new()));
    }

    #[test]
    fn name_decoder_rejects_reserved_marker_and_length_overrun() {
        // A reserved label-length marker (top two bits 0b10) is malformed.
        match decode_dns_name_typed(&[0x40], 0) {
            Err(CrafterError::InvalidFieldValue { field, .. }) => assert_eq!(field, "dns.name"),
            other => panic!("expected reserved-marker rejection, got {other:?}"),
        }

        // Four 63-octet labels exceed the 255-octet full-name limit.
        let mut overrun = Vec::new();
        for _ in 0..4 {
            overrun.push(DNS_MAX_LABEL_LEN as u8);
            overrun.extend_from_slice(&[b'a'; DNS_MAX_LABEL_LEN]);
        }
        overrun.push(0);
        match decode_dns_name_typed(&overrun, 0) {
            Err(CrafterError::InvalidFieldValue { field, .. }) => assert_eq!(field, "dns.name"),
            other => panic!("expected full-name overrun rejection, got {other:?}"),
        }
    }

    #[test]
    fn label_at_63_octet_boundary_is_accepted() {
        // The 63-octet label boundary is the largest valid label and must decode
        // successfully (the boundary itself is not an error).
        let mut wire = Vec::new();
        wire.push(DNS_MAX_LABEL_LEN as u8);
        wire.extend_from_slice(&[b'a'; DNS_MAX_LABEL_LEN]);
        wire.push(0);
        let (name, used) = decode_dns_name_typed(&wire, 0).unwrap();
        assert_eq!(used, wire.len());
        assert_eq!(name.labels(), &[vec![b'a'; DNS_MAX_LABEL_LEN]]);
    }
}

#[cfg(test)]
mod dns_golden_bytes {
    use super::{Dns, DnsQuestion, DNS_TYPE_A};
    use crate::{Ipv4, LinkType, Packet, Udp};
    use core::net::Ipv4Addr;

    const DNS_QUERY_FIXTURE: &[u8] = fixture_bytes!("bytes/ipv4-udp-dns-query-example-com.bin");

    #[test]
    fn dns_query_matches_golden_bytes() {
        let bytes = (Ipv4::new()
            .src(Ipv4Addr::new(192, 0, 2, 10))
            .dst(Ipv4Addr::new(198, 51, 100, 53))
            .id(0x1237)
            .ttl(61)
            / Udp::new().sport(53001).dport(53)
            / Dns::new()
                .id(0xbeef)
                .question(DnsQuestion::new("example.com.", DNS_TYPE_A)))
        .compile()
        .unwrap();

        assert_eq!(bytes.as_bytes(), DNS_QUERY_FIXTURE);
    }

    #[test]
    fn dns_query_fixture_decodes_to_typed_layer() {
        let decoded = Packet::decode_from_l3(crate::NetworkLayer::Ipv4, DNS_QUERY_FIXTURE).unwrap();
        let dns = decoded.layer::<Dns>().unwrap();

        assert_eq!(dns.id_value(), 0xbeef);
        assert_eq!(dns.questions()[0].name(), "example.com.");
        assert_eq!(dns.questions()[0].question_type(), DNS_TYPE_A);
        assert_eq!(decoded.compile().unwrap().as_bytes(), DNS_QUERY_FIXTURE);
    }

    #[test]
    fn non_dns_udp_payload_stays_raw_even_when_decoding_from_link() {
        let raw_fixture = fixture_bytes!("bytes/ethernet-vlan-ipv4-udp-raw.bin");
        let decoded = Packet::decode_from_link(LinkType::Ethernet, raw_fixture).unwrap();
        assert!(decoded.layer::<Dns>().is_none());
    }
}