hickory_proto/rr/rdata/
svcb.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//! SVCB records, see [draft-ietf-dnsop-svcb-https-03 SVCB and HTTPS RRs for DNS, February 2021](https://datatracker.ietf.org/doc/html/draft-ietf-dnsop-svcb-https-03)
9#![allow(clippy::use_self)]
10
11use std::{
12    cmp::{Ord, Ordering, PartialOrd},
13    convert::TryFrom,
14    fmt,
15};
16
17#[cfg(feature = "serde-config")]
18use serde::{Deserialize, Serialize};
19
20use enum_as_inner::EnumAsInner;
21
22use crate::{
23    error::{ProtoError, ProtoErrorKind, ProtoResult},
24    rr::{
25        rdata::{A, AAAA},
26        Name, RData, RecordData, RecordDataDecodable, RecordType,
27    },
28    serialize::binary::{
29        BinDecodable, BinDecoder, BinEncodable, BinEncoder, Restrict, RestrictedMath,
30    },
31};
32
33///  [draft-ietf-dnsop-svcb-https-03 SVCB and HTTPS RRs for DNS, February 2021](https://datatracker.ietf.org/doc/html/draft-ietf-dnsop-svcb-https-03#section-2.2)
34///
35/// ```text
36/// 2.2.  RDATA wire format
37///
38///   The RDATA for the SVCB RR consists of:
39///
40///   *  a 2 octet field for SvcPriority as an integer in network byte
41///      order.
42///   *  the uncompressed, fully-qualified TargetName, represented as a
43///      sequence of length-prefixed labels as in Section 3.1 of [RFC1035].
44///   *  the SvcParams, consuming the remainder of the record (so smaller
45///      than 65535 octets and constrained by the RDATA and DNS message
46///      sizes).
47///
48///   When the list of SvcParams is non-empty (ServiceMode), it contains a
49///   series of SvcParamKey=SvcParamValue pairs, represented as:
50///
51///   *  a 2 octet field containing the SvcParamKey as an integer in
52///      network byte order.  (See Section 14.3.2 for the defined values.)
53///   *  a 2 octet field containing the length of the SvcParamValue as an
54///      integer between 0 and 65535 in network byte order (but constrained
55///      by the RDATA and DNS message sizes).
56///   *  an octet string of this length whose contents are in a format
57///      determined by the SvcParamKey.
58///
59///   SvcParamKeys SHALL appear in increasing numeric order.
60///
61///   Clients MUST consider an RR malformed if:
62///
63///   *  the end of the RDATA occurs within a SvcParam.
64///   *  SvcParamKeys are not in strictly increasing numeric order.
65///   *  the SvcParamValue for an SvcParamKey does not have the expected
66///      format.
67///
68///   Note that the second condition implies that there are no duplicate
69///   SvcParamKeys.
70///
71///   If any RRs are malformed, the client MUST reject the entire RRSet and
72///   fall back to non-SVCB connection establishment.
73/// ```
74#[cfg_attr(feature = "serde-config", derive(Deserialize, Serialize))]
75#[derive(Debug, PartialEq, Eq, Hash, Clone)]
76pub struct SVCB {
77    svc_priority: u16,
78    target_name: Name,
79    svc_params: Vec<(SvcParamKey, SvcParamValue)>,
80}
81
82impl SVCB {
83    /// Create a new SVCB record from parts
84    ///
85    /// It is up to the caller to validate the data going into the record
86    pub fn new(
87        svc_priority: u16,
88        target_name: Name,
89        svc_params: Vec<(SvcParamKey, SvcParamValue)>,
90    ) -> Self {
91        Self {
92            svc_priority,
93            target_name,
94            svc_params,
95        }
96    }
97
98    ///  [draft-ietf-dnsop-svcb-https-03 SVCB and HTTPS RRs for DNS, February 2021](https://datatracker.ietf.org/doc/html/draft-ietf-dnsop-svcb-https-03#section-2.4.1)
99    /// ```text
100    /// 2.4.1.  SvcPriority
101    ///
102    ///   When SvcPriority is 0 the SVCB record is in AliasMode
103    ///   (Section 2.4.2).  Otherwise, it is in ServiceMode (Section 2.4.3).
104    ///
105    ///   Within a SVCB RRSet, all RRs SHOULD have the same Mode.  If an RRSet
106    ///   contains a record in AliasMode, the recipient MUST ignore any
107    ///   ServiceMode records in the set.
108    ///
109    ///   RRSets are explicitly unordered collections, so the SvcPriority field
110    ///   is used to impose an ordering on SVCB RRs.  SVCB RRs with a smaller
111    ///   SvcPriority value SHOULD be given preference over RRs with a larger
112    ///   SvcPriority value.
113    ///
114    ///   When receiving an RRSet containing multiple SVCB records with the
115    ///   same SvcPriority value, clients SHOULD apply a random shuffle within
116    ///   a priority level to the records before using them, to ensure uniform
117    ///   load-balancing.
118    /// ```
119    pub fn svc_priority(&self) -> u16 {
120        self.svc_priority
121    }
122
123    ///  [draft-ietf-dnsop-svcb-https-03 SVCB and HTTPS RRs for DNS, February 2021](https://datatracker.ietf.org/doc/html/draft-ietf-dnsop-svcb-https-03#section-2.5)
124    /// ```text
125    /// 2.5.  Special handling of "." in TargetName
126    ///
127    ///   If TargetName has the value "." (represented in the wire format as a
128    ///    zero-length label), special rules apply.
129    ///
130    /// 2.5.1.  AliasMode
131    ///
132    ///    For AliasMode SVCB RRs, a TargetName of "." indicates that the
133    ///    service is not available or does not exist.  This indication is
134    ///    advisory: clients encountering this indication MAY ignore it and
135    ///    attempt to connect without the use of SVCB.
136    ///
137    /// 2.5.2.  ServiceMode
138    ///
139    ///    For ServiceMode SVCB RRs, if TargetName has the value ".", then the
140    ///    owner name of this record MUST be used as the effective TargetName.
141    ///
142    ///    For example, in the following example "svc2.example.net" is the
143    ///    effective TargetName:
144    ///
145    ///    example.com.      7200  IN HTTPS 0 svc.example.net.
146    ///    svc.example.net.  7200  IN CNAME svc2.example.net.
147    ///    svc2.example.net. 7200  IN HTTPS 1 . port=8002 echconfig="..."
148    ///    svc2.example.net. 300   IN A     192.0.2.2
149    ///    svc2.example.net. 300   IN AAAA  2001:db8::2
150    /// ```
151    pub fn target_name(&self) -> &Name {
152        &self.target_name
153    }
154
155    /// See [`SvcParamKey`] for details on each parameter
156    pub fn svc_params(&self) -> &[(SvcParamKey, SvcParamValue)] {
157        &self.svc_params
158    }
159}
160
161/// ```text
162/// 14.3.2.  Initial contents
163///
164///   The "Service Binding (SVCB) Parameter Registry" shall initially be
165///   populated with the registrations below:
166///
167///   +=============+=================+======================+===========+
168///   | Number      | Name            | Meaning              | Reference |
169///   +=============+=================+======================+===========+
170///   | 0           | mandatory       | Mandatory keys in    | (This     |
171///   |             |                 | this RR              | document) |
172///   +-------------+-----------------+----------------------+-----------+
173///   | 1           | alpn            | Additional supported | (This     |
174///   |             |                 | protocols            | document) |
175///   +-------------+-----------------+----------------------+-----------+
176///   | 2           | no-default-alpn | No support for       | (This     |
177///   |             |                 | default protocol     | document) |
178///   +-------------+-----------------+----------------------+-----------+
179///   | 3           | port            | Port for alternative | (This     |
180///   |             |                 | endpoint             | document) |
181///   +-------------+-----------------+----------------------+-----------+
182///   | 4           | ipv4hint        | IPv4 address hints   | (This     |
183///   |             |                 |                      | document) |
184///   +-------------+-----------------+----------------------+-----------+
185///   | 5           | echconfig       | Encrypted            | (This     |
186///   |             |                 | ClientHello info     | document) |
187///   +-------------+-----------------+----------------------+-----------+
188///   | 6           | ipv6hint        | IPv6 address hints   | (This     |
189///   |             |                 |                      | document) |
190///   +-------------+-----------------+----------------------+-----------+
191///   | 65280-65534 | keyNNNNN        | Private Use          | (This     |
192///   |             |                 |                      | document) |
193///   +-------------+-----------------+----------------------+-----------+
194///   | 65535       | key65535        | Reserved ("Invalid   | (This     |
195///   |             |                 | key")                | document) |
196///   +-------------+-----------------+----------------------+-----------+
197///
198/// parsing done via:
199///   *  a 2 octet field containing the SvcParamKey as an integer in
200///      network byte order.  (See Section 14.3.2 for the defined values.)
201/// ```
202#[cfg_attr(feature = "serde-config", derive(Deserialize, Serialize))]
203#[derive(Debug, PartialEq, Eq, Hash, Clone, Copy)]
204pub enum SvcParamKey {
205    /// Mandatory keys in this RR
206    Mandatory,
207    /// Additional supported protocols
208    Alpn,
209    /// No support for default protocol
210    NoDefaultAlpn,
211    /// Port for alternative endpoint
212    Port,
213    /// IPv4 address hints
214    Ipv4Hint,
215    /// Encrypted ClientHello info
216    EchConfig,
217    /// IPv6 address hints
218    Ipv6Hint,
219    /// Private Use
220    Key(u16),
221    /// Reserved ("Invalid key")
222    Key65535,
223    /// Unknown
224    Unknown(u16),
225}
226
227impl From<u16> for SvcParamKey {
228    fn from(val: u16) -> Self {
229        match val {
230            0 => Self::Mandatory,
231            1 => Self::Alpn,
232            2 => Self::NoDefaultAlpn,
233            3 => Self::Port,
234            4 => Self::Ipv4Hint,
235            5 => Self::EchConfig,
236            6 => Self::Ipv6Hint,
237            65280..=65534 => Self::Key(val),
238            65535 => Self::Key65535,
239            _ => Self::Unknown(val),
240        }
241    }
242}
243
244impl From<SvcParamKey> for u16 {
245    fn from(val: SvcParamKey) -> Self {
246        match val {
247            SvcParamKey::Mandatory => 0,
248            SvcParamKey::Alpn => 1,
249            SvcParamKey::NoDefaultAlpn => 2,
250            SvcParamKey::Port => 3,
251            SvcParamKey::Ipv4Hint => 4,
252            SvcParamKey::EchConfig => 5,
253            SvcParamKey::Ipv6Hint => 6,
254            SvcParamKey::Key(val) => val,
255            SvcParamKey::Key65535 => 65535,
256            SvcParamKey::Unknown(val) => val,
257        }
258    }
259}
260
261impl<'r> BinDecodable<'r> for SvcParamKey {
262    // a 2 octet field containing the SvcParamKey as an integer in
263    //      network byte order.  (See Section 14.3.2 for the defined values.)
264    fn read(decoder: &mut BinDecoder<'r>) -> ProtoResult<Self> {
265        Ok(decoder.read_u16()?.unverified(/*any u16 is valid*/).into())
266    }
267}
268
269impl BinEncodable for SvcParamKey {
270    // a 2 octet field containing the SvcParamKey as an integer in
271    //      network byte order.  (See Section 14.3.2 for the defined values.)
272    fn emit(&self, encoder: &mut BinEncoder<'_>) -> ProtoResult<()> {
273        encoder.emit_u16((*self).into())
274    }
275}
276
277impl fmt::Display for SvcParamKey {
278    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
279        match *self {
280            Self::Mandatory => f.write_str("mandatory")?,
281            Self::Alpn => f.write_str("alpn")?,
282            Self::NoDefaultAlpn => f.write_str("no-default-alpn")?,
283            Self::Port => f.write_str("port")?,
284            Self::Ipv4Hint => f.write_str("ipv4hint")?,
285            Self::EchConfig => f.write_str("echconfig")?,
286            Self::Ipv6Hint => f.write_str("ipv6hint")?,
287            Self::Key(val) => write!(f, "key{val}")?,
288            Self::Key65535 => f.write_str("key65535")?,
289            Self::Unknown(val) => write!(f, "unknown{val}")?,
290        }
291
292        Ok(())
293    }
294}
295
296impl std::str::FromStr for SvcParamKey {
297    type Err = ProtoError;
298
299    fn from_str(s: &str) -> Result<Self, Self::Err> {
300        /// keys are in the format of key#, e.g. key12344, with a max value of u16
301        fn parse_unknown_key(key: &str) -> Result<SvcParamKey, ProtoError> {
302            let key_value = key.strip_prefix("key").ok_or_else(|| {
303                ProtoError::from(ProtoErrorKind::Msg(format!(
304                    "bad formatted key ({key}), expected key1234"
305                )))
306            })?;
307
308            let key_value = u16::from_str(key_value)?;
309            let key = SvcParamKey::from(key_value);
310            Ok(key)
311        }
312
313        let key = match s {
314            "mandatory" => Self::Mandatory,
315            "alpn" => Self::Alpn,
316            "no-default-alpn" => Self::NoDefaultAlpn,
317            "port" => Self::Port,
318            "ipv4hint" => Self::Ipv4Hint,
319            "echconfig" => Self::EchConfig,
320            "ipv6hint" => Self::Ipv6Hint,
321            "key65535" => Self::Key65535,
322            _ => parse_unknown_key(s)?,
323        };
324
325        Ok(key)
326    }
327}
328
329impl Ord for SvcParamKey {
330    fn cmp(&self, other: &Self) -> Ordering {
331        u16::from(*self).cmp(&u16::from(*other))
332    }
333}
334
335impl PartialOrd for SvcParamKey {
336    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
337        Some(self.cmp(other))
338    }
339}
340
341/// Warning, it is currently up to users of this type to validate the data against that expected by the key
342///
343/// ```text
344///   *  a 2 octet field containing the length of the SvcParamValue as an
345///      integer between 0 and 65535 in network byte order (but constrained
346///      by the RDATA and DNS message sizes).
347///   *  an octet string of this length whose contents are in a format
348///      determined by the SvcParamKey.
349/// ```
350#[cfg_attr(feature = "serde-config", derive(Deserialize, Serialize))]
351#[derive(Debug, PartialEq, Eq, Hash, Clone, EnumAsInner)]
352pub enum SvcParamValue {
353    ///    In a ServiceMode RR, a SvcParamKey is considered "mandatory" if the
354    ///    RR will not function correctly for clients that ignore this
355    ///    SvcParamKey.  Each SVCB protocol mapping SHOULD specify a set of keys
356    ///    that are "automatically mandatory", i.e. mandatory if they are
357    ///    present in an RR.  The SvcParamKey "mandatory" is used to indicate
358    ///    any mandatory keys for this RR, in addition to any automatically
359    ///    mandatory keys that are present.
360    ///
361    /// see `Mandatory`
362    Mandatory(Mandatory),
363    /// The "alpn" and "no-default-alpn" SvcParamKeys together indicate the
364    ///    set of Application Layer Protocol Negotiation (ALPN) protocol
365    ///    identifiers [Alpn] and associated transport protocols supported by
366    ///    this service endpoint.
367    Alpn(Alpn),
368    /// For "no-default-alpn", the presentation and wire format values MUST
369    ///    be empty.
370    /// See also `Alpn`
371    NoDefaultAlpn,
372    /// ```text
373    ///    6.2.  "port"
374    ///
375    ///   The "port" SvcParamKey defines the TCP or UDP port that should be
376    ///   used to reach this alternative endpoint.  If this key is not present,
377    ///   clients SHALL use the authority endpoint's port number.
378    ///
379    ///   The presentation "value" of the SvcParamValue is a single decimal
380    ///   integer between 0 and 65535 in ASCII.  Any other "value" (e.g. an
381    ///   empty value) is a syntax error.  To enable simpler parsing, this
382    ///   SvcParam MUST NOT contain escape sequences.
383    ///
384    ///   The wire format of the SvcParamValue is the corresponding 2 octet
385    ///   numeric value in network byte order.
386    ///
387    ///   If a port-restricting firewall is in place between some client and
388    ///   the service endpoint, changing the port number might cause that
389    ///   client to lose access to the service, so operators should exercise
390    ///   caution when using this SvcParamKey to specify a non-default port.
391    /// ```
392    Port(u16),
393    ///   The "ipv4hint" and "ipv6hint" keys convey IP addresses that clients
394    ///   MAY use to reach the service.  If A and AAAA records for TargetName
395    ///   are locally available, the client SHOULD ignore these hints.
396    ///   Otherwise, clients SHOULD perform A and/or AAAA queries for
397    ///   TargetName as in Section 3, and clients SHOULD use the IP address in
398    ///   those responses for future connections.  Clients MAY opt to terminate
399    ///   any connections using the addresses in hints and instead switch to
400    ///   the addresses in response to the TargetName query.  Failure to use A
401    ///   and/or AAAA response addresses could negatively impact load balancing
402    ///   or other geo-aware features and thereby degrade client performance.
403    ///
404    /// see `IpHint`
405    Ipv4Hint(IpHint<A>),
406    /// ```text
407    /// 6.3.  "echconfig"
408    ///
409    ///   The SvcParamKey to enable Encrypted ClientHello (ECH) is "echconfig".
410    ///   Its value is defined in Section 9.  It is applicable to most TLS-
411    ///   based protocols.
412    ///
413    ///   When publishing a record containing an "echconfig" parameter, the
414    ///   publisher MUST ensure that all IP addresses of TargetName correspond
415    ///   to servers that have access to the corresponding private key or are
416    ///   authoritative for the public name.  (See Section 7.2.2 of [ECH] for
417    ///   more details about the public name.)  This yields an anonymity set of
418    ///   cardinality equal to the number of ECH-enabled server domains
419    ///   supported by a given client-facing server.  Thus, even with an
420    ///   encrypted ClientHello, an attacker who can enumerate the set of ECH-
421    ///   enabled domains supported by a client-facing server can guess the
422    ///   correct SNI with probability at least 1/K, where K is the size of
423    ///   this ECH-enabled server anonymity set.  This probability may be
424    ///   increased via traffic analysis or other mechanisms.
425    /// ```
426    EchConfig(EchConfig),
427    /// See `IpHint`
428    Ipv6Hint(IpHint<AAAA>),
429    /// Unparsed network data. Refer to documents on the associated key value
430    ///
431    /// This will be left as is when read off the wire, and encoded in bas64
432    ///    for presentation.
433    Unknown(Unknown),
434}
435
436impl SvcParamValue {
437    // a 2 octet field containing the length of the SvcParamValue as an
438    //      integer between 0 and 65535 in network byte order (but constrained
439    //      by the RDATA and DNS message sizes).
440    fn read(key: SvcParamKey, decoder: &mut BinDecoder<'_>) -> ProtoResult<Self> {
441        let len: usize = decoder
442            .read_u16()?
443            .verify_unwrap(|len| *len as usize <= decoder.len())
444            .map(|len| len as usize)
445            .map_err(|u| {
446                ProtoError::from(format!(
447                    "length of SvcParamValue ({}) exceeds remainder in RDATA ({})",
448                    u,
449                    decoder.len()
450                ))
451            })?;
452
453        let param_data = decoder.read_slice(len)?.unverified(/*verification to be done by individual param types*/);
454        let mut decoder = BinDecoder::new(param_data);
455
456        let value = match key {
457            SvcParamKey::Mandatory => Self::Mandatory(Mandatory::read(&mut decoder)?),
458            SvcParamKey::Alpn => Self::Alpn(Alpn::read(&mut decoder)?),
459            // should always be empty
460            SvcParamKey::NoDefaultAlpn => {
461                if len > 0 {
462                    return Err(ProtoError::from("Alpn expects at least one value"));
463                }
464
465                Self::NoDefaultAlpn
466            }
467            // The wire format of the SvcParamValue is the corresponding 2 octet
468            // numeric value in network byte order.
469            SvcParamKey::Port => {
470                let port = decoder.read_u16()?.unverified(/*all values are legal ports*/);
471                Self::Port(port)
472            }
473            SvcParamKey::Ipv4Hint => Self::Ipv4Hint(IpHint::<A>::read(&mut decoder)?),
474            SvcParamKey::EchConfig => Self::EchConfig(EchConfig::read(&mut decoder)?),
475            SvcParamKey::Ipv6Hint => Self::Ipv6Hint(IpHint::<AAAA>::read(&mut decoder)?),
476            SvcParamKey::Key(_) | SvcParamKey::Key65535 | SvcParamKey::Unknown(_) => {
477                Self::Unknown(Unknown::read(&mut decoder)?)
478            }
479        };
480
481        Ok(value)
482    }
483}
484
485impl BinEncodable for SvcParamValue {
486    // a 2 octet field containing the length of the SvcParamValue as an
487    //      integer between 0 and 65535 in network byte order (but constrained
488    //      by the RDATA and DNS message sizes).
489    fn emit(&self, encoder: &mut BinEncoder<'_>) -> ProtoResult<()> {
490        // set the place for the length...
491        let place = encoder.place::<u16>()?;
492
493        match self {
494            Self::Mandatory(mandatory) => mandatory.emit(encoder)?,
495            Self::Alpn(alpn) => alpn.emit(encoder)?,
496            Self::NoDefaultAlpn => (),
497            Self::Port(port) => encoder.emit_u16(*port)?,
498            Self::Ipv4Hint(ip_hint) => ip_hint.emit(encoder)?,
499            Self::EchConfig(ech_config) => ech_config.emit(encoder)?,
500            Self::Ipv6Hint(ip_hint) => ip_hint.emit(encoder)?,
501            Self::Unknown(unknown) => unknown.emit(encoder)?,
502        }
503
504        // go back and set the length
505        let len = u16::try_from(encoder.len_since_place(&place))
506            .map_err(|_| ProtoError::from("Total length of SvcParamValue exceeds u16::MAX"))?;
507        place.replace(encoder, len)?;
508
509        Ok(())
510    }
511}
512
513impl fmt::Display for SvcParamValue {
514    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
515        match self {
516            Self::Mandatory(mandatory) => write!(f, "{mandatory}")?,
517            Self::Alpn(alpn) => write!(f, "{alpn}")?,
518            Self::NoDefaultAlpn => (),
519            Self::Port(port) => write!(f, "{port}")?,
520            Self::Ipv4Hint(ip_hint) => write!(f, "{ip_hint}")?,
521            Self::EchConfig(ech_config) => write!(f, "{ech_config}")?,
522            Self::Ipv6Hint(ip_hint) => write!(f, "{ip_hint}")?,
523            Self::Unknown(unknown) => write!(f, "{unknown}")?,
524        }
525
526        Ok(())
527    }
528}
529
530/// ```text
531/// 7.  ServiceMode RR compatibility and mandatory keys
532///
533///    In a ServiceMode RR, a SvcParamKey is considered "mandatory" if the
534///    RR will not function correctly for clients that ignore this
535///    SvcParamKey.  Each SVCB protocol mapping SHOULD specify a set of keys
536///    that are "automatically mandatory", i.e. mandatory if they are
537///    present in an RR.  The SvcParamKey "mandatory" is used to indicate
538///    any mandatory keys for this RR, in addition to any automatically
539///    mandatory keys that are present.
540///
541///    A ServiceMode RR is considered "compatible" with a client if the
542///    client recognizes all the mandatory keys, and their values indicate
543///    that successful connection establishment is possible.  If the SVCB
544///    RRSet contains no compatible RRs, the client will generally act as if
545///    the RRSet is empty.
546///
547///    The presentation "value" SHALL be a comma-separated list
548///    (Appendix A.1) of one or more valid SvcParamKeys, either by their
549///    registered name or in the unknown-key format (Section 2.1).  Keys MAY
550///    appear in any order, but MUST NOT appear more than once.  For self-
551///    consistency (Section 2.4.3), listed keys MUST also appear in the
552///    SvcParams.
553///
554///    To enable simpler parsing, this SvcParamValue MUST NOT contain escape
555///    sequences.
556///
557///    For example, the following is a valid list of SvcParams:
558///
559///    echconfig=... key65333=ex1 key65444=ex2 mandatory=key65444,echconfig
560///
561///    In wire format, the keys are represented by their numeric values in
562///    network byte order, concatenated in ascending order.
563///
564///    This SvcParamKey is always automatically mandatory, and MUST NOT
565///    appear in its own value-list.  Other automatically mandatory keys
566///    SHOULD NOT appear in the list either.  (Including them wastes space
567///    and otherwise has no effect.)
568/// ```
569#[cfg_attr(feature = "serde-config", derive(Deserialize, Serialize))]
570#[derive(Debug, PartialEq, Eq, Hash, Clone)]
571#[repr(transparent)]
572pub struct Mandatory(pub Vec<SvcParamKey>);
573
574impl<'r> BinDecodable<'r> for Mandatory {
575    /// This expects the decoder to be limited to only this field, i.e. the end of input for the decoder
576    ///   is the end of input for the fields
577    ///
578    /// ```text
579    ///    In wire format, the keys are represented by their numeric values in
580    ///    network byte order, concatenated in ascending order.
581    /// ```
582    fn read(decoder: &mut BinDecoder<'r>) -> ProtoResult<Self> {
583        let mut keys = Vec::with_capacity(1);
584
585        while decoder.peek().is_some() {
586            keys.push(SvcParamKey::read(decoder)?);
587        }
588
589        if keys.is_empty() {
590            return Err(ProtoError::from("Mandatory expects at least one value"));
591        }
592
593        Ok(Self(keys))
594    }
595}
596
597impl BinEncodable for Mandatory {
598    /// This expects the decoder to be limited to only this field, i.e. the end of input for the decoder
599    ///   is the end of input for the fields
600    ///
601    /// ```text
602    ///    In wire format, the keys are represented by their numeric values in
603    ///    network byte order, concatenated in ascending order.
604    /// ```
605    fn emit(&self, encoder: &mut BinEncoder<'_>) -> ProtoResult<()> {
606        if self.0.is_empty() {
607            return Err(ProtoError::from("Alpn expects at least one value"));
608        }
609
610        // TODO: order by key value
611        for key in self.0.iter() {
612            key.emit(encoder)?
613        }
614
615        Ok(())
616    }
617}
618
619impl fmt::Display for Mandatory {
620    ///    The presentation "value" SHALL be a comma-separated list
621    ///    (Appendix A.1) of one or more valid SvcParamKeys, either by their
622    ///    registered name or in the unknown-key format (Section 2.1).  Keys MAY
623    ///    appear in any order, but MUST NOT appear more than once.  For self-
624    ///    consistency (Section 2.4.3), listed keys MUST also appear in the
625    ///    SvcParams.
626    ///
627    ///    To enable simpler parsing, this SvcParamValue MUST NOT contain escape
628    ///    sequences.
629    ///
630    ///    For example, the following is a valid list of SvcParams:
631    ///
632    ///    echconfig=... key65333=ex1 key65444=ex2 mandatory=key65444,echconfig
633    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
634        for key in self.0.iter() {
635            // TODO: confirm in the RFC that trailing commas are ok
636            write!(f, "{key},")?;
637        }
638
639        Ok(())
640    }
641}
642
643///  [draft-ietf-dnsop-svcb-https-03 SVCB and HTTPS RRs for DNS, February 2021](https://datatracker.ietf.org/doc/html/draft-ietf-dnsop-svcb-https-03#section-6.1)
644///
645/// ```text
646/// 6.1.  "alpn" and "no-default-alpn"
647///
648///   The "alpn" and "no-default-alpn" SvcParamKeys together indicate the
649///   set of Application Layer Protocol Negotiation (ALPN) protocol
650///   identifiers [ALPN] and associated transport protocols supported by
651///   this service endpoint.
652///
653///   As with Alt-Svc [AltSvc], the ALPN protocol identifier is used to
654///   identify the application protocol and associated suite of protocols
655///   supported by the endpoint (the "protocol suite").  Clients filter the
656///   set of ALPN identifiers to match the protocol suites they support,
657///   and this informs the underlying transport protocol used (such as
658///   QUIC-over-UDP or TLS-over-TCP).
659///
660///   ALPNs are identified by their registered "Identification Sequence"
661///   ("alpn-id"), which is a sequence of 1-255 octets.
662///
663///   alpn-id = 1*255OCTET
664///
665///   The presentation "value" SHALL be a comma-separated list
666///   (Appendix A.1) of one or more "alpn-id"s.
667///
668///   The wire format value for "alpn" consists of at least one "alpn-id"
669///   prefixed by its length as a single octet, and these length-value
670///   pairs are concatenated to form the SvcParamValue.  These pairs MUST
671///   exactly fill the SvcParamValue; otherwise, the SvcParamValue is
672///   malformed.
673///
674///   For "no-default-alpn", the presentation and wire format values MUST
675///   be empty.  When "no-default-alpn" is specified in an RR, "alpn" must
676///   also be specified in order for the RR to be "self-consistent"
677///   (Section 2.4.3).
678///
679///   Each scheme that uses this SvcParamKey defines a "default set" of
680///   supported ALPNs, which SHOULD NOT be empty.  To determine the set of
681///   protocol suites supported by an endpoint (the "SVCB ALPN set"), the
682///   client adds the default set to the list of "alpn-id"s unless the "no-
683///   default-alpn" SvcParamKey is present.  The presence of an ALPN
684///   protocol in the SVCB ALPN set indicates that this service endpoint,
685///   described by TargetName and the other parameters (e.g. "port") offers
686///   service with the protocol suite associated with this ALPN protocol.
687///
688///   ALPN protocol names that do not uniquely identify a protocol suite
689///   (e.g. an Identification Sequence that can be used with both TLS and
690///   DTLS) are not compatible with this SvcParamKey and MUST NOT be
691///   included in the SVCB ALPN set.
692///
693///   To establish a connection to the endpoint, clients MUST
694///
695///   1.  Let SVCB-ALPN-Intersection be the set of protocols in the SVCB
696///       ALPN set that the client supports.
697///
698///   2.  Let Intersection-Transports be the set of transports (e.g.  TLS,
699///       DTLS, QUIC) implied by the protocols in SVCB-ALPN-Intersection.
700///
701///   3.  For each transport in Intersection-Transports, construct a
702///       ProtocolNameList containing the Identification Sequences of all
703///       the client's supported ALPN protocols for that transport, without
704///       regard to the SVCB ALPN set.
705///
706///   For example, if the SVCB ALPN set is ["http/1.1", "h3"], and the
707///   client supports HTTP/1.1, HTTP/2, and HTTP/3, the client could
708///   attempt to connect using TLS over TCP with a ProtocolNameList of
709///   ["http/1.1", "h2"], and could also attempt a connection using QUIC,
710///   with a ProtocolNameList of ["h3"].
711///
712///   Once the client has constructed a ClientHello, protocol negotiation
713///   in that handshake proceeds as specified in [ALPN], without regard to
714///   the SVCB ALPN set.
715///
716///   With this procedure in place, an attacker who can modify DNS and
717///   network traffic can prevent a successful transport connection, but
718///   cannot otherwise interfere with ALPN protocol selection.  This
719///   procedure also ensures that each ProtocolNameList includes at least
720///   one protocol from the SVCB ALPN set.
721///
722///   Clients SHOULD NOT attempt connection to a service endpoint whose
723///   SVCB ALPN set does not contain any supported protocols.  To ensure
724///   consistency of behavior, clients MAY reject the entire SVCB RRSet and
725///   fall back to basic connection establishment if all of the RRs
726///   indicate "no-default-alpn", even if connection could have succeeded
727///   using a non-default alpn.
728///
729///   For compatibility with clients that require default transports, zone
730///   operators SHOULD ensure that at least one RR in each RRSet supports
731///   the default transports.
732/// ```
733#[cfg_attr(feature = "serde-config", derive(Deserialize, Serialize))]
734#[derive(Debug, PartialEq, Eq, Hash, Clone)]
735#[repr(transparent)]
736pub struct Alpn(pub Vec<String>);
737
738impl<'r> BinDecodable<'r> for Alpn {
739    /// This expects the decoder to be limited to only this field, i.e. the end of input for the decoder
740    ///   is the end of input for the fields
741    ///
742    /// ```text
743    ///   The wire format value for "alpn" consists of at least one "alpn-id"
744    ///   prefixed by its length as a single octet, and these length-value
745    ///   pairs are concatenated to form the SvcParamValue.  These pairs MUST
746    ///   exactly fill the SvcParamValue; otherwise, the SvcParamValue is
747    ///   malformed.
748    /// ```
749    fn read(decoder: &mut BinDecoder<'r>) -> ProtoResult<Self> {
750        let mut alpns = Vec::with_capacity(1);
751
752        while decoder.peek().is_some() {
753            let alpn = decoder.read_character_data()?.unverified(/*will rely on string parser*/);
754            let alpn = String::from_utf8(alpn.to_vec())?;
755            alpns.push(alpn);
756        }
757
758        if alpns.is_empty() {
759            return Err(ProtoError::from("Alpn expects at least one value"));
760        }
761
762        Ok(Self(alpns))
763    }
764}
765
766impl BinEncodable for Alpn {
767    ///   The wire format value for "alpn" consists of at least one "alpn-id"
768    ///   prefixed by its length as a single octet, and these length-value
769    ///   pairs are concatenated to form the SvcParamValue.  These pairs MUST
770    ///   exactly fill the SvcParamValue; otherwise, the SvcParamValue is
771    ///   malformed.
772    fn emit(&self, encoder: &mut BinEncoder<'_>) -> ProtoResult<()> {
773        if self.0.is_empty() {
774            return Err(ProtoError::from("Alpn expects at least one value"));
775        }
776
777        for alpn in self.0.iter() {
778            encoder.emit_character_data(alpn)?
779        }
780
781        Ok(())
782    }
783}
784
785impl fmt::Display for Alpn {
786    ///   The presentation "value" SHALL be a comma-separated list
787    ///   (Appendix A.1) of one or more "alpn-id"s.
788    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
789        for alpn in self.0.iter() {
790            // TODO: confirm in the RFC that trailing commas are ok
791            write!(f, "{alpn},")?;
792        }
793
794        Ok(())
795    }
796}
797
798/// ```text
799/// 9.  SVCB/HTTPS RR parameter for ECH configuration
800///
801///   The SVCB "echconfig" parameter is defined for conveying the ECH
802///   configuration of an alternative endpoint.  In wire format, the value
803///   of the parameter is an ECHConfigs vector [ECH], including the
804///   redundant length prefix.  In presentation format, the value is a
805///   single ECHConfigs encoded in Base64 [base64].  Base64 is used here to
806///   simplify integration with TLS server software.  To enable simpler
807///   parsing, this SvcParam MUST NOT contain escape sequences.
808///
809///   When ECH is in use, the TLS ClientHello is divided into an
810///   unencrypted "outer" and an encrypted "inner" ClientHello.  The outer
811///   ClientHello is an implementation detail of ECH, and its contents are
812///   controlled by the ECHConfig in accordance with [ECH].  The inner
813///   ClientHello is used for establishing a connection to the service, so
814///   its contents may be influenced by other SVCB parameters.  For
815///   example, the requirements on the ProtocolNameList in Section 6.1
816///   apply only to the inner ClientHello.  Similarly, it is the inner
817///   ClientHello whose Server Name Indication identifies the desired
818/// ```
819#[cfg_attr(feature = "serde-config", derive(Deserialize, Serialize))]
820#[derive(PartialEq, Eq, Hash, Clone)]
821#[repr(transparent)]
822pub struct EchConfig(pub Vec<u8>);
823
824impl<'r> BinDecodable<'r> for EchConfig {
825    /// In wire format, the value
826    ///   of the parameter is an ECHConfigs vector (ECH), including the
827    ///   redundant length prefix (a 2 octet field containing the length of the SvcParamValue
828    ///   as an integer between 0 and 65535 in network byte order).
829    fn read(decoder: &mut BinDecoder<'r>) -> ProtoResult<Self> {
830        let redundant_len = decoder
831            .read_u16()?
832            .map(|len| len as usize)
833            .verify_unwrap(|len| *len <= decoder.len())
834            .map_err(|_| ProtoError::from("ECH value length exceeds max size of u16::MAX"))?;
835
836        let data =
837            decoder.read_vec(redundant_len)?.unverified(/*up to consumer to validate this data*/);
838
839        Ok(Self(data))
840    }
841}
842
843impl BinEncodable for EchConfig {
844    /// In wire format, the value
845    ///   of the parameter is an ECHConfigs vector (ECH), including the
846    ///   redundant length prefix (a 2 octet field containing the length of the SvcParamValue
847    ///   as an integer between 0 and 65535 in network byte order).
848    fn emit(&self, encoder: &mut BinEncoder<'_>) -> ProtoResult<()> {
849        let len = u16::try_from(self.0.len())
850            .map_err(|_| ProtoError::from("ECH value length exceeds max size of u16::MAX"))?;
851
852        // redundant length...
853        encoder.emit_u16(len)?;
854        encoder.emit_vec(&self.0)?;
855
856        Ok(())
857    }
858}
859
860impl fmt::Display for EchConfig {
861    /// As the documentation states, the presentation format (what this function outputs) must be a BASE64 encoded string.
862    ///   hickory-dns will encode to BASE64 during formatting of the internal data, and output the BASE64 value.
863    ///
864    /// [draft-ietf-dnsop-svcb-https-03 SVCB and HTTPS RRs for DNS, February 2021](https://datatracker.ietf.org/doc/html/draft-ietf-dnsop-svcb-https-03#section-9)
865    /// ```text
866    /// In presentation format, the value is a
867    ///   single ECHConfigs encoded in Base64 [base64].  Base64 is used here to
868    ///   simplify integration with TLS server software.  To enable simpler
869    ///   parsing, this SvcParam MUST NOT contain escape sequences.
870    /// ```
871    ///
872    /// *note* while the on the wire the EchConfig has a redundant length,
873    ///   the RFC is not explicit about including it in the BASE64 encoded value,
874    ///   hickory-dns will encode the data as it is stored, i.e. without the length encoding.
875    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
876        write!(f, "\"{}\"", data_encoding::BASE64.encode(&self.0))
877    }
878}
879
880impl fmt::Debug for EchConfig {
881    /// The debug format for EchConfig will output the value in BASE64 like Display, but will the addition of the type-name.
882    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
883        write!(
884            f,
885            "\"EchConfig ({})\"",
886            data_encoding::BASE64.encode(&self.0)
887        )
888    }
889}
890
891/// ```text
892///    6.4.  "ipv4hint" and "ipv6hint"
893///
894///   The "ipv4hint" and "ipv6hint" keys convey IP addresses that clients
895///   MAY use to reach the service.  If A and AAAA records for TargetName
896///   are locally available, the client SHOULD ignore these hints.
897///   Otherwise, clients SHOULD perform A and/or AAAA queries for
898///   TargetName as in Section 3, and clients SHOULD use the IP address in
899///   those responses for future connections.  Clients MAY opt to terminate
900///   any connections using the addresses in hints and instead switch to
901///   the addresses in response to the TargetName query.  Failure to use A
902///   and/or AAAA response addresses could negatively impact load balancing
903///   or other geo-aware features and thereby degrade client performance.
904///
905///   The presentation "value" SHALL be a comma-separated list
906///   (Appendix A.1) of one or more IP addresses of the appropriate family
907///   in standard textual format [RFC5952].  To enable simpler parsing,
908///   this SvcParamValue MUST NOT contain escape sequences.
909///
910///   The wire format for each parameter is a sequence of IP addresses in
911///   network byte order.  Like an A or AAAA RRSet, the list of addresses
912///   represents an unordered collection, and clients SHOULD pick addresses
913///   to use in a random order.  An empty list of addresses is invalid.
914///
915///   When selecting between IPv4 and IPv6 addresses to use, clients may
916///   use an approach such as Happy Eyeballs [HappyEyeballsV2].  When only
917///   "ipv4hint" is present, IPv6-only clients may synthesize IPv6
918///   addresses as specified in [RFC7050] or ignore the "ipv4hint" key and
919///   wait for AAAA resolution (Section 3).  Recursive resolvers MUST NOT
920///   perform DNS64 ([RFC6147]) on parameters within a SVCB record.  For
921///   best performance, server operators SHOULD include an "ipv6hint"
922///   parameter whenever they include an "ipv4hint" parameter.
923///
924///   These parameters are intended to minimize additional connection
925///   latency when a recursive resolver is not compliant with the
926///   requirements in Section 4, and SHOULD NOT be included if most clients
927///   are using compliant recursive resolvers.  When TargetName is the
928///   origin hostname or the owner name (which can be written as "."),
929///   server operators SHOULD NOT include these hints, because they are
930///   unlikely to convey any performance benefit.
931/// ```
932#[cfg_attr(feature = "serde-config", derive(Deserialize, Serialize))]
933#[derive(Debug, PartialEq, Eq, Hash, Clone)]
934#[repr(transparent)]
935pub struct IpHint<T>(pub Vec<T>);
936
937impl<'r, T> BinDecodable<'r> for IpHint<T>
938where
939    T: BinDecodable<'r>,
940{
941    ///   The wire format for each parameter is a sequence of IP addresses in
942    ///   network byte order.  Like an A or AAAA RRSet, the list of addresses
943    ///   represents an unordered collection, and clients SHOULD pick addresses
944    ///   to use in a random order.  An empty list of addresses is invalid.
945    fn read(decoder: &mut BinDecoder<'r>) -> ProtoResult<Self> {
946        let mut ips = Vec::new();
947
948        while decoder.peek().is_some() {
949            ips.push(T::read(decoder)?)
950        }
951
952        Ok(Self(ips))
953    }
954}
955
956impl<T> BinEncodable for IpHint<T>
957where
958    T: BinEncodable,
959{
960    ///   The wire format for each parameter is a sequence of IP addresses in
961    ///   network byte order.  Like an A or AAAA RRSet, the list of addresses
962    ///   represents an unordered collection, and clients SHOULD pick addresses
963    ///   to use in a random order.  An empty list of addresses is invalid.
964    fn emit(&self, encoder: &mut BinEncoder<'_>) -> ProtoResult<()> {
965        for ip in self.0.iter() {
966            ip.emit(encoder)?;
967        }
968
969        Ok(())
970    }
971}
972
973impl<T> fmt::Display for IpHint<T>
974where
975    T: fmt::Display,
976{
977    ///   The presentation "value" SHALL be a comma-separated list
978    ///   (Appendix A.1) of one or more IP addresses of the appropriate family
979    ///   in standard textual format [RFC 5952](https://tools.ietf.org/html/rfc5952).  To enable simpler parsing,
980    ///   this SvcParamValue MUST NOT contain escape sequences.
981    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
982        for ip in self.0.iter() {
983            write!(f, "{ip},")?;
984        }
985
986        Ok(())
987    }
988}
989
990/// [draft-ietf-dnsop-svcb-https-03 SVCB and HTTPS RRs for DNS, February 2021](https://datatracker.ietf.org/doc/html/draft-ietf-dnsop-svcb-https-03#section-2.1)
991/// ```text
992/// Unrecognized keys are represented in presentation format as
993///   "keyNNNNN" where NNNNN is the numeric value of the key type without
994///   leading zeros.  A SvcParam in this form SHALL be parsed as specified
995///   above, and the decoded "value" SHALL be used as its wire format
996///   encoding.
997///
998///   For some SvcParamKeys, the "value" corresponds to a list or set of
999///   items.  Presentation formats for such keys SHOULD use a comma-
1000///   separated list (Appendix A.1).
1001///
1002///   SvcParams in presentation format MAY appear in any order, but keys
1003///   MUST NOT be repeated.
1004/// ```
1005#[cfg_attr(feature = "serde-config", derive(Deserialize, Serialize))]
1006#[derive(Debug, PartialEq, Eq, Hash, Clone)]
1007#[repr(transparent)]
1008pub struct Unknown(pub Vec<u8>);
1009
1010impl<'r> BinDecodable<'r> for Unknown {
1011    fn read(decoder: &mut BinDecoder<'r>) -> ProtoResult<Self> {
1012        // The passed slice is already length delimited, and we cannot
1013        // assume it's a collection of anything.
1014        let len = decoder.len();
1015
1016        let data = decoder.read_vec(len)?;
1017        let unknowns = data.unverified(/*any data is valid here*/).to_vec();
1018
1019        Ok(Self(unknowns))
1020    }
1021}
1022
1023impl BinEncodable for Unknown {
1024    fn emit(&self, encoder: &mut BinEncoder<'_>) -> ProtoResult<()> {
1025        // draft-ietf-dnsop-svcb-https-11#appendix-A: The algorithm is the same as used by
1026        // <character-string> in RFC 1035, although the output length in this
1027        // document is not limited to 255 octets.
1028        encoder.emit_character_data_unrestricted(&self.0)?;
1029
1030        Ok(())
1031    }
1032}
1033
1034impl fmt::Display for Unknown {
1035    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
1036        // TODO: this needs to be properly encoded
1037        write!(f, "\"{}\",", String::from_utf8_lossy(&self.0))?;
1038
1039        Ok(())
1040    }
1041}
1042
1043impl BinEncodable for SVCB {
1044    fn emit(&self, encoder: &mut BinEncoder<'_>) -> ProtoResult<()> {
1045        self.svc_priority.emit(encoder)?;
1046        self.target_name.emit(encoder)?;
1047
1048        let mut last_key: Option<SvcParamKey> = None;
1049        for (key, param) in self.svc_params.iter() {
1050            if let Some(last_key) = last_key {
1051                if key <= &last_key {
1052                    return Err(ProtoError::from("SvcParams out of order"));
1053                }
1054            }
1055
1056            key.emit(encoder)?;
1057            param.emit(encoder)?;
1058
1059            last_key = Some(*key);
1060        }
1061
1062        Ok(())
1063    }
1064}
1065
1066impl RecordDataDecodable<'_> for SVCB {
1067    /// Reads the SVCB record from the decoder.
1068    ///
1069    /// ```text
1070    ///   Clients MUST consider an RR malformed if:
1071    ///
1072    ///   *  the end of the RDATA occurs within a SvcParam.
1073    ///   *  SvcParamKeys are not in strictly increasing numeric order.
1074    ///   *  the SvcParamValue for an SvcParamKey does not have the expected
1075    ///      format.
1076    ///
1077    ///   Note that the second condition implies that there are no duplicate
1078    ///   SvcParamKeys.
1079    ///
1080    ///   If any RRs are malformed, the client MUST reject the entire RRSet and
1081    ///   fall back to non-SVCB connection establishment.
1082    /// ```
1083    fn read_data(decoder: &mut BinDecoder<'_>, rdata_length: Restrict<u16>) -> ProtoResult<SVCB> {
1084        let start_index = decoder.index();
1085
1086        let svc_priority = decoder.read_u16()?.unverified(/*any u16 is valid*/);
1087        let target_name = Name::read(decoder)?;
1088
1089        let mut remainder_len = rdata_length
1090            .map(|len| len as usize)
1091            .checked_sub(decoder.index() - start_index)
1092            .map_err(|len| format!("Bad length for RDATA of SVCB: {len}"))?
1093            .unverified(); // valid len
1094        let mut svc_params: Vec<(SvcParamKey, SvcParamValue)> = Vec::new();
1095
1096        // must have at least 4 bytes left for the key and the length
1097        while remainder_len >= 4 {
1098            // a 2 octet field containing the SvcParamKey as an integer in
1099            //      network byte order.  (See Section 14.3.2 for the defined values.)
1100            let key = SvcParamKey::read(decoder)?;
1101
1102            // a 2 octet field containing the length of the SvcParamValue as an
1103            //      integer between 0 and 65535 in network byte order (but constrained
1104            //      by the RDATA and DNS message sizes).
1105            let value = SvcParamValue::read(key, decoder)?;
1106
1107            if let Some(last_key) = svc_params.last().map(|(key, _)| key) {
1108                if last_key >= &key {
1109                    return Err(ProtoError::from("SvcParams out of order"));
1110                }
1111            }
1112
1113            svc_params.push((key, value));
1114            remainder_len = rdata_length
1115                .map(|len| len as usize)
1116                .checked_sub(decoder.index() - start_index)
1117                .map_err(|len| format!("Bad length for RDATA of SVCB: {len}"))?
1118                .unverified(); // valid len
1119        }
1120
1121        Ok(Self {
1122            svc_priority,
1123            target_name,
1124            svc_params,
1125        })
1126    }
1127}
1128
1129impl RecordData for SVCB {
1130    fn try_from_rdata(data: RData) -> Result<Self, RData> {
1131        match data {
1132            RData::SVCB(data) => Ok(data),
1133            _ => Err(data),
1134        }
1135    }
1136
1137    fn try_borrow(data: &RData) -> Option<&Self> {
1138        match data {
1139            RData::SVCB(data) => Some(data),
1140            _ => None,
1141        }
1142    }
1143
1144    fn record_type(&self) -> RecordType {
1145        RecordType::SVCB
1146    }
1147
1148    fn into_rdata(self) -> RData {
1149        RData::SVCB(self)
1150    }
1151}
1152
1153/// [draft-ietf-dnsop-svcb-https-03 SVCB and HTTPS RRs for DNS, February 2021](https://datatracker.ietf.org/doc/html/draft-ietf-dnsop-svcb-https-03#section-10.3)
1154///
1155/// ```text
1156/// simple.example. 7200 IN HTTPS 1 . alpn=h3
1157/// pool  7200 IN HTTPS 1 h3pool alpn=h2,h3 echconfig="123..."
1158///               HTTPS 2 .      alpn=h2 echconfig="abc..."
1159/// @     7200 IN HTTPS 0 www
1160/// _8765._baz.api.example.com. 7200 IN SVCB 0 svc4-baz.example.net.
1161/// ```
1162impl fmt::Display for SVCB {
1163    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
1164        write!(
1165            f,
1166            "{svc_priority} {target_name}",
1167            svc_priority = self.svc_priority,
1168            target_name = self.target_name,
1169        )?;
1170
1171        for (key, param) in self.svc_params.iter() {
1172            write!(f, " {key}={param}")?
1173        }
1174
1175        Ok(())
1176    }
1177}
1178
1179#[cfg(test)]
1180mod tests {
1181    use super::*;
1182
1183    #[test]
1184    fn read_svcb_key() {
1185        assert_eq!(SvcParamKey::Mandatory, 0.into());
1186        assert_eq!(SvcParamKey::Alpn, 1.into());
1187        assert_eq!(SvcParamKey::NoDefaultAlpn, 2.into());
1188        assert_eq!(SvcParamKey::Port, 3.into());
1189        assert_eq!(SvcParamKey::Ipv4Hint, 4.into());
1190        assert_eq!(SvcParamKey::EchConfig, 5.into());
1191        assert_eq!(SvcParamKey::Ipv6Hint, 6.into());
1192        assert_eq!(SvcParamKey::Key(65280), 65280.into());
1193        assert_eq!(SvcParamKey::Key(65534), 65534.into());
1194        assert_eq!(SvcParamKey::Key65535, 65535.into());
1195        assert_eq!(SvcParamKey::Unknown(65279), 65279.into());
1196    }
1197
1198    #[test]
1199    fn read_svcb_key_to_u16() {
1200        assert_eq!(u16::from(SvcParamKey::Mandatory), 0);
1201        assert_eq!(u16::from(SvcParamKey::Alpn), 1);
1202        assert_eq!(u16::from(SvcParamKey::NoDefaultAlpn), 2);
1203        assert_eq!(u16::from(SvcParamKey::Port), 3);
1204        assert_eq!(u16::from(SvcParamKey::Ipv4Hint), 4);
1205        assert_eq!(u16::from(SvcParamKey::EchConfig), 5);
1206        assert_eq!(u16::from(SvcParamKey::Ipv6Hint), 6);
1207        assert_eq!(u16::from(SvcParamKey::Key(65280)), 65280);
1208        assert_eq!(u16::from(SvcParamKey::Key(65534)), 65534);
1209        assert_eq!(u16::from(SvcParamKey::Key65535), 65535);
1210        assert_eq!(u16::from(SvcParamKey::Unknown(65279)), 65279);
1211    }
1212
1213    #[track_caller]
1214    fn test_encode_decode(rdata: SVCB) {
1215        let mut bytes = Vec::new();
1216        let mut encoder: BinEncoder<'_> = BinEncoder::new(&mut bytes);
1217        rdata.emit(&mut encoder).expect("failed to emit SVCB");
1218        let bytes = encoder.into_bytes();
1219
1220        let mut decoder: BinDecoder<'_> = BinDecoder::new(bytes);
1221        let read_rdata = SVCB::read_data(&mut decoder, Restrict::new(bytes.len() as u16))
1222            .expect("failed to read back");
1223        assert_eq!(rdata, read_rdata);
1224    }
1225
1226    #[test]
1227    fn test_encode_decode_svcb() {
1228        test_encode_decode(SVCB::new(
1229            0,
1230            Name::from_utf8("www.example.com.").unwrap(),
1231            vec![],
1232        ));
1233        test_encode_decode(SVCB::new(
1234            0,
1235            Name::from_utf8(".").unwrap(),
1236            vec![(
1237                SvcParamKey::Alpn,
1238                SvcParamValue::Alpn(Alpn(vec!["h2".to_string()])),
1239            )],
1240        ));
1241        test_encode_decode(SVCB::new(
1242            0,
1243            Name::from_utf8("example.com.").unwrap(),
1244            vec![
1245                (
1246                    SvcParamKey::Mandatory,
1247                    SvcParamValue::Mandatory(Mandatory(vec![SvcParamKey::Alpn])),
1248                ),
1249                (
1250                    SvcParamKey::Alpn,
1251                    SvcParamValue::Alpn(Alpn(vec!["h2".to_string()])),
1252                ),
1253            ],
1254        ));
1255    }
1256
1257    #[test]
1258    #[should_panic]
1259    fn test_encode_decode_svcb_bad_order() {
1260        test_encode_decode(SVCB::new(
1261            0,
1262            Name::from_utf8(".").unwrap(),
1263            vec![
1264                (
1265                    SvcParamKey::Alpn,
1266                    SvcParamValue::Alpn(Alpn(vec!["h2".to_string()])),
1267                ),
1268                (
1269                    SvcParamKey::Mandatory,
1270                    SvcParamValue::Mandatory(Mandatory(vec![SvcParamKey::Alpn])),
1271                ),
1272            ],
1273        ));
1274    }
1275
1276    #[test]
1277    fn test_no_panic() {
1278        const BUF: &[u8] = &[
1279            255, 121, 0, 0, 0, 0, 40, 255, 255, 160, 160, 0, 0, 0, 64, 0, 1, 255, 158, 0, 0, 0, 8,
1280            0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
1281        ];
1282        assert!(crate::op::Message::from_vec(BUF).is_err());
1283    }
1284
1285    #[test]
1286    fn test_unrestricted_output_size() {
1287        let svcb = SVCB::new(
1288            8224,
1289            Name::from_utf8(".").unwrap(),
1290            vec![(
1291                SvcParamKey::Unknown(8224),
1292                SvcParamValue::Unknown(Unknown(vec![32; 257])),
1293            )],
1294        );
1295
1296        let mut buf = Vec::new();
1297        let mut encoder = BinEncoder::new(&mut buf);
1298        svcb.emit(&mut encoder).unwrap();
1299    }
1300}