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