domain/base/
header.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
//! The header of a DNS message.
//!
//! Each DNS message starts with a twelve octet long header section
//! containing some general information related to the message as well as
//! the number of records in each of the four sections that follow the header.
//! Its content and format are defined in section 4.1.1 of [RFC 1035].
//!
//! In order to reflect the fact that changing the section counts may
//! invalidate the rest of the message whereas the other elements of the
//! header section can safely be modified, the whole header has been split
//! into two separate types: [`Header`] contains the safely modifyable part
//! at the beginning and [`HeaderCounts`] contains the section counts. In
//! addition, the [`HeaderSection`] type wraps both of them into a single
//! type.
//!
//! [RFC 1035]: https://tools.ietf.org/html/rfc1035

use super::iana::{Opcode, Rcode};
use super::wire::ParseError;
use core::{fmt, mem, str::FromStr};
use octseq::builder::OctetsBuilder;
use octseq::parse::Parser;

//------------ Header --------------------------------------------------

/// The first part of the header of a DNS message.
///
/// This type represents the information contained in the first four octets
/// of the header: the message ID, opcode, rcode, and the various flags. It
/// keeps those four octets in wire representation, i.e., in network byte
/// order. The data is layed out like this:
///
/// ```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 |AD|CD|   RCODE   |
/// +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
/// ```
///
/// Methods are available for accessing each of these fields. For more
/// information on the fields, see these methods in the section
/// [Field Access] below.
///
/// You can create owned values via the [`new`][Self::new] method or
/// the [`Default`] trait.  However, more often the type will
/// be used via a reference into the octets of an actual message. The
/// functions [`for_message_slice`][Self::for_message_slice] and
/// [`for_message_slice_mut`][Self::for_message_slice_mut] create such
/// references from an octets slice.
///
/// The basic structure and most of the fields re defined in [RFC 1035],
/// except for the AD and CD flags, which are defined in [RFC 4035].
///
/// [Field Access]: #field-access
/// [RFC 1035]: https://tools.ietf.org/html/rfc1035
/// [RFC 4035]: https://tools.ietf.org/html/rfc4035
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
#[repr(transparent)]
pub struct Header {
    /// The actual header in its wire format representation.
    ///
    /// This means that the ID field is in big endian.
    inner: [u8; 4],
}

/// # Creation and Conversion
///
impl Header {
    /// Creates a new header.
    ///
    /// The new header has all fields as either zero or false. Thus, the
    /// opcode will be [`Opcode::QUERY`] and the response code will be
    /// [`Rcode::NOERROR`].
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Creates a header reference from an octets slice of a message.
    ///
    /// # Panics
    ///
    /// This function panics if the slice is less than four octets long.
    #[must_use]
    pub fn for_message_slice(s: &[u8]) -> &Header {
        assert!(s.len() >= mem::size_of::<Header>());

        // SAFETY: The pointer cast is sound because
        //  - Header has repr(transparent) and
        //  - the slice is large enough
        unsafe { &*(s.as_ptr() as *const Header) }
    }

    /// Creates a mutable header reference from an octets slice of a message.
    ///
    /// # Panics
    ///
    /// This function panics if the slice is less than four octets long.
    pub fn for_message_slice_mut(s: &mut [u8]) -> &mut Header {
        assert!(s.len() >= mem::size_of::<Header>());

        // SAFETY: The pointer cast is sound because
        //  - Header has repr(transparent) and
        //  - the slice is large enough
        unsafe { &mut *(s.as_mut_ptr() as *mut Header) }
    }

    /// Returns a reference to the underlying octets slice.
    #[must_use]
    pub fn as_slice(&self) -> &[u8] {
        &self.inner
    }
}

/// # Field Access
///
impl Header {
    /// Returns the value of the ID field.
    ///
    /// The ID field is an identifier chosen by whoever created a query
    /// and is copied into a response by a server. It allows matching
    /// incoming responses to their queries.
    ///
    /// When choosing an ID for an outgoing message, make sure it is random
    /// to avoid spoofing by guessing the message ID. If `std` support
    /// is enabled, the method
    #[cfg_attr(
        feature = "std",
        doc = "[`set_random_id`][Self::set_random_id]"
    )]
    #[cfg_attr(not(feature = "std"), doc = "`set_random_id`")]
    /// can be used for this purpose.
    #[must_use]
    pub fn id(self) -> u16 {
        u16::from_be_bytes(self.inner[..2].try_into().unwrap())
    }

    /// Sets the value of the ID field.
    pub fn set_id(&mut self, value: u16) {
        self.inner[..2].copy_from_slice(&value.to_be_bytes())
    }

    /// Sets the value of the ID field to a randomly chosen number.
    #[cfg(feature = "rand")]
    pub fn set_random_id(&mut self) {
        self.set_id(::rand::random())
    }

    /// Returns whether the [QR](Flags::qr) bit is set.
    #[must_use]
    pub fn qr(self) -> bool {
        self.get_bit(2, 7)
    }

    /// Sets the value of the [QR](Flags::qr) bit.
    pub fn set_qr(&mut self, set: bool) {
        self.set_bit(2, 7, set)
    }

    /// Returns the value of the Opcode field.
    ///
    /// This field specifies the kind of query a message contains. See
    /// the [`Opcode`] type for more information on the possible values and
    /// their meaning. Normal queries have the variant [`Opcode::QUERY`]
    /// which is also the default value when creating a new header.
    #[must_use]
    pub fn opcode(self) -> Opcode {
        Opcode::from_int((self.inner[2] >> 3) & 0x0F)
    }

    /// Sets the value of the opcode field.
    pub fn set_opcode(&mut self, opcode: Opcode) {
        self.inner[2] = self.inner[2] & 0x87 | (opcode.to_int() << 3);
    }

    /// Returns all flags contained in the header.
    ///
    /// This is a virtual field composed of all the flag bits that are present
    /// in the header. The returned [`Flags`] type can be useful when you're
    /// working with all flags, rather than a single one, which can be easily
    /// obtained from the header directly.
    #[must_use]
    pub fn flags(self) -> Flags {
        Flags {
            qr: self.qr(),
            aa: self.aa(),
            tc: self.tc(),
            rd: self.rd(),
            ra: self.ra(),
            ad: self.ad(),
            cd: self.cd(),
        }
    }

    /// Sets all flag bits.
    pub fn set_flags(&mut self, flags: Flags) {
        self.set_qr(flags.qr);
        self.set_aa(flags.aa);
        self.set_tc(flags.tc);
        self.set_rd(flags.rd);
        self.set_ra(flags.ra);
        self.set_ad(flags.ad);
        self.set_cd(flags.cd);
    }

    /// Returns whether the [AA](Flags::aa) bit is set.
    #[must_use]
    pub fn aa(self) -> bool {
        self.get_bit(2, 2)
    }

    /// Sets the value of the [AA](Flags::aa) bit.
    pub fn set_aa(&mut self, set: bool) {
        self.set_bit(2, 2, set)
    }

    /// Returns whether the [TC](Flags::tc) bit is set.
    #[must_use]
    pub fn tc(self) -> bool {
        self.get_bit(2, 1)
    }

    /// Sets the value of the [TC](Flags::tc) bit.
    pub fn set_tc(&mut self, set: bool) {
        self.set_bit(2, 1, set)
    }

    /// Returns whether the [RD](Flags::rd) bit is set.
    #[must_use]
    pub fn rd(self) -> bool {
        self.get_bit(2, 0)
    }

    /// Sets the value of the [RD](Flags::rd) bit.
    pub fn set_rd(&mut self, set: bool) {
        self.set_bit(2, 0, set)
    }

    /// Returns whether the [RA](Flags::ra) bit is set.
    #[must_use]
    pub fn ra(self) -> bool {
        self.get_bit(3, 7)
    }

    /// Sets the value of the [RA](Flags::ra) bit.
    pub fn set_ra(&mut self, set: bool) {
        self.set_bit(3, 7, set)
    }

    /// Returns whether the reserved bit is set.
    ///
    /// This bit must be `false` in all queries and responses.
    #[must_use]
    pub fn z(self) -> bool {
        self.get_bit(3, 6)
    }

    /// Sets the value of the reserved bit.
    pub fn set_z(&mut self, set: bool) {
        self.set_bit(3, 6, set)
    }

    /// Returns whether the [AD](Flags::ad) bit is set.
    #[must_use]
    pub fn ad(self) -> bool {
        self.get_bit(3, 5)
    }

    /// Sets the value of the [AD](Flags::ad) bit.
    pub fn set_ad(&mut self, set: bool) {
        self.set_bit(3, 5, set)
    }

    /// Returns whether the [CD](Flags::cd) bit is set.
    #[must_use]
    pub fn cd(self) -> bool {
        self.get_bit(3, 4)
    }

    /// Sets the value of the [CD](Flags::cd) bit.
    pub fn set_cd(&mut self, set: bool) {
        self.set_bit(3, 4, set)
    }

    /// Returns the value of the RCODE field.
    ///
    /// The *response code* is used in a response to indicate what happened
    /// when processing the query. See the [`Rcode`] type for information on
    /// possible values and their meaning.
    ///
    /// [`Rcode`]: ../../iana/rcode/enum.Rcode.html
    #[must_use]
    pub fn rcode(self) -> Rcode {
        Rcode::masked_from_int(self.inner[3])
    }

    /// Sets the value of the RCODE field.
    pub fn set_rcode(&mut self, rcode: Rcode) {
        self.inner[3] = self.inner[3] & 0xF0 | (rcode.to_int() & 0x0F);
    }

    //--- Internal helpers

    /// Returns the value of the bit at the given position.
    ///
    /// The argument `offset` gives the byte offset of the underlying bytes
    /// slice and `bit` gives the number of the bit with the most significant
    /// bit being 7.
    fn get_bit(self, offset: usize, bit: usize) -> bool {
        self.inner[offset] & (1 << bit) != 0
    }

    /// Sets or resets the given bit.
    fn set_bit(&mut self, offset: usize, bit: usize, set: bool) {
        if set {
            self.inner[offset] |= 1 << bit
        } else {
            self.inner[offset] &= !(1 << bit)
        }
    }
}

//------------ Flags ---------------------------------------------------

/// The flags contained in the DNS message header.
///
/// This is a utility type that makes it easier to work with flags. It contains
/// only standard DNS message flags that are part of the [`Header`], i.e., EDNS
/// flags are not included.
///
/// This type has a text notation and can be created from it as well. Each
/// flags that is set is represented by a two-letter token, which is the
/// uppercase version of the flag name.  If mutliple flags are set, the tokens
/// are separated by space.
///
/// ```
/// use core::str::FromStr;
/// use domain::base::header::Flags;
///
/// let flags = Flags::from_str("QR AA").unwrap();
/// assert!(flags.qr && flags.aa);
/// assert_eq!(format!("{}", flags), "QR AA");
/// ```
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Hash)]
pub struct Flags {
    /// The `QR` bit specifies whether a message is a query (`false`) or a
    /// response (`true`). In other words, this bit is actually stating whether
    /// the message is *not* a query. So, perhaps it might be good to read ‘QR’
    /// as ‘query response.’
    pub qr: bool,

    /// Using the `AA` bit, a name server generating a response states whether
    /// it is authoritative for the requested domain name, ie., whether this
    /// response is an *authoritative answer.* The field has no meaning in a
    /// query.
    pub aa: bool,

    /// The *truncation* (`TC`) bit is set if there was more data available then
    /// fit into the message. This is typically used when employing datagram
    /// transports such as UDP to signal that the answer didn’t fit into a
    /// response and the query should be tried again using a stream transport
    /// such as TCP.
    pub tc: bool,

    /// The *recursion desired* (`RD`) bit may be set in a query to ask the name
    /// server to try and recursively gather a response if it doesn’t have the
    /// data available locally. The bit’s value is copied into the response.
    pub rd: bool,

    /// In a response, the *recursion available* (`RA`) bit denotes whether the
    /// responding name server supports recursion. It has no meaning in a query.
    pub ra: bool,

    /// The *authentic data* (`AD`) bit is used by security-aware recursive name
    /// servers to indicate that it considers all RRsets in its response are
    /// authentic, i.e., have successfully passed DNSSEC validation.
    pub ad: bool,

    /// The *checking disabled* (`CD`) bit is used by a security-aware resolver
    /// to indicate that it does not want upstream name servers to perform
    /// verification but rather would like to verify everything itself.
    pub cd: bool,
}

/// # Creation and Conversion
///
impl Flags {
    /// Creates new flags.
    ///
    /// All flags will be unset.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }
}

//--- Display & FromStr

impl fmt::Display for Flags {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let mut sep = "";
        if self.qr {
            write!(f, "QR")?;
            sep = " ";
        }
        if self.aa {
            write!(f, "{}AA", sep)?;
            sep = " ";
        }
        if self.tc {
            write!(f, "{}TC", sep)?;
            sep = " ";
        }
        if self.rd {
            write!(f, "{}RD", sep)?;
            sep = " ";
        }
        if self.ra {
            write!(f, "{}RA", sep)?;
            sep = " ";
        }
        if self.ad {
            write!(f, "{}AD", sep)?;
            sep = " ";
        }
        if self.cd {
            write!(f, "{}CD", sep)?;
        }
        Ok(())
    }
}

impl FromStr for Flags {
    type Err = FlagsFromStrError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let mut flags = Flags::new();
        for token in s.split(' ') {
            match token {
                "QR" | "Qr" | "qR" | "qr" => flags.qr = true,
                "AA" | "Aa" | "aA" | "aa" => flags.aa = true,
                "TC" | "Tc" | "tC" | "tc" => flags.tc = true,
                "RD" | "Rd" | "rD" | "rd" => flags.rd = true,
                "RA" | "Ra" | "rA" | "ra" => flags.ra = true,
                "AD" | "Ad" | "aD" | "ad" => flags.ad = true,
                "CD" | "Cd" | "cD" | "cd" => flags.cd = true,
                "" => {}
                _ => return Err(FlagsFromStrError(())),
            }
        }
        Ok(flags)
    }
}

//------------ HeaderCounts -------------------------------------------------

/// The section count part of the header section of a DNS message.
///
/// This part consists of four 16 bit counters for the number of entries in
/// the four sections of a DNS message. The type contains the sequence of
/// these for values in wire format, i.e., in network byte order.
///
/// The counters are arranged in the same order as the sections themselves:
/// QDCOUNT for the question section, ANCOUNT for the answer section,
/// NSCOUNT for the authority section, and ARCOUNT for the additional section.
/// These are defined in [RFC 1035].
///
/// Like with the other header part, you can create an owned value via the
/// [`new`][Self::new] method or the `Default` trait or can get a reference
/// to the value atop a message slice via
/// [`for_message_slice`][Self::for_message_slice] or
/// [`for_message_slice_mut`][Self::for_message_slice_mut].
///
/// For each field there are three methods for getting, setting, and
/// incrementing.
///
/// [RFC 2136] defines the UPDATE method and reuses the four section for
/// different purposes. Here the counters are ZOCOUNT for the zone section,
/// PRCOUNT for the prerequisite section, UPCOUNT for the update section,
/// and ADCOUNT for the additional section. The type has convenience methods
/// for these fields as well so you don’t have to remember which is which.
///
/// [RFC 1035]: https://tools.ietf.org/html/rfc1035
/// [RFC 2136]: https://tools.ietf.org/html/rfc2136
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
#[repr(transparent)]
pub struct HeaderCounts {
    /// The actual headers in their wire-format representation.
    ///
    /// Ie., all values are stored big endian.
    inner: [u8; 8],
}

/// # Creation and Conversion
///
impl HeaderCounts {
    /// Creates a new value with all counters set to zero.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Creates a header counts reference from the octets slice of a message.
    ///
    /// The slice `message` mut be the whole message, i.e., start with the
    /// bytes of the [`Header`](struct.Header.html).
    ///
    /// # Panics
    ///
    /// This function panics if the octets slice is shorter than 24 octets.
    #[must_use]
    pub fn for_message_slice(message: &[u8]) -> &Self {
        assert!(message.len() >= mem::size_of::<HeaderSection>());

        // SAFETY: The pointer cast is sound because
        //  - HeaderCounts has repr(transparent) and
        //  - the slice is large enough for a HeaderSection, which contains
        //    both a Header (which we trim) and a HeaderCounts.
        unsafe {
            &*((message[mem::size_of::<Header>()..].as_ptr())
                as *const HeaderCounts)
        }
    }

    /// Creates a mutable counts reference from the octets slice of a message.
    ///
    /// The slice `message` mut be the whole message, i.e., start with the
    /// bytes of the [`Header`].
    ///
    /// # Panics
    ///
    /// This function panics if the octets slice is shorter than 24 octets.
    pub fn for_message_slice_mut(message: &mut [u8]) -> &mut Self {
        assert!(message.len() >= mem::size_of::<HeaderSection>());

        // SAFETY: The pointer cast is sound because
        //  - HeaderCounts has repr(transparent) and
        //  - the slice is large enough for a HeaderSection, which contains
        //    both a Header (which we trim) and a HeaderCounts.
        unsafe {
            &mut *((message[mem::size_of::<Header>()..].as_mut_ptr())
                as *mut HeaderCounts)
        }
    }

    /// Returns a reference to the raw octets slice of the header counts.
    #[must_use]
    pub fn as_slice(&self) -> &[u8] {
        &self.inner
    }

    /// Returns a mutable reference to the octets slice of the header counts.
    pub fn as_slice_mut(&mut self) -> &mut [u8] {
        &mut self.inner
    }

    /// Sets the counts to those from `counts`.
    pub fn set(&mut self, counts: HeaderCounts) {
        self.as_slice_mut().copy_from_slice(counts.as_slice())
    }
}

/// # Field Access
///
impl HeaderCounts {
    //--- Count fields in regular messages

    /// Returns the value of the QDCOUNT field.
    ///
    /// This field contains the number of questions in the first
    /// section of the message, normally the question section.
    #[must_use]
    pub fn qdcount(self) -> u16 {
        self.get_u16(0)
    }

    /// Sets the value of the QDCOUNT field.
    pub fn set_qdcount(&mut self, value: u16) {
        self.set_u16(0, value)
    }

    /// Increases the value of the QDCOUNT field by one.
    ///
    /// If increasing the counter would result in an overflow, returns an
    /// error.
    pub fn inc_qdcount(&mut self) -> Result<(), CountOverflow> {
        match self.qdcount().checked_add(1) {
            Some(count) => {
                self.set_qdcount(count);
                Ok(())
            }
            None => Err(CountOverflow(())),
        }
    }

    /// Decreases the value of the QDCOUNT field by one.
    ///
    /// # Panics
    ///
    /// This method panics if the count is already zero.
    pub fn dec_qdcount(&mut self) {
        let count = self.qdcount();
        assert!(count > 0);
        self.set_qdcount(count - 1);
    }

    /// Returns the value of the ANCOUNT field.
    ///
    /// This field contains the number of resource records in the second
    /// section of the message, normally the answer section.
    #[must_use]
    pub fn ancount(self) -> u16 {
        self.get_u16(2)
    }

    /// Sets the value of the ANCOUNT field.
    pub fn set_ancount(&mut self, value: u16) {
        self.set_u16(2, value)
    }

    /// Increases the value of the ANCOUNT field by one.
    ///
    /// If increasing the counter would result in an overflow, returns an
    /// error.
    pub fn inc_ancount(&mut self) -> Result<(), CountOverflow> {
        match self.ancount().checked_add(1) {
            Some(count) => {
                self.set_ancount(count);
                Ok(())
            }
            None => Err(CountOverflow(())),
        }
    }

    /// Decreases the value of the ANCOUNT field by one.
    ///
    /// # Panics
    ///
    /// This method panics if the count is already zero.
    pub fn dec_ancount(&mut self) {
        let count = self.ancount();
        assert!(count > 0);
        self.set_ancount(count - 1);
    }

    /// Returns the value of the NSCOUNT field.
    ///
    /// This field contains the number of resource records in the third
    /// section of the message, normally the authority section.
    #[must_use]
    pub fn nscount(self) -> u16 {
        self.get_u16(4)
    }

    /// Sets the value of the NSCOUNT field.
    pub fn set_nscount(&mut self, value: u16) {
        self.set_u16(4, value)
    }

    /// Increases the value of the NSCOUNT field by one.
    ///
    /// If increasing the counter would result in an overflow, returns an
    /// error.
    pub fn inc_nscount(&mut self) -> Result<(), CountOverflow> {
        match self.nscount().checked_add(1) {
            Some(count) => {
                self.set_nscount(count);
                Ok(())
            }
            None => Err(CountOverflow(())),
        }
    }

    /// Decreases the value of the NSCOUNT field by one.
    ///
    /// # Panics
    ///
    /// This method panics if the count is already zero.
    pub fn dec_nscount(&mut self) {
        let count = self.nscount();
        assert!(count > 0);
        self.set_nscount(count - 1);
    }

    /// Returns the value of the ARCOUNT field.
    ///
    /// This field contains the number of resource records in the fourth
    /// section of the message, normally the additional section.
    #[must_use]
    pub fn arcount(self) -> u16 {
        self.get_u16(6)
    }

    /// Sets the value of the ARCOUNT field.
    pub fn set_arcount(&mut self, value: u16) {
        self.set_u16(6, value)
    }

    /// Increases the value of the ARCOUNT field by one.
    ///
    /// If increasing the counter would result in an overflow, returns an
    /// error.
    pub fn inc_arcount(&mut self) -> Result<(), CountOverflow> {
        match self.arcount().checked_add(1) {
            Some(count) => {
                self.set_arcount(count);
                Ok(())
            }
            None => Err(CountOverflow(())),
        }
    }

    /// Decreases the value of the ARCOUNT field by one.
    ///
    /// # Panics
    ///
    /// This method panics if the count is already zero.
    pub fn dec_arcount(&mut self) {
        let count = self.arcount();
        assert!(count > 0);
        self.set_arcount(count - 1);
    }

    //--- Count fields in UPDATE messages

    /// Returns the value of the ZOCOUNT field.
    ///
    /// This is the same as the `qdcount()`. It is used in UPDATE queries
    /// where the first section is the zone section.
    #[must_use]
    pub fn zocount(self) -> u16 {
        self.qdcount()
    }

    /// Sets the value of the ZOCOUNT field.
    pub fn set_zocount(&mut self, value: u16) {
        self.set_qdcount(value)
    }

    /// Returns the value of the PRCOUNT field.
    ///
    /// This is the same as the `ancount()`. It is used in UPDATE queries
    /// where the first section is the prerequisite section.
    #[must_use]
    pub fn prcount(self) -> u16 {
        self.ancount()
    }

    /// Sete the value of the PRCOUNT field.
    pub fn set_prcount(&mut self, value: u16) {
        self.set_ancount(value)
    }

    /// Returns the value of the UPCOUNT field.
    ///
    /// This is the same as the `nscount()`. It is used in UPDATE queries
    /// where the first section is the update section.
    #[must_use]
    pub fn upcount(self) -> u16 {
        self.nscount()
    }

    /// Sets the value of the UPCOUNT field.
    pub fn set_upcount(&mut self, value: u16) {
        self.set_nscount(value)
    }

    /// Returns the value of the ADCOUNT field.
    ///
    /// This is the same as the `arcount()`. It is used in UPDATE queries
    /// where the first section is the additional section.
    #[must_use]
    pub fn adcount(self) -> u16 {
        self.arcount()
    }

    /// Sets the value of the ADCOUNT field.
    pub fn set_adcount(&mut self, value: u16) {
        self.set_arcount(value)
    }

    //--- Internal helpers

    /// Returns the value of the 16 bit integer starting at a given offset.
    fn get_u16(self, offset: usize) -> u16 {
        u16::from_be_bytes(self.inner[offset..offset + 2].try_into().unwrap())
    }

    /// Sets the value of the 16 bit integer starting at a given offset.
    fn set_u16(&mut self, offset: usize, value: u16) {
        self.inner[offset..offset + 2].copy_from_slice(&value.to_be_bytes())
    }
}

//------------ HeaderSection -------------------------------------------------

/// The complete header section of a DNS message.
///
/// Consists of a [`Header`] directly followed by a [`HeaderCounts`].
///
/// You can create an owned value via the [`new`][Self::new] function or the
/// `Default` trait and acquire a pointer referring the the header section of
/// an existing DNS message via the
/// [`for_message_slice`][Self::for_message_slice] or
/// [`for_message_slice_mut`][Self::for_message_slice_mut]
/// functions.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
#[repr(transparent)]
pub struct HeaderSection {
    inner: [u8; 12],
}

/// # Creation and Conversion
///
impl HeaderSection {
    /// Creates a new header section.
    ///
    /// The value will have all header and header counts fields set to zero
    /// or false.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Creates a reference from the octets slice of a message.
    ///
    /// # Panics
    ///
    /// This function panics if the octets slice is shorter than 12 octets.
    #[must_use]
    pub fn for_message_slice(s: &[u8]) -> &HeaderSection {
        assert!(s.len() >= mem::size_of::<HeaderSection>());
        unsafe { &*(s.as_ptr() as *const HeaderSection) }
    }

    /// Creates a mutable reference from the octets slice of a message.
    ///
    /// # Panics
    ///
    /// This function panics if the octets slice is shorter than 12 octets.
    pub fn for_message_slice_mut(s: &mut [u8]) -> &mut HeaderSection {
        assert!(s.len() >= mem::size_of::<HeaderSection>());
        unsafe { &mut *(s.as_mut_ptr() as *mut HeaderSection) }
    }

    /// Returns a reference to the underlying octets slice.
    #[must_use]
    pub fn as_slice(&self) -> &[u8] {
        &self.inner
    }
}

/// # Access to Header and Counts
///
impl HeaderSection {
    /// Returns a reference to the header.
    #[must_use]
    pub fn header(&self) -> &Header {
        Header::for_message_slice(&self.inner)
    }

    /// Returns a mutable reference to the header.
    pub fn header_mut(&mut self) -> &mut Header {
        Header::for_message_slice_mut(&mut self.inner)
    }

    /// Returns a reference to the header counts.
    #[must_use]
    pub fn counts(&self) -> &HeaderCounts {
        HeaderCounts::for_message_slice(&self.inner)
    }

    /// Returns a mutable reference to the header counts.
    pub fn counts_mut(&mut self) -> &mut HeaderCounts {
        HeaderCounts::for_message_slice_mut(&mut self.inner)
    }
}

/// # Parsing and Composing
///
impl HeaderSection {
    pub fn parse<Octs: AsRef<[u8]>>(
        parser: &mut Parser<Octs>,
    ) -> Result<Self, ParseError> {
        let mut res = Self::default();
        parser.parse_buf(&mut res.inner)?;
        Ok(res)
    }

    pub fn compose<Target: OctetsBuilder + ?Sized>(
        &self,
        target: &mut Target,
    ) -> Result<(), Target::AppendError> {
        target.append_slice(&self.inner)
    }
}

//--- AsRef and AsMut

impl AsRef<Header> for HeaderSection {
    fn as_ref(&self) -> &Header {
        self.header()
    }
}

impl AsMut<Header> for HeaderSection {
    fn as_mut(&mut self) -> &mut Header {
        self.header_mut()
    }
}

impl AsRef<HeaderCounts> for HeaderSection {
    fn as_ref(&self) -> &HeaderCounts {
        self.counts()
    }
}

impl AsMut<HeaderCounts> for HeaderSection {
    fn as_mut(&mut self) -> &mut HeaderCounts {
        self.counts_mut()
    }
}

//============ Error Types ===================================================

//------------ FlagsFromStrError --------------------------------------------

/// An error happened when converting string to flags.
#[derive(Debug)]
pub struct FlagsFromStrError(());

impl fmt::Display for FlagsFromStrError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "illegal flags token")
    }
}

#[cfg(feature = "std")]
impl std::error::Error for FlagsFromStrError {}

//------------ CountOverflow -------------------------------------------------

/// An error happened while increasing a header count.
#[derive(Debug)]
pub struct CountOverflow(());

impl fmt::Display for CountOverflow {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "increasing a header count lead to an overflow")
    }
}

#[cfg(feature = "std")]
impl std::error::Error for CountOverflow {}

//============ Testing ======================================================

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

    #[test]
    #[cfg(feature = "std")]
    fn for_slice() {
        use std::vec::Vec;

        let header = b"\x01\x02\x00\x00\x12\x34\x56\x78\x9a\xbc\xde\xf0";
        let mut vec = Vec::from(&header[..]);
        assert_eq!(
            Header::for_message_slice(header).as_slice(),
            b"\x01\x02\x00\x00"
        );
        assert_eq!(
            Header::for_message_slice_mut(vec.as_mut()).as_slice(),
            b"\x01\x02\x00\x00"
        );
        assert_eq!(
            HeaderCounts::for_message_slice(header).as_slice(),
            b"\x12\x34\x56\x78\x9a\xbc\xde\xf0"
        );
        assert_eq!(
            HeaderCounts::for_message_slice_mut(vec.as_mut()).as_slice(),
            b"\x12\x34\x56\x78\x9a\xbc\xde\xf0"
        );
        assert_eq!(
            HeaderSection::for_message_slice(header).as_slice(),
            header
        );
        assert_eq!(
            HeaderSection::for_message_slice_mut(vec.as_mut()).as_slice(),
            header
        );
    }

    #[test]
    #[should_panic]
    fn short_header() {
        let _ = Header::for_message_slice(b"134");
    }

    #[test]
    #[should_panic]
    fn short_header_counts() {
        let _ = HeaderCounts::for_message_slice(b"12345678");
    }

    #[test]
    #[should_panic]
    fn short_header_section() {
        let _ = HeaderSection::for_message_slice(b"1234");
    }

    macro_rules! test_field {
        ($get:ident, $set:ident, $default:expr, $($value:expr),*) => {
            $({
                let mut h = Header::new();
                assert_eq!(h.$get(), $default);
                h.$set($value);
                assert_eq!(h.$get(), $value);
            })*
        }
    }

    #[test]
    fn header() {
        test_field!(id, set_id, 0, 0x1234);
        test_field!(qr, set_qr, false, true, false);
        test_field!(opcode, set_opcode, Opcode::QUERY, Opcode::NOTIFY);
        test_field!(
            flags,
            set_flags,
            Flags::new(),
            Flags {
                qr: true,
                ..Default::default()
            }
        );
        test_field!(aa, set_aa, false, true, false);
        test_field!(tc, set_tc, false, true, false);
        test_field!(rd, set_rd, false, true, false);
        test_field!(ra, set_ra, false, true, false);
        test_field!(z, set_z, false, true, false);
        test_field!(ad, set_ad, false, true, false);
        test_field!(cd, set_cd, false, true, false);
        test_field!(rcode, set_rcode, Rcode::NOERROR, Rcode::REFUSED);
    }

    #[test]
    fn counts() {
        let mut c = HeaderCounts {
            inner: [1, 2, 3, 4, 5, 6, 7, 8],
        };
        assert_eq!(c.qdcount(), 0x0102);
        assert_eq!(c.ancount(), 0x0304);
        assert_eq!(c.nscount(), 0x0506);
        assert_eq!(c.arcount(), 0x0708);
        c.inc_qdcount().unwrap();
        c.inc_ancount().unwrap();
        c.inc_nscount().unwrap();
        c.inc_arcount().unwrap();
        assert_eq!(c.inner, [1, 3, 3, 5, 5, 7, 7, 9]);
        c.set_qdcount(0x0807);
        c.set_ancount(0x0605);
        c.set_nscount(0x0403);
        c.set_arcount(0x0201);
        assert_eq!(c.inner, [8, 7, 6, 5, 4, 3, 2, 1]);
    }

    #[test]
    fn update_counts() {
        let mut c = HeaderCounts {
            inner: [1, 2, 3, 4, 5, 6, 7, 8],
        };
        assert_eq!(c.zocount(), 0x0102);
        assert_eq!(c.prcount(), 0x0304);
        assert_eq!(c.upcount(), 0x0506);
        assert_eq!(c.adcount(), 0x0708);
        c.set_zocount(0x0807);
        c.set_prcount(0x0605);
        c.set_upcount(0x0403);
        c.set_adcount(0x0201);
        assert_eq!(c.inner, [8, 7, 6, 5, 4, 3, 2, 1]);
    }

    #[test]
    fn inc_qdcount() {
        let mut c = HeaderCounts {
            inner: [0xff, 0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff],
        };
        assert!(c.inc_qdcount().is_ok());
        assert!(c.inc_qdcount().is_err());
    }

    #[test]
    fn inc_ancount() {
        let mut c = HeaderCounts {
            inner: [0xff, 0xff, 0xff, 0xfe, 0xff, 0xff, 0xff, 0xff],
        };
        assert!(c.inc_ancount().is_ok());
        assert!(c.inc_ancount().is_err());
    }

    #[test]
    fn inc_nscount() {
        let mut c = HeaderCounts {
            inner: [0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 0xff, 0xff],
        };
        assert!(c.inc_nscount().is_ok());
        assert!(c.inc_nscount().is_err());
    }

    #[test]
    fn inc_arcount() {
        let mut c = HeaderCounts {
            inner: [0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe],
        };
        assert!(c.inc_arcount().is_ok());
        assert!(c.inc_arcount().is_err());
    }

    #[cfg(feature = "std")]
    #[test]
    fn flags_display() {
        let f = Flags::new();
        assert_eq!(format!("{}", f), "");
        let f = Flags {
            qr: true,
            aa: true,
            tc: true,
            rd: true,
            ra: true,
            ad: true,
            cd: true,
        };
        assert_eq!(format!("{}", f), "QR AA TC RD RA AD CD");
        let mut f = Flags::new();
        f.rd = true;
        f.cd = true;
        assert_eq!(format!("{}", f), "RD CD");
    }

    #[cfg(feature = "std")]
    #[test]
    fn flags_from_str() {
        let f1 = Flags::from_str("").unwrap();
        let f2 = Flags::new();
        assert_eq!(f1, f2);
        let f1 = Flags::from_str("QR AA TC RD RA AD CD").unwrap();
        let f2 = Flags {
            qr: true,
            aa: true,
            tc: true,
            rd: true,
            ra: true,
            ad: true,
            cd: true,
        };
        assert_eq!(f1, f2);
        let f1 = Flags::from_str("tC Aa CD rd").unwrap();
        let f2 = Flags {
            aa: true,
            tc: true,
            rd: true,
            cd: true,
            ..Default::default()
        };
        assert_eq!(f1, f2);
        let f1 = Flags::from_str("XXXX");
        assert!(f1.is_err());
    }
}