Add trivial helper method to get the label count in a `Name`
[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))
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 != '"') {
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                 Ok(Txt { name, data: parsed_data })
265         }
266         fn write_u16_len_prefixed_data(&self, out: &mut Vec<u8>) {
267                 let len = (self.data.len() + (self.data.len() + 254) / 255) as u16;
268                 out.extend_from_slice(&len.to_be_bytes());
269
270                 let mut data_write = &self.data[..];
271                 out.extend_from_slice(&[data_write.len().try_into().unwrap_or(255)]);
272                 while !data_write.is_empty() {
273                         let split_pos = core::cmp::min(255, data_write.len());
274                         out.extend_from_slice(&data_write[..split_pos]);
275                         data_write = &data_write[split_pos..];
276                         if !data_write.is_empty() {
277                                 out.extend_from_slice(&[data_write.len().try_into().unwrap_or(255)]);
278                         }
279                 }
280         }
281 }
282
283 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
284 /// A TLS Certificate Association resource record containing information about the TLS certificate
285 /// which should be expected when communicating with the host at the given name.
286 ///
287 /// See <https://en.wikipedia.org/wiki/DNS-based_Authentication_of_Named_Entities#TLSA_RR> for more
288 /// info.
289 pub struct TLSA {
290         /// The name this record is at.
291         pub name: Name,
292         /// The type of constraint on the TLS certificate(s) used which should be enforced by this
293         /// record.
294         pub cert_usage: u8,
295         /// Whether to match on the full certificate, or only the public key.
296         pub selector: u8,
297         /// The type of data included which is used to match the TLS certificate(s).
298         pub data_ty: u8,
299         /// The certificate data or hash of the certificate data itself.
300         pub data: Vec<u8>,
301 }
302 /// The wire type for TLSA records
303 pub const TLSA_TYPE: u16 = 52;
304 impl StaticRecord for TLSA {
305         const TYPE: u16 = TLSA_TYPE;
306         fn name(&self) -> &Name { &self.name }
307         fn json(&self) -> String {
308                 let mut out = String::with_capacity(128+self.data.len()*2);
309                 write!(&mut out,
310                         "{{\"type\":\"tlsa\",\"name\":\"{}\",\"usage\":{},\"selector\":{},\"data_ty\":{},\"data\":\"",
311                         self.name.0, self.cert_usage, self.selector, self.data_ty
312                 ).expect("Write to a String shouldn't fail");
313                 for c in self.data.iter() {
314                         write!(&mut out, "{:02X}", c)
315                                 .expect("Write to a String shouldn't fail");
316                 }
317                 out += "\"}";
318                 out
319         }
320         fn read_from_data(name: Name, mut data: &[u8], _wire_packet: &[u8]) -> Result<Self, ()> {
321                 Ok(TLSA {
322                         name, cert_usage: read_u8(&mut data)?, selector: read_u8(&mut data)?,
323                         data_ty: read_u8(&mut data)?, data: data.to_vec(),
324                 })
325         }
326         fn write_u16_len_prefixed_data(&self, out: &mut Vec<u8>) {
327                 let len = 3 + self.data.len();
328                 out.extend_from_slice(&(len as u16).to_be_bytes());
329                 out.extend_from_slice(&[self.cert_usage, self.selector, self.data_ty]);
330                 out.extend_from_slice(&self.data);
331         }
332 }
333
334 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
335 /// A Canonical Name resource record, referring all queries for this name to another name.
336 pub struct CName {
337         /// The name this record is at.
338         pub name: Name,
339         /// The canonical name.
340         ///
341         /// A resolver should use this name when looking up any further records for [`self.name`].
342         pub canonical_name: Name,
343 }
344 impl StaticRecord for CName {
345         const TYPE: u16 = 5;
346         fn name(&self) -> &Name { &self.name }
347         fn json(&self) -> String {
348                 format!("{{\"type\":\"cname\",\"name\":\"{}\",\"canonical_name\":\"{}\"}}",
349                         self.name.0, self.canonical_name.0)
350         }
351         fn read_from_data(name: Name, mut data: &[u8], wire_packet: &[u8]) -> Result<Self, ()> {
352                 Ok(CName { name, canonical_name: read_wire_packet_name(&mut data, wire_packet)? })
353         }
354         fn write_u16_len_prefixed_data(&self, out: &mut Vec<u8>) {
355                 let len: u16 = name_len(&self.canonical_name);
356                 out.extend_from_slice(&len.to_be_bytes());
357                 write_name(out, &self.canonical_name);
358         }
359 }
360
361 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
362 /// A Delegation Name resource record, referring all queries for subdomains of this name to another
363 /// subtree of the DNS.
364 pub struct DName {
365         /// The name this record is at.
366         pub name: Name,
367         /// The delegation name.
368         ///
369         /// A resolver should use this domain name tree when looking up any further records for
370         /// subdomains of [`self.name`].
371         pub delegation_name: Name,
372 }
373 impl StaticRecord for DName {
374         const TYPE: u16 = 39;
375         fn name(&self) -> &Name { &self.name }
376         fn json(&self) -> String {
377                 format!("{{\"type\":\"dname\",\"name\":\"{}\",\"delegation_name\":\"{}\"}}",
378                         self.name.0, self.delegation_name.0)
379         }
380         fn read_from_data(name: Name, mut data: &[u8], wire_packet: &[u8]) -> Result<Self, ()> {
381                 Ok(DName { name, delegation_name: read_wire_packet_name(&mut data, wire_packet)? })
382         }
383         fn write_u16_len_prefixed_data(&self, out: &mut Vec<u8>) {
384                 let len: u16 = name_len(&self.delegation_name);
385                 out.extend_from_slice(&len.to_be_bytes());
386                 write_name(out, &self.delegation_name);
387         }
388 }
389
390
391 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
392 /// A public key resource record which can be used to validate [`RRSig`]s.
393 pub struct DnsKey {
394         /// The name this record is at.
395         pub name: Name,
396         /// Flags which constrain the usage of this public key.
397         pub flags: u16,
398         /// The protocol this key is used for (protocol `3` is DNSSEC). 
399         pub protocol: u8,
400         /// The algorithm which this public key uses to sign data.
401         pub alg: u8,
402         /// The public key itself.
403         pub pubkey: Vec<u8>,
404 }
405 impl StaticRecord for DnsKey {
406         const TYPE: u16 = 48;
407         fn name(&self) -> &Name { &self.name }
408         fn json(&self) -> String {
409                 let mut out = String::with_capacity(128+self.pubkey.len()*2);
410                 write!(&mut out,
411                         "{{\"type\":\"dnskey\",\"name\":\"{}\",\"flags\":{},\"protocol\":{},\"alg\":{},\"pubkey\":\"",
412                         self.name.0, self.flags, self.protocol, self.alg
413                 ).expect("Write to a String shouldn't fail");
414                 for c in self.pubkey.iter() {
415                         write!(&mut out, "{:02X}", c)
416                                 .expect("Write to a String shouldn't fail");
417                 }
418                 out += "\"}";
419                 out
420         }
421         fn read_from_data(name: Name, mut data: &[u8], _wire_packet: &[u8]) -> Result<Self, ()> {
422                 Ok(DnsKey {
423                         name, flags: read_u16(&mut data)?, protocol: read_u8(&mut data)?,
424                         alg: read_u8(&mut data)?, pubkey: data.to_vec(),
425                 })
426         }
427         fn write_u16_len_prefixed_data(&self, out: &mut Vec<u8>) {
428                 let len = 2 + 1 + 1 + self.pubkey.len();
429                 out.extend_from_slice(&(len as u16).to_be_bytes());
430                 out.extend_from_slice(&self.flags.to_be_bytes());
431                 out.extend_from_slice(&self.protocol.to_be_bytes());
432                 out.extend_from_slice(&self.alg.to_be_bytes());
433                 out.extend_from_slice(&self.pubkey);
434         }
435 }
436 impl DnsKey {
437         /// A short (non-cryptographic) digest which can be used to refer to this [`DnsKey`].
438         pub fn key_tag(&self) -> u16 {
439                 let mut res = u32::from(self.flags);
440                 res += u32::from(self.protocol) << 8;
441                 res += u32::from(self.alg);
442                 for (idx, b) in self.pubkey.iter().enumerate() {
443                         if idx % 2 == 0 {
444                                 res += u32::from(*b) << 8;
445                         } else {
446                                 res += u32::from(*b);
447                         }
448                 }
449                 res += (res >> 16) & 0xffff;
450                 (res & 0xffff) as u16
451         }
452 }
453
454 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
455 /// A Delegation Signer resource record which indicates that some alternative [`DnsKey`] can sign
456 /// for records in the zone which matches [`self.name`].
457 pub struct DS {
458         /// The name this record is at.
459         ///
460         /// This is also the zone that a [`DnsKey`] which matches the [`Self::digest`] can sign for.
461         pub name: Name,
462         /// A short tag which describes the matching [`DnsKey`].
463         ///
464         /// This matches the [`DnsKey::key_tag`] for the [`DnsKey`] which is referred to by this
465         /// [`DS`].
466         pub key_tag: u16,
467         /// The algorithm which the [`DnsKey`] referred to by this [`DS`] uses.
468         ///
469         /// This matches the [`DnsKey::alg`] field in the referred-to [`DnsKey`].
470         pub alg: u8,
471         /// The type of digest used to hash the referred-to [`DnsKey`].
472         pub digest_type: u8,
473         /// The digest itself.
474         pub digest: Vec<u8>,
475 }
476 impl StaticRecord for DS {
477         const TYPE: u16 = 43;
478         fn name(&self) -> &Name { &self.name }
479         fn json(&self) -> String {
480                 let mut out = String::with_capacity(128+self.digest.len()*2);
481                 write!(&mut out,
482                         "{{\"type\":\"ds\",\"name\":\"{}\",\"key_tag\":{},\"alg\":{},\"digest_type\":{},\"digest\":\"",
483                         self.name.0, self.key_tag, self.alg, self.digest_type
484                 ).expect("Write to a String shouldn't fail");
485                 for c in self.digest.iter() {
486                         write!(&mut out, "{:02X}", c)
487                                 .expect("Write to a String shouldn't fail");
488                 }
489                 out += "\"}";
490                 out
491         }
492         fn read_from_data(name: Name, mut data: &[u8], _wire_packet: &[u8]) -> Result<Self, ()> {
493                 Ok(DS {
494                         name, key_tag: read_u16(&mut data)?, alg: read_u8(&mut data)?,
495                         digest_type: read_u8(&mut data)?, digest: data.to_vec(),
496                 })
497         }
498         fn write_u16_len_prefixed_data(&self, out: &mut Vec<u8>) {
499                 let len = 2 + 1 + 1 + self.digest.len();
500                 out.extend_from_slice(&(len as u16).to_be_bytes());
501                 out.extend_from_slice(&self.key_tag.to_be_bytes());
502                 out.extend_from_slice(&self.alg.to_be_bytes());
503                 out.extend_from_slice(&self.digest_type.to_be_bytes());
504                 out.extend_from_slice(&self.digest);
505         }
506 }
507
508 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
509 /// A Resource Record (set) Signature resource record. This contains a signature over all the
510 /// resources records of the given type at the given name.
511 pub struct RRSig {
512         /// The name this record is at.
513         ///
514         /// This is also the name of any records which this signature is covering (ignoring wildcards).
515         pub name: Name,
516         /// The resource record type which this [`RRSig`] is signing.
517         ///
518         /// All resources records of this type at the same name as [`self.name`] must be signed by
519         /// this [`RRSig`].
520         pub ty: u16,
521         /// The algorithm which is being used to sign.
522         ///
523         /// This must match the [`DnsKey::alg`] field in the [`DnsKey`] being used to sign.
524         pub alg: u8,
525         /// The number of labels in the name of the records that this signature is signing.
526         ///
527         /// If this is less than the number of labels in [`self.name`], this signature is covering a
528         /// wildcard entry.
529         pub labels: u8,
530         /// The TTL of the records which this [`RRSig`] is signing.
531         pub orig_ttl: u32,
532         /// The expiration (as a UNIX timestamp) of this signature.
533         pub expiration: u32,
534         /// The time (as a UNIX timestamp) at which this signature becomes valid.
535         pub inception: u32,
536         /// A short tag which describes the matching [`DnsKey`].
537         ///
538         /// This matches the [`DnsKey::key_tag`] for the [`DnsKey`] which created this signature.
539         pub key_tag: u16,
540         /// The [`DnsKey::name`] in the [`DnsKey`] which created this signature.
541         ///
542         /// This must be a parent of [`self.name`].
543         ///
544         /// [`DnsKey::name`]: Record::name
545         // We'd like to just link to the `DnsKey` member variable called `name`, but there doesn't
546         // appear to be a way to actually do that, so instead we have to link to the trait method.
547         pub key_name: Name,
548         /// The signature itself.
549         pub signature: Vec<u8>,
550 }
551 impl StaticRecord for RRSig {
552         const TYPE: u16 = 46;
553         fn name(&self) -> &Name { &self.name }
554         fn json(&self) -> String {
555                 let mut out = String::with_capacity(256 + self.signature.len()*2);
556                 write!(&mut out,
557                         "{{\"type\":\"ds\",\"name\":\"{}\",\"signed_record_type\":{},\"alg\":{},\"signed_labels\":{},\"orig_ttl\":{},\"expiration\"{},\"inception\":{},\"key_tag\":{},\"key_name\":\"{}\",\"signature\":\"",
558                         self.name.0, self.ty, self.alg, self.labels, self.orig_ttl, self.expiration, self.inception, self.key_tag, self.key_name.0
559                 ).expect("Write to a String shouldn't fail");
560                 for c in self.signature.iter() {
561                         write!(&mut out, "{:02X}", c)
562                                 .expect("Write to a String shouldn't fail");
563                 }
564                 out += "\"}";
565                 out
566         }
567         fn read_from_data(name: Name, mut data: &[u8], wire_packet: &[u8]) -> Result<Self, ()> {
568                 Ok(RRSig {
569                         name, ty: read_u16(&mut data)?, alg: read_u8(&mut data)?,
570                         labels: read_u8(&mut data)?, orig_ttl: read_u32(&mut data)?,
571                         expiration: read_u32(&mut data)?, inception: read_u32(&mut data)?,
572                         key_tag: read_u16(&mut data)?,
573                         key_name: read_wire_packet_name(&mut data, wire_packet)?,
574                         signature: data.to_vec(),
575                 })
576         }
577         fn write_u16_len_prefixed_data(&self, out: &mut Vec<u8>) {
578                 let len = 2 + 1 + 1 + 4*3 + 2 + name_len(&self.key_name) + self.signature.len() as u16;
579                 out.extend_from_slice(&len.to_be_bytes());
580                 out.extend_from_slice(&self.ty.to_be_bytes());
581                 out.extend_from_slice(&self.alg.to_be_bytes());
582                 out.extend_from_slice(&self.labels.to_be_bytes());
583                 out.extend_from_slice(&self.orig_ttl.to_be_bytes());
584                 out.extend_from_slice(&self.expiration.to_be_bytes());
585                 out.extend_from_slice(&self.inception.to_be_bytes());
586                 out.extend_from_slice(&self.key_tag.to_be_bytes());
587                 write_name(out, &self.key_name);
588                 out.extend_from_slice(&self.signature);
589         }
590 }
591
592 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
593 /// An IPv4 Address resource record
594 pub struct A {
595         /// The name this record is at.
596         pub name: Name,
597         /// The bytes of the IPv4 address.
598         pub address: [u8; 4],
599 }
600 /// The wire type for A records
601 pub const A_TYPE: u16 = 1;
602 impl StaticRecord for A {
603         const TYPE: u16 = A_TYPE;
604         fn name(&self) -> &Name { &self.name }
605         fn json(&self) -> String {
606                 format!("{{\"type\":\"a\",\"name\":\"{}\",\"address\":{:?}}}", self.name.0, self.address)
607         }
608         fn read_from_data(name: Name, data: &[u8], _wire_packet: &[u8]) -> Result<Self, ()> {
609                 if data.len() != 4 { return Err(()); }
610                 let mut address = [0; 4];
611                 address.copy_from_slice(&data);
612                 Ok(A { name, address })
613         }
614         fn write_u16_len_prefixed_data(&self, out: &mut Vec<u8>) {
615                 out.extend_from_slice(&4u16.to_be_bytes());
616                 out.extend_from_slice(&self.address);
617         }
618 }
619
620 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
621 /// An IPv6 Address resource record
622 pub struct AAAA {
623         /// The name this record is at.
624         pub name: Name,
625         /// The bytes of the IPv6 address.
626         pub address: [u8; 16],
627 }
628 /// The wire type for AAAA records
629 pub const AAAA_TYPE: u16 = 28;
630 impl StaticRecord for AAAA {
631         const TYPE: u16 = AAAA_TYPE;
632         fn name(&self) -> &Name { &self.name }
633         fn json(&self) -> String {
634                 format!("{{\"type\":\"aaaa\",\"name\":\"{}\",\"address\":{:?}}}", self.name.0, self.address)
635         }
636         fn read_from_data(name: Name, data: &[u8], _wire_packet: &[u8]) -> Result<Self, ()> {
637                 if data.len() != 16 { return Err(()); }
638                 let mut address = [0; 16];
639                 address.copy_from_slice(&data);
640                 Ok(AAAA { name, address })
641         }
642         fn write_u16_len_prefixed_data(&self, out: &mut Vec<u8>) {
643                 out.extend_from_slice(&16u16.to_be_bytes());
644                 out.extend_from_slice(&self.address);
645         }
646 }
647
648 #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
649 /// A Name Server resource record, which indicates the server responsible for handling queries for
650 /// a zone.
651 pub struct NS {
652         /// The name this record is at.
653         ///
654         /// This is also the zone which the server at [`Self::name_server`] is responsible for handling
655         /// queries for.
656         pub name: Name,
657         /// The name of the server which is responsible for handling queries for the [`self.name`]
658         /// zone.
659         pub name_server: Name,
660 }
661 impl StaticRecord for NS {
662         const TYPE: u16 = 2;
663         fn name(&self) -> &Name { &self.name }
664         fn json(&self) -> String {
665                 format!("{{\"type\":\"ns\",\"name\":\"{}\",\"ns\":\"{}\"}}", self.name.0, self.name_server.0)
666         }
667         fn read_from_data(name: Name, mut data: &[u8], wire_packet: &[u8]) -> Result<Self, ()> {
668                 Ok(NS { name, name_server: read_wire_packet_name(&mut data, wire_packet)? })
669         }
670         fn write_u16_len_prefixed_data(&self, out: &mut Vec<u8>) {
671                 out.extend_from_slice(&name_len(&self.name_server).to_be_bytes());
672                 write_name(out, &self.name_server);
673         }
674 }