dns_types/protocol/
types.rs

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
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
use bytes::{BufMut, Bytes, BytesMut};
use std::fmt;
use std::net::{Ipv4Addr, Ipv6Addr};
use std::str::FromStr;

/// Maximum encoded length of a domain name.  The number of labels
/// plus sum of the lengths of the labels.
pub const DOMAINNAME_MAX_LEN: usize = 255;

/// Maximum length of a single label in a domain name.
pub const LABEL_MAX_LEN: usize = 63;

/// Octet mask for the QR flag being set (response).
pub const HEADER_MASK_QR: u8 = 0b1000_0000;

/// Octet mask for the opcode field.
pub const HEADER_MASK_OPCODE: u8 = 0b0111_1000;

/// Offset for the opcode field.
pub const HEADER_OFFSET_OPCODE: usize = 3;

/// Octet mask for the AA flag being set (authoritative)
pub const HEADER_MASK_AA: u8 = 0b0000_0100;

/// Octet mask for the TC flag being set (truncated)
pub const HEADER_MASK_TC: u8 = 0b0000_0010;

/// Octet mask for the RD flag being set (desired)
pub const HEADER_MASK_RD: u8 = 0b0000_0001;

/// Octet mask for the RA flag being set (available)
pub const HEADER_MASK_RA: u8 = 0b1000_0000;

/// Octet mask for the rcode field.
pub const HEADER_MASK_RCODE: u8 = 0b0000_1111;

/// Offset for the rcode field.
pub const HEADER_OFFSET_RCODE: usize = 0;

/// Basic DNS message format, used for both queries and responses.
///
/// ```text
///     +---------------------+
///     |        Header       |
///     +---------------------+
///     |       Question      | the question for the name server
///     +---------------------+
///     |        Answer       | RRs answering the question
///     +---------------------+
///     |      Authority      | RRs pointing toward an authority
///     +---------------------+
///     |      Additional     | RRs holding additional information
///     +---------------------+
/// ```
///
/// See section 4.1 of RFC 1035.
#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
#[cfg_attr(any(feature = "test-util", test), derive(arbitrary::Arbitrary))]
pub struct Message {
    pub header: Header,
    pub questions: Vec<Question>,
    pub answers: Vec<ResourceRecord>,
    pub authority: Vec<ResourceRecord>,
    pub additional: Vec<ResourceRecord>,
}

impl Message {
    pub fn make_response(&self) -> Self {
        Self {
            header: Header {
                id: self.header.id,
                is_response: true,
                opcode: self.header.opcode,
                is_authoritative: false,
                is_truncated: false,
                recursion_desired: self.header.recursion_desired,
                recursion_available: true,
                rcode: Rcode::NoError,
            },
            questions: self.questions.clone(),
            answers: Vec::new(),
            authority: Vec::new(),
            additional: Vec::new(),
        }
    }

    pub fn make_format_error_response(id: u16) -> Self {
        Self {
            header: Header {
                id,
                is_response: true,
                opcode: Opcode::Standard,
                is_authoritative: false,
                is_truncated: false,
                recursion_desired: false,
                recursion_available: true,
                rcode: Rcode::FormatError,
            },
            questions: Vec::new(),
            answers: Vec::new(),
            authority: Vec::new(),
            additional: Vec::new(),
        }
    }

    pub fn from_question(id: u16, question: Question) -> Self {
        Self {
            header: Header {
                id,
                is_response: false,
                opcode: Opcode::Standard,
                is_authoritative: false,
                is_truncated: false,
                recursion_desired: false,
                recursion_available: false,
                rcode: Rcode::NoError,
            },
            questions: vec![question],
            answers: Vec::new(),
            authority: Vec::new(),
            additional: Vec::new(),
        }
    }
}

/// Common header type for all messages.
///
/// ```text
///                                     1  1  1  1  1  1
///       0  1  2  3  4  5  6  7  8  9  0  1  2  3  4  5
///     +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
///     |                      ID                       |
///     +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
///     |QR|   Opcode  |AA|TC|RD|RA|   Z    |   RCODE   |
///     +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
///     |                    QDCOUNT                    |
///     +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
///     |                    ANCOUNT                    |
///     +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
///     |                    NSCOUNT                    |
///     +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
///     |                    ARCOUNT                    |
///     +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
/// ```
///
/// See section 4.1.1 of RFC 1035.
///
/// The QECOUNT, ANCOUNT, NSCOUNT, and ARCOUNT fields are omitted from this
/// type, as they are only used during serialisation and deserialisation and can
/// be inferred from the other `Message` fields.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
#[cfg_attr(any(feature = "test-util", test), derive(arbitrary::Arbitrary))]
pub struct Header {
    /// A 16 bit identifier assigned by the program that generates any
    /// kind of query.  This identifier is copied the corresponding
    /// reply and can be used by the requester to match up replies to
    /// outstanding queries.
    pub id: u16,

    /// A one bit field that specifies whether this message is a query
    /// (0), or a response (1).
    pub is_response: bool,

    /// A four bit field that specifies kind of query in this message.
    /// This value is set by the originator of a query and copied into
    /// the response.  The values are:
    ///
    /// - `0` a standard query (`QUERY`)
    ///
    /// - `1` an inverse query (`IQUERY`)
    ///
    /// - `2` a server status request (`STATUS`)
    ///
    /// - `3-15` reserved for future use
    pub opcode: Opcode,

    /// Authoritative Answer - this bit is valid in responses, and
    /// specifies that the responding name server is an authority for
    /// the domain name in question section.
    ///
    /// Note that the contents of the answer section may have multiple
    /// owner names because of aliases.  The AA bit corresponds to the
    /// name which matches the query name, or the first owner name in
    /// the answer section.
    pub is_authoritative: bool,

    /// Truncation - specifies that this message was truncated due to
    /// length greater than that permitted on the transmission
    /// channel.
    pub is_truncated: bool,

    /// Recursion Desired - this bit may be set in a query and is
    /// copied into the response.  If RD is set, it directs the name
    /// server to pursue the query recursively.  Recursive query
    /// support is optional.
    pub recursion_desired: bool,

    /// Recursion Available - this be is set or cleared in a response,
    /// and denotes whether recursive query support is available in
    /// the name server.
    pub recursion_available: bool,

    /// Response code - this 4 bit field is set as part of responses.
    /// The values have the following interpretation:
    ///
    /// - `0` No error condition
    ///
    /// - `1` Format error - The name server was unable to interpret
    ///       the query.
    ///
    /// - `2` Server failure - The name server was unable to process
    ///       this query due to a problem with the name server.
    ///
    /// - `3` Name Error - Meaningful only for responses from an
    ///       authoritative name server, this code signifies that the
    ///       domain name referenced in the query does not exist.
    ///
    /// - `4` Not Implemented - The name server does not support the
    ///       requested kind of query.
    ///
    /// - `5` Refused - The name server refuses to perform the
    ///       specified operation for policy reasons.  For example, a
    ///       name server may not wish to provide the information to
    ///       the particular requester, or a name server may not wish
    ///       to perform a particular operation (e.g., zone transfer)
    ///       for particular data.
    ///
    /// - `6-15` Reserved for future use.
    pub rcode: Rcode,
}

/// The question section has a list of questions (usually 1 but
/// possibly more) being asked.  This is the structure for a single
/// question.
///
/// ```text
///                                     1  1  1  1  1  1
///       0  1  2  3  4  5  6  7  8  9  0  1  2  3  4  5
///     +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
///     |                                               |
///     /                     QNAME                     /
///     /                                               /
///     +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
///     |                     QTYPE                     |
///     +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
///     |                     QCLASS                    |
///     +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
/// ```
///
/// See section 4.1.2 of RFC 1035.
#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
#[cfg_attr(any(feature = "test-util", test), derive(arbitrary::Arbitrary))]
pub struct Question {
    /// a domain name represented as a sequence of labels, where each
    /// label consists of a length octet followed by that number of
    /// octets.  The domain name terminates with the zero length octet
    /// for the null label of the root.  Note that this field may be
    /// an odd number of octets; no padding is used.
    pub name: DomainName,

    /// a two octet code which specifies the type of the query.  The
    /// values for this field include all codes valid for a TYPE
    /// field, together with some more general codes which can match
    /// more than one type of RR.
    pub qtype: QueryType,

    /// a two octet code that specifies the class of the query.  For
    /// example, the QCLASS field is IN for the Internet.
    pub qclass: QueryClass,
}

impl Question {
    pub fn is_unknown(&self) -> bool {
        self.qtype.is_unknown() || self.qclass.is_unknown()
    }
}

impl fmt::Display for Question {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(
            f,
            "{} {} {}",
            self.name.to_dotted_string(),
            self.qclass,
            self.qtype
        )
    }
}

/// The answer, authority, and additional sections are all the same
/// format: a variable number of resource records.  This is the
/// structure for a single resource record.
///
/// ```text
///                                     1  1  1  1  1  1
///       0  1  2  3  4  5  6  7  8  9  0  1  2  3  4  5
///     +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
///     |                                               |
///     /                                               /
///     /                      NAME                     /
///     |                                               |
///     +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
///     |                      TYPE                     |
///     +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
///     |                     CLASS                     |
///     +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
///     |                      TTL                      |
///     |                                               |
///     +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
///     |                   RDLENGTH                    |
///     +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--|
///     /                     RDATA                     /
///     /                                               /
///     +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
/// ```
///
/// See section 4.1.3 of RFC 1035.
#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
#[cfg_attr(any(feature = "test-util", test), derive(arbitrary::Arbitrary))]
pub struct ResourceRecord {
    /// a domain name to which this resource record pertains.
    pub name: DomainName,

    /// A combination of the RTYPE and RDATA fields
    pub rtype_with_data: RecordTypeWithData,

    /// two octets which specify the class of the data in the RDATA
    /// field.
    pub rclass: RecordClass,

    /// a 32 bit unsigned integer that specifies the time interval (in
    /// seconds) that the resource record may be cached before it
    /// should be discarded.  Zero values are interpreted to mean that
    /// the RR can only be used for the transaction in progress, and
    /// should not be cached.
    pub ttl: u32,
}

impl ResourceRecord {
    pub fn is_unknown(&self) -> bool {
        self.rtype_with_data.is_unknown() || self.rclass.is_unknown()
    }

    pub fn matches(&self, question: &Question) -> bool {
        self.rtype_with_data.matches(question.qtype) && self.rclass.matches(question.qclass)
    }
}

/// A record type with its associated, deserialised, data.
#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub enum RecordTypeWithData {
    /// ```text
    ///     +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
    ///     |                    ADDRESS                    |
    ///     +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
    /// ```
    ///
    /// Where `ADDRESS` is a 32 bit Internet address.
    A { address: Ipv4Addr },

    /// ```text
    ///     +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
    ///     /                   NSDNAME                     /
    ///     /                                               /
    ///     +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
    /// ```
    ///
    /// Where `NSDNAME` is a domain name which specifies a host which
    /// should be authoritative for the specified class and domain.
    NS { nsdname: DomainName },

    /// ```text
    ///     +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
    ///     /                   MADNAME                     /
    ///     /                                               /
    ///     +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
    /// ```
    ///
    /// Where `MADNAME` is a domain name which specifies a host which
    /// has a mail agent for the domain which should be able to
    /// deliver mail for the domain.
    MD { madname: DomainName },

    /// ```text
    ///     +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
    ///     /                   MADNAME                     /
    ///     /                                               /
    ///     +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
    /// ```
    ///
    /// Where `MADNAME` is a domain name which specifies a host which
    /// has a mail agent for the domain which will accept mail for
    /// forwarding to the domain.
    MF { madname: DomainName },

    /// ```text
    ///     +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
    ///     /                     CNAME                     /
    ///     /                                               /
    ///     +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
    /// ```
    ///
    /// Where `CNAME` is a domain name which specifies the canonical
    /// or primary name for the owner.  The owner name is an alias.
    CNAME { cname: DomainName },

    /// ```text
    ///     +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
    ///     /                     MNAME                     /
    ///     /                                               /
    ///     +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
    ///     /                     RNAME                     /
    ///     +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
    ///     |                    SERIAL                     |
    ///     |                                               |
    ///     +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
    ///     |                    REFRESH                    |
    ///     |                                               |
    ///     +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
    ///     |                     RETRY                     |
    ///     |                                               |
    ///     +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
    ///     |                    EXPIRE                     |
    ///     |                                               |
    ///     +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
    ///     |                    MINIMUM                    |
    ///     |                                               |
    ///     +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
    /// ```
    ///
    /// Where `MNAME` is the domain name of the name server that was
    /// the original or primary source of data for this zone.
    ///
    /// Where `RNAME` is a domain name which specifies the mailbox of
    /// the person responsible for this zone.
    ///
    /// Where `SERIAL` is the unsigned 32 bit version number of the
    /// original copy of the zone.  Zone transfers preserve this
    /// value.  This value wraps and should be compared using sequence
    /// space arithmetic.
    ///
    /// Where `REFRESH` is a 32 bit time interval before the zone
    /// should be refreshed.
    ///
    /// Where `RETRY` is a 32 bit time interval that should elapse
    /// before a failed refresh should be retried.
    ///
    /// Where `EXPIRE` is a 32 bit time value that specifies an upper
    /// limit on the time interval that can elapse before the zone is
    /// no longer authoritative.
    ///
    /// Where `MINIMUM` is the unsigned 32 bit minimum TTL field that
    /// should be exported with any RR from this zone.
    ///
    /// All times are in units of seconds.
    SOA {
        mname: DomainName,
        rname: DomainName,
        serial: u32,
        refresh: u32,
        retry: u32,
        expire: u32,
        minimum: u32,
    },

    /// ```text
    ///     +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
    ///     /                   MADNAME                     /
    ///     /                                               /
    ///     +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
    /// ```
    ///
    /// Where `MADNAME` is a domain name which specifies a host which
    /// has the specified mailbox.
    MB { madname: DomainName },

    /// ```text
    ///     +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
    ///     /                   MGMNAME                     /
    ///     /                                               /
    ///     +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
    /// ```
    ///
    /// Where `MGMNAME` is a domain name which specifies a mailbox
    /// which is a member of the mail group specified by the domain
    /// name.
    MG { mdmname: DomainName },

    /// ```text
    ///     +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
    ///     /                   NEWNAME                     /
    ///     /                                               /
    ///     +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
    /// ```
    ///
    /// Where `NEWNAME` is a domain name which specifies a mailbox
    /// which is the proper rename of the specifies mailbox.
    MR { newname: DomainName },

    /// ```text
    ///     +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
    ///     /                  <anything>                   /
    ///     /                                               /
    ///     +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
    /// ```
    ///
    /// Anything at all may be in the RDATA field so long as it is
    /// 65535 octets or less.
    NULL { octets: Bytes },

    /// This application does not interpret `WKS` records.
    WKS { octets: Bytes },

    /// ```text
    ///     +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
    ///     /                   PTRDNAME                    /
    ///     +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
    /// ```
    ///
    /// Where `PTRDNAME` is a domain name which points to some
    /// location in the domain name space.
    PTR { ptrdname: DomainName },

    /// This application does not interpret `HINFO` records.
    HINFO { octets: Bytes },

    /// ```text
    ///     +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
    ///     /                    RMAILBX                    /
    ///     +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
    ///     /                    EMAILBX                    /
    ///     +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
    /// ```
    ///
    /// Where `RMAILBX` is a domain name which specifies a mailbox
    /// which is responsible for the mailing list or mailbox.  If this
    /// domain name names the root, the owner of the `MINFO` RR is
    /// responsible for itself.
    ///
    /// Where `EMAILBX` is a domain name which specifies a mailbox
    /// which is to receive error messages related to the mailing list
    /// or mailbox specified by the owner of the `MINFO` RR (similar
    /// to the `ERRORS-TO`: field which has been proposed).  If this
    /// domain name names the root, errors should be returned to the
    /// sender of the message.
    MINFO {
        rmailbx: DomainName,
        emailbx: DomainName,
    },

    /// ```text
    ///     +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
    ///     |                  PREFERENCE                   |
    ///     +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
    ///     /                   EXCHANGE                    /
    ///     /                                               /
    ///     +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
    /// ```
    ///
    /// Where `PREFERENCE` is a 16 bit integer which specifies the
    /// preference given to this RR among others at the same owner.
    /// Lower values are preferred.
    ///
    /// Where `EXCHANGE` is a domain name which specifies a host
    /// willing to act as a mail exchange for the owner name.
    MX {
        preference: u16,
        exchange: DomainName,
    },

    /// ```text
    ///     +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
    ///     /                   TXT-DATA                    /
    ///     +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
    /// ```
    ///
    /// Where `TXT-DATA` is one or more character strings.
    TXT { octets: Bytes },

    /// ```text
    ///     +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
    ///     |                    ADDRESS                    |
    ///     +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
    /// ```
    ///
    /// Where `ADDRESS` is a 128 bit Internet address.
    AAAA { address: Ipv6Addr },

    /// ```text
    ///     +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
    ///     |                   PRIORITY                    |
    ///     +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
    ///     |                    WEIGHT                     |
    ///     +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
    ///     |                     PORT                      |
    ///     +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
    ///     /                    TARGET                     /
    ///     /                                               /
    ///     +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
    /// ```
    ///
    /// Where `PRIORITY` is a 16 bit integer which specifies the order
    /// (lowest first) in which clients must attempt to use these RRs.
    ///
    /// Where `WEIGHT` is a 16 bit integer which specifies the
    /// preference given to this RR amongst others of the same
    /// priority.
    ///
    /// Where `PORT` is a 16 bit integer defining the port to contact
    /// the service on.
    ///
    /// Where `TARGET` is the domain name the service may be found at.
    /// This should point to a domain name that has an address record
    /// (A or AAAA) directly, rather than a domain name which has a
    /// CNAME or other alias type.  But this is not enforced.
    SRV {
        priority: u16,
        weight: u16,
        port: u16,
        target: DomainName,
    },

    /// Any other record.
    Unknown {
        tag: RecordTypeUnknown,
        octets: Bytes,
    },
}

impl RecordTypeWithData {
    pub fn is_unknown(&self) -> bool {
        self.rtype().is_unknown()
    }

    pub fn matches(&self, qtype: QueryType) -> bool {
        self.rtype().matches(qtype)
    }

    pub fn rtype(&self) -> RecordType {
        match self {
            RecordTypeWithData::A { .. } => RecordType::A,
            RecordTypeWithData::NS { .. } => RecordType::NS,
            RecordTypeWithData::MD { .. } => RecordType::MD,
            RecordTypeWithData::MF { .. } => RecordType::MF,
            RecordTypeWithData::CNAME { .. } => RecordType::CNAME,
            RecordTypeWithData::SOA { .. } => RecordType::SOA,
            RecordTypeWithData::MB { .. } => RecordType::MB,
            RecordTypeWithData::MG { .. } => RecordType::MG,
            RecordTypeWithData::MR { .. } => RecordType::MR,
            RecordTypeWithData::NULL { .. } => RecordType::NULL,
            RecordTypeWithData::WKS { .. } => RecordType::WKS,
            RecordTypeWithData::PTR { .. } => RecordType::PTR,
            RecordTypeWithData::HINFO { .. } => RecordType::HINFO,
            RecordTypeWithData::MINFO { .. } => RecordType::MINFO,
            RecordTypeWithData::MX { .. } => RecordType::MX,
            RecordTypeWithData::TXT { .. } => RecordType::TXT,
            RecordTypeWithData::AAAA { .. } => RecordType::AAAA,
            RecordTypeWithData::SRV { .. } => RecordType::SRV,
            RecordTypeWithData::Unknown { tag, .. } => RecordType::Unknown(*tag),
        }
    }
}

#[cfg(any(feature = "test-util", test))]
impl<'a> arbitrary::Arbitrary<'a> for RecordTypeWithData {
    // this is pretty verbose but it feels like a better way to guarantee the
    // max size of the `Bytes`s than adding a wrapper type
    fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<Self> {
        let len = u.int_in_range(0..=128)?;
        let octets = Bytes::copy_from_slice(u.bytes(len)?);

        let rtype_with_data = match u.arbitrary::<RecordType>()? {
            RecordType::A => RecordTypeWithData::A {
                address: u.arbitrary()?,
            },
            RecordType::NS => RecordTypeWithData::NS {
                nsdname: u.arbitrary()?,
            },
            RecordType::MD => RecordTypeWithData::MD {
                madname: u.arbitrary()?,
            },
            RecordType::MF => RecordTypeWithData::MF {
                madname: u.arbitrary()?,
            },
            RecordType::CNAME => RecordTypeWithData::CNAME {
                cname: u.arbitrary()?,
            },
            RecordType::SOA => RecordTypeWithData::SOA {
                mname: u.arbitrary()?,
                rname: u.arbitrary()?,
                serial: u.arbitrary()?,
                refresh: u.arbitrary()?,
                retry: u.arbitrary()?,
                expire: u.arbitrary()?,
                minimum: u.arbitrary()?,
            },
            RecordType::MB => RecordTypeWithData::MB {
                madname: u.arbitrary()?,
            },
            RecordType::MG => RecordTypeWithData::MG {
                mdmname: u.arbitrary()?,
            },
            RecordType::MR => RecordTypeWithData::MR {
                newname: u.arbitrary()?,
            },
            RecordType::NULL => RecordTypeWithData::NULL { octets },
            RecordType::WKS => RecordTypeWithData::WKS { octets },
            RecordType::PTR => RecordTypeWithData::PTR {
                ptrdname: u.arbitrary()?,
            },
            RecordType::HINFO => RecordTypeWithData::HINFO { octets },
            RecordType::MINFO => RecordTypeWithData::MINFO {
                rmailbx: u.arbitrary()?,
                emailbx: u.arbitrary()?,
            },
            RecordType::MX => RecordTypeWithData::MX {
                preference: u.arbitrary()?,
                exchange: u.arbitrary()?,
            },
            RecordType::TXT => RecordTypeWithData::TXT { octets },
            RecordType::AAAA => RecordTypeWithData::AAAA {
                address: u.arbitrary()?,
            },
            RecordType::SRV => RecordTypeWithData::SRV {
                priority: u.arbitrary()?,
                weight: u.arbitrary()?,
                port: u.arbitrary()?,
                target: u.arbitrary()?,
            },
            RecordType::Unknown(tag) => RecordTypeWithData::Unknown { tag, octets },
        };
        Ok(rtype_with_data)
    }
}

/// What sort of query this is.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub enum Opcode {
    Standard,
    Inverse,
    Status,
    Reserved(OpcodeReserved),
}

/// A struct with a private constructor, to ensure invalid `Opcode`s
/// cannot be created.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct OpcodeReserved(u8);

impl Opcode {
    pub fn is_reserved(&self) -> bool {
        matches!(self, Opcode::Reserved(_))
    }
}

impl From<u8> for Opcode {
    fn from(octet: u8) -> Self {
        match octet & 0b0000_1111 {
            0 => Opcode::Standard,
            1 => Opcode::Inverse,
            2 => Opcode::Status,
            other => Opcode::Reserved(OpcodeReserved(other)),
        }
    }
}

impl From<Opcode> for u8 {
    fn from(value: Opcode) -> Self {
        match value {
            Opcode::Standard => 0,
            Opcode::Inverse => 1,
            Opcode::Status => 2,
            Opcode::Reserved(OpcodeReserved(octet)) => octet,
        }
    }
}

#[cfg(any(feature = "test-util", test))]
impl<'a> arbitrary::Arbitrary<'a> for Opcode {
    fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<Self> {
        Ok(Self::from(u.arbitrary::<u8>()?))
    }
}

/// What sort of response this is.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub enum Rcode {
    NoError,
    FormatError,
    ServerFailure,
    NameError,
    NotImplemented,
    Refused,
    Reserved(RcodeReserved),
}

/// A struct with a private constructor, to ensure invalid `Rcode`s
/// cannot be created.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct RcodeReserved(u8);

impl Rcode {
    pub fn is_reserved(&self) -> bool {
        matches!(self, Rcode::Reserved(_))
    }
}

impl fmt::Display for Rcode {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Rcode::NoError => write!(f, "no-error"),
            Rcode::FormatError => write!(f, "format-error"),
            Rcode::ServerFailure => write!(f, "server-failure"),
            Rcode::NameError => write!(f, "name-error"),
            Rcode::NotImplemented => write!(f, "not-implemented"),
            Rcode::Refused => write!(f, "refused"),
            Rcode::Reserved(_) => write!(f, "reserved"),
        }
    }
}

impl From<u8> for Rcode {
    fn from(octet: u8) -> Self {
        match octet & 0b0000_1111 {
            0 => Rcode::NoError,
            1 => Rcode::FormatError,
            2 => Rcode::ServerFailure,
            3 => Rcode::NameError,
            4 => Rcode::NotImplemented,
            5 => Rcode::Refused,
            other => Rcode::Reserved(RcodeReserved(other)),
        }
    }
}

impl From<Rcode> for u8 {
    fn from(value: Rcode) -> Self {
        match value {
            Rcode::NoError => 0,
            Rcode::FormatError => 1,
            Rcode::ServerFailure => 2,
            Rcode::NameError => 3,
            Rcode::NotImplemented => 4,
            Rcode::Refused => 5,
            Rcode::Reserved(RcodeReserved(octet)) => octet,
        }
    }
}

#[cfg(any(feature = "test-util", test))]
impl<'a> arbitrary::Arbitrary<'a> for Rcode {
    fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<Self> {
        Ok(Self::from(u.arbitrary::<u8>()?))
    }
}

/// A domain name is a sequence of labels, where each label is a
/// length octet followed by that number of octets.
///
/// A label must be 63 octets or shorter.  A name must be 255 octets
/// or shorter in total, including both length and label octets.
#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct DomainName {
    pub labels: Vec<Label>,
    // INVARIANT: len == len(labels) + sum(map(len, labels))
    pub len: usize,
}

impl DomainName {
    pub fn root_domain() -> Self {
        DomainName {
            labels: vec![Label::new()],
            len: 1,
        }
    }

    pub fn is_root(&self) -> bool {
        self.len == 1 && self.labels[0].is_empty()
    }

    pub fn is_subdomain_of(&self, other: &DomainName) -> bool {
        self.labels.ends_with(&other.labels)
    }

    pub fn make_subdomain_of(&self, origin: &Self) -> Option<Self> {
        let mut labels = self.labels.clone();
        labels.pop();
        labels.append(&mut origin.labels.clone());
        DomainName::from_labels(labels)
    }

    pub fn to_dotted_string(&self) -> String {
        if self.is_root() {
            return ".".to_string();
        }

        let mut out = String::with_capacity(self.len);
        let mut first = true;
        for label in &self.labels {
            if first {
                first = false;
            } else {
                out.push('.');
            }
            for octet in &label.octets {
                out.push(*octet as char);
            }
        }

        out
    }

    pub fn from_relative_dotted_string(origin: &Self, s: &str) -> Option<Self> {
        if s.is_empty() {
            Some(origin.clone())
        } else if s.to_string().ends_with('.') {
            Self::from_dotted_string(s)
        } else {
            let suffix = origin.to_dotted_string();
            if suffix.starts_with('.') {
                Self::from_dotted_string(&format!("{s}{suffix}"))
            } else {
                Self::from_dotted_string(&format!("{s}.{suffix}"))
            }
        }
    }

    pub fn from_dotted_string(s: &str) -> Option<Self> {
        if s == "." {
            return Some(Self::root_domain());
        }

        let chunks = s.split('.').collect::<Vec<_>>();
        let mut labels = Vec::with_capacity(chunks.len());

        for (i, label_chars) in chunks.iter().enumerate() {
            if label_chars.is_empty() && i != chunks.len() - 1 {
                return None;
            }

            match label_chars.as_bytes().try_into() {
                Ok(label) => labels.push(label),
                Err(_) => return None,
            }
        }

        Self::from_labels(labels)
    }

    pub fn from_labels(labels: Vec<Label>) -> Option<Self> {
        if labels.is_empty() {
            return None;
        }

        let mut len = labels.len();
        let mut blank_label = false;

        for label in &labels {
            if blank_label {
                return None;
            }

            blank_label |= label.is_empty();
            len += label.len() as usize;
        }

        if blank_label && len <= DOMAINNAME_MAX_LEN {
            Some(Self { labels, len })
        } else {
            None
        }
    }
}

impl fmt::Debug for DomainName {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("DomainName")
            .field("to_dotted_string()", &self.to_dotted_string())
            .finish()
    }
}

impl fmt::Display for DomainName {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", &self.to_dotted_string())
    }
}

impl FromStr for DomainName {
    type Err = DomainNameFromStr;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        if let Some(domain) = DomainName::from_dotted_string(s) {
            Ok(domain)
        } else {
            Err(DomainNameFromStr::NoParse)
        }
    }
}

/// Errors that can arise when converting a `&str` into a `DomainName`.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
pub enum DomainNameFromStr {
    NoParse,
}

impl fmt::Display for DomainNameFromStr {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "could not parse string to domain name")
    }
}

impl std::error::Error for DomainNameFromStr {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        None
    }
}

#[cfg(any(feature = "test-util", test))]
impl<'a> arbitrary::Arbitrary<'a> for DomainName {
    fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<Self> {
        let num_labels = u.int_in_range::<usize>(0..=10)?;
        let mut labels = Vec::new();
        for _ in 0..num_labels {
            labels.push(u.arbitrary()?);
        }
        labels.push(Label::new());
        Ok(DomainName::from_labels(labels).unwrap())
    }
}

/// A label is just a sequence of octets, which are compared as
/// case-insensitive ASCII.  A label can be no longer than 63 octets.
#[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct Label {
    /// Private to this module so constructing an invalid `Label` is
    /// impossible.
    octets: Bytes,
}

impl Label {
    /// Create a new, empty, label.
    pub fn new() -> Self {
        Self {
            octets: Bytes::new(),
        }
    }

    #[allow(clippy::missing_panics_doc)]
    pub fn len(&self) -> u8 {
        // safe as the `TryFrom` ensures a label is <= 63 bytes
        self.octets.len().try_into().unwrap()
    }

    pub fn is_empty(&self) -> bool {
        self.octets.is_empty()
    }

    pub fn octets(&self) -> &Bytes {
        &self.octets
    }
}

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

impl TryFrom<&[u8]> for Label {
    type Error = LabelTryFromOctetsError;

    fn try_from(mixed_case_octets: &[u8]) -> Result<Self, Self::Error> {
        if mixed_case_octets.len() > LABEL_MAX_LEN {
            return Err(LabelTryFromOctetsError::TooLong);
        }

        Ok(Self {
            octets: Bytes::copy_from_slice(&mixed_case_octets.to_ascii_lowercase()),
        })
    }
}

#[cfg(any(feature = "test-util", test))]
impl<'a> arbitrary::Arbitrary<'a> for Label {
    // only generates non-empty labels
    fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<Label> {
        let label_len = u.int_in_range::<u8>(1..=20)?;
        let mut octets = BytesMut::with_capacity(label_len.into());
        let bs = u.bytes(label_len.into())?;
        for b in bs {
            let ascii_byte = if b.is_ascii() { *b } else { *b % 128 };
            octets.put_u8(
                if ascii_byte == b'.'
                    || ascii_byte == b'*'
                    || ascii_byte == b'@'
                    || ascii_byte == b'#'
                    || (ascii_byte as char).is_whitespace()
                {
                    b'x'
                } else {
                    ascii_byte.to_ascii_lowercase()
                },
            );
        }
        Ok(Self {
            octets: octets.freeze(),
        })
    }
}

/// Errors that can arise when converting a `[u8]` into a `Label`.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
pub enum LabelTryFromOctetsError {
    TooLong,
}

/// Query types are a superset of record types.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub enum QueryType {
    Record(RecordType),
    AXFR,
    MAILB,
    MAILA,
    Wildcard,
}

impl QueryType {
    pub fn is_unknown(&self) -> bool {
        match self {
            QueryType::Record(rtype) => rtype.is_unknown(),
            _ => false,
        }
    }
}

impl fmt::Display for QueryType {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            QueryType::Record(rtype) => rtype.fmt(f),
            QueryType::AXFR => write!(f, "AXFR"),
            QueryType::MAILA => write!(f, "MAILA"),
            QueryType::MAILB => write!(f, "MAILB"),
            QueryType::Wildcard => write!(f, "ANY"),
        }
    }
}

impl FromStr for QueryType {
    type Err = RecordTypeFromStr;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "AXFR" => Ok(QueryType::AXFR),
            "MAILA" => Ok(QueryType::MAILA),
            "MAILB" => Ok(QueryType::MAILB),
            "ANY" => Ok(QueryType::Wildcard),
            _ => RecordType::from_str(s).map(QueryType::Record),
        }
    }
}

impl From<u16> for QueryType {
    fn from(value: u16) -> Self {
        match value {
            252 => QueryType::AXFR,
            253 => QueryType::MAILB,
            254 => QueryType::MAILA,
            255 => QueryType::Wildcard,
            _ => QueryType::Record(RecordType::from(value)),
        }
    }
}

impl From<QueryType> for u16 {
    fn from(value: QueryType) -> Self {
        match value {
            QueryType::AXFR => 252,
            QueryType::MAILB => 253,
            QueryType::MAILA => 254,
            QueryType::Wildcard => 255,
            QueryType::Record(rtype) => rtype.into(),
        }
    }
}

#[cfg(any(feature = "test-util", test))]
impl<'a> arbitrary::Arbitrary<'a> for QueryType {
    fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<Self> {
        Ok(Self::from(u.arbitrary::<u16>()?))
    }
}

/// Query classes are a superset of record classes.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub enum QueryClass {
    Record(RecordClass),
    Wildcard,
}

impl QueryClass {
    pub fn is_unknown(&self) -> bool {
        match self {
            QueryClass::Record(rclass) => rclass.is_unknown(),
            QueryClass::Wildcard => false,
        }
    }
}

impl fmt::Display for QueryClass {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            QueryClass::Record(rclass) => rclass.fmt(f),
            QueryClass::Wildcard => write!(f, "ANY"),
        }
    }
}

impl FromStr for QueryClass {
    type Err = RecordClassFromStr;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "ANY" => Ok(QueryClass::Wildcard),
            _ => RecordClass::from_str(s).map(QueryClass::Record),
        }
    }
}

impl From<u16> for QueryClass {
    fn from(value: u16) -> Self {
        match value {
            255 => QueryClass::Wildcard,
            _ => QueryClass::Record(RecordClass::from(value)),
        }
    }
}

impl From<QueryClass> for u16 {
    fn from(value: QueryClass) -> Self {
        match value {
            QueryClass::Wildcard => 255,
            QueryClass::Record(rclass) => rclass.into(),
        }
    }
}

#[cfg(any(feature = "test-util", test))]
impl<'a> arbitrary::Arbitrary<'a> for QueryClass {
    fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<Self> {
        Ok(Self::from(u.arbitrary::<u16>()?))
    }
}

/// Record types are used by resource records and by queries.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub enum RecordType {
    A,
    NS,
    MD,
    MF,
    CNAME,
    SOA,
    MB,
    MG,
    MR,
    NULL,
    WKS,
    PTR,
    HINFO,
    MINFO,
    MX,
    TXT,
    AAAA,
    SRV,
    Unknown(RecordTypeUnknown),
}

/// A struct with a private constructor, to ensure invalid `RecordType`s
/// cannot be created.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct RecordTypeUnknown(u16);

impl RecordType {
    pub fn is_unknown(&self) -> bool {
        matches!(self, RecordType::Unknown(_))
    }

    pub fn matches(&self, qtype: QueryType) -> bool {
        match qtype {
            QueryType::Wildcard => true,
            QueryType::Record(rtype) => rtype == *self,
            _ => false,
        }
    }
}

impl fmt::Display for RecordType {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            RecordType::A => write!(f, "A"),
            RecordType::NS => write!(f, "NS"),
            RecordType::MD => write!(f, "MD"),
            RecordType::MF => write!(f, "MF"),
            RecordType::CNAME => write!(f, "CNAME"),
            RecordType::SOA => write!(f, "SOA"),
            RecordType::MB => write!(f, "MB"),
            RecordType::MG => write!(f, "MG"),
            RecordType::MR => write!(f, "MR"),
            RecordType::NULL => write!(f, "NULL"),
            RecordType::WKS => write!(f, "WKS"),
            RecordType::PTR => write!(f, "PTR"),
            RecordType::HINFO => write!(f, "HINFO"),
            RecordType::MINFO => write!(f, "MINFO"),
            RecordType::MX => write!(f, "MX"),
            RecordType::TXT => write!(f, "TXT"),
            RecordType::AAAA => write!(f, "AAAA"),
            RecordType::SRV => write!(f, "SRV"),
            RecordType::Unknown(RecordTypeUnknown(n)) => write!(f, "TYPE{n}"),
        }
    }
}

impl FromStr for RecordType {
    type Err = RecordTypeFromStr;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "A" => Ok(RecordType::A),
            "NS" => Ok(RecordType::NS),
            "MD" => Ok(RecordType::MD),
            "MF" => Ok(RecordType::MF),
            "CNAME" => Ok(RecordType::CNAME),
            "SOA" => Ok(RecordType::SOA),
            "MB" => Ok(RecordType::MB),
            "MG" => Ok(RecordType::MG),
            "MR" => Ok(RecordType::MR),
            "NULL" => Ok(RecordType::NULL),
            "WKS" => Ok(RecordType::WKS),
            "PTR" => Ok(RecordType::PTR),
            "HINFO" => Ok(RecordType::HINFO),
            "MINFO" => Ok(RecordType::MINFO),
            "MX" => Ok(RecordType::MX),
            "TXT" => Ok(RecordType::TXT),
            "AAAA" => Ok(RecordType::AAAA),
            "SRV" => Ok(RecordType::SRV),
            _ => {
                if let Some(type_str) = s.strip_prefix("TYPE") {
                    if let Ok(type_num) = u16::from_str(type_str) {
                        Ok(RecordType::from(type_num))
                    } else {
                        Err(RecordTypeFromStr::BadType)
                    }
                } else {
                    Err(RecordTypeFromStr::NoParse)
                }
            }
        }
    }
}

/// Errors that can arise when converting a `&str` into a `RecordType`.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
pub enum RecordTypeFromStr {
    BadType,
    NoParse,
}

impl fmt::Display for RecordTypeFromStr {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            RecordTypeFromStr::BadType => write!(f, "TYPE<num> number must be a u16"),
            RecordTypeFromStr::NoParse => write!(f, "could not parse string to type"),
        }
    }
}

impl std::error::Error for RecordTypeFromStr {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        None
    }
}

impl From<u16> for RecordType {
    fn from(value: u16) -> Self {
        match value {
            1 => RecordType::A,
            2 => RecordType::NS,
            3 => RecordType::MD,
            4 => RecordType::MF,
            5 => RecordType::CNAME,
            6 => RecordType::SOA,
            7 => RecordType::MB,
            8 => RecordType::MG,
            9 => RecordType::MR,
            10 => RecordType::NULL,
            11 => RecordType::WKS,
            12 => RecordType::PTR,
            13 => RecordType::HINFO,
            14 => RecordType::MINFO,
            15 => RecordType::MX,
            16 => RecordType::TXT,
            28 => RecordType::AAAA,
            33 => RecordType::SRV,
            _ => RecordType::Unknown(RecordTypeUnknown(value)),
        }
    }
}

impl From<RecordType> for u16 {
    fn from(value: RecordType) -> Self {
        match value {
            RecordType::A => 1,
            RecordType::NS => 2,
            RecordType::MD => 3,
            RecordType::MF => 4,
            RecordType::CNAME => 5,
            RecordType::SOA => 6,
            RecordType::MB => 7,
            RecordType::MG => 8,
            RecordType::MR => 9,
            RecordType::NULL => 10,
            RecordType::WKS => 11,
            RecordType::PTR => 12,
            RecordType::HINFO => 13,
            RecordType::MINFO => 14,
            RecordType::MX => 15,
            RecordType::TXT => 16,
            RecordType::AAAA => 28,
            RecordType::SRV => 33,
            RecordType::Unknown(RecordTypeUnknown(value)) => value,
        }
    }
}

#[cfg(any(feature = "test-util", test))]
impl<'a> arbitrary::Arbitrary<'a> for RecordType {
    fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<Self> {
        Ok(Self::from(u.arbitrary::<u16>()?))
    }
}

/// Record classes are used by resource records and by queries.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub enum RecordClass {
    IN,
    Unknown(RecordClassUnknown),
}

/// A struct with a private constructor, to ensure invalid
/// `RecordClass`es cannot be created.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct RecordClassUnknown(u16);

impl RecordClass {
    pub fn is_unknown(&self) -> bool {
        matches!(self, RecordClass::Unknown(_))
    }

    pub fn matches(&self, qclass: QueryClass) -> bool {
        match qclass {
            QueryClass::Wildcard => true,
            QueryClass::Record(rclass) => rclass == *self,
        }
    }
}

impl fmt::Display for RecordClass {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            RecordClass::IN => write!(f, "IN"),
            RecordClass::Unknown(RecordClassUnknown(n)) => write!(f, "CLASS{n}"),
        }
    }
}

impl FromStr for RecordClass {
    type Err = RecordClassFromStr;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "IN" => Ok(RecordClass::IN),
            _ => {
                if let Some(class_str) = s.strip_prefix("CLASS") {
                    if let Ok(class_num) = u16::from_str(class_str) {
                        Ok(RecordClass::from(class_num))
                    } else {
                        Err(RecordClassFromStr::BadClass)
                    }
                } else {
                    Err(RecordClassFromStr::NoParse)
                }
            }
        }
    }
}

/// Errors that can arise when converting a `&str` into a `RecordClass`.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
pub enum RecordClassFromStr {
    BadClass,
    NoParse,
}

impl fmt::Display for RecordClassFromStr {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            RecordClassFromStr::BadClass => write!(f, "CLASS<num> number must be a u16"),
            RecordClassFromStr::NoParse => write!(f, "could not parse string to class"),
        }
    }
}

impl std::error::Error for RecordClassFromStr {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        None
    }
}

impl From<u16> for RecordClass {
    fn from(value: u16) -> Self {
        match value {
            1 => RecordClass::IN,
            _ => RecordClass::Unknown(RecordClassUnknown(value)),
        }
    }
}

impl From<RecordClass> for u16 {
    fn from(value: RecordClass) -> Self {
        match value {
            RecordClass::IN => 1,
            RecordClass::Unknown(RecordClassUnknown(value)) => value,
        }
    }
}

#[cfg(any(feature = "test-util", test))]
impl<'a> arbitrary::Arbitrary<'a> for RecordClass {
    fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<Self> {
        Ok(Self::from(u.arbitrary::<u16>()?))
    }
}

#[cfg(test)]
mod tests {
    use rand::Rng;

    use super::test_util::*;
    use super::*;

    #[test]
    fn u8_opcode_roundtrip() {
        for i in 0..15 {
            assert_eq!(u8::from(Opcode::from(i)), i);
        }
    }

    #[test]
    fn u8_rcode_roundtrip() {
        for i in 0..15 {
            assert_eq!(u8::from(Rcode::from(i)), i);
        }
    }

    #[test]
    fn u16_querytype_roundtrip() {
        for i in 0..100 {
            assert_eq!(u16::from(QueryType::from(i)), i);
        }
    }

    #[test]
    fn u16_queryclass_roundtrip() {
        for i in 0..100 {
            assert_eq!(u16::from(QueryClass::from(i)), i);
        }
    }

    #[test]
    fn u16_recordtype_roundtrip() {
        for i in 0..100 {
            assert_eq!(u16::from(RecordType::from(i)), i);
        }
    }

    #[test]
    fn recordtype_unknown_implies_querytype_unknown() {
        for i in 0..100 {
            if RecordType::from(i).is_unknown() {
                assert!(QueryType::from(i).is_unknown());
            }
        }
    }

    #[test]
    fn u16_recordclass_roundtrip() {
        for i in 0..100 {
            assert_eq!(u16::from(RecordClass::from(i)), i);
        }
    }

    #[test]
    fn recordclass_unknown_implies_queryclass_unknown() {
        for i in 0..100 {
            if RecordClass::from(i).is_unknown() {
                assert!(QueryClass::from(i).is_unknown());
            }
        }
    }

    #[test]
    fn domainname_root_conversions() {
        assert_eq!(
            Some(DomainName::root_domain()),
            DomainName::from_dotted_string(".")
        );

        assert_eq!(
            Some(DomainName::root_domain()),
            DomainName::from_labels(vec![Label::new()])
        );

        assert_eq!(".", DomainName::root_domain().to_dotted_string());
    }

    #[test]
    fn from_relative_dotted_string_empty() {
        let origin = domain("com.");
        assert_eq!(
            Some(domain("com.")),
            DomainName::from_relative_dotted_string(&origin, "")
        );
    }

    #[test]
    fn from_relative_dotted_string_absolute() {
        let origin = domain("com.");
        assert_eq!(
            Some(domain("www.example.com.")),
            DomainName::from_relative_dotted_string(&origin, "www.example.com.")
        );
    }

    #[test]
    fn from_relative_dotted_string_relative() {
        let origin = domain("com.");
        assert_eq!(
            Some(domain("www.example.com.")),
            DomainName::from_relative_dotted_string(&origin, "www.example")
        );
    }

    #[test]
    fn make_subdomain_is_subdomain() {
        let sub = domain("foo.");
        let apex = domain("bar.");
        let combined = sub.make_subdomain_of(&apex);

        assert_eq!(Some(domain("foo.bar.")), combined);
        assert!(combined.unwrap().is_subdomain_of(&apex));
    }

    #[test]
    fn domainname_conversions() {
        let mut rng = rand::thread_rng();
        for _ in 0..100 {
            let labels_len = rng.gen_range(0..5);

            let mut dotted_string_input = String::new();
            let mut labels_input = Vec::with_capacity(labels_len);
            let mut output = String::new();

            for i in 0..labels_len {
                let label_len = rng.gen_range(1..10);

                if i > 0 {
                    dotted_string_input.push('.');
                    output.push('.');
                }

                let mut octets = BytesMut::with_capacity(label_len);
                for _ in 0..label_len {
                    let mut chr = rng.gen_range(32..126);

                    if chr == b'.'
                        || chr == b'*'
                        || chr == b'@'
                        || chr == b'#'
                        || (chr as char).is_whitespace()
                    {
                        chr = b'X';
                    }

                    octets.put_u8(chr);
                    dotted_string_input.push(chr as char);
                    output.push(chr.to_ascii_lowercase() as char);
                }
                labels_input.push(Label::try_from(&octets.freeze()[..]).unwrap());
            }

            labels_input.push(Label::new());
            dotted_string_input.push('.');
            output.push('.');

            assert_eq!(
                Some(output.clone()),
                DomainName::from_dotted_string(&dotted_string_input).map(|d| d.to_dotted_string())
            );

            assert_eq!(
                Some(output),
                DomainName::from_labels(labels_input.clone()).map(|d| d.to_dotted_string())
            );

            assert_eq!(
                DomainName::from_dotted_string(&dotted_string_input).map(|d| d.to_dotted_string()),
                DomainName::from_labels(labels_input).map(|d| d.to_dotted_string())
            );
        }
    }
}

#[cfg(any(feature = "test-util", test))]
#[allow(clippy::missing_panics_doc)]
pub mod test_util {
    use super::*;

    use arbitrary::{Arbitrary, Unstructured};
    use rand::Rng;

    pub fn arbitrary_resourcerecord() -> ResourceRecord {
        let mut rng = rand::thread_rng();
        for size in [128, 256, 512, 1024, 2048, 4096] {
            let mut buf = BytesMut::with_capacity(size);
            for _ in 0..size {
                buf.put_u8(rng.gen());
            }

            if let Ok(rr) = ResourceRecord::arbitrary(&mut Unstructured::new(&buf.freeze())) {
                return rr;
            }
        }

        panic!("could not generate arbitrary value!");
    }

    pub fn domain(name: &str) -> DomainName {
        DomainName::from_dotted_string(name).unwrap()
    }

    pub fn a_record(name: &str, address: Ipv4Addr) -> ResourceRecord {
        ResourceRecord {
            name: domain(name),
            rtype_with_data: RecordTypeWithData::A { address },
            rclass: RecordClass::IN,
            ttl: 300,
        }
    }

    pub fn aaaa_record(name: &str, address: Ipv6Addr) -> ResourceRecord {
        ResourceRecord {
            name: domain(name),
            rtype_with_data: RecordTypeWithData::AAAA { address },
            rclass: RecordClass::IN,
            ttl: 300,
        }
    }

    pub fn cname_record(name: &str, target_name: &str) -> ResourceRecord {
        ResourceRecord {
            name: domain(name),
            rtype_with_data: RecordTypeWithData::CNAME {
                cname: domain(target_name),
            },
            rclass: RecordClass::IN,
            ttl: 300,
        }
    }

    pub fn ns_record(superdomain_name: &str, nameserver_name: &str) -> ResourceRecord {
        ResourceRecord {
            name: domain(superdomain_name),
            rtype_with_data: RecordTypeWithData::NS {
                nsdname: domain(nameserver_name),
            },
            rclass: RecordClass::IN,
            ttl: 300,
        }
    }

    pub fn unknown_record(name: &str, octets: &[u8]) -> ResourceRecord {
        ResourceRecord {
            name: domain(name),
            rtype_with_data: RecordTypeWithData::Unknown {
                tag: RecordTypeUnknown(100),
                octets: Bytes::copy_from_slice(octets),
            },
            rclass: RecordClass::IN,
            ttl: 300,
        }
    }
}