1 //! Resource Records are the fundamental type in the DNS - individual records mapping a name to
4 //! This module holds structs and utilities for the Resource Records supported by this crate.
7 use alloc::string::String;
8 use alloc::borrow::ToOwned;
11 use core::cmp::{self, Ordering};
17 /// A valid domain name.
19 /// It must end with a ".", be no longer than 255 bytes, consist of only printable ASCII
20 /// characters and each label may be no longer than 63 bytes.
21 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
22 pub struct Name(String);
24 /// Gets the underlying human-readable domain name
25 pub fn as_str(&self) -> &str { &self.0 }
26 /// Gets the number of labels in this name
27 pub fn labels(&self) -> u8 {
28 if self.as_str() == "." {
31 self.as_str().chars().filter(|c| *c == '.').count() as u8
34 /// Gets a string containing the last `n` labels in this [`Name`] (which is also a valid name).
35 pub fn trailing_n_labels(&self, n: u8) -> Option<&str> {
36 let labels = self.labels();
39 } else if n == labels {
44 self.as_str().splitn(labels as usize - n as usize + 1, ".").last()
48 impl core::ops::Deref for Name {
50 fn deref(&self) -> &str { &self.0 }
52 impl fmt::Display for Name {
53 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
57 impl TryFrom<String> for Name {
59 fn try_from(s: String) -> Result<Name, ()> {
60 if s.is_empty() { return Err(()); }
61 if *s.as_bytes().last().unwrap_or(&0) != b"."[0] { return Err(()); }
62 if s.len() > 255 { return Err(()); }
63 if s.chars().any(|c| !c.is_ascii_graphic() || c == '"') { return Err(()); }
64 for label in s.split(".") {
65 if label.len() > 63 { return Err(()); }
68 Ok(Name(s.to_ascii_lowercase()))
71 impl TryFrom<&str> for Name {
73 fn try_from(s: &str) -> Result<Name, ()> {
74 Self::try_from(s.to_owned())
78 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
79 /// A supported Resource Record
81 /// Note that we only currently support a handful of RR types as needed to generate and validate
82 /// TXT or TLSA record proofs.
84 /// An IPv4 resource record
86 /// An IPv6 resource record
88 /// A name server resource record
90 /// A text resource record
92 /// A TLS Certificate Association resource record
94 /// A Canonical Name record
96 /// A Delegation Name record
98 /// A DNS (Public) Key resource record
100 /// A Delegated Signer resource record
102 /// A Resource Record Signature record
104 /// A Next Secure Record record
106 /// A Next Secure Record version 3 record
110 /// Gets the name this record refers to.
111 pub fn name(&self) -> &Name {
113 RR::A(rr) => &rr.name,
114 RR::AAAA(rr) => &rr.name,
115 RR::NS(rr) => &rr.name,
116 RR::Txt(rr) => &rr.name,
117 RR::CName(rr) => &rr.name,
118 RR::DName(rr) => &rr.name,
119 RR::TLSA(rr) => &rr.name,
120 RR::DnsKey(rr) => &rr.name,
121 RR::DS(rr) => &rr.name,
122 RR::RRSig(rr) => &rr.name,
123 RR::NSec(rr) => &rr.name,
124 RR::NSec3(rr) => &rr.name,
127 /// Gets a JSON encoding of this record
128 pub fn json(&self) -> String {
130 RR::A(rr) => StaticRecord::json(rr),
131 RR::AAAA(rr) => StaticRecord::json(rr),
132 RR::NS(rr) => StaticRecord::json(rr),
133 RR::Txt(rr) => StaticRecord::json(rr),
134 RR::CName(rr) => StaticRecord::json(rr),
135 RR::DName(rr) => StaticRecord::json(rr),
136 RR::TLSA(rr) => StaticRecord::json(rr),
137 RR::DnsKey(rr) => StaticRecord::json(rr),
138 RR::DS(rr) => StaticRecord::json(rr),
139 RR::RRSig(rr) => StaticRecord::json(rr),
140 RR::NSec(rr) => StaticRecord::json(rr),
141 RR::NSec3(rr) => StaticRecord::json(rr),
144 fn ty(&self) -> u16 {
147 RR::AAAA(_) => AAAA::TYPE,
148 RR::NS(_) => NS::TYPE,
149 RR::Txt(_) => Txt::TYPE,
150 RR::CName(_) => CName::TYPE,
151 RR::DName(_) => DName::TYPE,
152 RR::TLSA(_) => TLSA::TYPE,
153 RR::DnsKey(_) => DnsKey::TYPE,
154 RR::DS(_) => DS::TYPE,
155 RR::RRSig(_) => RRSig::TYPE,
156 RR::NSec(_) => NSec::TYPE,
157 RR::NSec3(_) => NSec3::TYPE,
160 fn write_u16_len_prefixed_data<W: Writer>(&self, out: &mut W) {
162 RR::A(rr) => StaticRecord::write_u16_len_prefixed_data(rr, out),
163 RR::AAAA(rr) => StaticRecord::write_u16_len_prefixed_data(rr, out),
164 RR::NS(rr) => StaticRecord::write_u16_len_prefixed_data(rr, out),
165 RR::Txt(rr) => StaticRecord::write_u16_len_prefixed_data(rr, out),
166 RR::CName(rr) => StaticRecord::write_u16_len_prefixed_data(rr, out),
167 RR::DName(rr) => StaticRecord::write_u16_len_prefixed_data(rr, out),
168 RR::TLSA(rr) => StaticRecord::write_u16_len_prefixed_data(rr, out),
169 RR::DnsKey(rr) => StaticRecord::write_u16_len_prefixed_data(rr, out),
170 RR::DS(rr) => StaticRecord::write_u16_len_prefixed_data(rr, out),
171 RR::RRSig(rr) => StaticRecord::write_u16_len_prefixed_data(rr, out),
172 RR::NSec(rr) => StaticRecord::write_u16_len_prefixed_data(rr, out),
173 RR::NSec3(rr) => StaticRecord::write_u16_len_prefixed_data(rr, out),
176 fn ty_to_rr_name(ty: u16) -> Option<&'static str> {
178 A::TYPE => Some("A"),
179 AAAA::TYPE => Some("AAAA"),
180 NS::TYPE => Some("NS"),
181 Txt::TYPE => Some("TXT"),
182 CName::TYPE => Some("CNAME"),
183 DName::TYPE => Some("DNAME"),
184 TLSA::TYPE => Some("TLSA"),
185 DnsKey::TYPE => Some("DNSKEY"),
186 DS::TYPE => Some("DS"),
187 RRSig::TYPE => Some("RRSIG"),
188 NSec::TYPE => Some("NSEC"),
189 NSec3::TYPE => Some("NSEC3"),
194 impl From<A> for RR { fn from(a: A) -> RR { RR::A(a) } }
195 impl From<AAAA> for RR { fn from(aaaa: AAAA) -> RR { RR::AAAA(aaaa) } }
196 impl From<NS> for RR { fn from(ns: NS) -> RR { RR::NS(ns) } }
197 impl From<Txt> for RR { fn from(txt: Txt) -> RR { RR::Txt(txt) } }
198 impl From<CName> for RR { fn from(cname: CName) -> RR { RR::CName(cname) } }
199 impl From<DName> for RR { fn from(cname: DName) -> RR { RR::DName(cname) } }
200 impl From<TLSA> for RR { fn from(tlsa: TLSA) -> RR { RR::TLSA(tlsa) } }
201 impl From<DnsKey> for RR { fn from(dnskey: DnsKey) -> RR { RR::DnsKey(dnskey) } }
202 impl From<DS> for RR { fn from(ds: DS) -> RR { RR::DS(ds) } }
203 impl From<RRSig> for RR { fn from(rrsig: RRSig) -> RR { RR::RRSig(rrsig) } }
204 impl From<NSec> for RR { fn from(nsec: NSec) -> RR { RR::NSec(nsec) } }
205 impl From<NSec3> for RR { fn from(nsec3: NSec3) -> RR { RR::NSec3(nsec3) } }
207 pub(crate) trait StaticRecord : Ord + Sized {
208 // http://www.iana.org/assignments/dns-parameters/dns-parameters.xhtml#dns-parameters-4
210 fn name(&self) -> &Name;
211 fn json(&self) -> String;
212 fn write_u16_len_prefixed_data<W: Writer>(&self, out: &mut W);
213 fn read_from_data(name: Name, data: &[u8], wire_packet: &[u8]) -> Result<Self, ()>;
216 /// A record that can be written to a generic [`Writer`]
217 pub(crate) trait WriteableRecord : Record {
218 fn serialize_u16_len_prefixed<W: Writer>(&self, out: &mut W);
220 impl<RR: StaticRecord> WriteableRecord for RR {
221 fn serialize_u16_len_prefixed<W: Writer>(&self, out: &mut W) {
222 RR::write_u16_len_prefixed_data(self, out)
225 impl WriteableRecord for RR {
226 fn serialize_u16_len_prefixed<W: Writer>(&self, out: &mut W) {
227 RR::write_u16_len_prefixed_data(self, out)
231 /// A trait describing a resource record (including the [`RR`] enum).
232 pub trait Record : Ord {
233 /// The resource record type, as maintained by IANA.
235 /// Current assignments can be found at
236 /// <http://www.iana.org/assignments/dns-parameters/dns-parameters.xhtml#dns-parameters-4>
238 /// The name this record is at.
239 fn name(&self) -> &Name;
240 /// Gets a JSON encoding of this record.
241 fn json(&self) -> String;
242 /// Writes the data of this record, prefixed by a u16 length, to the given `Vec`.
243 fn write_u16_len_prefixed_data(&self, out: &mut Vec<u8>);
245 impl<RR: StaticRecord> Record for RR {
246 fn ty(&self) -> u16 { RR::TYPE }
247 fn name(&self) -> &Name { RR::name(self) }
248 fn json(&self) -> String { RR::json(self) }
249 fn write_u16_len_prefixed_data(&self, out: &mut Vec<u8>) {
250 RR::write_u16_len_prefixed_data(self, out)
254 fn ty(&self) -> u16 { self.ty() }
255 fn name(&self) -> &Name { self.name() }
256 fn json(&self) -> String { self.json() }
257 fn write_u16_len_prefixed_data(&self, out: &mut Vec<u8>) {
258 self.write_u16_len_prefixed_data(out)
262 #[derive(Debug, Clone, PartialEq, Eq, Ord)]
263 /// A text resource record, containing arbitrary text data
265 /// The name this record is at.
267 /// The text record itself.
269 /// While this is generally UTF-8-valid, there is no specific requirement that it be, and thus
270 /// is an arbitrary series of bytes here.
273 /// The wire type for TXT records
274 pub const TXT_TYPE: u16 = 16;
275 impl PartialOrd for Txt {
276 fn partial_cmp(&self, o: &Txt) -> Option<Ordering> {
277 Some(self.name.cmp(&o.name)
279 // Compare in wire encoding form, i.e. compare in 255-byte chunks
280 for i in 1..(self.data.len() / 255) + 2 {
281 let start = (i - 1)*255;
282 let self_len = cmp::min(i * 255, self.data.len());
283 let o_len = cmp::min(i * 255, o.data.len());
284 let slice_cmp = self_len.cmp(&o_len)
285 .then_with(|| self.data[start..self_len].cmp(&o.data[start..o_len]));
286 if !slice_cmp.is_eq() { return slice_cmp; }
292 impl StaticRecord for Txt {
293 const TYPE: u16 = TXT_TYPE;
294 fn name(&self) -> &Name { &self.name }
295 fn json(&self) -> String {
296 if let Ok(s) = core::str::from_utf8(&self.data) {
297 if s.chars().all(|c| !c.is_control() && c != '"' && c != '\\') {
298 return format!("{{\"type\":\"txt\",\"name\":\"{}\",\"contents\":\"{}\"}}", self.name.0, s);
301 format!("{{\"type\":\"txt\",\"name\":\"{}\",\"contents\":{:?}}}", self.name.0, &self.data[..])
303 fn read_from_data(name: Name, mut data: &[u8], _wire_packet: &[u8]) -> Result<Self, ()> {
304 let mut parsed_data = Vec::with_capacity(data.len().saturating_sub(1));
305 while !data.is_empty() {
306 let len = read_u8(&mut data)? as usize;
307 if data.len() < len { return Err(()); }
308 parsed_data.extend_from_slice(&data[..len]);
311 debug_assert!(data.is_empty());
312 Ok(Txt { name, data: parsed_data })
314 fn write_u16_len_prefixed_data<W: Writer>(&self, out: &mut W) {
315 let len = (self.data.len() + (self.data.len() + 254) / 255) as u16;
316 out.write(&len.to_be_bytes());
318 let mut data_write = &self.data[..];
319 out.write(&[data_write.len().try_into().unwrap_or(255)]);
320 while !data_write.is_empty() {
321 let split_pos = core::cmp::min(255, data_write.len());
322 out.write(&data_write[..split_pos]);
323 data_write = &data_write[split_pos..];
324 if !data_write.is_empty() {
325 out.write(&[data_write.len().try_into().unwrap_or(255)]);
331 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
332 /// A TLS Certificate Association resource record containing information about the TLS certificate
333 /// which should be expected when communicating with the host at the given name.
335 /// See <https://en.wikipedia.org/wiki/DNS-based_Authentication_of_Named_Entities#TLSA_RR> for more
338 /// The name this record is at.
340 /// The type of constraint on the TLS certificate(s) used which should be enforced by this
343 /// Whether to match on the full certificate, or only the public key.
345 /// The type of data included which is used to match the TLS certificate(s).
347 /// The certificate data or hash of the certificate data itself.
350 /// The wire type for TLSA records
351 pub const TLSA_TYPE: u16 = 52;
352 impl StaticRecord for TLSA {
353 const TYPE: u16 = TLSA_TYPE;
354 fn name(&self) -> &Name { &self.name }
355 fn json(&self) -> String {
356 let mut out = String::with_capacity(128+self.data.len()*2);
358 "{{\"type\":\"tlsa\",\"name\":\"{}\",\"usage\":{},\"selector\":{},\"data_ty\":{},\"data\":\"",
359 self.name.0, self.cert_usage, self.selector, self.data_ty
360 ).expect("Write to a String shouldn't fail");
361 for c in self.data.iter() {
362 write!(&mut out, "{:02X}", c)
363 .expect("Write to a String shouldn't fail");
368 fn read_from_data(name: Name, mut data: &[u8], _wire_packet: &[u8]) -> Result<Self, ()> {
370 name, cert_usage: read_u8(&mut data)?, selector: read_u8(&mut data)?,
371 data_ty: read_u8(&mut data)?, data: data.to_vec(),
374 fn write_u16_len_prefixed_data<W: Writer>(&self, out: &mut W) {
375 let len = 3 + self.data.len();
376 out.write(&(len as u16).to_be_bytes());
377 out.write(&[self.cert_usage, self.selector, self.data_ty]);
378 out.write(&self.data);
382 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
383 /// A Canonical Name resource record, referring all queries for this name to another name.
385 /// The name this record is at.
387 /// The canonical name.
389 /// A resolver should use this name when looking up any further records for [`self.name`].
390 pub canonical_name: Name,
392 impl StaticRecord for CName {
394 fn name(&self) -> &Name { &self.name }
395 fn json(&self) -> String {
396 format!("{{\"type\":\"cname\",\"name\":\"{}\",\"canonical_name\":\"{}\"}}",
397 self.name.0, self.canonical_name.0)
399 fn read_from_data(name: Name, mut data: &[u8], wire_packet: &[u8]) -> Result<Self, ()> {
400 let res = CName { name, canonical_name: read_wire_packet_name(&mut data, wire_packet)? };
401 debug_assert!(data.is_empty());
404 fn write_u16_len_prefixed_data<W: Writer>(&self, out: &mut W) {
405 let len: u16 = name_len(&self.canonical_name);
406 out.write(&len.to_be_bytes());
407 write_name(out, &self.canonical_name);
411 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
412 /// A Delegation Name resource record, referring all queries for subdomains of this name to another
413 /// subtree of the DNS.
415 /// The name this record is at.
417 /// The delegation name.
419 /// A resolver should use this domain name tree when looking up any further records for
420 /// subdomains of [`self.name`].
421 pub delegation_name: Name,
423 impl StaticRecord for DName {
424 const TYPE: u16 = 39;
425 fn name(&self) -> &Name { &self.name }
426 fn json(&self) -> String {
427 format!("{{\"type\":\"dname\",\"name\":\"{}\",\"delegation_name\":\"{}\"}}",
428 self.name.0, self.delegation_name.0)
430 fn read_from_data(name: Name, mut data: &[u8], wire_packet: &[u8]) -> Result<Self, ()> {
431 let res = DName { name, delegation_name: read_wire_packet_name(&mut data, wire_packet)? };
432 debug_assert!(data.is_empty());
435 fn write_u16_len_prefixed_data<W: Writer>(&self, out: &mut W) {
436 let len: u16 = name_len(&self.delegation_name);
437 out.write(&len.to_be_bytes());
438 write_name(out, &self.delegation_name);
443 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
444 /// A public key resource record which can be used to validate [`RRSig`]s.
446 /// The name this record is at.
448 /// Flags which constrain the usage of this public key.
450 /// The protocol this key is used for (protocol `3` is DNSSEC).
452 /// The algorithm which this public key uses to sign data.
454 /// The public key itself.
457 impl StaticRecord for DnsKey {
458 const TYPE: u16 = 48;
459 fn name(&self) -> &Name { &self.name }
460 fn json(&self) -> String {
461 let mut out = String::with_capacity(128+self.pubkey.len()*2);
463 "{{\"type\":\"dnskey\",\"name\":\"{}\",\"flags\":{},\"protocol\":{},\"alg\":{},\"pubkey\":\"",
464 self.name.0, self.flags, self.protocol, self.alg
465 ).expect("Write to a String shouldn't fail");
466 for c in self.pubkey.iter() {
467 write!(&mut out, "{:02X}", c)
468 .expect("Write to a String shouldn't fail");
473 fn read_from_data(name: Name, mut data: &[u8], _wire_packet: &[u8]) -> Result<Self, ()> {
475 name, flags: read_u16(&mut data)?, protocol: read_u8(&mut data)?,
476 alg: read_u8(&mut data)?, pubkey: data.to_vec(),
479 fn write_u16_len_prefixed_data<W: Writer>(&self, out: &mut W) {
480 let len = 2 + 1 + 1 + self.pubkey.len();
481 out.write(&(len as u16).to_be_bytes());
482 out.write(&self.flags.to_be_bytes());
483 out.write(&self.protocol.to_be_bytes());
484 out.write(&self.alg.to_be_bytes());
485 out.write(&self.pubkey);
489 /// A short (non-cryptographic) digest which can be used to refer to this [`DnsKey`].
490 pub fn key_tag(&self) -> u16 {
491 let mut res = u32::from(self.flags);
492 res += u32::from(self.protocol) << 8;
493 res += u32::from(self.alg);
494 for (idx, b) in self.pubkey.iter().enumerate() {
496 res += u32::from(*b) << 8;
498 res += u32::from(*b);
501 res += (res >> 16) & 0xffff;
502 (res & 0xffff) as u16
506 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
507 /// A Delegation Signer resource record which indicates that some alternative [`DnsKey`] can sign
508 /// for records in the zone which matches [`self.name`].
510 /// The name this record is at.
512 /// This is also the zone that a [`DnsKey`] which matches the [`Self::digest`] can sign for.
514 /// A short tag which describes the matching [`DnsKey`].
516 /// This matches the [`DnsKey::key_tag`] for the [`DnsKey`] which is referred to by this
519 /// The algorithm which the [`DnsKey`] referred to by this [`DS`] uses.
521 /// This matches the [`DnsKey::alg`] field in the referred-to [`DnsKey`].
523 /// The type of digest used to hash the referred-to [`DnsKey`].
525 /// The digest itself.
528 impl StaticRecord for DS {
529 const TYPE: u16 = 43;
530 fn name(&self) -> &Name { &self.name }
531 fn json(&self) -> String {
532 let mut out = String::with_capacity(128+self.digest.len()*2);
534 "{{\"type\":\"ds\",\"name\":\"{}\",\"key_tag\":{},\"alg\":{},\"digest_type\":{},\"digest\":\"",
535 self.name.0, self.key_tag, self.alg, self.digest_type
536 ).expect("Write to a String shouldn't fail");
537 for c in self.digest.iter() {
538 write!(&mut out, "{:02X}", c)
539 .expect("Write to a String shouldn't fail");
544 fn read_from_data(name: Name, mut data: &[u8], _wire_packet: &[u8]) -> Result<Self, ()> {
546 name, key_tag: read_u16(&mut data)?, alg: read_u8(&mut data)?,
547 digest_type: read_u8(&mut data)?, digest: data.to_vec(),
550 fn write_u16_len_prefixed_data<W: Writer>(&self, out: &mut W) {
551 let len = 2 + 1 + 1 + self.digest.len();
552 out.write(&(len as u16).to_be_bytes());
553 out.write(&self.key_tag.to_be_bytes());
554 out.write(&self.alg.to_be_bytes());
555 out.write(&self.digest_type.to_be_bytes());
556 out.write(&self.digest);
560 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
561 /// A Resource Record (set) Signature resource record. This contains a signature over all the
562 /// resources records of the given type at the given name.
564 /// The name this record is at.
566 /// This is also the name of any records which this signature is covering (ignoring wildcards).
568 /// The resource record type which this [`RRSig`] is signing.
570 /// All resources records of this type at the same name as [`self.name`] must be signed by
573 /// The algorithm which is being used to sign.
575 /// This must match the [`DnsKey::alg`] field in the [`DnsKey`] being used to sign.
577 /// The number of labels in the name of the records that this signature is signing.
579 /// If this is less than the number of labels in [`self.name`], this signature is covering a
582 /// The TTL of the records which this [`RRSig`] is signing.
584 /// The expiration (as a UNIX timestamp) of this signature.
586 /// The time (as a UNIX timestamp) at which this signature becomes valid.
588 /// A short tag which describes the matching [`DnsKey`].
590 /// This matches the [`DnsKey::key_tag`] for the [`DnsKey`] which created this signature.
592 /// The [`DnsKey::name`] in the [`DnsKey`] which created this signature.
594 /// This must be a parent of [`self.name`].
596 /// [`DnsKey::name`]: Record::name
597 // We'd like to just link to the `DnsKey` member variable called `name`, but there doesn't
598 // appear to be a way to actually do that, so instead we have to link to the trait method.
600 /// The signature itself.
601 pub signature: Vec<u8>,
603 impl StaticRecord for RRSig {
604 const TYPE: u16 = 46;
605 fn name(&self) -> &Name { &self.name }
606 fn json(&self) -> String {
607 let mut out = String::with_capacity(256 + self.signature.len()*2);
609 "{{\"type\":\"ds\",\"name\":\"{}\",\"signed_record_type\":{},\"alg\":{},\"signed_labels\":{},\"orig_ttl\":{},\"expiration\"{},\"inception\":{},\"key_tag\":{},\"key_name\":\"{}\",\"signature\":\"",
610 self.name.0, self.ty, self.alg, self.labels, self.orig_ttl, self.expiration, self.inception, self.key_tag, self.key_name.0
611 ).expect("Write to a String shouldn't fail");
612 for c in self.signature.iter() {
613 write!(&mut out, "{:02X}", c)
614 .expect("Write to a String shouldn't fail");
619 fn read_from_data(name: Name, mut data: &[u8], wire_packet: &[u8]) -> Result<Self, ()> {
621 name, ty: read_u16(&mut data)?, alg: read_u8(&mut data)?,
622 labels: read_u8(&mut data)?, orig_ttl: read_u32(&mut data)?,
623 expiration: read_u32(&mut data)?, inception: read_u32(&mut data)?,
624 key_tag: read_u16(&mut data)?,
625 key_name: read_wire_packet_name(&mut data, wire_packet)?,
626 signature: data.to_vec(),
629 fn write_u16_len_prefixed_data<W: Writer>(&self, out: &mut W) {
630 let len = 2 + 1 + 1 + 4*3 + 2 + name_len(&self.key_name) + self.signature.len() as u16;
631 out.write(&len.to_be_bytes());
632 out.write(&self.ty.to_be_bytes());
633 out.write(&self.alg.to_be_bytes());
634 out.write(&self.labels.to_be_bytes());
635 out.write(&self.orig_ttl.to_be_bytes());
636 out.write(&self.expiration.to_be_bytes());
637 out.write(&self.inception.to_be_bytes());
638 out.write(&self.key_tag.to_be_bytes());
639 write_name(out, &self.key_name);
640 out.write(&self.signature);
644 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
645 /// A mask used in [`NSec`] and [`NSec3`] records which indicates the resource record types which
646 /// exist at the (hash of the) name described in [`Record::name`].
647 pub struct NSecTypeMask([u8; 8192]);
649 /// Constructs a new, empty, type mask.
650 pub fn new() -> Self { Self([0; 8192]) }
651 /// Builds a new type mask with the given types set
652 pub fn from_types(types: &[u16]) -> Self {
653 let mut flags = [0; 8192];
655 flags[*t as usize >> 3] |= 1 << (7 - (*t as usize % 8));
657 let res = Self(flags);
659 debug_assert!(res.contains_type(*t));
663 /// Checks if the given type (from [`Record::ty`]) is set, indicating a record of this type
665 pub fn contains_type(&self, ty: u16) -> bool {
666 let f = self.0[(ty >> 3) as usize];
667 // DNSSEC's bit fields are in wire order, so the high bit is type 0, etc.
668 f & (1 << (7 - (ty % 8))) != 0
670 fn write_json(&self, s: &mut String) {
672 let mut have_written = false;
673 for (idx, mask) in self.0.iter().enumerate() {
674 if *mask == 0 { continue; }
676 if *mask & (1 << b) != 0 {
681 let ty = ((idx as u16) << 3) | (7 - b);
682 match RR::ty_to_rr_name(ty) {
683 Some(name) => write!(s, "\"{}\"", name).expect("Writes to a string shouldn't fail"),
684 _ => write!(s, "{}", ty).expect("Writes to a string shouldn't fail"),
693 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
694 /// A Next Secure Record resource record. This indicates a range of possible names for which there
695 /// is no such record.
697 /// The name this record is at.
699 /// The next name which contains a record. There are no names between `name` and
700 /// [`Self::next_name`].
702 /// The set of record types which exist at `name`. Any other record types do not exist at
704 pub types: NSecTypeMask,
706 impl StaticRecord for NSec {
707 const TYPE: u16 = 47;
708 fn name(&self) -> &Name { &self.name }
709 fn json(&self) -> String {
710 let mut out = String::with_capacity(256 + self.next_name.len());
712 "{{\"type\":\"nsec\",\"name\":\"{}\",\"next_name\":\"{}\",\"types\":",
713 self.name.0, self.next_name.0,
714 ).expect("Write to a String shouldn't fail");
715 self.types.write_json(&mut out);
719 fn read_from_data(name: Name, mut data: &[u8], wire_packet: &[u8]) -> Result<Self, ()> {
721 name, next_name: read_wire_packet_name(&mut data, wire_packet)?,
722 types: NSecTypeMask(read_nsec_types_bitmap(&mut data)?),
724 debug_assert!(data.is_empty());
727 fn write_u16_len_prefixed_data<W: Writer>(&self, out: &mut W) {
728 let len = name_len(&self.next_name) + nsec_types_bitmap_len(&self.types.0);
729 out.write(&len.to_be_bytes());
730 write_name(out, &self.next_name);
731 write_nsec_types_bitmap(out, &self.types.0);
735 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
736 /// A Next Secure Record resource record. This indicates a range of possible names for which there
737 /// is no such record.
739 /// The name this record is at.
741 /// The hash algorithm used to hash the `name` and [`Self::next_name_hash`]. Currently only 1
742 /// (SHA-1) is defined.
744 /// Flags for this record. Currently only bit 0 (the "opt-out" bit) is defined.
746 /// The number of hash iterations required.
748 /// As of RFC 9276 this MUST be set to 0, but sadly is often still set higher in the wild. A
749 /// hard cap is applied in validation.
750 pub hash_iterations: u16,
751 /// The salt included in the hash.
753 /// As of RFC 9276 this SHOULD be empty, but often isn't in the wild.
755 /// The hash of the next name which contains a record. There are no records who's name's hash
756 /// lies between `name` and [`Self::next_name_hash`].
757 pub next_name_hash: Vec<u8>,
758 /// The set of record types which exist at `name`. Any other record types do not exist at
760 pub types: NSecTypeMask,
762 impl StaticRecord for NSec3 {
763 const TYPE: u16 = 50;
764 fn name(&self) -> &Name { &self.name }
765 fn json(&self) -> String {
766 let mut out = String::with_capacity(256);
768 "{{\"type\":\"nsec3\",\"name\":\"{}\",\"hash_algo\":{},\"flags\":{},\"hash_iterations\":{},\"salt\":{:?},\"next_name_hash\":{:?},\"types\":",
769 self.name.0, self.hash_algo, self.flags, self.hash_iterations, &self.salt[..], &self.next_name_hash[..]
770 ).expect("Write to a String shouldn't fail");
771 self.types.write_json(&mut out);
775 fn read_from_data(name: Name, mut data: &[u8], _wire_packet: &[u8]) -> Result<Self, ()> {
777 name, hash_algo: read_u8(&mut data)?, flags: read_u8(&mut data)?,
778 hash_iterations: read_u16(&mut data)?, salt: read_u8_len_prefixed_bytes(&mut data)?,
779 next_name_hash: read_u8_len_prefixed_bytes(&mut data)?,
780 types: NSecTypeMask(read_nsec_types_bitmap(&mut data)?),
782 debug_assert!(data.is_empty());
785 fn write_u16_len_prefixed_data<W: Writer>(&self, out: &mut W) {
786 let len = 4 + 2 + self.salt.len() as u16 + self.next_name_hash.len() as u16 +
787 nsec_types_bitmap_len(&self.types.0);
788 out.write(&len.to_be_bytes());
789 out.write(&self.hash_algo.to_be_bytes());
790 out.write(&self.flags.to_be_bytes());
791 out.write(&self.hash_iterations.to_be_bytes());
792 out.write(&(self.salt.len() as u8).to_be_bytes());
793 out.write(&self.salt);
794 out.write(&(self.next_name_hash.len() as u8).to_be_bytes());
795 out.write(&self.next_name_hash);
796 write_nsec_types_bitmap(out, &self.types.0);
800 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
801 /// An IPv4 Address resource record
803 /// The name this record is at.
805 /// The bytes of the IPv4 address.
806 pub address: [u8; 4],
808 /// The wire type for A records
809 pub const A_TYPE: u16 = 1;
810 impl StaticRecord for A {
811 const TYPE: u16 = A_TYPE;
812 fn name(&self) -> &Name { &self.name }
813 fn json(&self) -> String {
814 format!("{{\"type\":\"a\",\"name\":\"{}\",\"address\":{:?}}}", self.name.0, self.address)
816 fn read_from_data(name: Name, data: &[u8], _wire_packet: &[u8]) -> Result<Self, ()> {
817 if data.len() != 4 { return Err(()); }
818 let mut address = [0; 4];
819 address.copy_from_slice(&data);
820 Ok(A { name, address })
822 fn write_u16_len_prefixed_data<W: Writer>(&self, out: &mut W) {
823 out.write(&4u16.to_be_bytes());
824 out.write(&self.address);
828 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
829 /// An IPv6 Address resource record
831 /// The name this record is at.
833 /// The bytes of the IPv6 address.
834 pub address: [u8; 16],
836 /// The wire type for AAAA records
837 pub const AAAA_TYPE: u16 = 28;
838 impl StaticRecord for AAAA {
839 const TYPE: u16 = AAAA_TYPE;
840 fn name(&self) -> &Name { &self.name }
841 fn json(&self) -> String {
842 format!("{{\"type\":\"aaaa\",\"name\":\"{}\",\"address\":{:?}}}", self.name.0, self.address)
844 fn read_from_data(name: Name, data: &[u8], _wire_packet: &[u8]) -> Result<Self, ()> {
845 if data.len() != 16 { return Err(()); }
846 let mut address = [0; 16];
847 address.copy_from_slice(&data);
848 Ok(AAAA { name, address })
850 fn write_u16_len_prefixed_data<W: Writer>(&self, out: &mut W) {
851 out.write(&16u16.to_be_bytes());
852 out.write(&self.address);
856 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
857 /// A Name Server resource record, which indicates the server responsible for handling queries for
860 /// The name this record is at.
862 /// This is also the zone which the server at [`Self::name_server`] is responsible for handling
865 /// The name of the server which is responsible for handling queries for the [`self.name`]
867 pub name_server: Name,
869 impl StaticRecord for NS {
871 fn name(&self) -> &Name { &self.name }
872 fn json(&self) -> String {
873 format!("{{\"type\":\"ns\",\"name\":\"{}\",\"ns\":\"{}\"}}", self.name.0, self.name_server.0)
875 fn read_from_data(name: Name, mut data: &[u8], wire_packet: &[u8]) -> Result<Self, ()> {
876 let res = NS { name, name_server: read_wire_packet_name(&mut data, wire_packet)? };
877 debug_assert!(data.is_empty());
880 fn write_u16_len_prefixed_data<W: Writer>(&self, out: &mut W) {
881 out.write(&name_len(&self.name_server).to_be_bytes());
882 write_name(out, &self.name_server);