Add debug checks that we don't leave data behind after an RR
[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 }
105 impl RR {
106         /// Gets the name this record refers to.
107         pub fn name(&self) -> &Name {
108                 match self {
109                         RR::A(rr) => &rr.name,
110                         RR::AAAA(rr) => &rr.name,
111                         RR::NS(rr) => &rr.name,
112                         RR::Txt(rr) => &rr.name,
113                         RR::CName(rr) => &rr.name,
114                         RR::DName(rr) => &rr.name,
115                         RR::TLSA(rr) => &rr.name,
116                         RR::DnsKey(rr) => &rr.name,
117                         RR::DS(rr) => &rr.name,
118                         RR::RRSig(rr) => &rr.name,
119                 }
120         }
121         /// Gets a JSON encoding of this record
122         pub fn json(&self) -> String {
123                 match self {
124                         RR::A(rr) => StaticRecord::json(rr),
125                         RR::AAAA(rr) => StaticRecord::json(rr),
126                         RR::NS(rr) => StaticRecord::json(rr),
127                         RR::Txt(rr) => StaticRecord::json(rr),
128                         RR::CName(rr) => StaticRecord::json(rr),
129                         RR::DName(rr) => StaticRecord::json(rr),
130                         RR::TLSA(rr) => StaticRecord::json(rr),
131                         RR::DnsKey(rr) => StaticRecord::json(rr),
132                         RR::DS(rr) => StaticRecord::json(rr),
133                         RR::RRSig(rr) => StaticRecord::json(rr),
134                 }
135         }
136         fn ty(&self) -> u16 {
137                 match self {
138                         RR::A(_) => A::TYPE,
139                         RR::AAAA(_) => AAAA::TYPE,
140                         RR::NS(_) => NS::TYPE,
141                         RR::Txt(_) => Txt::TYPE,
142                         RR::CName(_) => CName::TYPE,
143                         RR::DName(_) => DName::TYPE,
144                         RR::TLSA(_) => TLSA::TYPE,
145                         RR::DnsKey(_) => DnsKey::TYPE,
146                         RR::DS(_) => DS::TYPE,
147                         RR::RRSig(_) => RRSig::TYPE,
148                 }
149         }
150         fn write_u16_len_prefixed_data(&self, out: &mut Vec<u8>) {
151                 match self {
152                         RR::A(rr) => StaticRecord::write_u16_len_prefixed_data(rr, out),
153                         RR::AAAA(rr) => StaticRecord::write_u16_len_prefixed_data(rr, out),
154                         RR::NS(rr) => StaticRecord::write_u16_len_prefixed_data(rr, out),
155                         RR::Txt(rr) => StaticRecord::write_u16_len_prefixed_data(rr, out),
156                         RR::CName(rr) => StaticRecord::write_u16_len_prefixed_data(rr, out),
157                         RR::DName(rr) => StaticRecord::write_u16_len_prefixed_data(rr, out),
158                         RR::TLSA(rr) => StaticRecord::write_u16_len_prefixed_data(rr, out),
159                         RR::DnsKey(rr) => StaticRecord::write_u16_len_prefixed_data(rr, out),
160                         RR::DS(rr) => StaticRecord::write_u16_len_prefixed_data(rr, out),
161                         RR::RRSig(rr) => StaticRecord::write_u16_len_prefixed_data(rr, out),
162                 }
163         }
164 }
165 impl From<A> for RR { fn from(a: A) -> RR { RR::A(a) } }
166 impl From<AAAA> for RR { fn from(aaaa: AAAA) -> RR { RR::AAAA(aaaa) } }
167 impl From<NS> for RR { fn from(ns: NS) -> RR { RR::NS(ns) } }
168 impl From<Txt> for RR { fn from(txt: Txt) -> RR { RR::Txt(txt) } }
169 impl From<CName> for RR { fn from(cname: CName) -> RR { RR::CName(cname) } }
170 impl From<DName> for RR { fn from(cname: DName) -> RR { RR::DName(cname) } }
171 impl From<TLSA> for RR { fn from(tlsa: TLSA) -> RR { RR::TLSA(tlsa) } }
172 impl From<DnsKey> for RR { fn from(dnskey: DnsKey) -> RR { RR::DnsKey(dnskey) } }
173 impl From<DS> for RR { fn from(ds: DS) -> RR { RR::DS(ds) } }
174 impl From<RRSig> for RR { fn from(rrsig: RRSig) -> RR { RR::RRSig(rrsig) } }
175
176 pub(crate) trait StaticRecord : Ord + Sized {
177         // http://www.iana.org/assignments/dns-parameters/dns-parameters.xhtml#dns-parameters-4
178         const TYPE: u16;
179         fn name(&self) -> &Name;
180         fn json(&self) -> String;
181         fn write_u16_len_prefixed_data(&self, out: &mut Vec<u8>);
182         fn read_from_data(name: Name, data: &[u8], wire_packet: &[u8]) -> Result<Self, ()>;
183 }
184 /// A trait describing a resource record (including the [`RR`] enum).
185 pub trait Record : Ord {
186         /// The resource record type, as maintained by IANA.
187         ///
188         /// Current assignments can be found at
189         /// <http://www.iana.org/assignments/dns-parameters/dns-parameters.xhtml#dns-parameters-4>
190         fn ty(&self) -> u16;
191         /// The name this record is at.
192         fn name(&self) -> &Name;
193         /// Gets a JSON encoding of this record.
194         fn json(&self) -> String;
195         /// Writes the data of this record, prefixed by a u16 length, to the given `Vec`.
196         fn write_u16_len_prefixed_data(&self, out: &mut Vec<u8>);
197 }
198 impl<RR: StaticRecord> Record for RR {
199         fn ty(&self) -> u16 { RR::TYPE }
200         fn name(&self) -> &Name { RR::name(self) }
201         fn json(&self) -> String { RR::json(self) }
202         fn write_u16_len_prefixed_data(&self, out: &mut Vec<u8>) {
203                 RR::write_u16_len_prefixed_data(self, out)
204         }
205 }
206 impl Record for RR {
207         fn ty(&self) -> u16 { self.ty() }
208         fn name(&self) -> &Name { self.name() }
209         fn json(&self) -> String { self.json() }
210         fn write_u16_len_prefixed_data(&self, out: &mut Vec<u8>) {
211                 self.write_u16_len_prefixed_data(out)
212         }
213 }
214
215 #[derive(Debug, Clone, PartialEq, Eq, Ord)]
216 /// A text resource record, containing arbitrary text data
217 pub struct Txt {
218         /// The name this record is at.
219         pub name: Name,
220         /// The text record itself.
221         ///
222         /// While this is generally UTF-8-valid, there is no specific requirement that it be, and thus
223         /// is an arbitrary series of bytes here.
224         pub data: Vec<u8>,
225 }
226 /// The wire type for TXT records
227 pub const TXT_TYPE: u16 = 16;
228 impl PartialOrd for Txt {
229         fn partial_cmp(&self, o: &Txt) -> Option<Ordering> {
230                 Some(self.name.cmp(&o.name)
231                         .then_with(|| {
232                                 // Compare in wire encoding form, i.e. compare in 255-byte chunks
233                                 for i in 1..(self.data.len() / 255) + 2 {
234                                         let start = (i - 1)*255;
235                                         let self_len = cmp::min(i * 255, self.data.len());
236                                         let o_len = cmp::min(i * 255, o.data.len());
237                                         let slice_cmp = self_len.cmp(&o_len)
238                                                 .then_with(|| self.data[start..self_len].cmp(&o.data[start..o_len]));
239                                         if !slice_cmp.is_eq() { return slice_cmp; }
240                                 }
241                                 Ordering::Equal
242                         }))
243         }
244 }
245 impl StaticRecord for Txt {
246         const TYPE: u16 = TXT_TYPE;
247         fn name(&self) -> &Name { &self.name }
248         fn json(&self) -> String {
249                 if let Ok(s) = core::str::from_utf8(&self.data) {
250                         if s.chars().all(|c| !c.is_control() && c != '"' && c != '\\') {
251                                 return format!("{{\"type\":\"txt\",\"name\":\"{}\",\"contents\":\"{}\"}}", self.name.0, s);
252                         }
253                 }
254                 format!("{{\"type\":\"txt\",\"name\":\"{}\",\"contents\":{:?}}}", self.name.0, &self.data[..])
255         }
256         fn read_from_data(name: Name, mut data: &[u8], _wire_packet: &[u8]) -> Result<Self, ()> {
257                 let mut parsed_data = Vec::with_capacity(data.len().saturating_sub(1));
258                 while !data.is_empty() {
259                         let len = read_u8(&mut data)? as usize;
260                         if data.len() < len { return Err(()); }
261                         parsed_data.extend_from_slice(&data[..len]);
262                         data = &data[len..];
263                 }
264                 debug_assert!(data.is_empty());
265                 Ok(Txt { name, data: parsed_data })
266         }
267         fn write_u16_len_prefixed_data(&self, out: &mut Vec<u8>) {
268                 let len = (self.data.len() + (self.data.len() + 254) / 255) as u16;
269                 out.extend_from_slice(&len.to_be_bytes());
270
271                 let mut data_write = &self.data[..];
272                 out.extend_from_slice(&[data_write.len().try_into().unwrap_or(255)]);
273                 while !data_write.is_empty() {
274                         let split_pos = core::cmp::min(255, data_write.len());
275                         out.extend_from_slice(&data_write[..split_pos]);
276                         data_write = &data_write[split_pos..];
277                         if !data_write.is_empty() {
278                                 out.extend_from_slice(&[data_write.len().try_into().unwrap_or(255)]);
279                         }
280                 }
281         }
282 }
283
284 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
285 /// A TLS Certificate Association resource record containing information about the TLS certificate
286 /// which should be expected when communicating with the host at the given name.
287 ///
288 /// See <https://en.wikipedia.org/wiki/DNS-based_Authentication_of_Named_Entities#TLSA_RR> for more
289 /// info.
290 pub struct TLSA {
291         /// The name this record is at.
292         pub name: Name,
293         /// The type of constraint on the TLS certificate(s) used which should be enforced by this
294         /// record.
295         pub cert_usage: u8,
296         /// Whether to match on the full certificate, or only the public key.
297         pub selector: u8,
298         /// The type of data included which is used to match the TLS certificate(s).
299         pub data_ty: u8,
300         /// The certificate data or hash of the certificate data itself.
301         pub data: Vec<u8>,
302 }
303 /// The wire type for TLSA records
304 pub const TLSA_TYPE: u16 = 52;
305 impl StaticRecord for TLSA {
306         const TYPE: u16 = TLSA_TYPE;
307         fn name(&self) -> &Name { &self.name }
308         fn json(&self) -> String {
309                 let mut out = String::with_capacity(128+self.data.len()*2);
310                 write!(&mut out,
311                         "{{\"type\":\"tlsa\",\"name\":\"{}\",\"usage\":{},\"selector\":{},\"data_ty\":{},\"data\":\"",
312                         self.name.0, self.cert_usage, self.selector, self.data_ty
313                 ).expect("Write to a String shouldn't fail");
314                 for c in self.data.iter() {
315                         write!(&mut out, "{:02X}", c)
316                                 .expect("Write to a String shouldn't fail");
317                 }
318                 out += "\"}";
319                 out
320         }
321         fn read_from_data(name: Name, mut data: &[u8], _wire_packet: &[u8]) -> Result<Self, ()> {
322                 Ok(TLSA {
323                         name, cert_usage: read_u8(&mut data)?, selector: read_u8(&mut data)?,
324                         data_ty: read_u8(&mut data)?, data: data.to_vec(),
325                 })
326         }
327         fn write_u16_len_prefixed_data(&self, out: &mut Vec<u8>) {
328                 let len = 3 + self.data.len();
329                 out.extend_from_slice(&(len as u16).to_be_bytes());
330                 out.extend_from_slice(&[self.cert_usage, self.selector, self.data_ty]);
331                 out.extend_from_slice(&self.data);
332         }
333 }
334
335 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
336 /// A Canonical Name resource record, referring all queries for this name to another name.
337 pub struct CName {
338         /// The name this record is at.
339         pub name: Name,
340         /// The canonical name.
341         ///
342         /// A resolver should use this name when looking up any further records for [`self.name`].
343         pub canonical_name: Name,
344 }
345 impl StaticRecord for CName {
346         const TYPE: u16 = 5;
347         fn name(&self) -> &Name { &self.name }
348         fn json(&self) -> String {
349                 format!("{{\"type\":\"cname\",\"name\":\"{}\",\"canonical_name\":\"{}\"}}",
350                         self.name.0, self.canonical_name.0)
351         }
352         fn read_from_data(name: Name, mut data: &[u8], wire_packet: &[u8]) -> Result<Self, ()> {
353                 let res = CName { name, canonical_name: read_wire_packet_name(&mut data, wire_packet)? };
354                 debug_assert!(data.is_empty());
355                 Ok(res)
356         }
357         fn write_u16_len_prefixed_data(&self, out: &mut Vec<u8>) {
358                 let len: u16 = name_len(&self.canonical_name);
359                 out.extend_from_slice(&len.to_be_bytes());
360                 write_name(out, &self.canonical_name);
361         }
362 }
363
364 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
365 /// A Delegation Name resource record, referring all queries for subdomains of this name to another
366 /// subtree of the DNS.
367 pub struct DName {
368         /// The name this record is at.
369         pub name: Name,
370         /// The delegation name.
371         ///
372         /// A resolver should use this domain name tree when looking up any further records for
373         /// subdomains of [`self.name`].
374         pub delegation_name: Name,
375 }
376 impl StaticRecord for DName {
377         const TYPE: u16 = 39;
378         fn name(&self) -> &Name { &self.name }
379         fn json(&self) -> String {
380                 format!("{{\"type\":\"dname\",\"name\":\"{}\",\"delegation_name\":\"{}\"}}",
381                         self.name.0, self.delegation_name.0)
382         }
383         fn read_from_data(name: Name, mut data: &[u8], wire_packet: &[u8]) -> Result<Self, ()> {
384                 let res = DName { name, delegation_name: read_wire_packet_name(&mut data, wire_packet)? };
385                 debug_assert!(data.is_empty());
386                 Ok(res)
387         }
388         fn write_u16_len_prefixed_data(&self, out: &mut Vec<u8>) {
389                 let len: u16 = name_len(&self.delegation_name);
390                 out.extend_from_slice(&len.to_be_bytes());
391                 write_name(out, &self.delegation_name);
392         }
393 }
394
395
396 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
397 /// A public key resource record which can be used to validate [`RRSig`]s.
398 pub struct DnsKey {
399         /// The name this record is at.
400         pub name: Name,
401         /// Flags which constrain the usage of this public key.
402         pub flags: u16,
403         /// The protocol this key is used for (protocol `3` is DNSSEC). 
404         pub protocol: u8,
405         /// The algorithm which this public key uses to sign data.
406         pub alg: u8,
407         /// The public key itself.
408         pub pubkey: Vec<u8>,
409 }
410 impl StaticRecord for DnsKey {
411         const TYPE: u16 = 48;
412         fn name(&self) -> &Name { &self.name }
413         fn json(&self) -> String {
414                 let mut out = String::with_capacity(128+self.pubkey.len()*2);
415                 write!(&mut out,
416                         "{{\"type\":\"dnskey\",\"name\":\"{}\",\"flags\":{},\"protocol\":{},\"alg\":{},\"pubkey\":\"",
417                         self.name.0, self.flags, self.protocol, self.alg
418                 ).expect("Write to a String shouldn't fail");
419                 for c in self.pubkey.iter() {
420                         write!(&mut out, "{:02X}", c)
421                                 .expect("Write to a String shouldn't fail");
422                 }
423                 out += "\"}";
424                 out
425         }
426         fn read_from_data(name: Name, mut data: &[u8], _wire_packet: &[u8]) -> Result<Self, ()> {
427                 Ok(DnsKey {
428                         name, flags: read_u16(&mut data)?, protocol: read_u8(&mut data)?,
429                         alg: read_u8(&mut data)?, pubkey: data.to_vec(),
430                 })
431         }
432         fn write_u16_len_prefixed_data(&self, out: &mut Vec<u8>) {
433                 let len = 2 + 1 + 1 + self.pubkey.len();
434                 out.extend_from_slice(&(len as u16).to_be_bytes());
435                 out.extend_from_slice(&self.flags.to_be_bytes());
436                 out.extend_from_slice(&self.protocol.to_be_bytes());
437                 out.extend_from_slice(&self.alg.to_be_bytes());
438                 out.extend_from_slice(&self.pubkey);
439         }
440 }
441 impl DnsKey {
442         /// A short (non-cryptographic) digest which can be used to refer to this [`DnsKey`].
443         pub fn key_tag(&self) -> u16 {
444                 let mut res = u32::from(self.flags);
445                 res += u32::from(self.protocol) << 8;
446                 res += u32::from(self.alg);
447                 for (idx, b) in self.pubkey.iter().enumerate() {
448                         if idx % 2 == 0 {
449                                 res += u32::from(*b) << 8;
450                         } else {
451                                 res += u32::from(*b);
452                         }
453                 }
454                 res += (res >> 16) & 0xffff;
455                 (res & 0xffff) as u16
456         }
457 }
458
459 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
460 /// A Delegation Signer resource record which indicates that some alternative [`DnsKey`] can sign
461 /// for records in the zone which matches [`self.name`].
462 pub struct DS {
463         /// The name this record is at.
464         ///
465         /// This is also the zone that a [`DnsKey`] which matches the [`Self::digest`] can sign for.
466         pub name: Name,
467         /// A short tag which describes the matching [`DnsKey`].
468         ///
469         /// This matches the [`DnsKey::key_tag`] for the [`DnsKey`] which is referred to by this
470         /// [`DS`].
471         pub key_tag: u16,
472         /// The algorithm which the [`DnsKey`] referred to by this [`DS`] uses.
473         ///
474         /// This matches the [`DnsKey::alg`] field in the referred-to [`DnsKey`].
475         pub alg: u8,
476         /// The type of digest used to hash the referred-to [`DnsKey`].
477         pub digest_type: u8,
478         /// The digest itself.
479         pub digest: Vec<u8>,
480 }
481 impl StaticRecord for DS {
482         const TYPE: u16 = 43;
483         fn name(&self) -> &Name { &self.name }
484         fn json(&self) -> String {
485                 let mut out = String::with_capacity(128+self.digest.len()*2);
486                 write!(&mut out,
487                         "{{\"type\":\"ds\",\"name\":\"{}\",\"key_tag\":{},\"alg\":{},\"digest_type\":{},\"digest\":\"",
488                         self.name.0, self.key_tag, self.alg, self.digest_type
489                 ).expect("Write to a String shouldn't fail");
490                 for c in self.digest.iter() {
491                         write!(&mut out, "{:02X}", c)
492                                 .expect("Write to a String shouldn't fail");
493                 }
494                 out += "\"}";
495                 out
496         }
497         fn read_from_data(name: Name, mut data: &[u8], _wire_packet: &[u8]) -> Result<Self, ()> {
498                 Ok(DS {
499                         name, key_tag: read_u16(&mut data)?, alg: read_u8(&mut data)?,
500                         digest_type: read_u8(&mut data)?, digest: data.to_vec(),
501                 })
502         }
503         fn write_u16_len_prefixed_data(&self, out: &mut Vec<u8>) {
504                 let len = 2 + 1 + 1 + self.digest.len();
505                 out.extend_from_slice(&(len as u16).to_be_bytes());
506                 out.extend_from_slice(&self.key_tag.to_be_bytes());
507                 out.extend_from_slice(&self.alg.to_be_bytes());
508                 out.extend_from_slice(&self.digest_type.to_be_bytes());
509                 out.extend_from_slice(&self.digest);
510         }
511 }
512
513 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
514 /// A Resource Record (set) Signature resource record. This contains a signature over all the
515 /// resources records of the given type at the given name.
516 pub struct RRSig {
517         /// The name this record is at.
518         ///
519         /// This is also the name of any records which this signature is covering (ignoring wildcards).
520         pub name: Name,
521         /// The resource record type which this [`RRSig`] is signing.
522         ///
523         /// All resources records of this type at the same name as [`self.name`] must be signed by
524         /// this [`RRSig`].
525         pub ty: u16,
526         /// The algorithm which is being used to sign.
527         ///
528         /// This must match the [`DnsKey::alg`] field in the [`DnsKey`] being used to sign.
529         pub alg: u8,
530         /// The number of labels in the name of the records that this signature is signing.
531         ///
532         /// If this is less than the number of labels in [`self.name`], this signature is covering a
533         /// wildcard entry.
534         pub labels: u8,
535         /// The TTL of the records which this [`RRSig`] is signing.
536         pub orig_ttl: u32,
537         /// The expiration (as a UNIX timestamp) of this signature.
538         pub expiration: u32,
539         /// The time (as a UNIX timestamp) at which this signature becomes valid.
540         pub inception: u32,
541         /// A short tag which describes the matching [`DnsKey`].
542         ///
543         /// This matches the [`DnsKey::key_tag`] for the [`DnsKey`] which created this signature.
544         pub key_tag: u16,
545         /// The [`DnsKey::name`] in the [`DnsKey`] which created this signature.
546         ///
547         /// This must be a parent of [`self.name`].
548         ///
549         /// [`DnsKey::name`]: Record::name
550         // We'd like to just link to the `DnsKey` member variable called `name`, but there doesn't
551         // appear to be a way to actually do that, so instead we have to link to the trait method.
552         pub key_name: Name,
553         /// The signature itself.
554         pub signature: Vec<u8>,
555 }
556 impl StaticRecord for RRSig {
557         const TYPE: u16 = 46;
558         fn name(&self) -> &Name { &self.name }
559         fn json(&self) -> String {
560                 let mut out = String::with_capacity(256 + self.signature.len()*2);
561                 write!(&mut out,
562                         "{{\"type\":\"ds\",\"name\":\"{}\",\"signed_record_type\":{},\"alg\":{},\"signed_labels\":{},\"orig_ttl\":{},\"expiration\"{},\"inception\":{},\"key_tag\":{},\"key_name\":\"{}\",\"signature\":\"",
563                         self.name.0, self.ty, self.alg, self.labels, self.orig_ttl, self.expiration, self.inception, self.key_tag, self.key_name.0
564                 ).expect("Write to a String shouldn't fail");
565                 for c in self.signature.iter() {
566                         write!(&mut out, "{:02X}", c)
567                                 .expect("Write to a String shouldn't fail");
568                 }
569                 out += "\"}";
570                 out
571         }
572         fn read_from_data(name: Name, mut data: &[u8], wire_packet: &[u8]) -> Result<Self, ()> {
573                 Ok(RRSig {
574                         name, ty: read_u16(&mut data)?, alg: read_u8(&mut data)?,
575                         labels: read_u8(&mut data)?, orig_ttl: read_u32(&mut data)?,
576                         expiration: read_u32(&mut data)?, inception: read_u32(&mut data)?,
577                         key_tag: read_u16(&mut data)?,
578                         key_name: read_wire_packet_name(&mut data, wire_packet)?,
579                         signature: data.to_vec(),
580                 })
581         }
582         fn write_u16_len_prefixed_data(&self, out: &mut Vec<u8>) {
583                 let len = 2 + 1 + 1 + 4*3 + 2 + name_len(&self.key_name) + self.signature.len() as u16;
584                 out.extend_from_slice(&len.to_be_bytes());
585                 out.extend_from_slice(&self.ty.to_be_bytes());
586                 out.extend_from_slice(&self.alg.to_be_bytes());
587                 out.extend_from_slice(&self.labels.to_be_bytes());
588                 out.extend_from_slice(&self.orig_ttl.to_be_bytes());
589                 out.extend_from_slice(&self.expiration.to_be_bytes());
590                 out.extend_from_slice(&self.inception.to_be_bytes());
591                 out.extend_from_slice(&self.key_tag.to_be_bytes());
592                 write_name(out, &self.key_name);
593                 out.extend_from_slice(&self.signature);
594         }
595 }
596
597 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
598 /// An IPv4 Address resource record
599 pub struct A {
600         /// The name this record is at.
601         pub name: Name,
602         /// The bytes of the IPv4 address.
603         pub address: [u8; 4],
604 }
605 /// The wire type for A records
606 pub const A_TYPE: u16 = 1;
607 impl StaticRecord for A {
608         const TYPE: u16 = A_TYPE;
609         fn name(&self) -> &Name { &self.name }
610         fn json(&self) -> String {
611                 format!("{{\"type\":\"a\",\"name\":\"{}\",\"address\":{:?}}}", self.name.0, self.address)
612         }
613         fn read_from_data(name: Name, data: &[u8], _wire_packet: &[u8]) -> Result<Self, ()> {
614                 if data.len() != 4 { return Err(()); }
615                 let mut address = [0; 4];
616                 address.copy_from_slice(&data);
617                 Ok(A { name, address })
618         }
619         fn write_u16_len_prefixed_data(&self, out: &mut Vec<u8>) {
620                 out.extend_from_slice(&4u16.to_be_bytes());
621                 out.extend_from_slice(&self.address);
622         }
623 }
624
625 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
626 /// An IPv6 Address resource record
627 pub struct AAAA {
628         /// The name this record is at.
629         pub name: Name,
630         /// The bytes of the IPv6 address.
631         pub address: [u8; 16],
632 }
633 /// The wire type for AAAA records
634 pub const AAAA_TYPE: u16 = 28;
635 impl StaticRecord for AAAA {
636         const TYPE: u16 = AAAA_TYPE;
637         fn name(&self) -> &Name { &self.name }
638         fn json(&self) -> String {
639                 format!("{{\"type\":\"aaaa\",\"name\":\"{}\",\"address\":{:?}}}", self.name.0, self.address)
640         }
641         fn read_from_data(name: Name, data: &[u8], _wire_packet: &[u8]) -> Result<Self, ()> {
642                 if data.len() != 16 { return Err(()); }
643                 let mut address = [0; 16];
644                 address.copy_from_slice(&data);
645                 Ok(AAAA { name, address })
646         }
647         fn write_u16_len_prefixed_data(&self, out: &mut Vec<u8>) {
648                 out.extend_from_slice(&16u16.to_be_bytes());
649                 out.extend_from_slice(&self.address);
650         }
651 }
652
653 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
654 /// A Name Server resource record, which indicates the server responsible for handling queries for
655 /// a zone.
656 pub struct NS {
657         /// The name this record is at.
658         ///
659         /// This is also the zone which the server at [`Self::name_server`] is responsible for handling
660         /// queries for.
661         pub name: Name,
662         /// The name of the server which is responsible for handling queries for the [`self.name`]
663         /// zone.
664         pub name_server: Name,
665 }
666 impl StaticRecord for NS {
667         const TYPE: u16 = 2;
668         fn name(&self) -> &Name { &self.name }
669         fn json(&self) -> String {
670                 format!("{{\"type\":\"ns\",\"name\":\"{}\",\"ns\":\"{}\"}}", self.name.0, self.name_server.0)
671         }
672         fn read_from_data(name: Name, mut data: &[u8], wire_packet: &[u8]) -> Result<Self, ()> {
673                 let res = NS { name, name_server: read_wire_packet_name(&mut data, wire_packet)? };
674                 debug_assert!(data.is_empty());
675                 Ok(res)
676         }
677         fn write_u16_len_prefixed_data(&self, out: &mut Vec<u8>) {
678                 out.extend_from_slice(&name_len(&self.name_server).to_be_bytes());
679                 write_name(out, &self.name_server);
680         }
681 }