Address further clippy lints
[dnssec-prover] / src / rr.rs
1 //! Resource Records are the fundamental type in the DNS - individual records mapping a name to
2 //! some data.
3 //!
4 //! This module holds structs and utilities for the Resource Records supported by this crate.
5
6 use alloc::vec::Vec;
7 use alloc::string::String;
8 use alloc::borrow::ToOwned;
9 use alloc::format;
10
11 use core::cmp::{self, Ordering};
12 use core::fmt;
13 use core::fmt::Write;
14
15 use crate::ser::*;
16
17 /// A valid domain name.
18 ///
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);
23 impl Name {
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() == "." {
29                         0
30                 } else {
31                         self.as_str().chars().filter(|c| *c == '.').count() as u8
32                 }
33         }
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();
37                 if n > labels {
38                         None
39                 } else if n == labels {
40                         Some(self.as_str())
41                 } else if n == 0 {
42                         Some(".")
43                 } else {
44                         self.as_str().splitn(labels as usize - n as usize + 1, '.').last()
45                 }
46         }
47 }
48 impl core::ops::Deref for Name {
49         type Target = str;
50         fn deref(&self) -> &str { &self.0 }
51 }
52 impl fmt::Display for Name {
53         fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
54                 self.0.fmt(f)
55         }
56 }
57 impl TryFrom<String> for Name {
58         type Error = ();
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(()); }
66                 }
67
68                 Ok(Name(s.to_ascii_lowercase()))
69         }
70 }
71 impl TryFrom<&str> for Name {
72         type Error = ();
73         fn try_from(s: &str) -> Result<Name, ()> {
74                 Self::try_from(s.to_owned())
75         }
76 }
77
78 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
79 /// A supported Resource Record
80 ///
81 /// Note that we only currently support a handful of RR types as needed to generate and validate
82 /// TXT or TLSA record proofs.
83 pub enum RR {
84         /// An IPv4 resource record
85         A(A),
86         /// An IPv6 resource record
87         AAAA(AAAA),
88         /// A name server resource record
89         NS(NS),
90         /// A text resource record
91         Txt(Txt),
92         /// A TLS Certificate Association resource record
93         TLSA(TLSA),
94         /// A Canonical Name record
95         CName(CName),
96         /// A Delegation Name record
97         DName(DName),
98         /// A DNS (Public) Key resource record
99         DnsKey(DnsKey),
100         /// A Delegated Signer resource record
101         DS(DS),
102         /// A Resource Record Signature record
103         RRSig(RRSig),
104         /// A Next Secure Record record
105         NSec(NSec),
106         /// A Next Secure Record version 3 record
107         NSec3(NSec3),
108 }
109 impl RR {
110         /// Gets the name this record refers to.
111         pub fn name(&self) -> &Name {
112                 match self {
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,
125                 }
126         }
127         /// Gets a JSON encoding of this record
128         pub fn json(&self) -> String {
129                 match self {
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),
142                 }
143         }
144         fn ty(&self) -> u16 {
145                 match self {
146                         RR::A(_) => A::TYPE,
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,
158                 }
159         }
160         fn write_u16_len_prefixed_data<W: Writer>(&self, out: &mut W) {
161                 match self {
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),
174                 }
175         }
176         fn ty_to_rr_name(ty: u16) -> Option<&'static str> {
177                 match ty {
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"),
190                         _ => None,
191                 }
192         }
193 }
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) } }
206
207 pub(crate) trait StaticRecord : Ord + Sized {
208         // http://www.iana.org/assignments/dns-parameters/dns-parameters.xhtml#dns-parameters-4
209         const TYPE: u16;
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, ()>;
214 }
215
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);
219 }
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)
223         }
224 }
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)
228         }
229 }
230
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.
234         ///
235         /// Current assignments can be found at
236         /// <http://www.iana.org/assignments/dns-parameters/dns-parameters.xhtml#dns-parameters-4>
237         fn ty(&self) -> u16;
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>);
244 }
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)
251         }
252 }
253 impl Record for RR {
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)
259         }
260 }
261
262 #[derive(Debug, Clone, PartialEq, Eq)]
263 /// A text resource record, containing arbitrary text data
264 pub struct Txt {
265         /// The name this record is at.
266         pub name: Name,
267         /// The text record itself.
268         ///
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.
271         pub data: Vec<u8>,
272 }
273 /// The wire type for TXT records
274 pub const TXT_TYPE: u16 = 16;
275 impl Ord for Txt {
276         fn cmp(&self, o: &Txt) -> Ordering {
277                 self.name.cmp(&o.name)
278                         .then_with(|| {
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; }
287                                 }
288                                 Ordering::Equal
289                         })
290         }
291 }
292 impl PartialOrd for Txt {
293         fn partial_cmp(&self, o: &Txt) -> Option<Ordering> { Some(self.cmp(o)) }
294 }
295 impl StaticRecord for Txt {
296         const TYPE: u16 = TXT_TYPE;
297         fn name(&self) -> &Name { &self.name }
298         fn json(&self) -> String {
299                 if let Ok(s) = core::str::from_utf8(&self.data) {
300                         if s.chars().all(|c| !c.is_control() && c != '"' && c != '\\') {
301                                 return format!("{{\"type\":\"txt\",\"name\":\"{}\",\"contents\":\"{}\"}}", self.name.0, s);
302                         }
303                 }
304                 format!("{{\"type\":\"txt\",\"name\":\"{}\",\"contents\":{:?}}}", self.name.0, &self.data[..])
305         }
306         fn read_from_data(name: Name, mut data: &[u8], _wire_packet: &[u8]) -> Result<Self, ()> {
307                 let mut parsed_data = Vec::with_capacity(data.len().saturating_sub(1));
308                 while !data.is_empty() {
309                         let len = read_u8(&mut data)? as usize;
310                         if data.len() < len { return Err(()); }
311                         parsed_data.extend_from_slice(&data[..len]);
312                         data = &data[len..];
313                 }
314                 debug_assert!(data.is_empty());
315                 Ok(Txt { name, data: parsed_data })
316         }
317         fn write_u16_len_prefixed_data<W: Writer>(&self, out: &mut W) {
318                 let len = (self.data.len() + (self.data.len() + 254) / 255) as u16;
319                 out.write(&len.to_be_bytes());
320
321                 let mut data_write = &self.data[..];
322                 out.write(&[data_write.len().try_into().unwrap_or(255)]);
323                 while !data_write.is_empty() {
324                         let split_pos = core::cmp::min(255, data_write.len());
325                         out.write(&data_write[..split_pos]);
326                         data_write = &data_write[split_pos..];
327                         if !data_write.is_empty() {
328                                 out.write(&[data_write.len().try_into().unwrap_or(255)]);
329                         }
330                 }
331         }
332 }
333
334 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
335 /// A TLS Certificate Association resource record containing information about the TLS certificate
336 /// which should be expected when communicating with the host at the given name.
337 ///
338 /// See <https://en.wikipedia.org/wiki/DNS-based_Authentication_of_Named_Entities#TLSA_RR> for more
339 /// info.
340 pub struct TLSA {
341         /// The name this record is at.
342         pub name: Name,
343         /// The type of constraint on the TLS certificate(s) used which should be enforced by this
344         /// record.
345         pub cert_usage: u8,
346         /// Whether to match on the full certificate, or only the public key.
347         pub selector: u8,
348         /// The type of data included which is used to match the TLS certificate(s).
349         pub data_ty: u8,
350         /// The certificate data or hash of the certificate data itself.
351         pub data: Vec<u8>,
352 }
353 /// The wire type for TLSA records
354 pub const TLSA_TYPE: u16 = 52;
355 impl StaticRecord for TLSA {
356         const TYPE: u16 = TLSA_TYPE;
357         fn name(&self) -> &Name { &self.name }
358         fn json(&self) -> String {
359                 let mut out = String::with_capacity(128+self.data.len()*2);
360                 write!(&mut out,
361                         "{{\"type\":\"tlsa\",\"name\":\"{}\",\"usage\":{},\"selector\":{},\"data_ty\":{},\"data\":\"",
362                         self.name.0, self.cert_usage, self.selector, self.data_ty
363                 ).expect("Write to a String shouldn't fail");
364                 for c in self.data.iter() {
365                         write!(&mut out, "{:02X}", c)
366                                 .expect("Write to a String shouldn't fail");
367                 }
368                 out += "\"}";
369                 out
370         }
371         fn read_from_data(name: Name, mut data: &[u8], _wire_packet: &[u8]) -> Result<Self, ()> {
372                 Ok(TLSA {
373                         name, cert_usage: read_u8(&mut data)?, selector: read_u8(&mut data)?,
374                         data_ty: read_u8(&mut data)?, data: data.to_vec(),
375                 })
376         }
377         fn write_u16_len_prefixed_data<W: Writer>(&self, out: &mut W) {
378                 let len = 3 + self.data.len();
379                 out.write(&(len as u16).to_be_bytes());
380                 out.write(&[self.cert_usage, self.selector, self.data_ty]);
381                 out.write(&self.data);
382         }
383 }
384
385 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
386 /// A Canonical Name resource record, referring all queries for this name to another name.
387 pub struct CName {
388         /// The name this record is at.
389         pub name: Name,
390         /// The canonical name.
391         ///
392         /// A resolver should use this name when looking up any further records for [`self.name`].
393         pub canonical_name: Name,
394 }
395 impl StaticRecord for CName {
396         const TYPE: u16 = 5;
397         fn name(&self) -> &Name { &self.name }
398         fn json(&self) -> String {
399                 format!("{{\"type\":\"cname\",\"name\":\"{}\",\"canonical_name\":\"{}\"}}",
400                         self.name.0, self.canonical_name.0)
401         }
402         fn read_from_data(name: Name, mut data: &[u8], wire_packet: &[u8]) -> Result<Self, ()> {
403                 let res = CName { name, canonical_name: read_wire_packet_name(&mut data, wire_packet)? };
404                 debug_assert!(data.is_empty());
405                 Ok(res)
406         }
407         fn write_u16_len_prefixed_data<W: Writer>(&self, out: &mut W) {
408                 let len: u16 = name_len(&self.canonical_name);
409                 out.write(&len.to_be_bytes());
410                 write_name(out, &self.canonical_name);
411         }
412 }
413
414 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
415 /// A Delegation Name resource record, referring all queries for subdomains of this name to another
416 /// subtree of the DNS.
417 pub struct DName {
418         /// The name this record is at.
419         pub name: Name,
420         /// The delegation name.
421         ///
422         /// A resolver should use this domain name tree when looking up any further records for
423         /// subdomains of [`self.name`].
424         pub delegation_name: Name,
425 }
426 impl StaticRecord for DName {
427         const TYPE: u16 = 39;
428         fn name(&self) -> &Name { &self.name }
429         fn json(&self) -> String {
430                 format!("{{\"type\":\"dname\",\"name\":\"{}\",\"delegation_name\":\"{}\"}}",
431                         self.name.0, self.delegation_name.0)
432         }
433         fn read_from_data(name: Name, mut data: &[u8], wire_packet: &[u8]) -> Result<Self, ()> {
434                 let res = DName { name, delegation_name: read_wire_packet_name(&mut data, wire_packet)? };
435                 debug_assert!(data.is_empty());
436                 Ok(res)
437         }
438         fn write_u16_len_prefixed_data<W: Writer>(&self, out: &mut W) {
439                 let len: u16 = name_len(&self.delegation_name);
440                 out.write(&len.to_be_bytes());
441                 write_name(out, &self.delegation_name);
442         }
443 }
444
445
446 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
447 /// A public key resource record which can be used to validate [`RRSig`]s.
448 pub struct DnsKey {
449         /// The name this record is at.
450         pub name: Name,
451         /// Flags which constrain the usage of this public key.
452         pub flags: u16,
453         /// The protocol this key is used for (protocol `3` is DNSSEC). 
454         pub protocol: u8,
455         /// The algorithm which this public key uses to sign data.
456         pub alg: u8,
457         /// The public key itself.
458         pub pubkey: Vec<u8>,
459 }
460 impl StaticRecord for DnsKey {
461         const TYPE: u16 = 48;
462         fn name(&self) -> &Name { &self.name }
463         fn json(&self) -> String {
464                 let mut out = String::with_capacity(128+self.pubkey.len()*2);
465                 write!(&mut out,
466                         "{{\"type\":\"dnskey\",\"name\":\"{}\",\"flags\":{},\"protocol\":{},\"alg\":{},\"pubkey\":\"",
467                         self.name.0, self.flags, self.protocol, self.alg
468                 ).expect("Write to a String shouldn't fail");
469                 for c in self.pubkey.iter() {
470                         write!(&mut out, "{:02X}", c)
471                                 .expect("Write to a String shouldn't fail");
472                 }
473                 out += "\"}";
474                 out
475         }
476         fn read_from_data(name: Name, mut data: &[u8], _wire_packet: &[u8]) -> Result<Self, ()> {
477                 Ok(DnsKey {
478                         name, flags: read_u16(&mut data)?, protocol: read_u8(&mut data)?,
479                         alg: read_u8(&mut data)?, pubkey: data.to_vec(),
480                 })
481         }
482         fn write_u16_len_prefixed_data<W: Writer>(&self, out: &mut W) {
483                 let len = 2 + 1 + 1 + self.pubkey.len();
484                 out.write(&(len as u16).to_be_bytes());
485                 out.write(&self.flags.to_be_bytes());
486                 out.write(&self.protocol.to_be_bytes());
487                 out.write(&self.alg.to_be_bytes());
488                 out.write(&self.pubkey);
489         }
490 }
491 impl DnsKey {
492         /// A short (non-cryptographic) digest which can be used to refer to this [`DnsKey`].
493         pub fn key_tag(&self) -> u16 {
494                 let mut res = u32::from(self.flags);
495                 res += u32::from(self.protocol) << 8;
496                 res += u32::from(self.alg);
497                 for (idx, b) in self.pubkey.iter().enumerate() {
498                         if idx % 2 == 0 {
499                                 res += u32::from(*b) << 8;
500                         } else {
501                                 res += u32::from(*b);
502                         }
503                 }
504                 res += (res >> 16) & 0xffff;
505                 (res & 0xffff) as u16
506         }
507 }
508
509 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
510 /// A Delegation Signer resource record which indicates that some alternative [`DnsKey`] can sign
511 /// for records in the zone which matches [`self.name`].
512 pub struct DS {
513         /// The name this record is at.
514         ///
515         /// This is also the zone that a [`DnsKey`] which matches the [`Self::digest`] can sign for.
516         pub name: Name,
517         /// A short tag which describes the matching [`DnsKey`].
518         ///
519         /// This matches the [`DnsKey::key_tag`] for the [`DnsKey`] which is referred to by this
520         /// [`DS`].
521         pub key_tag: u16,
522         /// The algorithm which the [`DnsKey`] referred to by this [`DS`] uses.
523         ///
524         /// This matches the [`DnsKey::alg`] field in the referred-to [`DnsKey`].
525         pub alg: u8,
526         /// The type of digest used to hash the referred-to [`DnsKey`].
527         pub digest_type: u8,
528         /// The digest itself.
529         pub digest: Vec<u8>,
530 }
531 impl StaticRecord for DS {
532         const TYPE: u16 = 43;
533         fn name(&self) -> &Name { &self.name }
534         fn json(&self) -> String {
535                 let mut out = String::with_capacity(128+self.digest.len()*2);
536                 write!(&mut out,
537                         "{{\"type\":\"ds\",\"name\":\"{}\",\"key_tag\":{},\"alg\":{},\"digest_type\":{},\"digest\":\"",
538                         self.name.0, self.key_tag, self.alg, self.digest_type
539                 ).expect("Write to a String shouldn't fail");
540                 for c in self.digest.iter() {
541                         write!(&mut out, "{:02X}", c)
542                                 .expect("Write to a String shouldn't fail");
543                 }
544                 out += "\"}";
545                 out
546         }
547         fn read_from_data(name: Name, mut data: &[u8], _wire_packet: &[u8]) -> Result<Self, ()> {
548                 Ok(DS {
549                         name, key_tag: read_u16(&mut data)?, alg: read_u8(&mut data)?,
550                         digest_type: read_u8(&mut data)?, digest: data.to_vec(),
551                 })
552         }
553         fn write_u16_len_prefixed_data<W: Writer>(&self, out: &mut W) {
554                 let len = 2 + 1 + 1 + self.digest.len();
555                 out.write(&(len as u16).to_be_bytes());
556                 out.write(&self.key_tag.to_be_bytes());
557                 out.write(&self.alg.to_be_bytes());
558                 out.write(&self.digest_type.to_be_bytes());
559                 out.write(&self.digest);
560         }
561 }
562
563 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
564 /// A Resource Record (set) Signature resource record. This contains a signature over all the
565 /// resources records of the given type at the given name.
566 pub struct RRSig {
567         /// The name this record is at.
568         ///
569         /// This is also the name of any records which this signature is covering (ignoring wildcards).
570         pub name: Name,
571         /// The resource record type which this [`RRSig`] is signing.
572         ///
573         /// All resources records of this type at the same name as [`self.name`] must be signed by
574         /// this [`RRSig`].
575         pub ty: u16,
576         /// The algorithm which is being used to sign.
577         ///
578         /// This must match the [`DnsKey::alg`] field in the [`DnsKey`] being used to sign.
579         pub alg: u8,
580         /// The number of labels in the name of the records that this signature is signing.
581         ///
582         /// If this is less than the number of labels in [`self.name`], this signature is covering a
583         /// wildcard entry.
584         pub labels: u8,
585         /// The TTL of the records which this [`RRSig`] is signing.
586         pub orig_ttl: u32,
587         /// The expiration (as a UNIX timestamp) of this signature.
588         pub expiration: u32,
589         /// The time (as a UNIX timestamp) at which this signature becomes valid.
590         pub inception: u32,
591         /// A short tag which describes the matching [`DnsKey`].
592         ///
593         /// This matches the [`DnsKey::key_tag`] for the [`DnsKey`] which created this signature.
594         pub key_tag: u16,
595         /// The [`DnsKey::name`] in the [`DnsKey`] which created this signature.
596         ///
597         /// This must be a parent of [`self.name`].
598         ///
599         /// [`DnsKey::name`]: Record::name
600         // We'd like to just link to the `DnsKey` member variable called `name`, but there doesn't
601         // appear to be a way to actually do that, so instead we have to link to the trait method.
602         pub key_name: Name,
603         /// The signature itself.
604         pub signature: Vec<u8>,
605 }
606 impl StaticRecord for RRSig {
607         const TYPE: u16 = 46;
608         fn name(&self) -> &Name { &self.name }
609         fn json(&self) -> String {
610                 let mut out = String::with_capacity(256 + self.signature.len()*2);
611                 write!(&mut out,
612                         "{{\"type\":\"ds\",\"name\":\"{}\",\"signed_record_type\":{},\"alg\":{},\"signed_labels\":{},\"orig_ttl\":{},\"expiration\"{},\"inception\":{},\"key_tag\":{},\"key_name\":\"{}\",\"signature\":\"",
613                         self.name.0, self.ty, self.alg, self.labels, self.orig_ttl, self.expiration, self.inception, self.key_tag, self.key_name.0
614                 ).expect("Write to a String shouldn't fail");
615                 for c in self.signature.iter() {
616                         write!(&mut out, "{:02X}", c)
617                                 .expect("Write to a String shouldn't fail");
618                 }
619                 out += "\"}";
620                 out
621         }
622         fn read_from_data(name: Name, mut data: &[u8], wire_packet: &[u8]) -> Result<Self, ()> {
623                 Ok(RRSig {
624                         name, ty: read_u16(&mut data)?, alg: read_u8(&mut data)?,
625                         labels: read_u8(&mut data)?, orig_ttl: read_u32(&mut data)?,
626                         expiration: read_u32(&mut data)?, inception: read_u32(&mut data)?,
627                         key_tag: read_u16(&mut data)?,
628                         key_name: read_wire_packet_name(&mut data, wire_packet)?,
629                         signature: data.to_vec(),
630                 })
631         }
632         fn write_u16_len_prefixed_data<W: Writer>(&self, out: &mut W) {
633                 let len = 2 + 1 + 1 + 4*3 + 2 + name_len(&self.key_name) + self.signature.len() as u16;
634                 out.write(&len.to_be_bytes());
635                 out.write(&self.ty.to_be_bytes());
636                 out.write(&self.alg.to_be_bytes());
637                 out.write(&self.labels.to_be_bytes());
638                 out.write(&self.orig_ttl.to_be_bytes());
639                 out.write(&self.expiration.to_be_bytes());
640                 out.write(&self.inception.to_be_bytes());
641                 out.write(&self.key_tag.to_be_bytes());
642                 write_name(out, &self.key_name);
643                 out.write(&self.signature);
644         }
645 }
646
647 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
648 /// A mask used in [`NSec`] and [`NSec3`] records which indicates the resource record types which
649 /// exist at the (hash of the) name described in [`Record::name`].
650 pub struct NSecTypeMask([u8; 8192]);
651 impl NSecTypeMask {
652         /// Constructs a new, empty, type mask.
653         pub fn new() -> Self { Self([0; 8192]) }
654         /// Builds a new type mask with the given types set
655         pub fn from_types(types: &[u16]) -> Self {
656                 let mut flags = [0; 8192];
657                 for t in types {
658                         flags[*t as usize >> 3] |= 1 << (7 - (*t as usize % 8));
659                 }
660                 let res = Self(flags);
661                 for t in types {
662                         debug_assert!(res.contains_type(*t));
663                 }
664                 res
665         }
666         /// Checks if the given type (from [`Record::ty`]) is set, indicating a record of this type
667         /// exists.
668         pub fn contains_type(&self, ty: u16) -> bool {
669                 let f = self.0[(ty >> 3) as usize];
670                 // DNSSEC's bit fields are in wire order, so the high bit is type 0, etc.
671                 f & (1 << (7 - (ty % 8))) != 0
672         }
673         fn write_json(&self, s: &mut String) {
674                 *s += "[";
675                 let mut have_written = false;
676                 for (idx, mask) in self.0.iter().enumerate() {
677                         if *mask == 0 { continue; }
678                         for b in 0..8 {
679                                 if *mask & (1 << b) != 0 {
680                                         if have_written {
681                                                 *s += ",";
682                                         }
683                                         have_written = true;
684                                         let ty = ((idx as u16) << 3) | (7 - b);
685                                         match RR::ty_to_rr_name(ty) {
686                                                 Some(name) => write!(s, "\"{}\"", name).expect("Writes to a string shouldn't fail"),
687                                                 _ => write!(s, "{}", ty).expect("Writes to a string shouldn't fail"),
688                                         }
689                                 }
690                         }
691                 }
692                 *s += "]";
693         }
694 }
695
696 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
697 /// A Next Secure Record resource record. This indicates a range of possible names for which there
698 /// is no such record.
699 pub struct NSec {
700         /// The name this record is at.
701         pub name: Name,
702         /// The next name which contains a record. There are no names between `name` and
703         /// [`Self::next_name`].
704         pub next_name: Name,
705         /// The set of record types which exist at `name`. Any other record types do not exist at
706         /// `name`.
707         pub types: NSecTypeMask,
708 }
709 impl StaticRecord for NSec {
710         const TYPE: u16 = 47;
711         fn name(&self) -> &Name { &self.name }
712         fn json(&self) -> String {
713                 let mut out = String::with_capacity(256 + self.next_name.len());
714                 write!(&mut out,
715                         "{{\"type\":\"nsec\",\"name\":\"{}\",\"next_name\":\"{}\",\"types\":",
716                         self.name.0, self.next_name.0,
717                 ).expect("Write to a String shouldn't fail");
718                 self.types.write_json(&mut out);
719                 out += "}";
720                 out
721         }
722         fn read_from_data(name: Name, mut data: &[u8], wire_packet: &[u8]) -> Result<Self, ()> {
723                 let res = NSec {
724                         name, next_name: read_wire_packet_name(&mut data, wire_packet)?,
725                         types: NSecTypeMask(read_nsec_types_bitmap(&mut data)?),
726                 };
727                 debug_assert!(data.is_empty());
728                 Ok(res)
729         }
730         fn write_u16_len_prefixed_data<W: Writer>(&self, out: &mut W) {
731                 let len = name_len(&self.next_name) + nsec_types_bitmap_len(&self.types.0);
732                 out.write(&len.to_be_bytes());
733                 write_name(out, &self.next_name);
734                 write_nsec_types_bitmap(out, &self.types.0);
735         }
736 }
737
738 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
739 /// A Next Secure Record resource record. This indicates a range of possible names for which there
740 /// is no such record.
741 pub struct NSec3 {
742         /// The name this record is at.
743         pub name: Name,
744         /// The hash algorithm used to hash the `name` and [`Self::next_name_hash`]. Currently only 1
745         /// (SHA-1) is defined.
746         pub hash_algo: u8,
747         /// Flags for this record. Currently only bit 0 (the "opt-out" bit) is defined.
748         pub flags: u8,
749         /// The number of hash iterations required.
750         ///
751         /// As of RFC 9276 this MUST be set to 0, but sadly is often still set higher in the wild. A
752         /// hard cap is applied in validation.
753         pub hash_iterations: u16,
754         /// The salt included in the hash.
755         ///
756         /// As of RFC 9276 this SHOULD be empty, but often isn't in the wild.
757         pub salt: Vec<u8>,
758         /// The hash of the next name which contains a record. There are no records who's name's hash
759         /// lies between `name` and [`Self::next_name_hash`].
760         pub next_name_hash: Vec<u8>,
761         /// The set of record types which exist at `name`. Any other record types do not exist at
762         /// `name`.
763         pub types: NSecTypeMask,
764 }
765 impl StaticRecord for NSec3 {
766         const TYPE: u16 = 50;
767         fn name(&self) -> &Name { &self.name }
768         fn json(&self) -> String {
769                 let mut out = String::with_capacity(256);
770                 write!(&mut out,
771                         "{{\"type\":\"nsec3\",\"name\":\"{}\",\"hash_algo\":{},\"flags\":{},\"hash_iterations\":{},\"salt\":{:?},\"next_name_hash\":{:?},\"types\":",
772                         self.name.0, self.hash_algo, self.flags, self.hash_iterations, &self.salt[..], &self.next_name_hash[..]
773                 ).expect("Write to a String shouldn't fail");
774                 self.types.write_json(&mut out);
775                 out += "}";
776                 out
777         }
778         fn read_from_data(name: Name, mut data: &[u8], _wire_packet: &[u8]) -> Result<Self, ()> {
779                 let res = NSec3 {
780                         name, hash_algo: read_u8(&mut data)?, flags: read_u8(&mut data)?,
781                         hash_iterations: read_u16(&mut data)?, salt: read_u8_len_prefixed_bytes(&mut data)?,
782                         next_name_hash: read_u8_len_prefixed_bytes(&mut data)?,
783                         types: NSecTypeMask(read_nsec_types_bitmap(&mut data)?),
784                 };
785                 debug_assert!(data.is_empty());
786                 Ok(res)
787         }
788         fn write_u16_len_prefixed_data<W: Writer>(&self, out: &mut W) {
789                 let len = 4 + 2 + self.salt.len() as u16 + self.next_name_hash.len() as u16 +
790                         nsec_types_bitmap_len(&self.types.0);
791                 out.write(&len.to_be_bytes());
792                 out.write(&self.hash_algo.to_be_bytes());
793                 out.write(&self.flags.to_be_bytes());
794                 out.write(&self.hash_iterations.to_be_bytes());
795                 out.write(&(self.salt.len() as u8).to_be_bytes());
796                 out.write(&self.salt);
797                 out.write(&(self.next_name_hash.len() as u8).to_be_bytes());
798                 out.write(&self.next_name_hash);
799                 write_nsec_types_bitmap(out, &self.types.0);
800         }
801 }
802
803 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
804 /// An IPv4 Address resource record
805 pub struct A {
806         /// The name this record is at.
807         pub name: Name,
808         /// The bytes of the IPv4 address.
809         pub address: [u8; 4],
810 }
811 /// The wire type for A records
812 pub const A_TYPE: u16 = 1;
813 impl StaticRecord for A {
814         const TYPE: u16 = A_TYPE;
815         fn name(&self) -> &Name { &self.name }
816         fn json(&self) -> String {
817                 format!("{{\"type\":\"a\",\"name\":\"{}\",\"address\":{:?}}}", self.name.0, self.address)
818         }
819         fn read_from_data(name: Name, data: &[u8], _wire_packet: &[u8]) -> Result<Self, ()> {
820                 if data.len() != 4 { return Err(()); }
821                 let mut address = [0; 4];
822                 address.copy_from_slice(data);
823                 Ok(A { name, address })
824         }
825         fn write_u16_len_prefixed_data<W: Writer>(&self, out: &mut W) {
826                 out.write(&4u16.to_be_bytes());
827                 out.write(&self.address);
828         }
829 }
830
831 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
832 /// An IPv6 Address resource record
833 pub struct AAAA {
834         /// The name this record is at.
835         pub name: Name,
836         /// The bytes of the IPv6 address.
837         pub address: [u8; 16],
838 }
839 /// The wire type for AAAA records
840 pub const AAAA_TYPE: u16 = 28;
841 impl StaticRecord for AAAA {
842         const TYPE: u16 = AAAA_TYPE;
843         fn name(&self) -> &Name { &self.name }
844         fn json(&self) -> String {
845                 format!("{{\"type\":\"aaaa\",\"name\":\"{}\",\"address\":{:?}}}", self.name.0, self.address)
846         }
847         fn read_from_data(name: Name, data: &[u8], _wire_packet: &[u8]) -> Result<Self, ()> {
848                 if data.len() != 16 { return Err(()); }
849                 let mut address = [0; 16];
850                 address.copy_from_slice(data);
851                 Ok(AAAA { name, address })
852         }
853         fn write_u16_len_prefixed_data<W: Writer>(&self, out: &mut W) {
854                 out.write(&16u16.to_be_bytes());
855                 out.write(&self.address);
856         }
857 }
858
859 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
860 /// A Name Server resource record, which indicates the server responsible for handling queries for
861 /// a zone.
862 pub struct NS {
863         /// The name this record is at.
864         ///
865         /// This is also the zone which the server at [`Self::name_server`] is responsible for handling
866         /// queries for.
867         pub name: Name,
868         /// The name of the server which is responsible for handling queries for the [`self.name`]
869         /// zone.
870         pub name_server: Name,
871 }
872 impl StaticRecord for NS {
873         const TYPE: u16 = 2;
874         fn name(&self) -> &Name { &self.name }
875         fn json(&self) -> String {
876                 format!("{{\"type\":\"ns\",\"name\":\"{}\",\"ns\":\"{}\"}}", self.name.0, self.name_server.0)
877         }
878         fn read_from_data(name: Name, mut data: &[u8], wire_packet: &[u8]) -> Result<Self, ()> {
879                 let res = NS { name, name_server: read_wire_packet_name(&mut data, wire_packet)? };
880                 debug_assert!(data.is_empty());
881                 Ok(res)
882         }
883         fn write_u16_len_prefixed_data<W: Writer>(&self, out: &mut W) {
884                 out.write(&name_len(&self.name_server).to_be_bytes());
885                 write_name(out, &self.name_server);
886         }
887 }