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