sparkle/
wire.rs

1// This module defines types for working with the DNS protocol on the
2// wire--i.e., encoding and decoding DNS messages.
3//
4// The overarching design goal is for message-encoding and -decoding to do zero
5// heap memory allocations. The purpose of this goal is run-time efficiency.
6//
7// Internally, there are many `unsafe` blocks to make this work. Why? The short
8// answer is that in many cases Rust's safety checks are redundant because we're
9// working with trusted memory and we can disable the checks for improved
10// speed and size.
11//
12// Here's a longer explanation, starting first with decoding.
13//
14// We decode messages without allocating any heap memory, and one consequence is
15// that decoding is generally two-pass:
16//
17// 1. The first pass checks the message's validity and returns offsets to
18//    important parts within the message buffer. This pass operates on
19//    *untrusted* data.
20//
21// 2. The second pass takes both a valid message and the offsets into it and
22//    returns useful values, such as record types and domain names. This pass
23//    operates on *trusted* data--i.e., can be `unsafe`.
24//
25// Note, none of the `unsafe` interfaces leak out through public interfaces in
26// this module--i.e., all unsafety is well contained. Callers using this module
27// can use these types knowing that they'll always get either valid data or a
28// proper error--and never a memory error.
29//
30// Encoding is similar to decoding. Encoding works by writing message data to an
31// external buffer. In some cases we are guaranteed that the buffer is big
32// enough (because we previously checked the buffer's length). In these cases,
33// we can use `unsafe` to do an unchecked write to the buffer.
34
35use {Class, Format, Name, QClass, QType, Question, RData, ResourceRecord, SerialNumber, Ttl, Type, class, format, std,
36     type_};
37
38/// Specifies the DNS on-the-wire protocol format.
39#[derive(Clone, Debug, Eq, PartialEq)]
40pub struct WireFormat;
41
42impl<'a> Format<'a> for WireFormat {
43    type Name = WireName<'a>;
44    type RawOctets = &'a [u8];
45}
46
47/// Encapsulates a DNS message domain name in an external buffer.
48#[derive(Clone, Debug, Eq, PartialEq)]
49pub struct WireName<'a> {
50    decoder: TrustedDecoder<'a>,
51}
52
53impl<'a> Name<'a> for WireName<'a> {
54    type LabelIter = WireLabelIter<'a>;
55    fn labels(&'a self) -> Self::LabelIter {
56        WireLabelIter { decoder: self.decoder.clone() }
57    }
58}
59
60impl<'a> std::fmt::Display for WireName<'a> {
61    fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
62        self.labels()
63            .fold(String::new(), |mut a, b| {
64                a.push_str(b);
65                a.push('.');
66                a
67            })
68            .fmt(f)
69    }
70}
71
72#[derive(Clone, Debug)]
73pub struct WireLabelIter<'a> {
74    decoder: TrustedDecoder<'a>,
75}
76
77impl<'a> Iterator for WireLabelIter<'a> {
78    type Item = &'a str;
79    fn next(&mut self) -> Option<Self::Item> {
80        unsafe { self.decoder.decode_label_unchecked() }
81    }
82}
83
84/// Encapsulates a DNS message in an external buffer.
85#[derive(Clone, Debug, Eq, PartialEq)]
86pub struct WireMessage<'a> {
87    id: u16,
88    flags: u16,
89    question_section: QuestionSection<'a>,
90    answer_section: ResourceRecordSection<'a>,
91    authority_section: ResourceRecordSection<'a>,
92    additional_section: ResourceRecordSection<'a>,
93}
94
95impl<'a> WireMessage<'a> {
96    pub fn id(&self) -> u16 {
97        self.id
98    }
99
100    pub fn recursion_desired(&self) -> bool {
101        0 != self.flags & RD_MASK
102    }
103
104    pub fn questions(&self) -> std::iter::Take<QuestionIter<'a>> {
105        self.question_section.questions()
106    }
107
108    pub fn answers(&self) -> std::iter::Take<ResourceRecordIter<'a>> {
109        self.answer_section.resource_records()
110    }
111
112    pub fn authorities(&self) -> std::iter::Take<ResourceRecordIter<'a>> {
113        self.authority_section.resource_records()
114    }
115
116    pub fn additionals(&self) -> std::iter::Take<ResourceRecordIter<'a>> {
117        self.additional_section.resource_records()
118    }
119}
120
121#[derive(Clone, Debug, Eq, PartialEq)]
122struct QuestionSection<'a> {
123    count: u16,
124    decoder: TrustedDecoder<'a>,
125}
126
127impl<'a> QuestionSection<'a> {
128    pub fn questions(&self) -> std::iter::Take<QuestionIter<'a>> {
129        QuestionIter { decoder: self.decoder.clone() }.take(self.count as usize)
130    }
131}
132
133#[derive(Clone, Debug)]
134pub struct QuestionIter<'a> {
135    decoder: TrustedDecoder<'a>,
136}
137
138impl<'a> Iterator for QuestionIter<'a> {
139    type Item = Question<'a, WireFormat>;
140    fn next(&mut self) -> Option<Self::Item> {
141        Some(unsafe { self.decoder.decode_question_unchecked() })
142    }
143}
144
145#[derive(Clone, Debug, Eq, PartialEq)]
146struct ResourceRecordSection<'a> {
147    count: u16,
148    decoder: TrustedDecoder<'a>,
149}
150
151impl<'a> ResourceRecordSection<'a> {
152    pub fn resource_records(&self) -> std::iter::Take<ResourceRecordIter<'a>> {
153        ResourceRecordIter { decoder: self.decoder.clone() }.take(self.count as usize)
154    }
155}
156
157#[derive(Clone, Debug)]
158pub struct ResourceRecordIter<'a> {
159    decoder: TrustedDecoder<'a>,
160}
161
162impl<'a> Iterator for ResourceRecordIter<'a> {
163    type Item = ResourceRecord<'a, WireFormat>;
164    fn next(&mut self) -> Option<Self::Item> {
165        Some(unsafe { self.decoder.decode_resource_record_unchecked() })
166    }
167}
168
169const QR_MASK: u16 = 0b_1000_0000_0000_0000; // 0 for query, 1 for response
170// const AA_MASK: u16 = 0b_0000_0100_0000_0000; // authoritative answer
171const TC_MASK: u16 = 0b_0000_0010_0000_0000; // truncation
172const RD_MASK: u16 = 0b_0000_0001_0000_0000; // recursion desired?
173// const RA_MASK: u16 = 0b_0000_0000_1000_0000; // recursion available?
174// const Z_MASK: u16 = 0b_0000_0000_0111_0000; // reserved for future use
175
176// const OPCODE_MASK: u16 = 0b_0111_1000_0000_0000;
177pub mod opcode {
178    // pub const QUERY: u16 = 0b_0000_0000_0000_0000; // standard query
179    // pub const IQUERY: u16 = 0b_0000_1000_0000_0000; // inverse query
180    // pub const STATUS: u16 = 0b_0001_0000_0000_0000; // server status request
181}
182
183// const RCODE_MASK: u16 = 0b_0000_0000_0000_1111;
184pub mod rcode {
185    // pub const NOERROR: u16 = 0b_0000_0000_0000_0000; // no error
186    // pub const FORMERR: u16 = 0b_0000_0000_0000_0001; // format error
187    // pub const SERVFAIL: u16 = 0b_0000_0000_0000_0010; // server failure
188    // pub const NXDOMAIN: u16 = 0b_0000_0000_0000_0011; // name error
189    // pub const NOTIMP: u16 = 0b_0000_0000_0000_0100; // not implemented
190    // pub const REFUSED: u16 = 0b_0000_0000_0000_0101; // refused
191}
192
193/// Defines marker types—should not be used directly.
194pub mod marker {
195    pub trait QueryOrResponse {}
196
197    #[derive(Clone, Debug, Eq, PartialEq)]
198    pub struct Query;
199    impl QueryOrResponse for Query {}
200
201    #[derive(Clone, Debug, Eq, PartialEq)]
202    pub struct Response;
203    impl QueryOrResponse for Response {}
204
205    pub trait EncoderState {}
206
207    #[derive(Clone, Debug, Eq, PartialEq)]
208    pub struct QuestionSection;
209    impl EncoderState for QuestionSection {}
210
211    #[derive(Clone, Debug, Eq, PartialEq)]
212    pub struct AnswerSection;
213    impl EncoderState for AnswerSection {}
214
215    #[derive(Clone, Debug, Eq, PartialEq)]
216    pub struct AuthoritySection;
217    impl EncoderState for AuthoritySection {}
218
219    #[derive(Clone, Debug, Eq, PartialEq)]
220    pub struct AdditionalSection;
221    impl EncoderState for AdditionalSection {}
222
223    #[derive(Clone, Debug, Eq, PartialEq)]
224    pub struct Done;
225    impl EncoderState for Done {}
226}
227
228/// Specifies an error that occurred while encoding a DNS message.
229#[derive(Clone, Debug, Eq, PartialEq)]
230pub struct EncoderError;
231
232impl std::error::Error for EncoderError {
233    fn description(&self) -> &str {
234        "Buffer is too small to contain message--message truncated"
235    }
236}
237
238impl std::fmt::Display for EncoderError {
239    fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
240        let d = (self as &std::error::Error).description();
241        d.fmt(f)
242    }
243}
244
245/// Writes a DNS message to an external buffer.
246///
247/// `WireEncoder` guards against buffer overflow. If the external buffer is too
248/// small to contain all content, then the encoder sets the message's TC
249/// (truncation) flag and elides questions and/or resource records such that the
250/// DNS message is valid and fits within the buffer.
251///
252#[derive(Debug, Eq, PartialEq)]
253pub struct WireEncoder<'a, Q: marker::QueryOrResponse, S: marker::EncoderState> {
254    _phantom: std::marker::PhantomData<(Q, S)>,
255    buffer: &'a mut [u8],
256    cursor: usize,
257}
258
259impl<'a, Q: marker::QueryOrResponse, S: marker::EncoderState> WireEncoder<'a, Q, S> {
260    fn new(buffer: &'a mut [u8]) -> Result<Self, EncoderError> {
261        const HEADER_LEN: usize = 12;
262        if buffer.len() < HEADER_LEN {
263            return Err(EncoderError);
264        }
265
266        // Zero-out all bytes in the header.
267        for i in 0..HEADER_LEN {
268            buffer[i] = 0;
269        }
270
271        Ok(WireEncoder {
272            _phantom: std::marker::PhantomData,
273            buffer: buffer,
274            cursor: HEADER_LEN,
275        })
276    }
277
278    unsafe fn read_u16_at_unchecked(&self, index: usize) -> u16 {
279        debug_assert!(index + 2 <= self.buffer.len());
280        let hi = (*self.buffer.get_unchecked(index + 0) as u16) << 8;
281        let lo = (*self.buffer.get_unchecked(index + 1) as u16) << 0;
282        hi | lo
283    }
284
285    unsafe fn write_u16_at_unchecked(&mut self, index: usize, v: u16) {
286        debug_assert!(index + 2 <= self.buffer.len());
287        *self.buffer.get_unchecked_mut(index + 0) = (v >> 8) as u8;
288        *self.buffer.get_unchecked_mut(index + 1) = (v >> 0) as u8;
289    }
290
291    fn encode_id(&mut self, id: u16) {
292        unsafe { self.write_u16_at_unchecked(0, id) };
293    }
294
295    fn encode_flags(&mut self, mask: u16, flags: u16) {
296        debug_assert_eq!(flags | mask, mask);
297        unsafe {
298            let bits = self.read_u16_at_unchecked(2) & !mask | flags;
299            self.write_u16_at_unchecked(2, bits);
300        }
301    }
302
303    fn encode_octets_at(&mut self, cursor: &mut usize, octets: &[u8]) -> Result<(), EncoderError> {
304        if *cursor + octets.len() > self.buffer.len() {
305            self.encode_flags(TC_MASK, TC_MASK);
306            Err(EncoderError)
307        } else {
308            (&mut self.buffer[*cursor..*cursor + octets.len()]).copy_from_slice(octets);
309            *cursor += octets.len();
310            Ok(())
311        }
312    }
313
314    fn encode_u8_at(&mut self, cursor: &mut usize, v: u8) -> Result<(), EncoderError> {
315        self.buffer
316            .get_mut(*cursor)
317            .and_then(|x| {
318                *x = v;
319                *cursor += 1;
320                Some(())
321            })
322            .or_else(|| {
323                self.encode_flags(TC_MASK, TC_MASK);
324                None
325            })
326            .map(|_| ())
327            .ok_or(EncoderError)
328    }
329
330    fn encode_u16_at(&mut self, cursor: &mut usize, v: u16) -> Result<(), EncoderError> {
331        let mut w = *cursor;
332        self.encode_u8_at(&mut w, (v >> 8) as u8)?;
333        self.encode_u8_at(&mut w, (v >> 0) as u8)?;
334        *cursor = w;
335        Ok(())
336    }
337
338    fn encode_u32_at(&mut self, cursor: &mut usize, v: u32) -> Result<(), EncoderError> {
339        let mut w = *cursor;
340        self.encode_u16_at(&mut w, (v >> 16) as u16)?;
341        self.encode_u16_at(&mut w, (v >> 0) as u16)?;
342        *cursor = w;
343        Ok(())
344    }
345
346    fn encode_class_at(&mut self, cursor: &mut usize, class: Class) -> Result<(), EncoderError> {
347        self.encode_u16_at(cursor, class.0)
348    }
349
350    fn encode_qclass_at(&mut self, cursor: &mut usize, qclass: QClass) -> Result<(), EncoderError> {
351        self.encode_u16_at(cursor, qclass.0)
352    }
353
354    fn encode_type_at(&mut self, cursor: &mut usize, type_: Type) -> Result<(), EncoderError> {
355        self.encode_u16_at(cursor, type_.0)
356    }
357
358    fn encode_qtype_at(&mut self, cursor: &mut usize, qtype: QType) -> Result<(), EncoderError> {
359        self.encode_u16_at(cursor, qtype.0)
360    }
361
362    fn encode_name_at<'b, N: Name<'b>>(&mut self, cursor: &mut usize, name: &'b N) -> Result<(), EncoderError> {
363        // TODO: Compress the name, if possible.
364        let mut w = *cursor;
365        for label in name.labels() {
366            debug_assert!(label.len() < 64);
367            self.encode_u8_at(&mut w, label.len() as u8)?;
368            self.encode_octets_at(&mut w, label.as_bytes())?;
369        }
370        self.encode_u8_at(&mut w, 0)?;
371        *cursor = w;
372        Ok(())
373    }
374
375    fn encode_question_at<'b, F: Format<'b>>(&mut self,
376                                             cursor: &mut usize,
377                                             q: &'b Question<'b, F>)
378                                             -> Result<(), EncoderError> {
379        let mut w = *cursor;
380        self.encode_name_at(&mut w, q.qname())?;
381        self.encode_qtype_at(&mut w, q.qtype())?;
382        self.encode_qclass_at(&mut w, q.qclass())?;
383        *cursor = w;
384        Ok(())
385    }
386
387    fn encode_rdlength_and_rdata_at<'b, F: Format<'b>>(&mut self,
388                                                       cursor: &mut usize,
389                                                       rdata: &'b RData<'b, F>)
390                                                       -> Result<(), EncoderError> {
391        let mut w = *cursor + 2; // leave room for RDLENGTH
392        match rdata {
393            &RData::A { ref address } => self.encode_octets_at(&mut w, &address.octets()[..])?,
394            &RData::CName { ref cname } => self.encode_name_at(&mut w, cname)?,
395            &RData::NS { ref nsdname } => self.encode_name_at(&mut w, nsdname)?,
396            &RData::SOA { ref mname, ref rname, serial, refresh, retry, expire, minimum } => {
397                self.encode_name_at(&mut w, mname)?;
398                self.encode_name_at(&mut w, rname)?;
399                self.encode_u32_at(&mut w, u32::from(serial))?;
400                self.encode_u32_at(&mut w, refresh.as_u32())?;
401                self.encode_u32_at(&mut w, retry.as_u32())?;
402                self.encode_u32_at(&mut w, expire.as_u32())?;
403                self.encode_u32_at(&mut w, minimum.as_u32())?;
404            }
405            &RData::Other { ref octets } => self.encode_octets_at(&mut w, octets.as_ref())?,
406        }
407        let rdlength = w - (*cursor + 2);
408        debug_assert!(rdlength <= 0xffff);
409        unsafe { self.write_u16_at_unchecked(*cursor, rdlength as u16) }
410        *cursor = w;
411        Ok(())
412    }
413
414    fn encode_resource_record_at<'b, F: Format<'b>>(&mut self,
415                                                    cursor: &mut usize,
416                                                    r: &'b ResourceRecord<'b, F>)
417                                                    -> Result<(), EncoderError> {
418        let mut w = *cursor;
419        self.encode_name_at(&mut w, r.name())?;
420        self.encode_type_at(&mut w, r.type_())?;
421        self.encode_class_at(&mut w, r.class())?;
422        self.encode_u32_at(&mut w, r.ttl().as_u32())?;
423        self.encode_rdlength_and_rdata_at(&mut w, r.rdata())?;
424        *cursor = w;
425        Ok(())
426    }
427}
428
429impl<'a, Q: marker::QueryOrResponse> WireEncoder<'a, Q, marker::QuestionSection> {
430    /// Transitions the encoder into a state for encoding answers.
431    pub fn finalize_questions(self) -> WireEncoder<'a, Q, marker::AnswerSection> {
432        WireEncoder {
433            _phantom: std::marker::PhantomData,
434            buffer: self.buffer,
435            cursor: self.cursor,
436        }
437    }
438
439    pub fn encode_question<'b, F: Format<'b>>(&mut self, q: &'b Question<'b, F>) -> Result<(), EncoderError> {
440        let mut cursor = self.cursor;
441        self.encode_question_at(&mut cursor, q)?;
442        self.cursor = cursor;
443        unsafe {
444            let qdcount = self.read_u16_at_unchecked(4) + 1;
445            self.write_u16_at_unchecked(4, qdcount);
446        }
447        Ok(())
448    }
449}
450
451impl<'a> WireEncoder<'a, marker::Query, marker::QuestionSection> {
452    pub fn new_query(buffer: &'a mut [u8], id: u16) -> Result<Self, EncoderError> {
453        let mut e = WireEncoder::<marker::Query, marker::QuestionSection>::new(buffer)?;
454        e.encode_id(id);
455        // QR flag is zero to indicate we're a query
456        Ok(e)
457    }
458}
459
460impl<'a> WireEncoder<'a, marker::Response, marker::AnswerSection> {
461    /// Constructs an encoder for encoding a response message.
462    ///
463    /// The target response is initialized such that:
464    ///
465    /// * Its **ID** field is copied from the request.
466    /// * Its **QR** bit is set.
467    /// * Its **RD** bit is copied from the request.
468    /// * Its question section is copied verbatim from the request.
469    ///
470    /// If the request contains multiple questions, then the response will also
471    /// contain multiple questions.
472    ///
473    pub fn new_response(buffer: &'a mut [u8], request: &WireMessage) -> Result<Self, EncoderError> {
474        let mut e = WireEncoder::<marker::Response, marker::QuestionSection>::new(buffer)?;
475
476        e.encode_id(request.id()); // copied from request
477        e.encode_flags(QR_MASK, QR_MASK); // yes, we're a response
478        let bit = if request.recursion_desired() { RD_MASK } else { 0 };
479        e.encode_flags(RD_MASK, bit); // copied from request
480
481        // TODO: The subsequent `for` loop is a workaround for a lifetime error.
482        // Here's the loop I want to use:
483        //
484        // for q in request.questions() {
485        //     e.encode_question(&q);
486        // }
487        //
488        // I don't understand why this causes a lifetime error. I've asked a
489        // StackOverflow question about it here:
490        //
491        // http://stackoverflow.com/q/41337021/1094609
492
493        for q in request.questions() {
494            let mut w = e.cursor;
495            e.encode_name_at(&mut w, q.qname())?;
496            e.encode_qtype_at(&mut w, q.qtype())?;
497            e.encode_qclass_at(&mut w, q.qclass())?;
498            e.cursor = w;
499            unsafe {
500                let qdcount = e.read_u16_at_unchecked(4) + 1;
501                e.write_u16_at_unchecked(4, qdcount);
502            }
503        }
504
505        Ok(e.finalize_questions()) // prevent caller from fiddling with question section
506    }
507
508    pub fn finalize_answers(self) -> WireEncoder<'a, marker::Response, marker::AuthoritySection> {
509        WireEncoder {
510            _phantom: std::marker::PhantomData,
511            buffer: self.buffer,
512            cursor: self.cursor,
513        }
514    }
515
516    pub fn encode_answer<'b, F: Format<'b>>(&mut self, r: &'b ResourceRecord<'b, F>) -> Result<(), EncoderError> {
517        let mut cursor = self.cursor;
518        self.encode_resource_record_at(&mut cursor, r)?;
519        self.cursor = cursor;
520        unsafe {
521            let ancount = self.read_u16_at_unchecked(6) + 1;
522            self.write_u16_at_unchecked(6, ancount);
523        }
524        Ok(())
525    }
526}
527
528impl<'a> WireEncoder<'a, marker::Response, marker::AuthoritySection> {
529    pub fn finalize_authorities(self) -> WireEncoder<'a, marker::Response, marker::AdditionalSection> {
530        WireEncoder {
531            _phantom: std::marker::PhantomData,
532            buffer: self.buffer,
533            cursor: self.cursor,
534        }
535    }
536
537    pub fn encode_authority<'b, F: Format<'b>>(&mut self, r: &'b ResourceRecord<'b, F>) -> Result<(), EncoderError> {
538        let mut cursor = self.cursor;
539        self.encode_resource_record_at(&mut cursor, r)?;
540        self.cursor = cursor;
541        unsafe {
542            let nscount = self.read_u16_at_unchecked(8) + 1;
543            self.write_u16_at_unchecked(8, nscount);
544        }
545        Ok(())
546    }
547}
548
549impl<'a> WireEncoder<'a, marker::Response, marker::AdditionalSection> {
550    pub fn finalize_additionals(self) -> WireEncoder<'a, marker::Response, marker::Done> {
551        WireEncoder {
552            _phantom: std::marker::PhantomData,
553            buffer: self.buffer,
554            cursor: self.cursor,
555        }
556    }
557
558    pub fn encode_additional<'b, F: Format<'b>>(&mut self, r: &'b ResourceRecord<'b, F>) -> Result<(), EncoderError> {
559        let mut cursor = self.cursor;
560        self.encode_resource_record_at(&mut cursor, r)?;
561        self.cursor = cursor;
562        unsafe {
563            let arcount = self.read_u16_at_unchecked(10) + 1;
564            self.write_u16_at_unchecked(10, arcount);
565        }
566        Ok(())
567    }
568}
569
570impl<'a, Q: marker::QueryOrResponse> WireEncoder<'a, Q, marker::Done> {
571    pub fn as_bytes(&self) -> &[u8] {
572        &self.buffer[..self.cursor]
573    }
574}
575
576/// Specifies an error that occurred while decoding a DNS message.
577#[derive(Clone, Debug, Eq, PartialEq)]
578pub enum DecoderError {
579    /// **RDATA** content does not match **RDLENGTH**.
580    BadRdlength,
581
582    /// Domain name compression results in an infinite name.
583    InfiniteName,
584
585    /// Domain name label length uses reserved bits.
586    InvalidLabelLength,
587
588    /// Domain name contains one or more invalid characters.
589    InvalidName,
590
591    /// Domain name compression offset is out of range.
592    NameOffsetOutOfRange,
593
594    /// Message ends unexpectedly.
595    UnexpectedEof,
596
597    /// Message contains extra octets.
598    UnexpectedOctets,
599}
600
601impl std::error::Error for DecoderError {
602    fn description(&self) -> &str {
603        match self {
604            &DecoderError::BadRdlength => "RDATA content does not match RDLENGTH",
605            &DecoderError::InfiniteName => "Domain name compression results in an infinite name",
606            &DecoderError::InvalidLabelLength => "Domain name label field is invalid",
607            &DecoderError::InvalidName => "Domain name contains one or more invalid characters",
608            &DecoderError::NameOffsetOutOfRange => "Domain name compression offset is out of range",
609            &DecoderError::UnexpectedEof => "Message ends unexpectedly",
610            &DecoderError::UnexpectedOctets => "Message contains extra octets",
611        }
612    }
613}
614
615impl std::fmt::Display for DecoderError {
616    fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
617        let d = (self as &std::error::Error).description();
618        d.fmt(f)
619    }
620}
621
622/// Reads an untrusted DNS message from an external buffer while providing
623/// error-checking.
624#[derive(Clone, Debug, Eq, PartialEq)]
625pub struct WireDecoder<'a> {
626    buffer: &'a [u8],
627    cursor: usize,
628}
629
630impl<'a> WireDecoder<'a> {
631    pub fn new(buffer: &'a [u8]) -> Self {
632        WireDecoder {
633            buffer: buffer,
634            cursor: 0,
635        }
636    }
637
638    #[cfg(test)]
639    fn with_cursor_offset(&self, n: usize) -> Self {
640        WireDecoder { cursor: self.cursor + n, ..*self }
641    }
642
643    unsafe fn as_trusted(&self) -> TrustedDecoder<'a> {
644        TrustedDecoder { cursor: self.cursor, ..TrustedDecoder::new(self.buffer) }
645    }
646
647    fn decode_u8(&mut self) -> Result<u8, DecoderError> {
648        match self.buffer.get(self.cursor) {
649            None => Err(DecoderError::UnexpectedEof),
650            Some(x) => {
651                self.cursor += std::mem::size_of::<u8>();
652                Ok(*x)
653            }
654        }
655    }
656
657    fn decode_u16(&mut self) -> Result<u16, DecoderError> {
658        let mut w = self.clone();
659        let hi = (w.decode_u8()? as u16) << 8;
660        let lo = (w.decode_u8()? as u16) << 0;
661        *self = w;
662        Ok(hi | lo)
663    }
664
665    fn decode_u32(&mut self) -> Result<u32, DecoderError> {
666        let mut w = self.clone();
667        let hi = (w.decode_u16()? as u32) << 16;
668        let lo = w.decode_u16()? as u32;
669        *self = w;
670        Ok(hi | lo)
671    }
672
673    fn decode_octets(&mut self, n: usize) -> Result<&'a [u8], DecoderError> {
674        if self.cursor + n > self.buffer.len() {
675            return Err(DecoderError::UnexpectedEof);
676        }
677        let x = &self.buffer[self.cursor..self.cursor + n];
678        self.cursor += n;
679        Ok(x)
680    }
681
682    fn decode_class(&mut self) -> Result<Class, DecoderError> {
683        Ok(Class(self.decode_u16()?))
684    }
685
686    fn decode_qclass(&mut self) -> Result<QClass, DecoderError> {
687        Ok(QClass(self.decode_u16()?))
688    }
689
690    fn decode_type(&mut self) -> Result<Type, DecoderError> {
691        Ok(Type(self.decode_u16()?))
692    }
693
694    fn decode_qtype(&mut self) -> Result<QType, DecoderError> {
695        Ok(QType(self.decode_u16()?))
696    }
697
698    fn decode_name(&mut self) -> Result<WireName<'a>, DecoderError> {
699
700        // When we're done (successfully) decoding the name, our cursor must
701        // point to the next field in the message. This position *isn't* the
702        // same as where we stop decoding. Why? Because *name compression* might
703        // cause us to jump around and finish decoding at a prior position in
704        // the message.
705
706        let mut end_of_name = 0;
707        let mut compressed = false;
708
709        // If an error occurs, then we must not have mutated our decoder's
710        // state. To make this easier, we use a temporary decoder and mutate its
711        // state instead.
712
713        let mut w = self.clone();
714
715        // An invalid DNS message could contain an infinite cycle of DNS labels.
716        // To guard against this, we place an upper bound on the number of
717        // labels. Otherwise, we would loop endlessly.
718        //
719        // Note: The maximum number of labels is equal to N / L, where N is the
720        // maximum name length (256 octets) and L is the minimum label length (2
721        // octets).
722
723        const MAX_LABELS: u32 = 128;
724
725        // Ok, all set. Now do the decoding.
726
727        for _ in 0..MAX_LABELS {
728            let len = w.decode_u8()?;
729            if !compressed {
730                end_of_name = w.cursor;
731            }
732            match len & 0b_1100_0000 {
733                0b_1100_0000 => {
734                    compressed = true;
735                    let offset = (len & 0b_0011_1111) as usize;
736
737                    // According to RFC 1035, section 4.1.4, it's illegal to jump
738                    // *forward* in a message (emphasis ours):
739                    //
740                    // > In this scheme, an entire domain name or a list of labels
741                    // at the end of a domain name is replaced with a pointer to a
742                    // **prior** occurance of the same name. <
743
744                    if offset >= w.cursor {
745                        return Err(DecoderError::NameOffsetOutOfRange);
746                    }
747
748                    w.cursor = offset;
749                }
750                0b_0000_0000 => {
751                    let len = len as usize;
752                    if 0 == len {
753                        let name = WireName { decoder: unsafe { self.as_trusted() } };
754                        self.cursor = end_of_name; // no error -> now safe to mutate
755                        return Ok(name);
756                    }
757                    let label = w.decode_octets(len)?;
758                    if !format::is_label_valid(label) {
759                        return Err(DecoderError::InvalidName);
760                    }
761                }
762                _ => {
763                    // Other bit combinations are reserved for future use, as
764                    // according to RFC 1035, section 4.1.4.
765                    return Err(DecoderError::InvalidLabelLength);
766                }
767            }
768        }
769
770        Err(DecoderError::InfiniteName)
771
772    }
773
774    fn decode_rdata(&mut self, c: Class, t: Type, rdlength: u16) -> Result<RData<'a, WireFormat>, DecoderError> {
775
776        let mut w = self.clone();
777        let rdata = match (c, t) {
778            (class::IN, type_::A) => RData::A { address: std::net::Ipv4Addr::from(w.decode_u32()?) },
779            (_, type_::CNAME) => RData::CName { cname: w.decode_name()? },
780            (_, type_::NS) => RData::NS { nsdname: w.decode_name()? },
781            (_, type_::SOA) => RData::SOA {
782                mname: w.decode_name()?,
783                rname: w.decode_name()?,
784                serial: SerialNumber(w.decode_u32()?),
785                refresh: Ttl(w.decode_u32()?),
786                retry: Ttl(w.decode_u32()?),
787                expire: Ttl(w.decode_u32()?),
788                minimum: Ttl(w.decode_u32()?),
789            },
790            (_, _) => RData::Other { octets: w.decode_octets(rdlength as usize)? },
791        };
792
793        // Check that the rdlength matches the number of bytes we actually
794        // decoded.
795        debug_assert!(self.cursor <= w.cursor);
796        if rdlength as usize != w.cursor - self.cursor {
797            return Err(DecoderError::BadRdlength);
798        }
799
800        *self = w; // no error -> now safe to mutate (move cursor)
801        Ok(rdata)
802    }
803
804    fn decode_resource_record_section(&mut self, count: u16) -> Result<ResourceRecordSection<'a>, DecoderError> {
805
806        // Validate all resource records and move the cursor.
807
808        let mut w = self.clone();
809        for _ in 0..count {
810            w.decode_name()?;
811            let t = w.decode_type()?;
812            let c = w.decode_class()?;
813            w.decode_u32()?;
814            let rdlength = w.decode_u16()?;
815            w.decode_rdata(c, t, rdlength)?;
816        }
817
818        // Ok, all resource records are valid.
819
820        let r = ResourceRecordSection {
821            count: count,
822            decoder: unsafe { self.as_trusted() },
823        };
824
825        *self = w; // no error -> now safe to mutate (move cursor)
826        Ok(r)
827    }
828
829    fn decode_question_section(&mut self, count: u16) -> Result<QuestionSection<'a>, DecoderError> {
830
831        // Validate all questions and move the cursor.
832
833        let mut w = self.clone();
834        for _ in 0..count {
835            w.decode_name()?;
836            w.decode_qtype()?;
837            w.decode_qclass()?;
838        }
839
840        // Ok, all questions are valid.
841
842        let q = QuestionSection {
843            count: count,
844            decoder: unsafe { self.as_trusted() },
845        };
846
847        *self = w; // no error -> now safe to mutate (move cursor)
848        Ok(q)
849    }
850
851    pub fn decode_message(&mut self) -> Result<WireMessage<'a>, DecoderError> {
852
853        let mut w = self.clone();
854
855        let id = w.decode_u16()?;
856        let flags = w.decode_u16()?;
857        let qdcount = w.decode_u16()?;
858        let ancount = w.decode_u16()?;
859        let nscount = w.decode_u16()?;
860        let arcount = w.decode_u16()?;
861
862        let question_section = w.decode_question_section(qdcount)?;
863        let answer_section = w.decode_resource_record_section(ancount)?;
864        let authority_section = w.decode_resource_record_section(nscount)?;
865        let additional_section = w.decode_resource_record_section(arcount)?;
866
867        if w.cursor != self.buffer.len() {
868            return Err(DecoderError::UnexpectedOctets);
869        }
870
871        *self = w; // no error -> now safe to mutate (move cursor)
872
873        Ok(WireMessage {
874            id: id,
875            flags: flags,
876            question_section: question_section,
877            answer_section: answer_section,
878            authority_section: authority_section,
879            additional_section: additional_section,
880        })
881    }
882}
883
884/// Decodes trusted DNS messages without providing error-checking.
885///
886/// An `TrustedDecoder` is literally unsafe and must only be used to decoded
887/// trusted DNS messages—i.e., messages that have already been decoded without
888/// error.
889///
890#[derive(Clone, Debug, Eq, PartialEq)]
891struct TrustedDecoder<'a> {
892    // Because the message is trusted, we don't need to keep track of the
893    // message's length, which would otherwise be used only for error-checking.
894    // By using a pointer (*const u8) instead of a slice (&'a [u8]), we save a
895    // little memory by eliding the slice's length.
896    buffer: *const u8,
897    cursor: usize,
898
899    // We explicitly track the lifetime so that maybe the compiler will save us
900    // from doing something stupid.
901    _phantom: std::marker::PhantomData<&'a ()>,
902
903    // When debugging, add the slice's length back in. This allows us to do
904    // some debug-only error-checking.
905    #[cfg(debug_assertions)]
906    size: usize,
907}
908
909impl<'a> TrustedDecoder<'a> {
910    #[cfg(not(debug_assertions))]
911    pub unsafe fn new(buffer: &'a [u8]) -> Self {
912        TrustedDecoder {
913            _phantom: std::marker::PhantomData,
914            buffer: buffer.as_ptr(),
915            cursor: 0,
916        }
917    }
918
919    #[cfg(debug_assertions)]
920    pub unsafe fn new(buffer: &'a [u8]) -> Self {
921        TrustedDecoder {
922            _phantom: std::marker::PhantomData,
923            buffer: buffer.as_ptr(),
924            cursor: 0,
925            size: buffer.len(),
926        }
927    }
928
929    #[cfg(test)]
930    fn with_cursor_offset(&self, n: usize) -> Self {
931        TrustedDecoder { cursor: self.cursor + n, ..*self }
932    }
933
934    #[cfg(not(debug_assertions))]
935    fn size(&self) -> usize {
936        0 // dummy value, never used
937    }
938
939    #[cfg(debug_assertions)]
940    fn size(&self) -> usize {
941        self.size
942    }
943
944    pub unsafe fn decode_u8_unchecked(&mut self) -> u8 {
945        debug_assert!(self.cursor + std::mem::size_of::<u8>() <= self.size());
946        let x = *self.buffer.offset(self.cursor as isize);
947        self.cursor += std::mem::size_of::<u8>();
948        x
949    }
950
951    pub unsafe fn decode_u16_unchecked(&mut self) -> u16 {
952        let hi = (self.decode_u8_unchecked() as u16) << 8;
953        let lo = (self.decode_u8_unchecked() as u16) << 0;
954        hi | lo
955    }
956
957    pub unsafe fn decode_u32_unchecked(&mut self) -> u32 {
958        let hi = (self.decode_u16_unchecked() as u32) << 16;
959        let lo = (self.decode_u16_unchecked() as u32) << 0;
960        hi | lo
961    }
962
963    pub unsafe fn decode_octets_unchecked(&mut self, n: usize) -> &'a [u8] {
964        debug_assert!(self.cursor + n <= self.size());
965        let x = std::slice::from_raw_parts(self.buffer.offset(self.cursor as isize), n);
966        self.cursor += n;
967        x
968    }
969
970    pub unsafe fn decode_class_unchecked(&mut self) -> Class {
971        Class(self.decode_u16_unchecked())
972    }
973
974    pub unsafe fn decode_qclass_unchecked(&mut self) -> QClass {
975        QClass(self.decode_u16_unchecked())
976    }
977
978    pub unsafe fn decode_type_unchecked(&mut self) -> Type {
979        Type(self.decode_u16_unchecked())
980    }
981
982    pub unsafe fn decode_qtype_unchecked(&mut self) -> QType {
983        QType(self.decode_u16_unchecked())
984    }
985
986    pub unsafe fn decode_label_unchecked(&mut self) -> Option<&'a str> {
987        loop {
988            let len = self.decode_u8_unchecked();
989            if 0b_1100_0000 == len & 0b_1100_0000 {
990                let offset = (len & 0b_0011_1111) as usize;
991                self.cursor = offset;
992            } else {
993                debug_assert_eq!(len & 0b_1100_0000, 0b_0000_0000);
994                return match len as usize {
995                    0 => None,
996                    len @ _ => Some(std::str::from_utf8_unchecked(self.decode_octets_unchecked(len))),
997                };
998            }
999        }
1000    }
1001
1002    pub unsafe fn decode_name_unchecked(&mut self) -> WireName<'a> {
1003
1004        // Because the name is valid and we don't need to check for any errors,
1005        // we needn't traverse the whole name. Instead, we need only find the
1006        // first byte of the field immediately following the name and set the
1007        // decoder's cursor to point to that byte. I.e., we stop traversing as
1008        // soon as we reach either (1) the end of the name or (2) the first
1009        // compressed label.
1010
1011        let name = WireName { decoder: self.clone() };
1012
1013        loop {
1014            let len = self.decode_u8_unchecked();
1015            if 0b_1100_0000 == len & 0b_1100_0000 {
1016                return name; // the remainder of the name is compressed
1017            } else {
1018                debug_assert_eq!(len & 0b_1100_0000, 0b_0000_0000);
1019                if 0 == len {
1020                    return name; // end of name
1021                }
1022                self.cursor += len as usize;
1023            }
1024        }
1025    }
1026
1027    pub unsafe fn decode_rdata_unchecked(&mut self, c: Class, t: Type, rdlength: u16) -> RData<'a, WireFormat> {
1028        match (c, t) {
1029            (class::IN, type_::A) => RData::A { address: std::net::Ipv4Addr::from(self.decode_u32_unchecked()) },
1030            (_, type_::CNAME) => RData::CName { cname: self.decode_name_unchecked() },
1031            (_, type_::NS) => RData::NS { nsdname: self.decode_name_unchecked() },
1032            (_, type_::SOA) => RData::SOA {
1033                mname: self.decode_name_unchecked(),
1034                rname: self.decode_name_unchecked(),
1035                serial: SerialNumber(self.decode_u32_unchecked()),
1036                refresh: Ttl(self.decode_u32_unchecked()),
1037                retry: Ttl(self.decode_u32_unchecked()),
1038                expire: Ttl(self.decode_u32_unchecked()),
1039                minimum: Ttl(self.decode_u32_unchecked()),
1040            },
1041            _ => RData::Other { octets: self.decode_octets_unchecked(rdlength as usize) },
1042        }
1043    }
1044
1045    pub unsafe fn decode_resource_record_unchecked(&mut self) -> ResourceRecord<'a, WireFormat> {
1046        let name = self.decode_name_unchecked();
1047        let type_ = self.decode_type_unchecked();
1048        let class = self.decode_class_unchecked();
1049        let ttl = Ttl(self.decode_u32_unchecked());
1050        let rdlength = self.decode_u16_unchecked();
1051        let rdata = self.decode_rdata_unchecked(class, type_, rdlength);
1052        ResourceRecord::new(name, type_, class, ttl, rdata)
1053    }
1054
1055    pub unsafe fn decode_question_unchecked(&mut self) -> Question<'a, WireFormat> {
1056        Question::new(self.decode_name_unchecked(),
1057                      self.decode_qtype_unchecked(),
1058                      self.decode_qclass_unchecked())
1059    }
1060}
1061
1062#[cfg(test)]
1063mod tests {
1064    use {Class, Format, Name, Question, RData, ResourceRecord, SerialNumber, Ttl, Type, class, qclass, qtype, std,
1065         type_};
1066    use std::str::FromStr;
1067    use super::*;
1068    use super::{QuestionSection, ResourceRecordSection, TrustedDecoder};
1069
1070    struct TestFormat;
1071
1072    impl<'a> Format<'a> for TestFormat {
1073        type Name = TestName;
1074        type RawOctets = Vec<u8>;
1075    }
1076
1077    struct TestName(Vec<String>);
1078
1079    impl TestName {
1080        fn new<S: Into<String>>(s: S) -> Self {
1081            let mut s = s.into();
1082            if s.ends_with('.') {
1083                s.pop();
1084            }
1085            TestName(s.split('.').map(|x| String::from(x)).collect())
1086        }
1087    }
1088
1089    impl<'a> Name<'a> for TestName {
1090        type LabelIter = TestLabelIter<'a>;
1091        fn labels(&'a self) -> Self::LabelIter {
1092            TestLabelIter { inner: self.0.iter() }
1093        }
1094    }
1095
1096    impl std::fmt::Display for TestName {
1097        fn fmt(&self, _f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
1098            unreachable!();
1099        }
1100    }
1101
1102    struct TestLabelIter<'a> {
1103        inner: std::slice::Iter<'a, String>,
1104    }
1105
1106    impl<'a> Iterator for TestLabelIter<'a> {
1107        type Item = &'a str;
1108        fn next(&mut self) -> Option<Self::Item> {
1109            match self.inner.next() {
1110                None => None,
1111                Some(x) => Some(&x),
1112            }
1113        }
1114    }
1115
1116    #[test]
1117    fn wire_name_display() {
1118        let mut d = WireDecoder::new(b"\x03foo\x03bar\x00");
1119        let n = d.decode_name().unwrap();
1120        let got = format!("{}", n);
1121        let expected = "foo.bar.";
1122        assert_eq!(got, expected);
1123    }
1124
1125    #[test]
1126    fn new_encoder_clears_header_bytes() {
1127        let mut b: [u8; 12] = [0xff; 12];
1128        WireEncoder::<marker::Response, marker::QuestionSection>::new(&mut b).unwrap();
1129        let expected = b"\x00\x00\x00\x00\
1130                         \x00\x00\x00\x00\
1131                         \x00\x00\x00\x00";
1132        assert_eq!(&b, expected);
1133    }
1134
1135    #[test]
1136    fn new_encoder_nok() {
1137        let mut b: [u8; 11] = [0xff; 11];
1138        let got = WireEncoder::<marker::Response, marker::QuestionSection>::new(&mut b);
1139        let expected = Err(EncoderError);
1140        assert_eq!(got, expected);
1141    }
1142
1143    #[test]
1144    fn encoder_read_write_u16_at_unchecked() {
1145        let mut b: [u8; 12] = [0; 12];
1146        let mut e = WireEncoder::<marker::Response, marker::QuestionSection>::new(&mut b).unwrap();
1147        let got = unsafe { e.read_u16_at_unchecked(3) };
1148        let expected = 0x0000;
1149        assert_eq!(got, expected);
1150
1151        unsafe { e.write_u16_at_unchecked(3, 0x1234) };
1152        let expected = b"\x00\x00\x00\x12\
1153                         \x34\x00\x00\x00\
1154                         \x00\x00\x00\x00";
1155        assert_eq!(e.buffer, expected);
1156
1157        let got = unsafe { e.read_u16_at_unchecked(3) };
1158        let expected = 0x1234;
1159        assert_eq!(got, expected);
1160    }
1161
1162    #[test]
1163    fn encoder_id() {
1164        let mut b: [u8; 12] = [0; 12];
1165        {
1166            let mut e = WireEncoder::<marker::Response, marker::QuestionSection>::new(&mut b).unwrap();
1167            e.encode_id(0x1234);
1168        }
1169        let expected = b"\x12\x34\x00\x00\
1170                         \x00\x00\x00\x00\
1171                         \x00\x00\x00\x00";
1172        assert_eq!(&b, expected);
1173    }
1174
1175    #[test]
1176    fn encoder_flags_set_all() {
1177        let mut b: [u8; 12] = [0; 12];
1178        {
1179            let mut e = WireEncoder::<marker::Response, marker::QuestionSection>::new(&mut b).unwrap();
1180            e.encode_flags(0xffff, 0xffff);
1181        }
1182        let expected = b"\x00\x00\xff\xff\
1183                         \x00\x00\x00\x00\
1184                         \x00\x00\x00\x00";
1185        assert_eq!(&b, expected);
1186    }
1187
1188    #[test]
1189    fn encoder_flags_clear_all() {
1190        let mut b: [u8; 12] = [0; 12];
1191        {
1192            let mut e = WireEncoder::<marker::Response, marker::QuestionSection>::new(&mut b).unwrap();
1193            unsafe { e.write_u16_at_unchecked(2, 0xffff) }
1194            e.encode_flags(0xffff, 0xffff);
1195        }
1196        let expected = b"\x00\x00\xff\xff\
1197                         \x00\x00\x00\x00\
1198                         \x00\x00\x00\x00";
1199        assert_eq!(&b, expected);
1200    }
1201
1202    #[test]
1203    fn encoder_flags_set_and_clear_some() {
1204        let mut b: [u8; 12] = [0; 12];
1205        {
1206            let mut e = WireEncoder::<marker::Response, marker::QuestionSection>::new(&mut b).unwrap();
1207            unsafe { e.write_u16_at_unchecked(2, 0x0950) }
1208            e.encode_flags(0x0ff0, 0x0590);
1209        }
1210        let expected = b"\x00\x00\x05\x90\
1211                         \x00\x00\x00\x00\
1212                         \x00\x00\x00\x00";
1213        assert_eq!(&b, expected);
1214    }
1215
1216    #[test]
1217    fn encoder_octets_at_ok() {
1218        let mut b: [u8; 512] = [0; 512];
1219        let len = {
1220            let mut e = WireEncoder::<marker::Response, marker::QuestionSection>::new(&mut b).unwrap();
1221            let mut cursor = 12;
1222            let got = e.encode_octets_at(&mut cursor, b"foo");
1223            let expected = Ok(());
1224            assert_eq!(got, expected);
1225            cursor
1226        };
1227        let expected = b"\x00\x00\x00\x00\
1228                         \x00\x00\x00\x00\
1229                         \x00\x00\x00\x00\
1230                              foo";
1231        assert_eq!(&b[..len], expected);
1232    }
1233
1234    #[test]
1235    fn encoder_octets_at_nok() {
1236        let mut b: [u8; 14] = [0; 14];
1237        let len = {
1238            let mut e = WireEncoder::<marker::Response, marker::QuestionSection>::new(&mut b).unwrap();
1239            let mut cursor = 12;
1240            let got = e.encode_octets_at(&mut cursor, b"foo");
1241            let expected = Err(EncoderError);
1242            assert_eq!(got, expected);
1243            cursor
1244        };
1245        let expected = b"\x00\x00\x02\x00\
1246                         \x00\x00\x00\x00\
1247                         \x00\x00\x00\x00";
1248        assert_eq!(&b[..len], expected);
1249    }
1250
1251    #[test]
1252    fn encoder_u8_at_ok() {
1253        let mut b: [u8; 512] = [0; 512];
1254        let len = {
1255            let mut e = WireEncoder::<marker::Response, marker::QuestionSection>::new(&mut b).unwrap();
1256            let mut cursor = 12;
1257            let got = e.encode_u8_at(&mut cursor, 0x12);
1258            let expected = Ok(());
1259            assert_eq!(got, expected);
1260            cursor
1261        };
1262        let expected = b"\x00\x00\x00\x00\
1263                         \x00\x00\x00\x00\
1264                         \x00\x00\x00\x00\
1265                         \x12";
1266        assert_eq!(&b[..len], expected);
1267    }
1268
1269    #[test]
1270    fn encoder_u8_at_nok() {
1271        let mut b: [u8; 12] = [0; 12];
1272        let len = {
1273            let mut e = WireEncoder::<marker::Response, marker::QuestionSection>::new(&mut b).unwrap();
1274            let mut cursor = 12;
1275            let got = e.encode_u8_at(&mut cursor, 0x12);
1276            let expected = Err(EncoderError);
1277            assert_eq!(got, expected);
1278            cursor
1279        };
1280        let expected = b"\x00\x00\x02\x00\
1281                         \x00\x00\x00\x00\
1282                         \x00\x00\x00\x00";
1283        assert_eq!(&b[..len], expected);
1284    }
1285
1286    #[test]
1287    fn encoder_u16_at_ok() {
1288        let mut b: [u8; 512] = [0; 512];
1289        let len = {
1290            let mut e = WireEncoder::<marker::Response, marker::QuestionSection>::new(&mut b).unwrap();
1291            let mut cursor = 12;
1292            let got = e.encode_u16_at(&mut cursor, 0x1234);
1293            let expected = Ok(());
1294            assert_eq!(got, expected);
1295            cursor
1296        };
1297        let expected = b"\x00\x00\x00\x00\
1298                         \x00\x00\x00\x00\
1299                         \x00\x00\x00\x00\
1300                         \x12\x34";
1301        assert_eq!(&b[..len], expected);
1302    }
1303
1304    #[test]
1305    fn encoder_u16_at_nok() {
1306        let mut b: [u8; 13] = [0; 13];
1307        let len = {
1308            let mut e = WireEncoder::<marker::Response, marker::QuestionSection>::new(&mut b).unwrap();
1309            let mut cursor = 12;
1310            let got = e.encode_u16_at(&mut cursor, 0x1234);
1311            let expected = Err(EncoderError);
1312            assert_eq!(got, expected);
1313            cursor
1314        };
1315        let expected = b"\x00\x00\x02\x00\
1316                         \x00\x00\x00\x00\
1317                         \x00\x00\x00\x00";
1318        assert_eq!(&b[..len], expected);
1319    }
1320
1321    #[test]
1322    fn encoder_u32_at_ok() {
1323        let mut b: [u8; 512] = [0; 512];
1324        let len = {
1325            let mut e = WireEncoder::<marker::Response, marker::QuestionSection>::new(&mut b).unwrap();
1326            let mut cursor = 12;
1327            let got = e.encode_u32_at(&mut cursor, 0x12345678);
1328            let expected = Ok(());
1329            assert_eq!(got, expected);
1330            cursor
1331        };
1332        let expected = b"\x00\x00\x00\x00\
1333                         \x00\x00\x00\x00\
1334                         \x00\x00\x00\x00\
1335                         \x12\x34\x56\x78";
1336        assert_eq!(&b[..len], expected);
1337    }
1338
1339    #[test]
1340    fn encoder_u32_at_nok() {
1341        let mut b: [u8; 15] = [0; 15];
1342        let len = {
1343            let mut e = WireEncoder::<marker::Response, marker::QuestionSection>::new(&mut b).unwrap();
1344            let mut cursor = 12;
1345            let got = e.encode_u32_at(&mut cursor, 0x12345678);
1346            let expected = Err(EncoderError);
1347            assert_eq!(got, expected);
1348            cursor
1349        };
1350        let expected = b"\x00\x00\x02\x00\
1351                         \x00\x00\x00\x00\
1352                         \x00\x00\x00\x00";
1353        assert_eq!(&b[..len], expected);
1354    }
1355
1356    #[test]
1357    fn encoder_class_at_ok() {
1358        let mut b: [u8; 512] = [0; 512];
1359        let len = {
1360            let mut e = WireEncoder::<marker::Response, marker::QuestionSection>::new(&mut b).unwrap();
1361            let mut cursor = 12;
1362            let got = e.encode_class_at(&mut cursor, class::IN);
1363            let expected = Ok(());
1364            assert_eq!(got, expected);
1365            cursor
1366        };
1367        let expected = b"\x00\x00\x00\x00\
1368                         \x00\x00\x00\x00\
1369                         \x00\x00\x00\x00\
1370                         \x00\x01";
1371        assert_eq!(&b[..len], expected);
1372    }
1373
1374    #[test]
1375    fn encoder_class_at_nok() {
1376        let mut b: [u8; 13] = [0; 13];
1377        let len = {
1378            let mut e = WireEncoder::<marker::Response, marker::QuestionSection>::new(&mut b).unwrap();
1379            let mut cursor = 12;
1380            let got = e.encode_class_at(&mut cursor, class::IN);
1381            let expected = Err(EncoderError);
1382            assert_eq!(got, expected);
1383            cursor
1384        };
1385        let expected = b"\x00\x00\x02\x00\
1386                         \x00\x00\x00\x00\
1387                         \x00\x00\x00\x00";
1388        assert_eq!(&b[..len], expected);
1389    }
1390
1391    #[test]
1392    fn encoder_qclass_at_ok() {
1393        let mut b: [u8; 512] = [0; 512];
1394        let len = {
1395            let mut e = WireEncoder::<marker::Response, marker::QuestionSection>::new(&mut b).unwrap();
1396            let mut cursor = 12;
1397            let got = e.encode_qclass_at(&mut cursor, qclass::ANY);
1398            let expected = Ok(());
1399            assert_eq!(got, expected);
1400            cursor
1401        };
1402        let expected = b"\x00\x00\x00\x00\
1403                         \x00\x00\x00\x00\
1404                         \x00\x00\x00\x00\
1405                         \x00\xff";
1406        assert_eq!(&b[..len], expected);
1407    }
1408
1409    #[test]
1410    fn encoder_qclass_at_nok() {
1411        let mut b: [u8; 13] = [0; 13];
1412        let len = {
1413            let mut e = WireEncoder::<marker::Response, marker::QuestionSection>::new(&mut b).unwrap();
1414            let mut cursor = 12;
1415            let got = e.encode_qclass_at(&mut cursor, qclass::ANY);
1416            let expected = Err(EncoderError);
1417            assert_eq!(got, expected);
1418            cursor
1419        };
1420        let expected = b"\x00\x00\x02\x00\
1421                         \x00\x00\x00\x00\
1422                         \x00\x00\x00\x00";
1423        assert_eq!(&b[..len], expected);
1424    }
1425
1426    #[test]
1427    fn encoder_type_at_ok() {
1428        let mut b: [u8; 512] = [0; 512];
1429        let len = {
1430            let mut e = WireEncoder::<marker::Response, marker::QuestionSection>::new(&mut b).unwrap();
1431            let mut cursor = 12;
1432            let got = e.encode_type_at(&mut cursor, type_::CNAME);
1433            let expected = Ok(());
1434            assert_eq!(got, expected);
1435            cursor
1436        };
1437        let expected = b"\x00\x00\x00\x00\
1438                         \x00\x00\x00\x00\
1439                         \x00\x00\x00\x00\
1440                         \x00\x05";
1441        assert_eq!(&b[..len], expected);
1442    }
1443
1444    #[test]
1445    fn encoder_type_at_nok() {
1446        let mut b: [u8; 13] = [0; 13];
1447        let len = {
1448            let mut e = WireEncoder::<marker::Response, marker::QuestionSection>::new(&mut b).unwrap();
1449            let mut cursor = 12;
1450            let got = e.encode_type_at(&mut cursor, type_::CNAME);
1451            let expected = Err(EncoderError);
1452            assert_eq!(got, expected);
1453            cursor
1454        };
1455        let expected = b"\x00\x00\x02\x00\
1456                         \x00\x00\x00\x00\
1457                         \x00\x00\x00\x00";
1458        assert_eq!(&b[..len], expected);
1459    }
1460
1461    #[test]
1462    fn encoder_qtype_at_ok() {
1463        let mut b: [u8; 512] = [0; 512];
1464        let len = {
1465            let mut e = WireEncoder::<marker::Response, marker::QuestionSection>::new(&mut b).unwrap();
1466            let mut cursor = 12;
1467            let got = e.encode_qtype_at(&mut cursor, qtype::ANY);
1468            let expected = Ok(());
1469            assert_eq!(got, expected);
1470            cursor
1471        };
1472        let expected = b"\x00\x00\x00\x00\
1473                         \x00\x00\x00\x00\
1474                         \x00\x00\x00\x00\
1475                         \x00\xff";
1476        assert_eq!(&b[..len], expected);
1477    }
1478
1479    #[test]
1480    fn encoder_qtype_at_nok() {
1481        let mut b: [u8; 13] = [0; 13];
1482        let len = {
1483            let mut e = WireEncoder::<marker::Response, marker::QuestionSection>::new(&mut b).unwrap();
1484            let mut cursor = 12;
1485            let got = e.encode_qtype_at(&mut cursor, qtype::ANY);
1486            let expected = Err(EncoderError);
1487            assert_eq!(got, expected);
1488            cursor
1489        };
1490        let expected = b"\x00\x00\x02\x00\
1491                         \x00\x00\x00\x00\
1492                         \x00\x00\x00\x00";
1493        assert_eq!(&b[..len], expected);
1494    }
1495
1496    #[test]
1497    fn encoder_name_at_ok() {
1498        let mut b: [u8; 512] = [0; 512];
1499        let len = {
1500            let mut e = WireEncoder::<marker::Response, marker::QuestionSection>::new(&mut b).unwrap();
1501            let mut cursor = 12;
1502            let got = e.encode_name_at(&mut cursor, &TestName::new("foo.bar."));
1503            let expected = Ok(());
1504            assert_eq!(got, expected);
1505            cursor
1506        };
1507        let expected = b"\x00\x00\x00\x00\
1508                         \x00\x00\x00\x00\
1509                         \x00\x00\x00\x00\
1510                         \x03foo\
1511                         \x03bar\
1512                         \x00";
1513        assert_eq!(&b[..len], expected);
1514    }
1515
1516    #[test]
1517    fn encoder_name_at_nok() {
1518        let mut b: [u8; 20] = [0; 20];
1519        let len = {
1520            let mut e = WireEncoder::<marker::Response, marker::QuestionSection>::new(&mut b).unwrap();
1521            let mut cursor = 12;
1522            let got = e.encode_name_at(&mut cursor, &TestName::new("foo.bar."));
1523            let expected = Err(EncoderError);
1524            assert_eq!(got, expected);
1525            cursor
1526        };
1527        let expected = b"\x00\x00\x02\x00\
1528                         \x00\x00\x00\x00\
1529                         \x00\x00\x00\x00";
1530        assert_eq!(&b[..len], expected);
1531    }
1532
1533    #[test]
1534    fn encoder_question_at_ok() {
1535        let mut b: [u8; 512] = [0; 512];
1536        let len = {
1537            let mut e = WireEncoder::<marker::Query, marker::QuestionSection>::new(&mut b).unwrap();
1538            let r = Question::<TestFormat>::new(TestName::new("foo."), qtype::ANY, qclass::ANY);
1539            let mut cursor = 12;
1540            let got = e.encode_question_at(&mut cursor, &r);
1541            let expected = Ok(());
1542            assert_eq!(got, expected);
1543            cursor
1544        };
1545        let expected = b"\x00\x00\x00\x00\
1546                         \x00\x00\x00\x00\
1547                         \x00\x00\x00\x00\
1548                         \x03foo\x00\
1549                         \x00\xff\
1550                         \x00\xff";
1551        assert_eq!(&b[..len], expected);
1552    }
1553
1554    #[test]
1555    fn encoder_question_at_nok() {
1556        let mut b: [u8; 20] = [0; 20];
1557        let len = {
1558            let mut e = WireEncoder::<marker::Query, marker::QuestionSection>::new(&mut b).unwrap();
1559            let r = Question::<TestFormat>::new(TestName::new("foo."), qtype::ANY, qclass::ANY);
1560            let mut cursor = 12;
1561            let got = e.encode_question_at(&mut cursor, &r);
1562            let expected = Err(EncoderError);
1563            assert_eq!(got, expected);
1564            cursor
1565        };
1566        let expected = b"\x00\x00\x02\x00\
1567                         \x00\x00\x00\x00\
1568                         \x00\x00\x00\x00";
1569        assert_eq!(&b[..len], expected);
1570    }
1571
1572    #[test]
1573    fn encoder_question_ok() {
1574        let mut b: [u8; 512] = [0; 512];
1575        let len = {
1576            let mut e = WireEncoder::<marker::Query, marker::QuestionSection>::new(&mut b).unwrap();
1577            let q = Question::<TestFormat>::new(TestName::new("foo."), qtype::ANY, qclass::ANY);
1578            let got = e.encode_question(&q);
1579            let expected = Ok(());
1580            assert_eq!(got, expected);
1581            assert_eq!(e.cursor, 12 + 9); // next byte after question
1582            e.cursor
1583        };
1584        let expected = b"\x00\x00\x00\x00\
1585                         \x00\x01\x00\x00\
1586                         \x00\x00\x00\x00\
1587                         \x03foo\x00\
1588                         \x00\xff\
1589                         \x00\xff";
1590        assert_eq!(&b[..len], expected);
1591    }
1592
1593    #[test]
1594    fn encoder_question_nok() {
1595        let mut b: [u8; 20] = [0; 20];
1596        let len = {
1597            let mut e = WireEncoder::<marker::Query, marker::QuestionSection>::new(&mut b).unwrap();
1598            let q = Question::<TestFormat>::new(TestName::new("foo."), qtype::ANY, qclass::IN);
1599            let got = e.encode_question(&q);
1600            let expected = Err(EncoderError);
1601            assert_eq!(got, expected);
1602            e.cursor
1603        };
1604        let expected = b"\x00\x00\x02\x00\
1605                         \x00\x00\x00\x00\
1606                         \x00\x00\x00\x00";
1607        assert_eq!(&b[..len], expected);
1608    }
1609
1610    #[test]
1611    fn encoder_rdlength_and_rdata_at_a_ok() {
1612        let mut b: [u8; 512] = [0; 512];
1613        let len = {
1614            let mut e = WireEncoder::<marker::Query, marker::QuestionSection>::new(&mut b).unwrap();
1615            let rdata: RData<TestFormat> = RData::A { address: std::net::Ipv4Addr::from_str("1.2.3.4").unwrap() };
1616            let mut cursor = 12;
1617            let got = e.encode_rdlength_and_rdata_at(&mut cursor, &rdata);
1618            let expected = Ok(());
1619            assert_eq!(got, expected);
1620            cursor
1621        };
1622        let expected = b"\x00\x00\x00\x00\
1623                         \x00\x00\x00\x00\
1624                         \x00\x00\x00\x00\
1625                         \x00\x04\x01\x02\
1626                         \x03\x04";
1627        assert_eq!(&b[..len], expected);
1628    }
1629
1630    #[test]
1631    fn encoder_rdlength_and_rdata_at_a_nok() {
1632        let mut b: [u8; 17] = [0; 17];
1633        let len = {
1634            let mut e = WireEncoder::<marker::Query, marker::QuestionSection>::new(&mut b).unwrap();
1635            let rdata: RData<TestFormat> = RData::A { address: std::net::Ipv4Addr::from_str("1.2.3.4").unwrap() };
1636            let mut cursor = 12;
1637            let got = e.encode_rdlength_and_rdata_at(&mut cursor, &rdata);
1638            let expected = Err(EncoderError);
1639            assert_eq!(got, expected);
1640            cursor
1641        };
1642        let expected = b"\x00\x00\x02\x00\
1643                         \x00\x00\x00\x00\
1644                         \x00\x00\x00\x00";
1645        assert_eq!(&b[..len], expected);
1646    }
1647
1648    #[test]
1649    fn encoder_rdlength_and_rdata_at_cname_ok() {
1650        let mut b: [u8; 512] = [0; 512];
1651        let len = {
1652            let mut e = WireEncoder::<marker::Query, marker::QuestionSection>::new(&mut b).unwrap();
1653            let rdata: RData<TestFormat> = RData::CName { cname: TestName::new("foo.") };
1654            let mut cursor = 12;
1655            let got = e.encode_rdlength_and_rdata_at(&mut cursor, &rdata);
1656            let expected = Ok(());
1657            assert_eq!(got, expected);
1658            cursor
1659        };
1660        let expected = b"\x00\x00\x00\x00\
1661                         \x00\x00\x00\x00\
1662                         \x00\x00\x00\x00\
1663                         \x00\x05\x03foo\x00";
1664        assert_eq!(&b[..len], expected);
1665    }
1666
1667    #[test]
1668    fn encoder_rdlength_and_rdata_at_cname_nok() {
1669        let mut b: [u8; 16] = [0; 16];
1670        let len = {
1671            let mut e = WireEncoder::<marker::Query, marker::QuestionSection>::new(&mut b).unwrap();
1672            let rdata: RData<TestFormat> = RData::CName { cname: TestName::new("foo.") };
1673            let mut cursor = 12;
1674            let got = e.encode_rdlength_and_rdata_at(&mut cursor, &rdata);
1675            let expected = Err(EncoderError);
1676            assert_eq!(got, expected);
1677            cursor
1678        };
1679        let expected = b"\x00\x00\x02\x00\
1680                         \x00\x00\x00\x00\
1681                         \x00\x00\x00\x00";
1682        assert_eq!(&b[..len], expected);
1683    }
1684
1685    #[test]
1686    fn encoder_rdlength_and_rdata_at_ns_ok() {
1687        let mut b: [u8; 512] = [0; 512];
1688        let len = {
1689            let mut e = WireEncoder::<marker::Query, marker::QuestionSection>::new(&mut b).unwrap();
1690            let rdata: RData<TestFormat> = RData::NS { nsdname: TestName::new("foo.") };
1691            let mut cursor = 12;
1692            let got = e.encode_rdlength_and_rdata_at(&mut cursor, &rdata);
1693            let expected = Ok(());
1694            assert_eq!(got, expected);
1695            cursor
1696        };
1697        let expected = b"\x00\x00\x00\x00\
1698                         \x00\x00\x00\x00\
1699                         \x00\x00\x00\x00\
1700                         \x00\x05\x03foo\x00";
1701        assert_eq!(&b[..len], expected);
1702    }
1703
1704    #[test]
1705    fn encoder_rdlength_and_rdata_at_ns_nok() {
1706        let mut b: [u8; 16] = [0; 16];
1707        let len = {
1708            let mut e = WireEncoder::<marker::Query, marker::QuestionSection>::new(&mut b).unwrap();
1709            let rdata: RData<TestFormat> = RData::NS { nsdname: TestName::new("foo.") };
1710            let mut cursor = 12;
1711            let got = e.encode_rdlength_and_rdata_at(&mut cursor, &rdata);
1712            let expected = Err(EncoderError);
1713            assert_eq!(got, expected);
1714            cursor
1715        };
1716        let expected = b"\x00\x00\x02\x00\
1717                         \x00\x00\x00\x00\
1718                         \x00\x00\x00\x00";
1719        assert_eq!(&b[..len], expected);
1720    }
1721
1722    #[test]
1723    fn encoder_rdlength_and_rdata_at_soa_ok() {
1724        let mut b: [u8; 512] = [0; 512];
1725        let len = {
1726            let mut e = WireEncoder::<marker::Query, marker::QuestionSection>::new(&mut b).unwrap();
1727            let rdata: RData<TestFormat> = RData::SOA {
1728                mname: TestName::new("foo."),
1729                rname: TestName::new("bar."),
1730                serial: SerialNumber(0x01020304),
1731                refresh: Ttl(0x5060708),
1732                retry: Ttl(0x090a0b0c),
1733                expire: Ttl(0x0d0e0f10),
1734                minimum: Ttl(0x11121314),
1735            };
1736            let mut cursor = 12;
1737            let got = e.encode_rdlength_and_rdata_at(&mut cursor, &rdata);
1738            let expected = Ok(());
1739            assert_eq!(got, expected);
1740            cursor
1741        };
1742        let expected = b"\x00\x00\x00\x00\
1743                         \x00\x00\x00\x00\
1744                         \x00\x00\x00\x00\
1745                         \x00\x1e\
1746                         \x03foo\x00\
1747                         \x03bar\x00\
1748                         \x01\x02\x03\x04\
1749                         \x05\x06\x07\x08\
1750                         \x09\x0a\x0b\x0c\
1751                         \x0d\x0e\x0f\x10\
1752                         \x11\x12\x13\x14";
1753        assert_eq!(&b[..len], &expected[..]);
1754    }
1755
1756    #[test]
1757    fn encoder_rdlength_and_rdata_at_soa_nok() {
1758        let mut b: [u8; 43] = [0; 43];
1759        let len = {
1760            let mut e = WireEncoder::<marker::Query, marker::QuestionSection>::new(&mut b).unwrap();
1761            let rdata: RData<TestFormat> = RData::SOA {
1762                mname: TestName::new("foo."),
1763                rname: TestName::new("bar."),
1764                serial: SerialNumber(0x01020304),
1765                refresh: Ttl(0x5060708),
1766                retry: Ttl(0x090a0b0c),
1767                expire: Ttl(0x0d0e0f10),
1768                minimum: Ttl(0x11121314),
1769            };
1770            let mut cursor = 12;
1771            let got = e.encode_rdlength_and_rdata_at(&mut cursor, &rdata);
1772            let expected = Err(EncoderError);
1773            assert_eq!(got, expected);
1774            cursor
1775        };
1776        let expected = b"\x00\x00\x02\x00\
1777                         \x00\x00\x00\x00\
1778                         \x00\x00\x00\x00";
1779        assert_eq!(&b[..len], expected);
1780    }
1781
1782    #[test]
1783    fn encoder_rdlength_and_rdata_at_other_ok() {
1784        let mut b: [u8; 512] = [0; 512];
1785        let len = {
1786            let mut e = WireEncoder::<marker::Query, marker::QuestionSection>::new(&mut b).unwrap();
1787            let rdata: RData<TestFormat> = RData::Other { octets: b"foo".to_vec() };
1788            let mut cursor = 12;
1789            let got = e.encode_rdlength_and_rdata_at(&mut cursor, &rdata);
1790            let expected = Ok(());
1791            assert_eq!(got, expected);
1792            cursor
1793        };
1794        let expected = b"\x00\x00\x00\x00\
1795                         \x00\x00\x00\x00\
1796                         \x00\x00\x00\x00\
1797                         \x00\x03\
1798                         foo";
1799        assert_eq!(&b[..len], expected);
1800    }
1801
1802    #[test]
1803    fn encoder_rdlength_and_rdata_at_other_nok() {
1804        let mut b: [u8; 16] = [0; 16];
1805        let len = {
1806            let mut e = WireEncoder::<marker::Query, marker::QuestionSection>::new(&mut b).unwrap();
1807            let rdata: RData<TestFormat> = RData::Other { octets: b"foo".to_vec() };
1808            let mut cursor = 12;
1809            let got = e.encode_rdlength_and_rdata_at(&mut cursor, &rdata);
1810            let expected = Err(EncoderError);
1811            assert_eq!(got, expected);
1812            cursor
1813        };
1814        let expected = b"\x00\x00\x02\x00\
1815                         \x00\x00\x00\x00\
1816                         \x00\x00\x00\x00";
1817        assert_eq!(&b[..len], expected);
1818    }
1819
1820    #[test]
1821    fn encoder_resource_record_at_ok() {
1822        let mut b: [u8; 512] = [0; 512];
1823        let len = {
1824            let mut e = WireEncoder::<marker::Query, marker::QuestionSection>::new(&mut b).unwrap();
1825            let r = ResourceRecord::<TestFormat>::new(TestName::new("foo."),
1826                                                      type_::CNAME,
1827                                                      class::IN,
1828                                                      Ttl(1000),
1829                                                      RData::CName { cname: TestName::new("bar.") });
1830            let mut cursor = 12;
1831            let got = e.encode_resource_record_at(&mut cursor, &r);
1832            let expected = Ok(());
1833            assert_eq!(got, expected);
1834            cursor
1835        };
1836        let expected = b"\x00\x00\x00\x00\
1837                         \x00\x00\x00\x00\
1838                         \x00\x00\x00\x00\
1839                         \x03foo\x00\
1840                         \x00\x05\
1841                         \x00\x01\
1842                         \x00\x00\x03\xe8\
1843                         \x00\x05\
1844                         \x03bar\x00";
1845        assert_eq!(&b[..len], expected);
1846    }
1847
1848    #[test]
1849    fn encoder_resource_record_at_nok() {
1850        let mut b: [u8; 31] = [0; 31];
1851        let len = {
1852            let mut e = WireEncoder::<marker::Query, marker::QuestionSection>::new(&mut b).unwrap();
1853            let r = ResourceRecord::<TestFormat>::new(TestName::new("foo."),
1854                                                      type_::CNAME,
1855                                                      class::IN,
1856                                                      Ttl(1000),
1857                                                      RData::CName { cname: TestName::new("bar.") });
1858            let mut cursor = 12;
1859            let got = e.encode_resource_record_at(&mut cursor, &r);
1860            let expected = Err(EncoderError);
1861            assert_eq!(got, expected);
1862            cursor
1863        };
1864        let expected = b"\x00\x00\x02\x00\
1865                         \x00\x00\x00\x00\
1866                         \x00\x00\x00\x00";
1867        assert_eq!(&b[..len], expected);
1868    }
1869
1870    #[test]
1871    fn encoder_new_response() {
1872
1873        let request_buffer = b"\x12\x34\x01\x00\
1874                               \x00\x02\x00\x00\
1875                               \x00\x00\x00\x00\
1876                               \x03foo\x00\x00\x01\x00\x01\
1877                               \x03bar\x00\x00\x01\x00\x01";
1878        let mut decoder = WireDecoder::new(request_buffer);
1879        let request = decoder.decode_message().unwrap();
1880
1881        let mut b: [u8; 512] = [0xff; 512];
1882        let len = {
1883            let e = WireEncoder::new_response(&mut b, &request).unwrap();
1884            e.cursor
1885        };
1886        let expected = b"\x12\x34\x81\x00\
1887                         \x00\x02\x00\x00\
1888                         \x00\x00\x00\x00\
1889                         \x03foo\x00\x00\x01\x00\x01\
1890                         \x03bar\x00\x00\x01\x00\x01";
1891        assert_eq!(&b[..len], expected);
1892    }
1893
1894    #[test]
1895    fn encoder_answer_ok() {
1896        let mut b: [u8; 512] = [0xff; 512];
1897        let len = {
1898            let mut e = WireEncoder::<marker::Response, marker::AnswerSection>::new(&mut b).unwrap();
1899            let r = ResourceRecord::<TestFormat>::new(TestName::new("foo."),
1900                                                      type_::CNAME,
1901                                                      class::IN,
1902                                                      Ttl(1000),
1903                                                      RData::CName { cname: TestName::new("bar.") });
1904            let got = e.encode_answer(&r);
1905            let expected = Ok(());
1906            assert_eq!(got, expected);
1907            e.cursor
1908        };
1909        let expected = b"\x00\x00\x00\x00\
1910                         \x00\x00\x00\x01\
1911                         \x00\x00\x00\x00\
1912                         \x03foo\x00\
1913                         \x00\x05\
1914                         \x00\x01\
1915                         \x00\x00\x03\xe8\
1916                         \x00\x05\
1917                         \x03bar\x00";
1918        assert_eq!(&b[..len], expected);
1919    }
1920
1921    #[test]
1922    fn encoder_answer_nok() {
1923        let mut b: [u8; 31] = [0xff; 31];
1924        let len = {
1925            let mut e = WireEncoder::<marker::Response, marker::AnswerSection>::new(&mut b).unwrap();
1926            let r = ResourceRecord::<TestFormat>::new(TestName::new("foo."),
1927                                                      type_::CNAME,
1928                                                      class::IN,
1929                                                      Ttl(1000),
1930                                                      RData::CName { cname: TestName::new("bar.") });
1931            let got = e.encode_answer(&r);
1932            let expected = Err(EncoderError);
1933            assert_eq!(got, expected);
1934            e.cursor
1935        };
1936        let expected = b"\x00\x00\x02\x00\
1937                         \x00\x00\x00\x00\
1938                         \x00\x00\x00\x00";
1939        assert_eq!(&b[..len], expected);
1940    }
1941
1942    #[test]
1943    fn encoder_authority_ok() {
1944        let mut b: [u8; 512] = [0xff; 512];
1945        let len = {
1946            let mut e = WireEncoder::<marker::Response, marker::AuthoritySection>::new(&mut b).unwrap();
1947            let r = ResourceRecord::<TestFormat>::new(TestName::new("foo."),
1948                                                      type_::NS,
1949                                                      class::IN,
1950                                                      Ttl(1000),
1951                                                      RData::NS { nsdname: TestName::new("bar.") });
1952            let got = e.encode_authority(&r);
1953            let expected = Ok(());
1954            assert_eq!(got, expected);
1955            e.cursor
1956        };
1957        let expected = b"\x00\x00\x00\x00\
1958                         \x00\x00\x00\x00\
1959                         \x00\x01\x00\x00\
1960                         \x03foo\x00\
1961                         \x00\x02\
1962                         \x00\x01\
1963                         \x00\x00\x03\xe8\
1964                         \x00\x05\
1965                         \x03bar\x00";
1966        assert_eq!(&b[..len], expected);
1967    }
1968
1969    #[test]
1970    fn encoder_authority_nok() {
1971        let mut b: [u8; 31] = [0xff; 31];
1972        let len = {
1973            let mut e = WireEncoder::<marker::Response, marker::AuthoritySection>::new(&mut b).unwrap();
1974            let r = ResourceRecord::<TestFormat>::new(TestName::new("foo."),
1975                                                      type_::NS,
1976                                                      class::IN,
1977                                                      Ttl(1000),
1978                                                      RData::NS { nsdname: TestName::new("bar.") });
1979            let got = e.encode_authority(&r);
1980            let expected = Err(EncoderError);
1981            assert_eq!(got, expected);
1982            e.cursor
1983        };
1984        let expected = b"\x00\x00\x02\x00\
1985                         \x00\x00\x00\x00\
1986                         \x00\x00\x00\x00";
1987        assert_eq!(&b[..len], expected);
1988    }
1989
1990    #[test]
1991    fn encoder_additional_ok() {
1992        let mut b: [u8; 512] = [0xff; 512];
1993        let len = {
1994            let mut e = WireEncoder::<marker::Response, marker::AdditionalSection>::new(&mut b).unwrap();
1995            let r = ResourceRecord::<TestFormat>::new(TestName::new("foo."),
1996                                                      type_::A,
1997                                                      class::IN,
1998                                                      Ttl(1000),
1999                                                      RData::A {
2000                                                          address: std::net::Ipv4Addr::from_str("1.2.3.4").unwrap(),
2001                                                      });
2002            let got = e.encode_additional(&r);
2003            let expected = Ok(());
2004            assert_eq!(got, expected);
2005            e.cursor
2006        };
2007        let expected = b"\x00\x00\x00\x00\
2008                         \x00\x00\x00\x00\
2009                         \x00\x00\x00\x01\
2010                         \x03foo\x00\
2011                         \x00\x01\
2012                         \x00\x01\
2013                         \x00\x00\x03\xe8\
2014                         \x00\x04\
2015                         \x01\x02\x03\x04";
2016        assert_eq!(&b[..len], expected);
2017    }
2018
2019    #[test]
2020    fn encoder_additional_nok() {
2021        let mut b: [u8; 30] = [0xff; 30];
2022        let len = {
2023            let mut e = WireEncoder::<marker::Response, marker::AdditionalSection>::new(&mut b).unwrap();
2024            let r = ResourceRecord::<TestFormat>::new(TestName::new("foo."),
2025                                                      type_::A,
2026                                                      class::IN,
2027                                                      Ttl(1000),
2028                                                      RData::A {
2029                                                          address: std::net::Ipv4Addr::from_str("1.2.3.4").unwrap(),
2030                                                      });
2031            let got = e.encode_additional(&r);
2032            let expected = Err(EncoderError);
2033            assert_eq!(got, expected);
2034            e.cursor
2035        };
2036        let expected = b"\x00\x00\x02\x00\
2037                         \x00\x00\x00\x00\
2038                         \x00\x00\x00\x00";
2039        assert_eq!(&b[..len], expected);
2040    }
2041
2042    #[test]
2043    fn untrusted_decoder_u8_ok() {
2044        let mut d = WireDecoder::new(b"\x00\x12").with_cursor_offset(1);
2045        let o = d.clone();
2046        let got = d.decode_u8();
2047        let expected = Ok(18);
2048        assert_eq!(got, expected);
2049        assert_eq!(d, o.with_cursor_offset(std::mem::size_of::<u8>()));
2050    }
2051
2052    #[test]
2053    fn untrusted_decoder_u8_nok_truncated() {
2054        let mut d = WireDecoder::new(b"");
2055        let o = d.clone();
2056        let got = d.decode_u8();
2057        let expected = Err(DecoderError::UnexpectedEof);
2058        assert_eq!(got, expected);
2059        assert_eq!(d, o);
2060    }
2061
2062    #[test]
2063    fn untrusted_decoder_u16_ok() {
2064        let mut d = WireDecoder::new(b"\x00\x02\x05").with_cursor_offset(1);
2065        let o = d.clone();
2066        let got = d.decode_u16();
2067        let expected = Ok(517);
2068        assert_eq!(got, expected);
2069        assert_eq!(d, o.with_cursor_offset(std::mem::size_of::<u16>()));
2070    }
2071
2072    #[test]
2073    fn untrusted_decoder_u16_nok_truncated() {
2074        let mut d = WireDecoder::new(b"\x00");
2075        let o = d.clone();
2076        let got = d.decode_u16();
2077        let expected = Err(DecoderError::UnexpectedEof);
2078        assert_eq!(got, expected);
2079        assert_eq!(d, o);
2080    }
2081
2082    #[test]
2083    fn untrusted_decoder_u32_ok() {
2084        let mut d = WireDecoder::new(b"\x00\x12\x34\x56\x78").with_cursor_offset(1);
2085        let o = d.clone();
2086        let got = d.decode_u32();
2087        let expected = Ok(0x12345678);
2088        assert_eq!(got, expected);
2089        assert_eq!(d, o.with_cursor_offset(std::mem::size_of::<u32>()));
2090    }
2091
2092    #[test]
2093    fn untrusted_decoder_u32_nok_truncated() {
2094        let mut d = WireDecoder::new(b"\x00\x00\x00");
2095        let o = d.clone();
2096        let got = d.decode_u32();
2097        let expected = Err(DecoderError::UnexpectedEof);
2098        assert_eq!(got, expected);
2099        assert_eq!(d, o);
2100    }
2101
2102    #[test]
2103    fn untrusted_decoder_octets_ok_empty() {
2104        let mut d = WireDecoder::new(b"\x00").with_cursor_offset(1);
2105        let o = d.clone();
2106        let got = d.decode_octets(0);
2107        let expected = Ok(&b""[..]);
2108        assert_eq!(got, expected);
2109        assert_eq!(d, o.with_cursor_offset(0));
2110    }
2111
2112    #[test]
2113    fn untrusted_decoder_octets_ok_nonempty() {
2114        let mut d = WireDecoder::new(b"\x00\x01\x02\x03").with_cursor_offset(1);
2115        let o = d.clone();
2116        let got = d.decode_octets(3);
2117        let expected = Ok(&b"\x01\x02\x03"[..]);
2118        assert_eq!(got, expected);
2119        assert_eq!(d, o.with_cursor_offset(3));
2120    }
2121
2122    #[test]
2123    fn untrusted_decoder_octets_nok_truncated() {
2124        let mut d = WireDecoder::new(b"\x00\x00\x00");
2125        let o = d.clone();
2126        let got = d.decode_octets(4);
2127        let expected = Err(DecoderError::UnexpectedEof);
2128        assert_eq!(got, expected);
2129        assert_eq!(d, o);
2130    }
2131
2132    #[test]
2133    fn untrusted_decoder_class_ok() {
2134        let mut d = WireDecoder::new(b"\x00\x00\x01").with_cursor_offset(1);
2135        let o = d.clone();
2136        let got = d.decode_class();
2137        let expected = Ok(class::IN);
2138        assert_eq!(got, expected);
2139        assert_eq!(d, o.with_cursor_offset(std::mem::size_of::<u16>()));
2140    }
2141
2142    #[test]
2143    fn untrusted_decoder_class_nok_truncated() {
2144        let mut d = WireDecoder::new(b"\x00");
2145        let o = d.clone();
2146        let got = d.decode_class();
2147        let expected = Err(DecoderError::UnexpectedEof);
2148        assert_eq!(got, expected);
2149        assert_eq!(d, o);
2150    }
2151
2152    #[test]
2153    fn untrusted_decoder_qclass_ok() {
2154        let mut d = WireDecoder::new(b"\x00\x00\xff").with_cursor_offset(1);
2155        let o = d.clone();
2156        let got = d.decode_qclass();
2157        let expected = Ok(qclass::ANY);
2158        assert_eq!(got, expected);
2159        assert_eq!(d, o.with_cursor_offset(std::mem::size_of::<u16>()));
2160    }
2161
2162    #[test]
2163    fn untrusted_decoder_qclass_nok_truncated() {
2164        let mut d = WireDecoder::new(b"\x00");
2165        let o = d.clone();
2166        let got = d.decode_qclass();
2167        let expected = Err(DecoderError::UnexpectedEof);
2168        assert_eq!(got, expected);
2169        assert_eq!(d, o);
2170    }
2171
2172    #[test]
2173    fn untrusted_decoder_type_ok() {
2174        let mut d = WireDecoder::new(b"\x00\x00\x05").with_cursor_offset(1);
2175        let o = d.clone();
2176        let got = d.decode_type();
2177        let expected = Ok(type_::CNAME);
2178        assert_eq!(got, expected);
2179        assert_eq!(d, o.with_cursor_offset(std::mem::size_of::<u16>()));
2180    }
2181
2182    #[test]
2183    fn untrusted_decoder_type_nok_truncated() {
2184        let mut d = WireDecoder::new(b"\x00");
2185        let o = d.clone();
2186        let got = d.decode_type();
2187        let expected = Err(DecoderError::UnexpectedEof);
2188        assert_eq!(got, expected);
2189        assert_eq!(d, o);
2190    }
2191
2192    #[test]
2193    fn untrusted_decoder_qtype_ok() {
2194        let mut d = WireDecoder::new(b"\x00\x00\xff").with_cursor_offset(1);
2195        let o = d.clone();
2196        let got = d.decode_qtype();
2197        let expected = Ok(qtype::ANY);
2198        assert_eq!(got, expected);
2199        assert_eq!(d, o.with_cursor_offset(std::mem::size_of::<u16>()));
2200    }
2201
2202    #[test]
2203    fn untrusted_decoder_qtype_nok_truncated() {
2204        let mut d = WireDecoder::new(b"\x00");
2205        let o = d.clone();
2206        let got = d.decode_qtype();
2207        let expected = Err(DecoderError::UnexpectedEof);
2208        assert_eq!(got, expected);
2209        assert_eq!(d, o);
2210    }
2211
2212    #[test]
2213    fn untrusted_decoder_name_ok_empty() {
2214        let mut d = WireDecoder::new(b"\x00\x00").with_cursor_offset(1);
2215        let o = d.clone();
2216        let got = d.decode_name();
2217        let expected = Ok(WireName { decoder: unsafe { o.as_trusted() } });
2218        assert_eq!(got, expected);
2219        assert_eq!(d, o.with_cursor_offset(1));
2220    }
2221
2222    #[test]
2223    fn untrusted_decoder_name_ok_uncompressed() {
2224        let mut d = WireDecoder::new(b"\x00\
2225                                          \x03foo\
2226                                          \x03bar\
2227                                          \x00")
2228            .with_cursor_offset(1);
2229        let o = d.clone();
2230        let got = d.decode_name();
2231        let expected = Ok(WireName { decoder: unsafe { o.as_trusted() } });
2232        assert_eq!(got, expected);
2233        assert_eq!(d, o.with_cursor_offset(9));
2234    }
2235
2236    #[test]
2237    fn untrusted_decoder_name_ok_compressed() {
2238        let mut d = WireDecoder::new(b"\x00\
2239                                          \x03qux\
2240                                          \x00\
2241                                          \x03bar\
2242                                          \xc1\
2243                                          \x03foo\
2244                                          \xc6")
2245            .with_cursor_offset(11);
2246        let o = d.clone();
2247        let got = d.decode_name();
2248        let expected = Ok(WireName { decoder: unsafe { o.as_trusted() } });
2249        assert_eq!(got, expected);
2250        assert_eq!(d, o.with_cursor_offset(5));
2251    }
2252
2253    #[test]
2254    fn untrusted_decoder_name_nok_label_offset_jumps_forward() {
2255        let mut d = WireDecoder::new(b"\x03foo\
2256                                          \xc5\
2257                                          \x03bar
2258                                          \x00");
2259        let o = d.clone();
2260        let got = d.decode_name();
2261        let expected = Err(DecoderError::NameOffsetOutOfRange);
2262        assert_eq!(got, expected);
2263        assert_eq!(d, o);
2264    }
2265
2266    #[test]
2267    fn untrusted_decoder_name_nok_label_offset_jumps_out_of_message() {
2268        let mut d = WireDecoder::new(b"\x03foo\
2269                                          \xc5");
2270        let o = d.clone();
2271        let got = d.decode_name();
2272        let expected = Err(DecoderError::NameOffsetOutOfRange);
2273        assert_eq!(got, expected);
2274        assert_eq!(d, o);
2275    }
2276
2277    #[test]
2278    fn untrusted_decoder_name_nok_label_length_is_truncated() {
2279        let mut d = WireDecoder::new(b"");
2280        let o = d.clone();
2281        let got = d.decode_name();
2282        let expected = Err(DecoderError::UnexpectedEof);
2283        assert_eq!(got, expected);
2284        assert_eq!(d, o);
2285    }
2286
2287    #[test]
2288    fn untrusted_decoder_name_nok_label_is_truncated() {
2289        let mut d = WireDecoder::new(b"\x03fo");
2290        let o = d.clone();
2291        let got = d.decode_name();
2292        let expected = Err(DecoderError::UnexpectedEof);
2293        assert_eq!(got, expected);
2294        assert_eq!(d, o);
2295    }
2296
2297    #[test]
2298    fn untrusted_decoder_name_nok_label_is_invalid() {
2299        let mut d = WireDecoder::new(b"\x01-\x00");// names cannot start with a hyphen
2300        let o = d.clone();
2301        let got = d.decode_name();
2302        let expected = Err(DecoderError::InvalidName);
2303        assert_eq!(got, expected);
2304        assert_eq!(d, o);
2305    }
2306
2307    #[test]
2308    fn untrusted_decoder_name_nok_label_length_uses_reserved_bits() {
2309        // The reserved bits are 0x80 and 0x40 (high bits).
2310
2311        let mut d = WireDecoder::new(b"\x43foo\x00");
2312        let o = d.clone();
2313        let got = d.decode_name();
2314        let expected = Err(DecoderError::InvalidLabelLength);
2315        assert_eq!(got, expected);
2316        assert_eq!(d, o);
2317
2318        let mut d = WireDecoder::new(b"\x83foo\x00");
2319        let o = d.clone();
2320        let got = d.decode_name();
2321        let expected = Err(DecoderError::InvalidLabelLength);
2322        assert_eq!(got, expected);
2323        assert_eq!(d, o);
2324    }
2325
2326    #[test]
2327    fn untrusted_decoder_name_nok_name_is_infinite_cycle() {
2328        let mut d = WireDecoder::new(b"\x03foo\xc0");
2329        let o = d.clone();
2330        let got = d.decode_name();
2331        let expected = Err(DecoderError::InfiniteName);
2332        assert_eq!(got, expected);
2333        assert_eq!(d, o);
2334    }
2335
2336    #[test]
2337    fn untrusted_decoder_question_section_ok_empty() {
2338        let mut d = WireDecoder::new(b"\x00\
2339                                            \x03foo\x00\x00\x05\x00\x01\
2340                                            \x03bar\x00\x00\x05\x00\x01")
2341            .with_cursor_offset(1);
2342        let o = d.clone();
2343        let got = d.decode_question_section(2);
2344        let expected = Ok(QuestionSection {
2345            count: 2,
2346            decoder: unsafe { o.clone().as_trusted() },
2347        });
2348        assert_eq!(got, expected);
2349        assert_eq!(d, o.with_cursor_offset(18));
2350    }
2351
2352    #[test]
2353    fn untrusted_decoder_question_section_nok_bad_qname() {
2354        let mut d = WireDecoder::new(b"\x01-\x00\x00\x05\x00\x01");
2355        let o = d.clone();
2356        let got = d.decode_question_section(1);
2357        let expected = Err(DecoderError::InvalidName);
2358        assert_eq!(got, expected);
2359        assert_eq!(d, o);
2360    }
2361
2362    #[test]
2363    fn untrusted_decoder_question_section_nok_truncated_qtype() {
2364        let mut d = WireDecoder::new(b"\x03foo\x00\x00");
2365        let o = d.clone();
2366        let got = d.decode_question_section(1);
2367        let expected = Err(DecoderError::UnexpectedEof);
2368        assert_eq!(got, expected);
2369        assert_eq!(d, o);
2370    }
2371
2372    #[test]
2373    fn untrusted_decoder_question_section_nok_truncated_qclass() {
2374        let mut d = WireDecoder::new(b"\x03foo\x00\x00\x05\x00");
2375        let o = d.clone();
2376        let got = d.decode_question_section(1);
2377        let expected = Err(DecoderError::UnexpectedEof);
2378        assert_eq!(got, expected);
2379        assert_eq!(d, o);
2380    }
2381
2382    #[test]
2383    fn untrusted_decoder_question_section_nok_too_few_questions() {
2384        let mut d = WireDecoder::new(b"\x03foo\x00\x00\x05\x00\x01");
2385        let o = d.clone();
2386        let got = d.decode_question_section(2);
2387        let expected = Err(DecoderError::UnexpectedEof);
2388        assert_eq!(got, expected);
2389        assert_eq!(d, o);
2390    }
2391
2392    #[test]
2393    fn untrusted_decoder_rdata_other_ok() {
2394        let mut d = WireDecoder::new(b"\x00\x01\x02\x03").with_cursor_offset(1);
2395        let o = d.clone();
2396        let got = d.decode_rdata(Class(255), Type(255), 3);
2397        let expected = Ok(RData::Other { octets: &b"\x01\x02\x03"[..] });
2398        assert_eq!(got, expected);
2399        assert_eq!(d, o.with_cursor_offset(3));
2400    }
2401
2402    #[test]
2403    fn untrusted_decoder_rdata_other_nok_truncated() {
2404        let mut d = WireDecoder::new(b"\x00\x01\x02\x03").with_cursor_offset(1);
2405        let o = d.clone();
2406        let got = d.decode_rdata(Class(255), Type(255), 4);
2407        let expected = Err(DecoderError::UnexpectedEof);
2408        assert_eq!(got, expected);
2409        assert_eq!(d, o);
2410    }
2411
2412    #[test]
2413    fn untrusted_decoder_rdata_a_ok() {
2414        let mut d = WireDecoder::new(b"\x00\x01\x02\x03\x04").with_cursor_offset(1);
2415        let o = d.clone();
2416        let got = d.decode_rdata(class::IN, type_::A, 4);
2417        let expected = Ok(RData::A { address: std::net::Ipv4Addr::from_str("1.2.3.4").unwrap() });
2418        assert_eq!(got, expected);
2419        assert_eq!(d, o.with_cursor_offset(4));
2420    }
2421
2422    #[test]
2423    fn untrusted_decoder_rdata_a_nok_address_truncated() {
2424        let mut d = WireDecoder::new(b"\x00\x0a\x00\x00").with_cursor_offset(1);
2425        let o = d.clone();
2426        let got = d.decode_rdata(class::IN, type_::A, 4);
2427        let expected = Err(DecoderError::UnexpectedEof);
2428        assert_eq!(got, expected);
2429        assert_eq!(d, o);
2430    }
2431
2432    #[test]
2433    fn untrusted_decoder_rdata_a_nok_bad_rdlength() {
2434        let mut d = WireDecoder::new(b"\x00\x0a\x00\x00\x01").with_cursor_offset(1);
2435        let o = d.clone();
2436        let got = d.decode_rdata(class::IN, type_::A, 3);
2437        let expected = Err(DecoderError::BadRdlength);
2438        assert_eq!(got, expected);
2439        assert_eq!(d, o);
2440    }
2441
2442    #[test]
2443    fn untrusted_decoder_rdata_cname_ok() {
2444        let mut d = WireDecoder::new(b"\x00\x03foo\x00").with_cursor_offset(1);
2445        let o = d.clone();
2446        let got = d.decode_rdata(class::IN, type_::CNAME, 5);
2447        let expected = Ok(RData::CName { cname: WireName { decoder: unsafe { o.as_trusted() } } });
2448        assert_eq!(got, expected);
2449        assert_eq!(d, o.with_cursor_offset(5));
2450    }
2451
2452    #[test]
2453    fn untrusted_decoder_rdata_cname_nok_cname_truncated() {
2454        let mut d = WireDecoder::new(b"\x00\x03foo").with_cursor_offset(1);
2455        let o = d.clone();
2456        let got = d.decode_rdata(class::IN, type_::CNAME, 4);
2457        let expected = Err(DecoderError::UnexpectedEof);
2458        assert_eq!(got, expected);
2459        assert_eq!(d, o);
2460    }
2461
2462    #[test]
2463    fn untrusted_decoder_rdata_cname_nok_bad_rdlength() {
2464        let mut d = WireDecoder::new(b"\x00\x03foo\x00").with_cursor_offset(1);
2465        let o = d.clone();
2466        let got = d.decode_rdata(class::IN, type_::CNAME, 4);
2467        let expected = Err(DecoderError::BadRdlength);
2468        assert_eq!(got, expected);
2469        assert_eq!(d, o);
2470    }
2471
2472    #[test]
2473    fn untrusted_decoder_rdata_ns_ok() {
2474        let mut d = WireDecoder::new(b"\x00\x03foo\x00").with_cursor_offset(1);
2475        let o = d.clone();
2476        let got = d.decode_rdata(class::IN, type_::NS, 5);
2477        let expected = Ok(RData::NS { nsdname: WireName { decoder: unsafe { o.as_trusted() } } });
2478        assert_eq!(got, expected);
2479        assert_eq!(d, o.with_cursor_offset(5));
2480    }
2481
2482    #[test]
2483    fn untrusted_decoder_rdata_ns_nok_nsdname_truncated() {
2484        let mut d = WireDecoder::new(b"\x00\x03foo").with_cursor_offset(1);
2485        let o = d.clone();
2486        let got = d.decode_rdata(class::IN, type_::NS, 4);
2487        let expected = Err(DecoderError::UnexpectedEof);
2488        assert_eq!(got, expected);
2489        assert_eq!(d, o);
2490    }
2491
2492    #[test]
2493    fn untrusted_decoder_rdata_ns_nok_bad_rdlength() {
2494        let mut d = WireDecoder::new(b"\x00\x03foo\x00").with_cursor_offset(1);
2495        let o = d.clone();
2496        let got = d.decode_rdata(class::IN, type_::NS, 4);
2497        let expected = Err(DecoderError::BadRdlength);
2498        assert_eq!(got, expected);
2499        assert_eq!(d, o);
2500    }
2501
2502    #[test]
2503    fn untrusted_decoder_rdata_soa_ok() {
2504        let mut d = WireDecoder::new(b"\x00\
2505                                       \x03foo\x00\
2506                                       \x03bar\x00\
2507                                       \x01\x02\x03\x04\
2508                                       \x05\x06\x07\x08\
2509                                       \x09\x0a\x0b\x0c\
2510                                       \x0d\x0e\x0f\x10\
2511                                       \x11\x12\x13\x14")
2512            .with_cursor_offset(1);
2513        let o = d.clone();
2514        let got = d.decode_rdata(class::IN, type_::SOA, 30);
2515        let expected = Ok(RData::SOA {
2516            mname: WireName { decoder: unsafe { o.as_trusted() } },
2517            rname: WireName { decoder: unsafe { o.with_cursor_offset(5).as_trusted() } },
2518            serial: SerialNumber(0x01020304),
2519            refresh: Ttl(0x05060708),
2520            retry: Ttl(0x090a0b0c),
2521            expire: Ttl(0x0d0e0f10),
2522            minimum: Ttl(0x11121314),
2523        });
2524        assert_eq!(got, expected);
2525        assert_eq!(d, o.with_cursor_offset(30));
2526    }
2527
2528    #[test]
2529    fn untrusted_decoder_rdata_soa_nok_bad_mname() {
2530        let mut d = WireDecoder::new(b"\x00\
2531                                       \x03---\x00\
2532                                       \x03bar\x00\
2533                                       \x01\x02\x03\x04\
2534                                       \x05\x06\x07\x08\
2535                                       \x09\x0a\x0b\x0c\
2536                                       \x0d\x0e\x0f\x10\
2537                                       \x11\x12\x13\x14")
2538            .with_cursor_offset(1);
2539        let o = d.clone();
2540        let got = d.decode_rdata(class::IN, type_::SOA, 30);
2541        let expected = Err(DecoderError::InvalidName);
2542        assert_eq!(got, expected);
2543        assert_eq!(d, o);
2544    }
2545
2546    #[test]
2547    fn untrusted_decoder_rdata_soa_nok_bad_rname() {
2548        let mut d = WireDecoder::new(b"\x00\
2549                                       \x03foo\x00\
2550                                       \x03---\x00\
2551                                       \x01\x02\x03\x04\
2552                                       \x05\x06\x07\x08\
2553                                       \x09\x0a\x0b\x0c\
2554                                       \x0d\x0e\x0f\x10\
2555                                       \x11\x12\x13\x14")
2556            .with_cursor_offset(1);
2557        let o = d.clone();
2558        let got = d.decode_rdata(class::IN, type_::SOA, 30);
2559        let expected = Err(DecoderError::InvalidName);
2560        assert_eq!(got, expected);
2561        assert_eq!(d, o);
2562    }
2563
2564    #[test]
2565    fn untrusted_decoder_rdata_soa_nok_integer_fields_truncated() {
2566        let mut d = WireDecoder::new(b"\x00\
2567                                       \x03foo\x00\
2568                                       \x03bar\x00\
2569                                       \x01\x02\x03\x04\
2570                                       \x05\x06\x07\x08\
2571                                       \x09\x0a\x0b\x0c\
2572                                       \x0d\x0e\x0f\x10\
2573                                       \x11\x12\x13")
2574            .with_cursor_offset(1);
2575        let o = d.clone();
2576        let got = d.decode_rdata(class::IN, type_::SOA, 29);
2577        let expected = Err(DecoderError::UnexpectedEof);
2578        assert_eq!(got, expected);
2579        assert_eq!(d, o);
2580    }
2581
2582    #[test]
2583    fn untrusted_decoder_rdata_soa_nok_bad_rdlength() {
2584        let mut d = WireDecoder::new(b"\x00\
2585                                       \x03foo\x00\
2586                                       \x03bar\x00\
2587                                       \x01\x02\x03\x04\
2588                                       \x05\x06\x07\x08\
2589                                       \x09\x0a\x0b\x0c\
2590                                       \x0d\x0e\x0f\x10\
2591                                       \x11\x12\x13\x14")
2592            .with_cursor_offset(1);
2593        let o = d.clone();
2594        let got = d.decode_rdata(class::IN, type_::SOA, 29);
2595        let expected = Err(DecoderError::BadRdlength);
2596        assert_eq!(got, expected);
2597        assert_eq!(d, o);
2598    }
2599
2600    #[test]
2601    fn untrusted_decoder_resource_record_section_ok() {
2602        let mut d = WireDecoder::new(b"\x00\
2603                                         \x03foo\x00\
2604                                         \x00\x05\
2605                                         \x00\x01\
2606                                         \x00\x00\x03\xe8\
2607                                         \x00\x05\
2608                                         \x03bar\x00\
2609                                         \x03qux\x00\
2610                                         \x00\x05\
2611                                         \x00\x01\
2612                                         \x00\x00\x03\xe8\
2613                                         \x00\x05\
2614                                         \x03baz\x00")
2615            .with_cursor_offset(1);
2616        let o = d.clone();
2617        let got = d.decode_resource_record_section(2);
2618        let expected = Ok(ResourceRecordSection {
2619            count: 2,
2620            decoder: unsafe { o.as_trusted() },
2621        });
2622        assert_eq!(got, expected);
2623        assert_eq!(d, o.with_cursor_offset(40));
2624    }
2625
2626    #[test]
2627    fn untrusted_decoder_message_ok() {
2628        let b = b"\x00\
2629                  \x12\x34\x81\x80\
2630                  \x00\x01\x00\x02\
2631                  \x00\x00\x00\x00\
2632                  \x03foo\x00\
2633                  \x00\x01\
2634                  \x00\x01\
2635                  \x03foo\x00\
2636                  \x00\x01\
2637                  \x00\x01\
2638                  \x00\x00\x03\xe8\
2639                  \x00\x04\
2640                  \x01\x02\x03\x04\
2641                  \x03foo\x00\
2642                  \x00\x01\
2643                  \x00\x01\
2644                  \x00\x00\x03\xe8\
2645                  \x00\x04\
2646                  \x05\x06\x07\x08";
2647        let mut d = WireDecoder::new(b).with_cursor_offset(1);
2648        d.cursor = 1;
2649        let o = d.clone();
2650        let got = d.decode_message();
2651        let expected = Ok(WireMessage {
2652            id: 0x1234,
2653            flags: 0x8180,
2654            question_section: QuestionSection {
2655                count: 1,
2656                decoder: unsafe { o.with_cursor_offset(12).as_trusted() },
2657            },
2658            answer_section: ResourceRecordSection {
2659                count: 2,
2660                decoder: unsafe { o.with_cursor_offset(21).as_trusted() },
2661            },
2662            authority_section: ResourceRecordSection {
2663                count: 0,
2664                decoder: unsafe { o.with_cursor_offset(59).as_trusted() },
2665            },
2666            additional_section: ResourceRecordSection {
2667                count: 0,
2668                decoder: unsafe { o.with_cursor_offset(59).as_trusted() },
2669            },
2670        });
2671        assert_eq!(got, expected);
2672        assert_eq!(d, o.with_cursor_offset(59));
2673    }
2674
2675    #[test]
2676    fn untrusted_decoder_message_nok_unexpected_octets() {
2677        let b = b"\x00\
2678                  \x12\x34\x81\x80\
2679                  \x00\x01\x00\x02\
2680                  \x00\x00\x00\x00\
2681                  \x03foo\x00\
2682                  \x00\x01\
2683                  \x00\x01\
2684                  \x03foo\x00\
2685                  \x00\x01\
2686                  \x00\x01\
2687                  \x00\x00\x03\xe8\
2688                  \x00\x04\
2689                  \x01\x02\x03\x04\
2690                  \x03foo\x00\
2691                  \x00\x01\
2692                  \x00\x01\
2693                  \x00\x00\x03\xe8\
2694                  \x00\x04\
2695                  \x05\x06\x07\x08
2696                  extra octets here";
2697        let mut d = WireDecoder::new(b).with_cursor_offset(1);
2698        d.cursor = 1;
2699        let o = d.clone();
2700        let got = d.decode_message();
2701        let expected = Err(DecoderError::UnexpectedOctets);
2702        assert_eq!(got, expected);
2703        assert_eq!(d, o);
2704    }
2705
2706    #[test]
2707    fn trusted_decoder_u8() {
2708        let mut d = unsafe { TrustedDecoder::new(b"\x00\x12") }.with_cursor_offset(1);
2709        let o = d.clone();
2710        let got = unsafe { d.decode_u8_unchecked() };
2711        let expected = 18;
2712        assert_eq!(got, expected);
2713        assert_eq!(d, o.with_cursor_offset(std::mem::size_of::<u8>()));
2714    }
2715
2716    #[test]
2717    fn trusted_decoder_u16() {
2718        let mut d = unsafe { TrustedDecoder::new(b"\x00\x02\x05") }.with_cursor_offset(1);
2719        let o = d.clone();
2720        let got = unsafe { d.decode_u16_unchecked() };
2721        let expected = 517;
2722        assert_eq!(got, expected);
2723        assert_eq!(d, o.with_cursor_offset(std::mem::size_of::<u16>()));
2724    }
2725
2726    #[test]
2727    fn trusted_decoder_u32() {
2728        let mut d = unsafe { TrustedDecoder::new(b"\x00\x12\x34\x56\x78") }.with_cursor_offset(1);
2729        let o = d.clone();
2730        let got = unsafe { d.decode_u32_unchecked() };
2731        let expected = 0x12345678;
2732        assert_eq!(got, expected);
2733        assert_eq!(d, o.with_cursor_offset(std::mem::size_of::<u32>()));
2734    }
2735
2736    #[test]
2737    fn trusted_decoder_octets_empty() {
2738        let mut d = unsafe { TrustedDecoder::new(b"\x00") }.with_cursor_offset(1);
2739        let o = d.clone();
2740        let got = unsafe { d.decode_octets_unchecked(0) };
2741        let expected = &b""[..];
2742        assert_eq!(got, expected);
2743        assert_eq!(d, o.with_cursor_offset(0));
2744    }
2745
2746    #[test]
2747    fn trusted_decoder_octets_nonempty() {
2748        let mut d = unsafe { TrustedDecoder::new(b"\x00\x01\x02\x03") }.with_cursor_offset(1);
2749        let o = d.clone();
2750        let got = unsafe { d.decode_octets_unchecked(3) };
2751        let expected = &b"\x01\x02\x03"[..];
2752        assert_eq!(got, expected);
2753        assert_eq!(d, o.with_cursor_offset(3));
2754    }
2755
2756    #[test]
2757    fn trusted_decoder_class() {
2758        let mut d = unsafe { TrustedDecoder::new(b"\x00\x00\x01") }.with_cursor_offset(1);
2759        let o = d.clone();
2760        let got = unsafe { d.decode_class_unchecked() };
2761        let expected = class::IN;
2762        assert_eq!(got, expected);
2763        assert_eq!(d, o.with_cursor_offset(std::mem::size_of::<u16>()));
2764    }
2765
2766    #[test]
2767    fn trusted_decoder_qclass() {
2768        let mut d = unsafe { TrustedDecoder::new(b"\x00\x00\xff") }.with_cursor_offset(1);
2769        let o = d.clone();
2770        let got = unsafe { d.decode_qclass_unchecked() };
2771        let expected = qclass::ANY;
2772        assert_eq!(got, expected);
2773        assert_eq!(d, o.with_cursor_offset(std::mem::size_of::<u16>()));
2774    }
2775
2776    #[test]
2777    fn trusted_decoder_type() {
2778        let mut d = unsafe { TrustedDecoder::new(b"\x00\x00\x05") }.with_cursor_offset(1);
2779        let o = d.clone();
2780        let got = unsafe { d.decode_type_unchecked() };
2781        let expected = type_::CNAME;
2782        assert_eq!(got, expected);
2783        assert_eq!(d, o.with_cursor_offset(std::mem::size_of::<u16>()));
2784    }
2785
2786    #[test]
2787    fn trusted_decoder_qtype() {
2788        let mut d = unsafe { TrustedDecoder::new(b"\x00\x00\xff") }.with_cursor_offset(1);
2789        let o = d.clone();
2790        let got = unsafe { d.decode_qtype_unchecked() };
2791        let expected = qtype::ANY;
2792        assert_eq!(got, expected);
2793        assert_eq!(d, o.with_cursor_offset(std::mem::size_of::<u16>()));
2794    }
2795
2796    #[test]
2797    fn trusted_decoder_label_end() {
2798        let mut d = unsafe { TrustedDecoder::new(b"\x00\x00") }.with_cursor_offset(1);
2799        let o = d.clone();
2800        let got = unsafe { d.decode_label_unchecked() };
2801        let expected = None;
2802        assert_eq!(got, expected);
2803        assert_eq!(d, o.with_cursor_offset(1));
2804    }
2805
2806    #[test]
2807    fn trusted_decoder_label_uncompressed() {
2808        let mut d = unsafe { TrustedDecoder::new(b"\x00\x03foo") }.with_cursor_offset(1);
2809        let o = d.clone();
2810        let got = unsafe { d.decode_label_unchecked() };
2811        let expected = Some("foo");
2812        assert_eq!(got, expected);
2813        assert_eq!(d, o.with_cursor_offset(4));
2814    }
2815
2816    #[test]
2817    fn trusted_decoder_label_compressed() {
2818        let mut d = unsafe { TrustedDecoder::new(b"\x00\x03foo\x00\xc1") }.with_cursor_offset(6);
2819        let o = d.clone();
2820        let got = unsafe { d.decode_label_unchecked() };
2821        let expected = Some("foo");
2822        assert_eq!(got, expected);
2823        assert_eq!(d, TrustedDecoder { cursor: 5, ..o });
2824    }
2825
2826    #[test]
2827    fn trusted_decoder_name_empty() {
2828        let mut d = unsafe { TrustedDecoder::new(b"\x00\x00") }.with_cursor_offset(1);
2829        let o = d.clone();
2830        let got = unsafe { d.decode_name_unchecked() };
2831        let expected = WireName { decoder: o.clone() };
2832        assert_eq!(got, expected);
2833        assert_eq!(d, o.with_cursor_offset(1));
2834    }
2835
2836    #[test]
2837    fn trusted_decoder_name_uncompressed() {
2838        let mut d = unsafe {
2839                TrustedDecoder::new(b"\x00\
2840                                      \x03foo\
2841                                      \x03bar\
2842                                      \x00")
2843            }
2844            .with_cursor_offset(1);
2845        let o = d.clone();
2846        let got = unsafe { d.decode_name_unchecked() };
2847        let expected = WireName { decoder: o.clone() };
2848        assert_eq!(got, expected);
2849        assert_eq!(d, o.with_cursor_offset(9));
2850    }
2851
2852    #[test]
2853    fn trusted_decoder_name_compressed() {
2854        let mut d = unsafe { TrustedDecoder::new(b"\x00\x03foo\x00\xc1") }.with_cursor_offset(6);
2855        let o = d.clone();
2856        let got = unsafe { d.decode_name_unchecked() };
2857        let expected = WireName { decoder: o.clone() };
2858        assert_eq!(got, expected);
2859        assert_eq!(d, o.with_cursor_offset(1));
2860    }
2861
2862    #[test]
2863    fn trusted_decoder_rdata_other() {
2864        let mut d = unsafe { TrustedDecoder::new(b"\x00\x01\x02\x03") }.with_cursor_offset(1);
2865        let o = d.clone();
2866        let got = unsafe { d.decode_rdata_unchecked(Class(255), Type(255), 3) };
2867        let expected = RData::Other { octets: &b"\x01\x02\x03"[..] };
2868        assert_eq!(got, expected);
2869        assert_eq!(d, o.with_cursor_offset(3));
2870    }
2871
2872    #[test]
2873    fn trusted_decoder_rdata_a() {
2874        let mut d = unsafe { TrustedDecoder::new(b"\x00\x01\x02\x03\x04") }.with_cursor_offset(1);
2875        let o = d.clone();
2876        let got = unsafe { d.decode_rdata_unchecked(class::IN, type_::A, 4) };
2877        let expected = RData::A { address: std::net::Ipv4Addr::from_str("1.2.3.4").unwrap() };
2878        assert_eq!(got, expected);
2879        assert_eq!(d, o.with_cursor_offset(4));
2880    }
2881
2882    #[test]
2883    fn trusted_decoder_rdata_cname() {
2884        let mut d = unsafe { TrustedDecoder::new(b"\x00\x03foo\x00") }.with_cursor_offset(1);
2885        let o = d.clone();
2886        let got = unsafe { d.decode_rdata_unchecked(class::IN, type_::CNAME, 5) };
2887        let expected = RData::CName { cname: WireName { decoder: o.clone() } };
2888        assert_eq!(got, expected);
2889        assert_eq!(d, o.with_cursor_offset(5));
2890    }
2891
2892    #[test]
2893    fn trusted_decoder_rdata_ns() {
2894        let mut d = unsafe { TrustedDecoder::new(b"\x00\x03foo\x00") }.with_cursor_offset(1);
2895        let o = d.clone();
2896        let got = unsafe { d.decode_rdata_unchecked(class::IN, type_::NS, 5) };
2897        let expected = RData::NS { nsdname: WireName { decoder: o.clone() } };
2898        assert_eq!(got, expected);
2899        assert_eq!(d, o.with_cursor_offset(5));
2900    }
2901
2902    #[test]
2903    fn trusted_decoder_question() {
2904        let mut d = unsafe {
2905                TrustedDecoder::new(b"\x00\
2906                                      \x03foo\x00\x00\x05\x00\x01")
2907            }
2908            .with_cursor_offset(1);
2909        let o = d.clone();
2910        let got = unsafe { d.decode_question_unchecked() };
2911        let expected = Question::new(WireName { decoder: o.clone() }, qtype::CNAME, qclass::IN);
2912        assert_eq!(got, expected);
2913        assert_eq!(d, o.with_cursor_offset(9));
2914    }
2915
2916    #[test]
2917    fn trusted_decoder_rdata_soa() {
2918        let mut d = unsafe {
2919                TrustedDecoder::new(b"\x00\
2920                                      \x03foo\x00\
2921                                      \x03bar\x00\
2922                                      \x01\x02\x03\x04\
2923                                      \x05\x06\x07\x08\
2924                                      \x09\x0a\x0b\x0c\
2925                                      \x0d\x0e\x0f\x10\
2926                                      \x11\x12\x13\x14")
2927            }
2928            .with_cursor_offset(1);
2929        let o = d.clone();
2930        let got = unsafe { d.decode_rdata_unchecked(class::IN, type_::SOA, 30) };
2931        let expected = RData::SOA {
2932            mname: WireName { decoder: o.clone() },
2933            rname: WireName { decoder: o.clone().with_cursor_offset(5) },
2934            serial: SerialNumber(0x01020304),
2935            refresh: Ttl(0x05060708),
2936            retry: Ttl(0x090a0b0c),
2937            expire: Ttl(0x0d0e0f10),
2938            minimum: Ttl(0x11121314),
2939        };
2940        assert_eq!(got, expected);
2941        assert_eq!(d, o.with_cursor_offset(30));
2942    }
2943
2944    #[test]
2945    fn trusted_decoder_resource_record() {
2946        let mut d = unsafe {
2947                TrustedDecoder::new(b"\x00\
2948                                      \x03foo\x00\
2949                                      \x00\x05\
2950                                      \x00\x01\
2951                                      \x00\x00\x03\xe8\
2952                                      \x00\x05\
2953                                      \x03bar\x00")
2954            }
2955            .with_cursor_offset(1);
2956        let o = d.clone();
2957        let got = unsafe { d.decode_resource_record_unchecked() };
2958        let expected =
2959            ResourceRecord::new(WireName { decoder: o.clone() },
2960                                type_::CNAME,
2961                                class::IN,
2962                                Ttl(1000),
2963                                RData::CName { cname: WireName { decoder: o.clone().with_cursor_offset(15) } });
2964        assert_eq!(got, expected);
2965        assert_eq!(d, o.with_cursor_offset(20));
2966    }
2967}