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 core::fmt;
11
12#[cfg(feature = "serde")]
13use serde::{Deserialize, Serialize};
14
15use crate::{
16 error::*,
17 rr::{RData, RecordData, RecordDataDecodable, RecordType, RecordTypeSet},
18 serialize::binary::*,
19};
20
21/// [RFC 7477, Child-to-Parent Synchronization in DNS, March 2015][rfc7477]
22///
23/// ```text
24/// 2.1.1. The CSYNC Resource Record Wire Format
25///
26/// The CSYNC RDATA consists of the following fields:
27///
28/// 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 3 3
29/// 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
30/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
31/// | SOA Serial |
32/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
33/// | Flags | Type Bit Map /
34/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
35/// / Type Bit Map (continued) /
36/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
37/// ```
38///
39/// [rfc7477]: https://tools.ietf.org/html/rfc7477
40#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
41#[derive(Debug, PartialEq, Eq, Hash, Clone)]
42pub struct CSYNC {
43 soa_serial: u32,
44 immediate: bool,
45 soa_minimum: bool,
46 reserved_flags: u16,
47 type_bit_maps: RecordTypeSet,
48}
49
50impl CSYNC {
51 /// Creates a new CSYNC record data.
52 ///
53 /// # Arguments
54 ///
55 /// * `soa_serial` - A serial number for the zone
56 /// * `immediate` - A flag signalling if the change should happen immediately
57 /// * `soa_minimum` - A flag to used to signal if the soa_serial should be validated
58 /// * `type_bit_maps` - a bit map of the types to synchronize
59 ///
60 /// # Return value
61 ///
62 /// The new CSYNC record data.
63 pub fn new(
64 soa_serial: u32,
65 immediate: bool,
66 soa_minimum: bool,
67 type_bit_maps: impl IntoIterator<Item = RecordType>,
68 ) -> Self {
69 Self {
70 soa_serial,
71 immediate,
72 soa_minimum,
73 reserved_flags: 0,
74 type_bit_maps: RecordTypeSet::new(type_bit_maps),
75 }
76 }
77
78 /// [RFC 7477](https://tools.ietf.org/html/rfc7477#section-2.1.1.2.1), Child-to-Parent Synchronization in DNS, March 2015
79 ///
80 /// ```text
81 /// 2.1.1.2.1. The Type Bit Map Field
82 ///
83 /// The Type Bit Map field indicates the record types to be processed by
84 /// the parental agent, according to the procedures in Section 3. The
85 /// Type Bit Map field is encoded in the same way as the Type Bit Map
86 /// field of the NSEC record, described in [RFC4034], Section 4.1.2. If
87 /// a bit has been set that a parental agent implementation does not
88 /// understand, the parental agent MUST NOT act upon the record.
89 /// Specifically, a parental agent must not simply copy the data, and it
90 /// must understand the semantics associated with a bit in the Type Bit
91 /// Map field that has been set to 1.
92 /// ```
93 pub fn type_bit_maps(&self) -> impl Iterator<Item = RecordType> + '_ {
94 self.type_bit_maps.iter()
95 }
96
97 /// [RFC 7477](https://tools.ietf.org/html/rfc7477#section-2.1.1.2), Child-to-Parent Synchronization in DNS, March 2015
98 ///
99 /// ```text
100 /// 2.1.1.2. The Flags Field
101 ///
102 /// The Flags field contains 16 bits of boolean flags that define
103 /// operations that affect the processing of the CSYNC record. The flags
104 /// defined in this document are as follows:
105 ///
106 /// 0x00 0x01: "immediate"
107 ///
108 /// 0x00 0x02: "soaminimum"
109 ///
110 /// The definitions for how the flags are to be used can be found in
111 /// Section 3.
112 ///
113 /// The remaining flags are reserved for use by future specifications.
114 /// Undefined flags MUST be set to 0 by CSYNC publishers. Parental
115 /// agents MUST NOT process a CSYNC record if it contains a 1 value for a
116 /// flag that is unknown to or unsupported by the parental agent.
117 /// ```
118 pub fn flags(&self) -> u16 {
119 let mut flags = self.reserved_flags & 0b1111_1111_1111_1100;
120 if self.immediate {
121 flags |= 0b0000_0001
122 };
123 if self.soa_minimum {
124 flags |= 0b0000_0010
125 };
126 flags
127 }
128}
129
130impl BinEncodable for CSYNC {
131 fn emit(&self, encoder: &mut BinEncoder<'_>) -> ProtoResult<()> {
132 encoder.emit_u32(self.soa_serial)?;
133 encoder.emit_u16(self.flags())?;
134 self.type_bit_maps.emit(encoder)?;
135
136 Ok(())
137 }
138}
139
140impl<'r> RecordDataDecodable<'r> for CSYNC {
141 fn read_data(decoder: &mut BinDecoder<'r>, length: Restrict<u16>) -> ProtoResult<Self> {
142 let start_idx = decoder.index();
143
144 let soa_serial = decoder.read_u32()?.unverified();
145
146 let flags: u16 = decoder
147 .read_u16()?
148 .verify_unwrap(|flags| flags & 0b1111_1100 == 0)
149 .map_err(|flags| ProtoError::from(ProtoErrorKind::UnrecognizedCsyncFlags(flags)))?;
150
151 let immediate: bool = flags & 0b0000_0001 == 0b0000_0001;
152 let soa_minimum: bool = flags & 0b0000_0010 == 0b0000_0010;
153 let reserved_flags = flags & 0b1111_1111_1111_1100;
154
155 let offset = u16::try_from(decoder.index() - start_idx)
156 .map_err(|_| ProtoError::from("decoding offset too large in CSYNC"))?;
157 let bit_map_len = length
158 .checked_sub(offset)
159 .map_err(|_| ProtoError::from("invalid rdata length in CSYNC"))?;
160 let type_bit_maps = RecordTypeSet::read_data(decoder, bit_map_len)?;
161
162 Ok(Self {
163 soa_serial,
164 immediate,
165 soa_minimum,
166 reserved_flags,
167 type_bit_maps,
168 })
169 }
170}
171
172impl RecordData for CSYNC {
173 fn try_from_rdata(data: RData) -> Result<Self, RData> {
174 match data {
175 RData::CSYNC(csync) => Ok(csync),
176 _ => Err(data),
177 }
178 }
179
180 fn try_borrow(data: &RData) -> Option<&Self> {
181 match data {
182 RData::CSYNC(csync) => Some(csync),
183 _ => None,
184 }
185 }
186
187 fn record_type(&self) -> RecordType {
188 RecordType::CSYNC
189 }
190
191 fn into_rdata(self) -> RData {
192 RData::CSYNC(self)
193 }
194}
195
196impl fmt::Display for CSYNC {
197 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
198 write!(
199 f,
200 "{soa_serial} {flags}",
201 soa_serial = &self.soa_serial,
202 flags = &self.flags(),
203 )?;
204
205 for ty in self.type_bit_maps.iter() {
206 write!(f, " {ty}")?;
207 }
208
209 Ok(())
210 }
211}
212
213#[cfg(test)]
214mod tests {
215 #![allow(clippy::dbg_macro, clippy::print_stdout)]
216
217 #[cfg(feature = "std")]
218 use std::println;
219
220 use alloc::vec::Vec;
221
222 use super::*;
223
224 #[test]
225 fn test() {
226 let types = [RecordType::A, RecordType::NS, RecordType::AAAA];
227
228 let rdata = CSYNC::new(123, true, true, types);
229
230 let mut bytes = Vec::new();
231 let mut encoder: BinEncoder<'_> = BinEncoder::new(&mut bytes);
232 assert!(rdata.emit(&mut encoder).is_ok());
233 let bytes = encoder.into_bytes();
234
235 #[cfg(feature = "std")]
236 println!("bytes: {bytes:?}");
237
238 let mut decoder: BinDecoder<'_> = BinDecoder::new(bytes);
239 let restrict = Restrict::new(bytes.len() as u16);
240 let read_rdata = CSYNC::read_data(&mut decoder, restrict).expect("Decoding error");
241 assert_eq!(rdata, read_rdata);
242 }
243}