trust_dns_proto/rr/rdata/
csync.rs

1// Copyright 2015-2021 Benjamin Fry <benjaminfry@me.com>
2//
3// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
4// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
5// http://opensource.org/licenses/MIT>, at your option. This file may not be
6// copied, modified, or distributed except according to those terms.
7
8//! CSYNC record for synchronizing data from a child zone to the parent
9
10use std::fmt;
11
12#[cfg(feature = "serde-config")]
13use serde::{Deserialize, Serialize};
14
15use crate::error::*;
16use crate::rr::type_bit_map::{decode_type_bit_maps, encode_type_bit_maps};
17use crate::rr::RecordType;
18use crate::serialize::binary::*;
19
20/// [RFC 7477, Child-to-Parent Synchronization in DNS, March 2015][rfc7477]
21///
22/// ```text
23/// 2.1.1.  The CSYNC Resource Record Wire Format
24///
25/// The CSYNC RDATA consists of the following fields:
26///
27///                       1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
28///   0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
29///  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
30///  |                          SOA Serial                           |
31///  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
32///  |       Flags                   |            Type Bit Map       /
33///  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
34///  /                     Type Bit Map (continued)                  /
35///  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
36/// ```
37///
38/// [rfc7477]: https://tools.ietf.org/html/rfc7477
39#[cfg_attr(feature = "serde-config", derive(Deserialize, Serialize))]
40#[derive(Debug, PartialEq, Eq, Hash, Clone)]
41pub struct CSYNC {
42    soa_serial: u32,
43    immediate: bool,
44    soa_minimum: bool,
45    type_bit_maps: Vec<RecordType>,
46}
47
48impl CSYNC {
49    /// Creates a new CSYNC record data.
50    ///
51    /// # Arguments
52    ///
53    /// * `soa_serial` - A serial number for the zone
54    /// * `immediate` - A flag signalling if the change should happen immediately
55    /// * `soa_minimum` - A flag to used to signal if the soa_serial should be validated
56    /// * `type_bit_maps` - a bit map of the types to synchronize
57    ///
58    /// # Return value
59    ///
60    /// The new CSYNC record data.
61    pub fn new(
62        soa_serial: u32,
63        immediate: bool,
64        soa_minimum: bool,
65        type_bit_maps: Vec<RecordType>,
66    ) -> Self {
67        Self {
68            soa_serial,
69            immediate,
70            soa_minimum,
71            type_bit_maps,
72        }
73    }
74
75    /// [RFC 7477](https://tools.ietf.org/html/rfc7477#section-2.1.1.2.1), Child-to-Parent Synchronization in DNS, March 2015
76    ///
77    /// ```text
78    /// 2.1.1.2.1.  The Type Bit Map Field
79    ///
80    ///    The Type Bit Map field indicates the record types to be processed by
81    ///    the parental agent, according to the procedures in Section 3.  The
82    ///    Type Bit Map field is encoded in the same way as the Type Bit Map
83    ///    field of the NSEC record, described in [RFC4034], Section 4.1.2.  If
84    ///    a bit has been set that a parental agent implementation does not
85    ///    understand, the parental agent MUST NOT act upon the record.
86    ///    Specifically, a parental agent must not simply copy the data, and it
87    ///    must understand the semantics associated with a bit in the Type Bit
88    ///    Map field that has been set to 1.
89    /// ```
90    pub fn type_bit_maps(&self) -> &[RecordType] {
91        &self.type_bit_maps
92    }
93
94    /// [RFC 7477](https://tools.ietf.org/html/rfc7477#section-2.1.1.2), Child-to-Parent Synchronization in DNS, March 2015
95    ///
96    /// ```text
97    /// 2.1.1.2.  The Flags Field
98    ///
99    ///    The Flags field contains 16 bits of boolean flags that define
100    ///    operations that affect the processing of the CSYNC record.  The flags
101    ///    defined in this document are as follows:
102    ///
103    ///       0x00 0x01: "immediate"
104    ///
105    ///       0x00 0x02: "soaminimum"
106    ///
107    ///    The definitions for how the flags are to be used can be found in
108    ///    Section 3.
109    ///
110    ///    The remaining flags are reserved for use by future specifications.
111    ///    Undefined flags MUST be set to 0 by CSYNC publishers.  Parental
112    ///    agents MUST NOT process a CSYNC record if it contains a 1 value for a
113    ///    flag that is unknown to or unsupported by the parental agent.
114    /// ```
115    pub fn flags(&self) -> u16 {
116        let mut flags: u16 = 0;
117        if self.immediate {
118            flags |= 0b0000_0001
119        };
120        if self.soa_minimum {
121            flags |= 0b0000_0010
122        };
123        flags
124    }
125}
126
127/// Read the RData from the given Decoder
128pub fn read(decoder: &mut BinDecoder<'_>, rdata_length: Restrict<u16>) -> ProtoResult<CSYNC> {
129    let start_idx = decoder.index();
130
131    let soa_serial = decoder.read_u32()?.unverified();
132
133    let flags: u16 = decoder
134        .read_u16()?
135        .verify_unwrap(|flags| flags & 0b1111_1100 == 0)
136        .map_err(|flags| ProtoError::from(ProtoErrorKind::UnrecognizedCsyncFlags(flags)))?;
137
138    let immediate: bool = flags & 0b0000_0001 == 0b0000_0001;
139    let soa_minimum: bool = flags & 0b0000_0010 == 0b0000_0010;
140
141    let bit_map_len = rdata_length
142        .map(|u| u as usize)
143        .checked_sub(decoder.index() - start_idx)
144        .map_err(|_| ProtoError::from("invalid rdata length in CSYNC"))?;
145    let record_types = decode_type_bit_maps(decoder, bit_map_len)?;
146
147    Ok(CSYNC::new(soa_serial, immediate, soa_minimum, record_types))
148}
149
150/// Write the RData from the given Decoder
151pub fn emit(encoder: &mut BinEncoder<'_>, csync: &CSYNC) -> ProtoResult<()> {
152    encoder.emit_u32(csync.soa_serial)?;
153    encoder.emit_u16(csync.flags())?;
154    encode_type_bit_maps(encoder, csync.type_bit_maps())?;
155
156    Ok(())
157}
158
159impl fmt::Display for CSYNC {
160    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
161        write!(
162            f,
163            "{soa_serial} {flags}",
164            soa_serial = &self.soa_serial,
165            flags = &self.flags(),
166        )?;
167
168        for ty in &self.type_bit_maps {
169            write!(f, " {}", ty)?;
170        }
171
172        Ok(())
173    }
174}
175
176#[cfg(test)]
177mod tests {
178    #![allow(clippy::dbg_macro, clippy::print_stdout)]
179
180    use super::*;
181
182    #[test]
183    fn test() {
184        let types = vec![RecordType::A, RecordType::NS, RecordType::AAAA];
185
186        let rdata = CSYNC::new(123, true, true, types);
187
188        let mut bytes = Vec::new();
189        let mut encoder: BinEncoder<'_> = BinEncoder::new(&mut bytes);
190        assert!(emit(&mut encoder, &rdata).is_ok());
191        let bytes = encoder.into_bytes();
192
193        println!("bytes: {:?}", bytes);
194
195        let mut decoder: BinDecoder<'_> = BinDecoder::new(bytes);
196        let restrict = Restrict::new(bytes.len() as u16);
197        let read_rdata = read(&mut decoder, restrict).expect("Decoding error");
198        assert_eq!(rdata, read_rdata);
199    }
200}