Skip to main content

hickory_proto/serialize/binary/
encoder.rs

1// Copyright 2015-2023 Benjamin Fry <benjaminfry@me.com>
2//
3// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
4// https://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
5// https://opensource.org/licenses/MIT>, at your option. This file may not be
6// copied, modified, or distributed except according to those terms.
7
8use alloc::vec::Vec;
9use core::{
10    marker::PhantomData,
11    ops::{Deref, DerefMut},
12};
13
14use super::BinEncodable;
15use crate::error::{ProtoError, ProtoResult};
16
17// this is private to make sure there is no accidental access to the inner buffer.
18mod private {
19    use alloc::vec::Vec;
20
21    use crate::{ProtoError, error::ProtoResult};
22
23    /// A wrapper for a buffer that guarantees writes never exceed a defined set of bytes
24    pub(super) struct MaximalBuf<'a> {
25        max_size: usize,
26        buffer: &'a mut Vec<u8>,
27    }
28
29    impl<'a> MaximalBuf<'a> {
30        pub(super) fn new(max_size: u16, buffer: &'a mut Vec<u8>) -> Self {
31            MaximalBuf {
32                max_size: max_size as usize,
33                buffer,
34            }
35        }
36
37        /// Sets the maximum size to enforce
38        pub(super) fn set_max_size(&mut self, max: u16) {
39            self.max_size = max as usize;
40        }
41
42        /// Returns the maximum size currently enforced
43        pub(super) fn max_size(&self) -> u16 {
44            self.max_size as u16
45        }
46
47        pub(super) fn write(&mut self, offset: usize, data: &[u8]) -> ProtoResult<()> {
48            debug_assert!(offset <= self.buffer.len());
49            if offset + data.len() > self.max_size {
50                return Err(ProtoError::MaxBufferSizeExceeded(self.max_size));
51            }
52
53            if offset == self.buffer.len() {
54                self.buffer.extend(data);
55                return Ok(());
56            }
57
58            let end = offset + data.len();
59            if end > self.buffer.len() {
60                self.buffer.resize(end, 0);
61            }
62
63            self.buffer[offset..end].copy_from_slice(data);
64            Ok(())
65        }
66
67        pub(super) fn reserve(&mut self, offset: usize, len: usize) -> ProtoResult<()> {
68            let end = offset + len;
69            if end > self.max_size {
70                return Err(ProtoError::MaxBufferSizeExceeded(self.max_size));
71            }
72
73            self.buffer.resize(end, 0);
74            Ok(())
75        }
76
77        /// truncates are always safe
78        pub(super) fn truncate(&mut self, len: usize) {
79            self.buffer.truncate(len)
80        }
81
82        /// returns the length of the underlying buffer
83        pub(super) fn len(&self) -> usize {
84            self.buffer.len()
85        }
86
87        /// Immutable reads are always safe
88        pub(super) fn buffer(&'a self) -> &'a [u8] {
89            self.buffer as &'a [u8]
90        }
91
92        /// Returns a reference to the internal buffer
93        pub(super) fn into_bytes(self) -> &'a Vec<u8> {
94            self.buffer
95        }
96    }
97}
98
99/// Encode DNS messages and resource record types.
100pub struct BinEncoder<'a> {
101    offset: usize,
102    buffer: private::MaximalBuf<'a>,
103    /// start of label pointers with their labels in fully decompressed form for easy comparison, smallvec here?
104    name_pointers: Vec<(usize, Vec<u8>)>,
105    /// Whether the encoder should use the DNSSEC canonical form for RDATA.
106    canonical_form: bool,
107    /// How names should be encoded.
108    name_encoding: NameEncoding,
109    /// Number of names encoded with compression enabled.
110    pub(crate) compressed_name_count: usize,
111}
112
113impl<'a> BinEncoder<'a> {
114    /// Create a new encoder with the Vec to fill
115    pub fn new(buf: &'a mut Vec<u8>) -> Self {
116        Self::with_offset(buf, 0)
117    }
118
119    /// Begins the encoder at the given offset
120    ///
121    /// This is used for pointers. If this encoder is starting at some point further in
122    ///  the sequence of bytes, for the proper offset of the pointer, the offset accounts for that
123    ///  by using the offset to add to the pointer location being written.
124    ///
125    /// # Arguments
126    ///
127    /// * `offset` - index at which to start writing into the buffer
128    pub fn with_offset(buf: &'a mut Vec<u8>, offset: u32) -> Self {
129        if buf.capacity() < 512 {
130            let reserve = 512 - buf.capacity();
131            buf.reserve(reserve);
132        }
133
134        BinEncoder {
135            offset: offset as usize,
136            // TODO: add max_size to signature
137            buffer: private::MaximalBuf::new(u16::MAX, buf),
138            name_pointers: Vec::new(),
139            canonical_form: false,
140            name_encoding: NameEncoding::Compressed,
141            compressed_name_count: 0,
142        }
143    }
144
145    // TODO: move to constructor (kept for backward compatibility)
146    /// Sets the maximum size of the buffer
147    ///
148    /// DNS message lens must be smaller than u16::max_value due to hard limits in the protocol
149    ///
150    /// *this method will move to the constructor in a future release*
151    pub fn set_max_size(&mut self, max: u16) {
152        self.buffer.set_max_size(max);
153    }
154
155    /// Returns the maximum size of the buffer currently in effect
156    pub(crate) fn max_size(&self) -> u16 {
157        self.buffer.max_size()
158    }
159
160    /// Returns a reference to the internal buffer
161    pub fn into_bytes(self) -> &'a Vec<u8> {
162        self.buffer.into_bytes()
163    }
164
165    /// Returns the length of the buffer
166    pub fn len(&self) -> usize {
167        self.buffer.len()
168    }
169
170    /// Returns `true` if the buffer is empty
171    pub fn is_empty(&self) -> bool {
172        self.buffer.buffer().is_empty()
173    }
174
175    /// Returns the current offset into the buffer
176    pub fn offset(&self) -> usize {
177        self.offset
178    }
179
180    /// sets the current offset to the new offset
181    pub fn set_offset(&mut self, offset: usize) {
182        self.offset = offset;
183    }
184
185    /// If set to true, then records will be written into the buffer in DNSSEC canonical form
186    pub fn set_canonical_form(&mut self, canonical_form: bool) {
187        self.canonical_form = canonical_form;
188    }
189
190    /// Returns true if the encoder is writing in DNSSEC canonical form
191    pub fn is_canonical_form(&self) -> bool {
192        self.canonical_form
193    }
194
195    /// Select how names are encoded
196    pub fn set_name_encoding(&mut self, name_encoding: NameEncoding) {
197        self.name_encoding = name_encoding;
198    }
199
200    /// Returns the current name encoding mode
201    pub fn name_encoding(&self) -> NameEncoding {
202        self.name_encoding
203    }
204
205    /// Returns a guard type that uses a different name encoding mode.
206    pub fn with_name_encoding<'e>(
207        &'e mut self,
208        name_encoding: NameEncoding,
209    ) -> ModalEncoder<'a, 'e> {
210        let previous_name_encoding = self.name_encoding();
211
212        self.set_name_encoding(name_encoding);
213
214        ModalEncoder {
215            previous_name_encoding,
216            inner: self,
217        }
218    }
219
220    /// Returns a guard type that uses a different name encoding mode, for RDATA.
221    ///
222    /// If the encoder is using canonical form, name compression will not be used. Otherwise, name
223    /// compression will be used for standard record types.
224    ///
225    /// If the encoder is using canonical form, the case of names will depend on the record type.
226    /// Otherwise, the case will be unchanged.
227    pub fn with_rdata_behavior<'e>(
228        &'e mut self,
229        rdata_encoding: RDataEncoding,
230    ) -> ModalEncoder<'a, 'e> {
231        let previous_name_encoding = self.name_encoding();
232
233        match (rdata_encoding, self.is_canonical_form()) {
234            (RDataEncoding::StandardRecord, true) | (RDataEncoding::Canonical, true) => {
235                self.set_name_encoding(NameEncoding::UncompressedLowercase)
236            }
237            (RDataEncoding::StandardRecord, false) => {}
238            (RDataEncoding::Canonical, false)
239            | (RDataEncoding::Other, true)
240            | (RDataEncoding::Other, false) => self.set_name_encoding(NameEncoding::Uncompressed),
241        }
242
243        ModalEncoder {
244            previous_name_encoding,
245            inner: self,
246        }
247    }
248
249    /// trims to the current offset
250    pub fn trim(&mut self) {
251        let offset = self.offset;
252        self.buffer.truncate(offset);
253        self.name_pointers.retain(|&(start, _)| start < offset);
254    }
255
256    // /// returns an error if the maximum buffer size would be exceeded with the addition number of elements
257    // ///
258    // /// and reserves the additional space in the buffer
259    // fn enforce_size(&mut self, additional: usize) -> ProtoResult<()> {
260    //     if (self.buffer.len() + additional) > self.max_size {
261    //         Err(ProtoErrorKind::MaxBufferSizeExceeded(self.max_size).into())
262    //     } else {
263    //         self.reserve(additional);
264    //         Ok(())
265    //     }
266    // }
267
268    /// borrow a slice from the encoder
269    pub fn slice_of(&self, start: usize, end: usize) -> &[u8] {
270        assert!(start < self.offset);
271        assert!(end <= self.buffer.len());
272        &self.buffer.buffer()[start..end]
273    }
274
275    /// Stores a label pointer to an already written label
276    ///
277    /// The location is the current position in the buffer
278    ///  implicitly, it is expected that the name will be written to the stream after the current index.
279    pub fn store_label_pointer(&mut self, start: usize, end: usize) {
280        assert!(start <= (u16::MAX as usize));
281        assert!(end <= (u16::MAX as usize));
282        assert!(start <= end);
283        if self.offset < 0x3FFF_usize && self.name_pointers.len() < COMPRESSION_CANDIDATE_LIMIT {
284            self.name_pointers
285                .push((start, self.slice_of(start, end).to_vec())); // the next char will be at the len() location
286        }
287    }
288
289    /// Looks up the index of an already written label
290    pub fn get_label_pointer(&self, start: usize, end: usize) -> Option<u16> {
291        let search = self.slice_of(start, end);
292
293        for (match_start, matcher) in &self.name_pointers {
294            if matcher.as_slice() == search {
295                assert!(match_start <= &(u16::MAX as usize));
296                return Some(*match_start as u16);
297            }
298        }
299
300        None
301    }
302
303    /// Emit one byte into the buffer
304    pub fn emit(&mut self, b: u8) -> ProtoResult<()> {
305        self.buffer.write(self.offset, &[b])?;
306        self.offset += 1;
307        Ok(())
308    }
309
310    /// matches description from above.
311    ///
312    /// ```
313    /// use hickory_proto::serialize::binary::BinEncoder;
314    ///
315    /// let mut bytes: Vec<u8> = Vec::new();
316    /// {
317    ///   let mut encoder: BinEncoder = BinEncoder::new(&mut bytes);
318    ///   encoder.emit_character_data("abc");
319    /// }
320    /// assert_eq!(bytes, vec![3,b'a',b'b',b'c']);
321    /// ```
322    pub fn emit_character_data<S: AsRef<[u8]>>(&mut self, char_data: S) -> ProtoResult<()> {
323        let char_bytes = char_data.as_ref();
324        if char_bytes.len() > 255 {
325            return Err(ProtoError::CharacterDataTooLong {
326                max: 255,
327                len: char_bytes.len(),
328            });
329        }
330
331        self.emit_character_data_unrestricted(char_data)
332    }
333
334    /// Emit character data of unrestricted length
335    ///
336    /// Although character strings are typically restricted to being no longer than 255 characters,
337    /// some modern standards allow longer strings to be encoded.
338    pub fn emit_character_data_unrestricted<S: AsRef<[u8]>>(&mut self, data: S) -> ProtoResult<()> {
339        // first the length is written
340        let data = data.as_ref();
341        self.emit(data.len() as u8)?;
342        self.write_slice(data)
343    }
344
345    /// Emit one byte into the buffer
346    pub fn emit_u8(&mut self, data: u8) -> ProtoResult<()> {
347        self.emit(data)
348    }
349
350    /// Writes a u16 in network byte order to the buffer
351    pub fn emit_u16(&mut self, data: u16) -> ProtoResult<()> {
352        self.write_slice(&data.to_be_bytes())
353    }
354
355    /// Writes an i32 in network byte order to the buffer
356    pub fn emit_i32(&mut self, data: i32) -> ProtoResult<()> {
357        self.write_slice(&data.to_be_bytes())
358    }
359
360    /// Writes an u32 in network byte order to the buffer
361    pub fn emit_u32(&mut self, data: u32) -> ProtoResult<()> {
362        self.write_slice(&data.to_be_bytes())
363    }
364
365    fn write_slice(&mut self, data: &[u8]) -> ProtoResult<()> {
366        self.buffer.write(self.offset, data)?;
367        self.offset += data.len();
368        Ok(())
369    }
370
371    /// Writes the byte slice to the stream
372    pub fn emit_vec(&mut self, data: &[u8]) -> ProtoResult<()> {
373        self.write_slice(data)
374    }
375
376    /// Emits all the elements of an Iterator to the encoder
377    pub fn emit_all<'e, I: Iterator<Item = &'e E>, E: 'e + BinEncodable>(
378        &mut self,
379        mut iter: I,
380    ) -> ProtoResult<usize> {
381        self.emit_iter(&mut iter)
382    }
383
384    // TODO: dedup with above emit_all
385    /// Emits all the elements of an Iterator to the encoder
386    pub fn emit_all_refs<'r, 'e, I, E>(&mut self, iter: I) -> ProtoResult<usize>
387    where
388        'e: 'r,
389        I: Iterator<Item = &'r &'e E>,
390        E: 'r + 'e + BinEncodable,
391    {
392        let mut iter = iter.cloned();
393        self.emit_iter(&mut iter)
394    }
395
396    /// emits all items in the iterator, return the number emitted
397    pub fn emit_iter<'e, I: Iterator<Item = &'e E>, E: 'e + BinEncodable>(
398        &mut self,
399        iter: &mut I,
400    ) -> ProtoResult<usize> {
401        let mut count = 0;
402        for i in iter {
403            let rollback = self.set_rollback();
404            if let Err(e) = i.emit(self) {
405                return Err(match &e {
406                    ProtoError::MaxBufferSizeExceeded(_) => {
407                        rollback.rollback(self);
408                        ProtoError::NotAllRecordsWritten { count }
409                    }
410                    _ => e,
411                });
412            }
413
414            count += 1;
415        }
416        Ok(count)
417    }
418
419    /// capture a location to write back to
420    pub fn place<T: EncodedSize>(&mut self) -> ProtoResult<Place<T>> {
421        let index = self.offset;
422
423        // resize the buffer
424        self.buffer.reserve(self.offset, T::LEN)?;
425
426        // update the offset
427        self.offset += T::LEN;
428
429        Ok(Place {
430            start_index: index,
431            phantom: PhantomData,
432        })
433    }
434
435    /// calculates the length of data written since the place was creating
436    pub fn len_since_place<T: EncodedSize>(&self, place: &Place<T>) -> usize {
437        (self.offset - place.start_index) - T::LEN
438    }
439
440    /// write back to a previously captured location
441    pub fn emit_at<T: EncodedSize>(&mut self, place: Place<T>, data: T) -> ProtoResult<()> {
442        // preserve current index
443        let current_index = self.offset;
444
445        // reset the current index back to place before writing
446        //   this is an assert because it's programming error for it to be wrong.
447        assert!(place.start_index < current_index);
448        self.offset = place.start_index;
449
450        // emit the data to be written at this place
451        let emit_result = data.emit(self);
452
453        // double check that the current number of bytes were written
454        //   this is an assert because it's programming error for it to be wrong.
455        assert!((self.offset - place.start_index) == T::LEN);
456
457        // reset to original location
458        self.offset = current_index;
459
460        emit_result
461    }
462
463    fn set_rollback(&self) -> Rollback {
464        Rollback {
465            offset: self.offset(),
466            pointers: self.name_pointers.len(),
467        }
468    }
469}
470
471/// Maximum number of label pointers we will store for later use in name compression.
472///
473/// This is chosen to be a power of two, so that we use the full capacity of the backing vector.
474/// With the current limits, name compression searches make up a small portion of the time it takes
475/// to encode pathologically large messages.
476const COMPRESSION_CANDIDATE_LIMIT: usize = 64;
477
478/// Selects how names should be encoded.
479#[derive(Clone, Copy)]
480pub enum NameEncoding {
481    /// Encode names with compression enabled. The case of the name is unchanged.
482    Compressed,
483    /// Encode names without compression. The case of the name is unchanged.
484    Uncompressed,
485    /// Encode names transformed to lowercase and without compression.
486    UncompressedLowercase,
487}
488
489/// Determines how names inside RDATA are encoded, depending on the record type and whether DNSSEC
490/// canonical form is used.
491#[derive(Clone, Copy)]
492pub enum RDataEncoding {
493    /// Applicable to standard record types defined in [RFC 1035 section
494    /// 3.3](https://datatracker.ietf.org/doc/html/rfc1035#section-3.3).
495    ///
496    /// Names in the RDATA may be compressed, since these record types are well-known. When encoding
497    /// in DNSSEC canonical form, compression is not used, and names are transformed to lowercase.
498    /// Note that all standard types that contain names in the RDATA are also on the list in [RFC
499    /// 4034 section 6.2](https://datatracker.ietf.org/doc/html/rfc4034#section-6.2).
500    StandardRecord,
501    /// Applicable to record types that were defined after RFC 1035, for which the DNSSEC canonical
502    /// form of the RDATA has names transformed to lowercase. Compression is never used.
503    ///
504    /// This applies to the list of record types defined in [RFC 4034 section
505    /// 6.2](https://datatracker.ietf.org/doc/html/rfc4034#section-6.2) and modified by [RFC 6840,
506    /// section 5.1](https://datatracker.ietf.org/doc/html/rfc6840#section-5.1).
507    Canonical,
508    /// Applicable to record types for which names in the RDATA are never compressed and never
509    /// transformed to lowercase.
510    ///
511    /// All newly defined record types must have this behavior, per [RFC 3597 section
512    /// 4](https://datatracker.ietf.org/doc/html/rfc3597#section-4) and [section
513    /// 7](https://datatracker.ietf.org/doc/html/rfc3597#section-7).
514    Other,
515}
516
517/// This wraps a [BinEncoder] and applies different name encoding options.
518///
519/// Original name encoding options will be restored when this is dropped.
520pub struct ModalEncoder<'a, 'e> {
521    previous_name_encoding: NameEncoding,
522    inner: &'e mut BinEncoder<'a>,
523}
524
525impl<'a> Deref for ModalEncoder<'a, '_> {
526    type Target = BinEncoder<'a>;
527
528    fn deref(&self) -> &Self::Target {
529        self.inner
530    }
531}
532
533impl DerefMut for ModalEncoder<'_, '_> {
534    fn deref_mut(&mut self) -> &mut Self::Target {
535        self.inner
536    }
537}
538
539impl Drop for ModalEncoder<'_, '_> {
540    fn drop(&mut self) {
541        self.inner.set_name_encoding(self.previous_name_encoding);
542    }
543}
544
545/// A trait to return the size of a type as it will be encoded in DNS
546///
547/// it does not necessarily equal `core::mem::size_of`, though it might, especially for primitives
548pub trait EncodedSize: BinEncodable {
549    /// Number of bytes used when encoding the type
550    const LEN: usize;
551}
552
553impl EncodedSize for u16 {
554    const LEN: usize = 2;
555}
556
557/// A place in the encoded stream that the encoder can rewrite
558#[derive(Debug)]
559#[must_use = "data must be written back to the place"]
560pub struct Place<T: EncodedSize> {
561    start_index: usize,
562    phantom: PhantomData<T>,
563}
564
565impl<T: EncodedSize> Place<T> {
566    /// Replaces the data at this place with the given data
567    pub fn replace(self, encoder: &mut BinEncoder<'_>, data: T) -> ProtoResult<()> {
568        encoder.emit_at(self, data)
569    }
570}
571
572/// A type representing a rollback point in a stream
573pub(crate) struct Rollback {
574    offset: usize,
575    pointers: usize,
576}
577
578impl Rollback {
579    pub(crate) fn rollback(self, encoder: &mut BinEncoder<'_>) {
580        let Self { offset, pointers } = self;
581        encoder.set_offset(offset);
582        encoder.name_pointers.truncate(pointers);
583        encoder.trim();
584    }
585}
586
587#[cfg(test)]
588mod tests {
589    #[cfg(any(feature = "std", feature = "no-std-rand"))]
590    use core::str::FromStr;
591
592    use super::*;
593    use crate::{op::Message, serialize::binary::BinDecoder};
594    #[cfg(any(feature = "std", feature = "no-std-rand"))]
595    use crate::{
596        op::Query,
597        rr::Name,
598        rr::{
599            RData, Record, RecordType,
600            rdata::{CNAME, SRV, TXT},
601        },
602    };
603
604    #[test]
605    fn test_label_compression_regression() {
606        // https://github.com/hickory-dns/hickory-dns/issues/339
607        /*
608        ;; QUESTION SECTION:
609        ;bluedot.is.autonavi.com.gds.alibabadns.com. IN AAAA
610
611        ;; AUTHORITY SECTION:
612        gds.alibabadns.com.     1799    IN      SOA     gdsns1.alibabadns.com. none. 2015080610 1800 600 3600 360
613        */
614        let data = vec![
615            154, 50, 129, 128, 0, 1, 0, 0, 0, 1, 0, 1, 7, 98, 108, 117, 101, 100, 111, 116, 2, 105,
616            115, 8, 97, 117, 116, 111, 110, 97, 118, 105, 3, 99, 111, 109, 3, 103, 100, 115, 10,
617            97, 108, 105, 98, 97, 98, 97, 100, 110, 115, 3, 99, 111, 109, 0, 0, 28, 0, 1, 192, 36,
618            0, 6, 0, 1, 0, 0, 7, 7, 0, 35, 6, 103, 100, 115, 110, 115, 49, 192, 40, 4, 110, 111,
619            110, 101, 0, 120, 27, 176, 162, 0, 0, 7, 8, 0, 0, 2, 88, 0, 0, 14, 16, 0, 0, 1, 104, 0,
620            0, 41, 2, 0, 0, 0, 0, 0, 0, 0,
621        ];
622
623        let msg = Message::from_vec(&data).unwrap();
624        msg.to_bytes().unwrap();
625    }
626
627    #[test]
628    fn test_place() {
629        let mut buf = vec![];
630        {
631            let mut encoder = BinEncoder::new(&mut buf);
632            let place = encoder.place::<u16>().unwrap();
633            assert_eq!(encoder.len_since_place(&place), 0);
634
635            encoder.emit(42_u8).expect("failed 0");
636            assert_eq!(encoder.len_since_place(&place), 1);
637
638            encoder.emit(48_u8).expect("failed 1");
639            assert_eq!(encoder.len_since_place(&place), 2);
640
641            place
642                .replace(&mut encoder, 4_u16)
643                .expect("failed to replace");
644            drop(encoder);
645        }
646
647        assert_eq!(buf.len(), 4);
648
649        let mut decoder = BinDecoder::new(&buf);
650        let written = decoder.read_u16().expect("cound not read u16").unverified();
651
652        assert_eq!(written, 4);
653    }
654
655    #[test]
656    fn test_max_size() {
657        let mut buf = vec![];
658        let mut encoder = BinEncoder::new(&mut buf);
659
660        encoder.set_max_size(5);
661        encoder.emit(0).expect("failed to write");
662        encoder.emit(1).expect("failed to write");
663        encoder.emit(2).expect("failed to write");
664        encoder.emit(3).expect("failed to write");
665        encoder.emit(4).expect("failed to write");
666        let error = encoder.emit(5).unwrap_err();
667
668        match error {
669            ProtoError::MaxBufferSizeExceeded(_) => (),
670            _ => panic!(),
671        }
672    }
673
674    #[test]
675    fn test_max_size_0() {
676        let mut buf = vec![];
677        let mut encoder = BinEncoder::new(&mut buf);
678
679        encoder.set_max_size(0);
680        let error = encoder.emit(0).unwrap_err();
681
682        match error {
683            ProtoError::MaxBufferSizeExceeded(_) => (),
684            _ => panic!(),
685        }
686    }
687
688    #[test]
689    fn test_max_size_place() {
690        let mut buf = vec![];
691        let mut encoder = BinEncoder::new(&mut buf);
692
693        encoder.set_max_size(2);
694        let place = encoder.place::<u16>().expect("place failed");
695        place.replace(&mut encoder, 16).expect("placeback failed");
696
697        let error = encoder.place::<u16>().unwrap_err();
698
699        match error {
700            ProtoError::MaxBufferSizeExceeded(_) => (),
701            _ => panic!(),
702        }
703    }
704
705    #[cfg(any(feature = "std", feature = "no-std-rand"))]
706    #[test]
707    fn test_message_truncation_trims_buffer() {
708        // A response whose answers do not fit within the 512-byte non-EDNS UDP payload
709        // limit. Encoding must truncate part way through a record, and the partially
710        // written record must be rolled back without leaving trailing bytes in the buffer
711        // beyond the records that were actually emitted.
712        let name = Name::from_str("example.com.").unwrap();
713        let mut msg = Message::query();
714        msg.add_query(Query::query(name.clone(), RecordType::TXT));
715        for _ in 0..3 {
716            msg.add_answer(Record::from_rdata(
717                name.clone(),
718                0,
719                RData::TXT(TXT::try_from("a".repeat(255)).unwrap()),
720            ));
721        }
722
723        let mut buf = vec![];
724        let mut encoder = BinEncoder::new(&mut buf);
725        encoder.set_max_size(512);
726        msg.emit(&mut encoder).unwrap();
727        drop(encoder);
728
729        // The encoded message must respect the payload limit...
730        assert!(
731            buf.len() <= 512,
732            "encoded {} bytes exceeds limit",
733            buf.len()
734        );
735
736        // ...and must not contain any bytes from the record that did not fit. If the
737        // partial record were left behind, decoding (which stops after the header's record
738        // counts) would drop those trailing bytes, so a clean re-encode would be shorter.
739        let decoded = Message::from_vec(&buf).unwrap();
740        assert!(decoded.truncation);
741        assert_eq!(decoded.to_vec().unwrap(), buf);
742    }
743
744    #[cfg(any(feature = "std", feature = "no-std-rand"))]
745    #[test]
746    fn test_target_compression() {
747        let mut msg = Message::query();
748        msg.add_query(Query::query(
749            Name::from_str("www.google.com.").unwrap(),
750            RecordType::A,
751        ))
752        .add_answer(Record::from_rdata(
753            Name::from_str("www.google.com.").unwrap(),
754            0,
755            RData::SRV(SRV::new(
756                0,
757                0,
758                0,
759                Name::from_str("www.compressme.com.").unwrap(),
760            )),
761        ))
762        .add_additional(Record::from_rdata(
763            Name::from_str("www.google.com.").unwrap(),
764            0,
765            RData::SRV(SRV::new(
766                0,
767                0,
768                0,
769                Name::from_str("www.compressme.com.").unwrap(),
770            )),
771        ))
772        // name here should use compressed label from target in previous records
773        .add_answer(Record::from_rdata(
774            Name::from_str("www.compressme.com.").unwrap(),
775            0,
776            RData::CNAME(CNAME(Name::from_str("www.foo.com.").unwrap())),
777        ));
778
779        let bytes = msg.to_vec().unwrap();
780        // label is compressed pointing to target, would be 145 otherwise
781        assert_eq!(bytes.len(), 130);
782        // check re-serializing
783        assert!(Message::from_vec(&bytes).is_ok());
784    }
785}