Skip to main content

hickory_proto/rr/rdata/
csync.rs

1// Copyright 2015-2023 Benjamin Fry <benjaminfry@me.com>
2//
3// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
4// https://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
5// https://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 alloc::{collections::BTreeSet, string::ToString};
11use core::{fmt, str::FromStr};
12
13#[cfg(feature = "serde")]
14use serde::{Deserialize, Serialize};
15
16use crate::{
17    error::*,
18    rr::{RData, RecordData, RecordDataDecodable, RecordType, RecordTypeSet},
19    serialize::{binary::*, txt::ParseError},
20};
21
22/// [RFC 7477, Child-to-Parent Synchronization in DNS, March 2015][rfc7477]
23///
24/// ```text
25/// 2.1.1.  The CSYNC Resource Record Wire Format
26///
27/// The CSYNC RDATA consists of the following fields:
28///
29///                       1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
30///   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
31///  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
32///  |                          SOA Serial                           |
33///  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
34///  |       Flags                   |            Type Bit Map       /
35///  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
36///  /                     Type Bit Map (continued)                  /
37///  +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
38/// ```
39///
40/// [rfc7477]: https://tools.ietf.org/html/rfc7477
41#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
42#[derive(Debug, PartialEq, Eq, Hash, Clone)]
43#[non_exhaustive]
44pub struct CSYNC {
45    /// [RFC 7477](https://datatracker.ietf.org/doc/html/rfc7477#section-2.1.1.1)
46    ///
47    /// ```text
48    /// 2.1.1.1.  The SOA Serial Field
49    ///
50    ///    The SOA Serial field contains a copy of the 32-bit SOA serial number
51    ///    from the child zone.  If the soaminimum flag is set, parental agents
52    ///    querying children's authoritative servers MUST NOT act on data from
53    ///    zones advertising an SOA serial number less than this value.  See
54    ///    [RFC1982] for properly implementing "less than" logic.  If the
55    ///    soaminimum flag is not set, parental agents MUST ignore the value in
56    ///    the SOA Serial field.  Clients can set the field to any value if the
57    ///    soaminimum flag is unset, such as the number zero.
58    ///
59    ///    Note that a child zone's current SOA serial number may be greater
60    ///    than the number indicated by the CSYNC record.  A child SHOULD update
61    ///    the SOA Serial field in the CSYNC record every time the data being
62    ///    referenced by the CSYNC record is changed (e.g., an NS record or
63    ///    associated address record is changed).  A child MAY choose to update
64    ///    the SOA Serial field to always match the current SOA Serial field.
65    ///
66    ///    Parental agents MAY cache SOA serial numbers from data they use and
67    ///    refuse to process data from zones older than the last instance from
68    ///    which they pulled data.
69    ///
70    ///    Although Section 3.2 of [RFC1982] describes how to properly implement
71    ///    a less-than comparison operation with SOA serial numbers that may
72    ///    wrap beyond the 32-bit value in both the SOA record and the CSYNC
73    ///    record, it is important that a child using the soaminimum flag must
74    ///    not increment its SOA serial number value more than 2^16 within the
75    ///    period of time that a parent might wait between polling the child for
76    ///    the CSYNC record.
77    /// ```
78    pub soa_serial: u32,
79
80    /// The immediate flag
81    pub immediate: bool,
82    /// The soaminimum flag
83    pub soa_minimum: bool,
84    /// The reserved flags
85    pub reserved_flags: u16,
86
87    /// [RFC 7477](https://tools.ietf.org/html/rfc7477#section-2.1.1.2.1), Child-to-Parent Synchronization in DNS, March 2015
88    ///
89    /// ```text
90    /// 2.1.1.2.1.  The Type Bit Map Field
91    ///
92    ///    The Type Bit Map field indicates the record types to be processed by
93    ///    the parental agent, according to the procedures in Section 3.  The
94    ///    Type Bit Map field is encoded in the same way as the Type Bit Map
95    ///    field of the NSEC record, described in [RFC4034], Section 4.1.2.  If
96    ///    a bit has been set that a parental agent implementation does not
97    ///    understand, the parental agent MUST NOT act upon the record.
98    ///    Specifically, a parental agent must not simply copy the data, and it
99    ///    must understand the semantics associated with a bit in the Type Bit
100    ///    Map field that has been set to 1.
101    /// ```
102    pub type_bit_maps: RecordTypeSet,
103}
104
105impl CSYNC {
106    /// Creates a new CSYNC record data.
107    ///
108    /// # Arguments
109    ///
110    /// * `soa_serial` - A serial number for the zone
111    /// * `immediate` - A flag signalling if the change should happen immediately
112    /// * `soa_minimum` - A flag to used to signal if the soa_serial should be validated
113    /// * `type_bit_maps` - a bit map of the types to synchronize
114    ///
115    /// # Return value
116    ///
117    /// The new CSYNC record data.
118    pub fn new(
119        soa_serial: u32,
120        immediate: bool,
121        soa_minimum: bool,
122        type_bit_maps: impl IntoIterator<Item = RecordType>,
123    ) -> Self {
124        Self {
125            soa_serial,
126            immediate,
127            soa_minimum,
128            reserved_flags: 0,
129            type_bit_maps: RecordTypeSet::new(type_bit_maps),
130        }
131    }
132
133    /// Parse the RData from a set of Tokens
134    ///
135    /// ```text
136    /// IN CSYNC 1 3 A NS AAAA
137    /// IN CSYNC 66 0 MX
138    /// ```
139    pub(crate) fn from_tokens<'i, I: Iterator<Item = &'i str>>(
140        mut tokens: I,
141    ) -> Result<Self, ParseError> {
142        let soa_serial: u32 = tokens
143            .next()
144            .ok_or_else(|| ParseError::MissingToken("soa_serial".to_string()))
145            .and_then(|s| s.parse().map_err(Into::into))?;
146
147        let flags: u16 = tokens
148            .next()
149            .ok_or_else(|| ParseError::MissingToken("flags".to_string()))
150            .and_then(|s| s.parse().map_err(Into::into))?;
151
152        let immediate: bool = flags & 0b0000_0001 == 0b0000_0001;
153        let soa_minimum: bool = flags & 0b0000_0010 == 0b0000_0010;
154
155        let mut record_types = BTreeSet::new();
156
157        for token in tokens {
158            record_types.insert(RecordType::from_str(token)?);
159        }
160
161        Ok(Self::new(soa_serial, immediate, soa_minimum, record_types))
162    }
163
164    /// [RFC 7477](https://tools.ietf.org/html/rfc7477#section-2.1.1.2), Child-to-Parent Synchronization in DNS, March 2015
165    ///
166    /// ```text
167    /// 2.1.1.2.  The Flags Field
168    ///
169    ///    The Flags field contains 16 bits of boolean flags that define
170    ///    operations that affect the processing of the CSYNC record.  The flags
171    ///    defined in this document are as follows:
172    ///
173    ///       0x00 0x01: "immediate"
174    ///
175    ///       0x00 0x02: "soaminimum"
176    ///
177    ///    The definitions for how the flags are to be used can be found in
178    ///    Section 3.
179    ///
180    ///    The remaining flags are reserved for use by future specifications.
181    ///    Undefined flags MUST be set to 0 by CSYNC publishers.  Parental
182    ///    agents MUST NOT process a CSYNC record if it contains a 1 value for a
183    ///    flag that is unknown to or unsupported by the parental agent.
184    /// ```
185    pub fn flags(&self) -> u16 {
186        let mut flags = self.reserved_flags & 0b1111_1111_1111_1100;
187        if self.immediate {
188            flags |= 0b0000_0001
189        };
190        if self.soa_minimum {
191            flags |= 0b0000_0010
192        };
193        flags
194    }
195}
196
197impl BinEncodable for CSYNC {
198    fn emit(&self, encoder: &mut BinEncoder<'_>) -> ProtoResult<()> {
199        encoder.emit_u32(self.soa_serial)?;
200        encoder.emit_u16(self.flags())?;
201        self.type_bit_maps.emit(encoder)?;
202
203        Ok(())
204    }
205}
206
207impl<'r> RecordDataDecodable<'r> for CSYNC {
208    fn read_data(decoder: &mut BinDecoder<'r>, length: Restrict<u16>) -> Result<Self, DecodeError> {
209        let start_idx = decoder.index();
210
211        let soa_serial = decoder.read_u32()?.unverified();
212
213        let flags: u16 = decoder
214            .read_u16()?
215            .verify_unwrap(|flags| flags & 0b1111_1100 == 0)
216            .map_err(DecodeError::UnrecognizedCsyncFlags)?;
217
218        let immediate: bool = flags & 0b0000_0001 == 0b0000_0001;
219        let soa_minimum: bool = flags & 0b0000_0010 == 0b0000_0010;
220        let reserved_flags = flags & 0b1111_1111_1111_1100;
221
222        let offset = u16::try_from(decoder.index() - start_idx).map_err(|_| {
223            DecodeError::IncorrectRDataLengthRead {
224                read: decoder.index() - start_idx,
225                len: u16::MAX as usize,
226            }
227        })?;
228        let bit_map_len =
229            length
230                .checked_sub(offset)
231                .map_err(|len| DecodeError::IncorrectRDataLengthRead {
232                    read: offset as usize,
233                    len: len as usize,
234                })?;
235        let type_bit_maps = RecordTypeSet::read_data(decoder, bit_map_len)?;
236
237        Ok(Self {
238            soa_serial,
239            immediate,
240            soa_minimum,
241            reserved_flags,
242            type_bit_maps,
243        })
244    }
245}
246
247impl RecordData for CSYNC {
248    fn try_borrow(data: &RData) -> Option<&Self> {
249        match data {
250            RData::CSYNC(csync) => Some(csync),
251            _ => None,
252        }
253    }
254
255    fn record_type(&self) -> RecordType {
256        RecordType::CSYNC
257    }
258
259    fn into_rdata(self) -> RData {
260        RData::CSYNC(self)
261    }
262}
263
264impl fmt::Display for CSYNC {
265    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
266        write!(
267            f,
268            "{soa_serial} {flags}",
269            soa_serial = &self.soa_serial,
270            flags = &self.flags(),
271        )?;
272
273        for ty in self.type_bit_maps.iter() {
274            write!(f, " {ty}")?;
275        }
276
277        Ok(())
278    }
279}
280
281#[cfg(test)]
282mod tests {
283    #![allow(clippy::dbg_macro, clippy::print_stdout)]
284
285    #[cfg(feature = "std")]
286    use std::println;
287
288    use alloc::vec::Vec;
289
290    use super::*;
291
292    #[test]
293    fn test() {
294        let types = [RecordType::A, RecordType::NS, RecordType::AAAA];
295
296        let rdata = CSYNC::new(123, true, true, types);
297
298        let mut bytes = Vec::new();
299        let mut encoder: BinEncoder<'_> = BinEncoder::new(&mut bytes);
300        assert!(rdata.emit(&mut encoder).is_ok());
301        let bytes = encoder.into_bytes();
302
303        #[cfg(feature = "std")]
304        println!("bytes: {bytes:?}");
305
306        let mut decoder: BinDecoder<'_> = BinDecoder::new(bytes);
307        let restrict = Restrict::new(bytes.len() as u16);
308        let read_rdata = CSYNC::read_data(&mut decoder, restrict).expect("Decoding error");
309        assert_eq!(rdata, read_rdata);
310    }
311
312    #[test]
313    fn test_parsing() {
314        // IN CSYNC 123 3 NS
315        assert_eq!(
316            CSYNC::from_tokens(vec!["123", "3", "NS"].into_iter()).expect("failed to parse CSYNC"),
317            CSYNC::new(123, true, true, [RecordType::NS]),
318        );
319    }
320
321    #[test]
322    fn test_parsing_fails() {
323        // IN CSYNC NS
324        assert!(CSYNC::from_tokens(vec!["NS"].into_iter()).is_err());
325        assert!(CSYNC::from_tokens(vec![].into_iter()).is_err());
326    }
327}