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