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