trust_dns_proto/rr/rdata/
svcb.rs

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