Skip to main content

hickory_proto/rr/rdata/
txt.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
8//! text records for storing arbitrary data
9use alloc::{boxed::Box, string::String, vec::Vec};
10use core::fmt;
11
12#[cfg(feature = "serde")]
13use serde::{Deserialize, Serialize};
14
15use crate::{
16    error::ProtoResult,
17    rr::{RData, RecordData, RecordDataDecodable, RecordType},
18    serialize::{binary::*, txt::ParseError},
19};
20
21/// [RFC 1035, DOMAIN NAMES - IMPLEMENTATION AND SPECIFICATION, November 1987](https://tools.ietf.org/html/rfc1035)
22///
23/// ```text
24/// 3.3.14. TXT RDATA format
25///
26///     +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
27///     /                   TXT-DATA                    /
28///     +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
29///
30///
31/// TXT RRs are used to hold descriptive text.  The semantics of the text
32/// depends on the domain where it is found.
33/// ```
34#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
35#[derive(Debug, PartialEq, Eq, Hash, Clone)]
36#[non_exhaustive]
37pub struct TXT {
38    /// ```text
39    /// TXT-DATA        One or more <character-string>s.
40    /// ```
41    pub txt_data: Box<[Box<[u8]>]>,
42}
43
44impl TXT {
45    /// Creates a new TXT record data from bytes.
46    ///
47    /// Fails if any element of the iterator is longer than 255 bytes, or if the total length of
48    /// all elements exceeds 65535 bytes.
49    pub fn try_new(
50        txt_data: impl Iterator<Item = impl Into<Box<[u8]>>>,
51    ) -> Result<Self, ParseError> {
52        Self::new_inner(txt_data.map(Into::into).collect::<Box<[_]>>())
53    }
54
55    /// Creates a new TXT record data.
56    #[deprecated(since = "0.26.4", note = "use `try_new()` or `try_from()` instead")]
57    pub fn new(txt_data: Vec<String>) -> Self {
58        Self {
59            txt_data: txt_data
60                .into_iter()
61                .map(|s| s.into_bytes().into_boxed_slice())
62                .collect::<Vec<_>>()
63                .into_boxed_slice(),
64        }
65    }
66
67    /// Creates a new TXT record data from bytes.
68    #[deprecated(since = "0.26.4", note = "use `try_new()` or `try_from()` instead")]
69    pub fn from_bytes(txt_data: Vec<&[u8]>) -> Self {
70        Self {
71            txt_data: txt_data
72                .into_iter()
73                .map(|s| s.to_vec().into_boxed_slice())
74                .collect::<Vec<_>>()
75                .into_boxed_slice(),
76        }
77    }
78
79    /// Parse the RData from a set of Tokens
80    #[allow(clippy::unnecessary_wraps)]
81    pub(crate) fn from_tokens<'i, I: Iterator<Item = &'i str>>(
82        tokens: I,
83    ) -> Result<Self, ParseError> {
84        let txt_data = tokens
85            .map(|s| Box::from(s.as_bytes()))
86            .collect::<Box<[_]>>();
87
88        if txt_data.is_empty() {
89            return Err(ParseError::Message(
90                "TXT record must contain at least one character-string",
91            ));
92        }
93
94        Self::new_inner(txt_data)
95    }
96
97    fn new_inner(txt_data: Box<[Box<[u8]>]>) -> Result<Self, ParseError> {
98        let mut total = 0;
99        for part in txt_data.iter() {
100            // Each character-string is encoded with a one-octet length prefix.
101            total += 1 + part.len();
102            if part.len() > 255 {
103                return Err(ParseError::Message(
104                    "character-string in TXT record must not exceed 255 octets",
105                ));
106            }
107        }
108
109        if total > 65535 {
110            return Err(ParseError::Message(
111                "TXT record data must not exceed 65535 octets",
112            ));
113        }
114
115        Ok(Self { txt_data })
116    }
117}
118
119impl BinEncodable for TXT {
120    fn emit(&self, encoder: &mut BinEncoder<'_>) -> ProtoResult<()> {
121        for s in &self.txt_data {
122            encoder.emit_character_data(s)?;
123        }
124
125        Ok(())
126    }
127}
128
129impl RecordDataDecodable<'_> for TXT {
130    fn read_data(
131        decoder: &mut BinDecoder<'_>,
132        rdata_length: Restrict<u16>,
133    ) -> Result<Self, DecodeError> {
134        let data_len = decoder.len();
135        let mut strings = Vec::with_capacity(1);
136
137        // no unsafe usage of rdata length after this point
138        let rdata_length =
139            rdata_length.map(|u| u as usize).unverified(/*used as a higher bound, safely*/);
140        while data_len - decoder.len() < rdata_length {
141            let string = decoder.read_character_data()?.unverified(/*any data should be validate in TXT usage*/);
142            strings.push(string.to_vec().into_boxed_slice());
143        }
144        Ok(Self {
145            txt_data: strings.into_boxed_slice(),
146        })
147    }
148}
149
150impl RecordData for TXT {
151    fn try_borrow(data: &RData) -> Option<&Self> {
152        match data {
153            RData::TXT(data) => Some(data),
154            _ => None,
155        }
156    }
157
158    fn record_type(&self) -> RecordType {
159        RecordType::TXT
160    }
161
162    fn into_rdata(self) -> RData {
163        RData::TXT(self)
164    }
165}
166
167impl TryFrom<String> for TXT {
168    type Error = ParseError;
169
170    fn try_from(value: String) -> Result<Self, Self::Error> {
171        Self::new_inner(Box::new([value.into_boxed_str().into()]))
172    }
173}
174
175impl fmt::Display for TXT {
176    /// Format a [TXT] with lossy conversion of invalid utf8.
177    ///
178    /// ## Case of invalid utf8
179    ///
180    /// Invalid utf8 will be converted to:
181    /// `U+FFFD REPLACEMENT CHARACTER`, which looks like this: �
182    ///
183    /// Same behaviour as `alloc::string::String::from_utf8_lossy`.
184    /// ```rust
185    /// # use hickory_proto::rr::rdata::TXT;
186    /// let first_bytes = b"Invalid utf8 <\xF0\x90\x80>.";
187    /// let second_bytes = b" Valid utf8 <\xF0\x9F\xA4\xA3>";
188    /// let txt = TXT::try_new([first_bytes.to_vec(), second_bytes.to_vec()].into_iter()).unwrap();
189    ///
190    /// let tested = format!("{}", txt);
191    /// assert_eq!(
192    ///     tested.as_bytes(),
193    ///     b"Invalid utf8 <\xEF\xBF\xBD>. Valid utf8 <\xF0\x9F\xA4\xA3>",
194    ///     "Utf8 lossy conversion error! Mismatch between input and expected"
195    /// );
196    /// ```
197    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
198        for txt in self.txt_data.iter() {
199            f.write_str(&String::from_utf8_lossy(txt))?;
200        }
201
202        Ok(())
203    }
204}
205
206#[cfg(test)]
207mod tests {
208    #![allow(clippy::dbg_macro, clippy::print_stdout)]
209
210    #[cfg(feature = "std")]
211    use std::println;
212
213    use super::*;
214
215    #[test]
216    fn test() {
217        let rdata =
218            TXT::try_new([b"Test me some".to_vec(), b"more please".to_vec()].into_iter()).unwrap();
219
220        let mut bytes = Vec::new();
221        let mut encoder: BinEncoder<'_> = BinEncoder::new(&mut bytes);
222        assert!(rdata.emit(&mut encoder).is_ok());
223        let bytes = encoder.into_bytes();
224
225        #[cfg(feature = "std")]
226        println!("bytes: {bytes:?}");
227
228        let mut decoder: BinDecoder<'_> = BinDecoder::new(bytes);
229        let restrict = Restrict::new(bytes.len() as u16);
230        let read_rdata = TXT::read_data(&mut decoder, restrict).expect("Decoding error");
231        assert_eq!(rdata, read_rdata);
232    }
233
234    #[test]
235    fn publish_binary_txt_record() {
236        let bin_data = vec![0, 1, 2, 3, 4, 5, 6, 7, 8];
237        let rdata = TXT::try_new([b"Test me some".to_vec(), bin_data].into_iter()).unwrap();
238
239        let mut bytes = Vec::new();
240        let mut encoder: BinEncoder<'_> = BinEncoder::new(&mut bytes);
241        assert!(rdata.emit(&mut encoder).is_ok());
242        let bytes = encoder.into_bytes();
243
244        #[cfg(feature = "std")]
245        println!("bytes: {bytes:?}");
246
247        let mut decoder: BinDecoder<'_> = BinDecoder::new(bytes);
248        let restrict = Restrict::new(bytes.len() as u16);
249        let read_rdata = TXT::read_data(&mut decoder, restrict).expect("Decoding error");
250        assert_eq!(rdata, read_rdata);
251    }
252
253    #[test]
254    fn empty_txt_is_rejected() {
255        assert!(TXT::from_tokens([].into_iter()).is_err());
256    }
257
258    #[test]
259    fn empty_character_string_is_allowed() {
260        let txt = TXT::try_new([Vec::new()].into_iter()).unwrap();
261
262        assert_eq!(txt.txt_data.len(), 1);
263        assert!(txt.txt_data[0].is_empty());
264    }
265
266    #[test]
267    fn from_tokens_string_at_limit() {
268        // A single character-string of exactly 255 octets is valid.
269        let token = "a".repeat(255);
270        let rdata = TXT::from_tokens([token.as_str()].into_iter())
271            .expect("a 255-octet character-string should be allowed");
272        assert_eq!(rdata.txt_data.len(), 1);
273        assert_eq!(rdata.txt_data[0].len(), 255);
274    }
275
276    #[test]
277    fn from_tokens_string_over_limit() {
278        // A single character-string longer than 255 octets is rejected.
279        let token = "a".repeat(256);
280        assert!(
281            TXT::from_tokens([token.as_str()].into_iter()).is_err(),
282            "a character-string longer than 255 octets should be rejected"
283        );
284    }
285
286    #[test]
287    fn from_tokens_many_strings_allowed() {
288        // The count of character-strings is not capped at 255; only per-string
289        // length and total data size are constrained.
290        let tokens = vec!["a"; 256];
291        let rdata = TXT::from_tokens(tokens.iter().copied())
292            .expect("many short character-strings should be allowed");
293        assert_eq!(rdata.txt_data.len(), 256);
294    }
295
296    #[test]
297    fn from_tokens_total_data_at_limit() {
298        // Total encoded data of 255 * (1 + 255) = 65280 octets fits in RDATA.
299        let token = "a".repeat(255);
300        let tokens = vec![token.as_str(); 255];
301        let rdata = TXT::from_tokens(tokens.into_iter())
302            .expect("total TXT data within 65535 octets should be allowed");
303        assert_eq!(rdata.txt_data.len(), 255);
304    }
305
306    #[test]
307    fn from_tokens_total_data_over_limit() {
308        // Total data exceeding 65535 octets is rejected, even when every
309        // individual character-string is within the 255-octet limit. The
310        // one-octet length prefix of each character-string counts towards the
311        // limit: 256 * (1 + 255) = 65536 octets.
312        let token = "a".repeat(255);
313        let tokens = vec![token.as_str(); 256];
314        assert!(
315            TXT::from_tokens(tokens.into_iter()).is_err(),
316            "total TXT data exceeding 65535 octets should be rejected"
317        );
318    }
319}