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::{
12 string::{String, ToString},
13 vec::Vec,
14};
15use core::{
16 cmp::{Ord, Ordering, PartialOrd},
17 convert::TryFrom,
18 fmt,
19 str::FromStr,
20};
21
22#[cfg(feature = "serde")]
23use serde::{Deserialize, Serialize};
24
25use crate::{
26 error::{ProtoError, ProtoResult},
27 rr::{
28 Name, RData, RecordData, RecordDataDecodable, RecordType,
29 rdata::{A, AAAA},
30 },
31 serialize::{
32 binary::{
33 BinDecodable, BinDecoder, BinEncodable, BinEncoder, DecodeError, RDataEncoding,
34 Restrict, RestrictedMath,
35 },
36 txt::{Lexer, ParseError, Token},
37 },
38};
39
40/// [RFC 9460 SVCB and HTTPS Resource Records, Nov 2023](https://datatracker.ietf.org/doc/html/rfc9460#section-2.2)
41///
42/// ```text
43/// 2.2. RDATA wire format
44///
45/// The RDATA for the SVCB RR consists of:
46///
47/// * a 2 octet field for SvcPriority as an integer in network byte
48/// order.
49/// * the uncompressed, fully-qualified TargetName, represented as a
50/// sequence of length-prefixed labels as in Section 3.1 of [RFC1035].
51/// * the SvcParams, consuming the remainder of the record (so smaller
52/// than 65535 octets and constrained by the RDATA and DNS message
53/// sizes).
54///
55/// When the list of SvcParams is non-empty (ServiceMode), it contains a
56/// series of SvcParamKey=SvcParamValue pairs, represented as:
57///
58/// * a 2 octet field containing the SvcParamKey as an integer in
59/// network byte order. (See Section 14.3.2 for the defined values.)
60/// * a 2 octet field containing the length of the SvcParamValue as an
61/// integer between 0 and 65535 in network byte order
62/// * an octet string of this length whose contents are the SvcParamValue
63/// in a format determined by the SvcParamKey
64///
65/// SvcParamKeys SHALL appear in increasing numeric order.
66///
67/// Clients MUST consider an RR malformed if:
68///
69/// * the end of the RDATA occurs within a SvcParam.
70/// * SvcParamKeys are not in strictly increasing numeric order.
71/// * the SvcParamValue for an SvcParamKey does not have the expected
72/// format.
73///
74/// Note that the second condition implies that there are no duplicate
75/// SvcParamKeys.
76///
77/// If any RRs are malformed, the client MUST reject the entire RRSet and
78/// fall back to non-SVCB connection establishment.
79/// ```
80#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
81#[derive(Debug, PartialEq, Eq, Hash, Clone)]
82#[non_exhaustive]
83pub struct SVCB {
84 /// [RFC 9460 SVCB and HTTPS Resource Records, Nov 2023](https://datatracker.ietf.org/doc/html/rfc9460#section-2.4.1)
85 /// ```text
86 /// 2.4.1. SvcPriority
87 ///
88 /// When SvcPriority is 0 the SVCB record is in AliasMode
89 /// (Section 2.4.2). Otherwise, it is in ServiceMode (Section 2.4.3).
90 ///
91 /// Within a SVCB RRSet, all RRs SHOULD have the same Mode. If an RRSet
92 /// contains a record in AliasMode, the recipient MUST ignore any
93 /// ServiceMode records in the set.
94 ///
95 /// RRSets are explicitly unordered collections, so the SvcPriority field
96 /// is used to impose an ordering on SVCB RRs. A smaller SvcPriority indicates
97 /// that the domain owner recommends the use of this record over ServiceMode
98 /// RRs with a larger SvcPriority value.
99 ///
100 /// When receiving an RRSet containing multiple SVCB records with the
101 /// same SvcPriority value, clients SHOULD apply a random shuffle within
102 /// a priority level to the records before using them, to ensure uniform
103 /// load-balancing.
104 /// ```
105 pub svc_priority: u16,
106
107 /// [RFC 9460 SVCB and HTTPS Resource Records, Nov 2023](https://datatracker.ietf.org/doc/html/rfc9460#section-2.5)
108 /// ```text
109 /// 2.5. Special handling of "." in TargetName
110 ///
111 /// If TargetName has the value "." (represented in the wire format as a
112 /// zero-length label), special rules apply.
113 ///
114 /// 2.5.1. AliasMode
115 ///
116 /// For AliasMode SVCB RRs, a TargetName of "." indicates that the
117 /// service is not available or does not exist. This indication is
118 /// advisory: clients encountering this indication MAY ignore it and
119 /// attempt to connect without the use of SVCB.
120 ///
121 /// 2.5.2. ServiceMode
122 ///
123 /// For ServiceMode SVCB RRs, if TargetName has the value ".", then the
124 /// owner name of this record MUST be used as the effective TargetName.
125 /// If the record has a wildcard owner name in the zone file, the recipient
126 /// SHALL use the response's synthesized owner name as the effective TargetName.
127 ///
128 /// Here, for example, "svc2.example.net" is the effective TargetName:
129 ///
130 /// example.com. 7200 IN HTTPS 0 svc.example.net.
131 /// svc.example.net. 7200 IN CNAME svc2.example.net.
132 /// svc2.example.net. 7200 IN HTTPS 1 . port=8002
133 /// svc2.example.net. 300 IN A 192.0.2.2
134 /// svc2.example.net. 300 IN AAAA 2001:db8::2
135 /// ```
136 pub target_name: Name,
137
138 /// See [`SvcParamKey`] for details on each parameter
139 pub svc_params: Vec<(SvcParamKey, SvcParamValue)>,
140}
141
142impl SVCB {
143 /// Create a new SVCB record from parts
144 ///
145 /// It is up to the caller to validate the data going into the record
146 pub fn new(
147 svc_priority: u16,
148 target_name: Name,
149 svc_params: Vec<(SvcParamKey, SvcParamValue)>,
150 ) -> Self {
151 Self {
152 svc_priority,
153 target_name,
154 svc_params,
155 }
156 }
157
158 /// [RFC 9460 SVCB and HTTPS Resource Records, Nov 2023](https://datatracker.ietf.org/doc/html/rfc9460#section-2.1)
159 ///
160 /// ```text
161 /// 2.1. Zone file presentation format
162 ///
163 /// The presentation format <RDATA> of the record ([RFC1035]) has the form:
164 ///
165 /// SvcPriority TargetName SvcParams
166 ///
167 /// The SVCB record is defined specifically within the Internet ("IN")
168 /// Class ([RFC1035]).
169 ///
170 /// SvcPriority is a number in the range 0-65535, TargetName is a
171 /// <domain-name> ([RFC1035], Section 5.1), and the SvcParams are
172 /// a whitespace-separated list, with each SvcParam consisting of a
173 /// SvcParamKey=SvcParamValue pair or a standalone SvcParamKey.
174 /// SvcParamKeys are registered by IANA (Section 14.3).
175 ///
176 /// Each SvcParamKey SHALL appear at most once in the SvcParams. In
177 /// presentation format, SvcParamKeys are lowercase alphanumeric
178 /// strings. Key names should contain 1-63 characters from the ranges
179 /// "a"-"z", "0"-"9", and "-". In ABNF [RFC5234],
180 ///
181 /// alpha-lc = %x61-7A ; a-z
182 /// SvcParamKey = 1*63(alpha-lc / DIGIT / "-")
183 /// SvcParam = SvcParamKey ["=" SvcParamValue]
184 /// SvcParamValue = char-string ; See Appendix A.
185 /// value = *OCTET ; Value before key-specific parsing
186 ///
187 /// The SvcParamValue is parsed using the character-string decoding
188 /// algorithm (Appendix A), producing a value. The value is then
189 /// validated and converted into wire-format in a manner specific to each
190 /// key.
191 ///
192 /// When the optional "=" and SvcParamValue are omitted, the value is
193 /// interpreted as empty.
194 ///
195 /// Arbitrary keys can be represented using the unknown-key presentation
196 /// format "keyNNNNN" where NNNNN is the numeric value of the key type
197 /// without leading zeros. A SvcParam in this form SHALL be parsed as
198 /// specified above, and the decoded value SHALL be used as its wire-format
199 /// encoding.
200 ///
201 /// For some SvcParamKeys, the value corresponds to a list or set of
202 /// items. Presentation formats for such keys SHOULD use a comma-
203 /// separated list (Appendix A.1).
204 ///
205 /// SvcParams in presentation format MAY appear in any order, but keys
206 /// MUST NOT be repeated.
207 /// ```
208 pub(crate) fn from_tokens<'i, I: Iterator<Item = &'i str>>(
209 mut tokens: I,
210 ) -> Result<Self, ParseError> {
211 // SvcPriority
212 let svc_priority: u16 = tokens
213 .next()
214 .ok_or_else(|| ParseError::MissingToken("SvcPriority".to_string()))
215 .and_then(|s| s.parse().map_err(Into::into))?;
216
217 // svcb target
218 let target_name: Name = tokens
219 .next()
220 .ok_or_else(|| ParseError::MissingToken("Target".to_string()))
221 .and_then(|s| Name::from_str(s).map_err(ParseError::from))?;
222
223 // Loop over all of the service parameters
224 let mut svc_params = Vec::new();
225 for token in tokens {
226 // first need to split the key and (optional) value
227 let mut key_value = token.splitn(2, '=');
228 let key = key_value
229 .next()
230 .ok_or_else(|| ParseError::MissingToken("SVCB SvcbParams missing".to_string()))?;
231
232 // get the value, and remove any quotes
233 let mut value = key_value.next();
234 if let Some(value) = value.as_mut() {
235 if value.starts_with('"') && value.ends_with('"') {
236 *value = &value[1..value.len() - 1];
237 }
238 }
239 svc_params.push(into_svc_param(key, value)?);
240 }
241
242 Ok(SVCB::new(svc_priority, target_name, svc_params))
243 }
244}
245
246// first take the param and convert to
247fn into_svc_param(
248 key: &str,
249 value: Option<&str>,
250) -> Result<(SvcParamKey, SvcParamValue), ParseError> {
251 let key = SvcParamKey::from_str(key)?;
252 let value = parse_value(key, value)?;
253
254 Ok((key, value))
255}
256
257fn parse_value(key: SvcParamKey, value: Option<&str>) -> Result<SvcParamValue, ParseError> {
258 match key {
259 SvcParamKey::Mandatory => parse_mandatory(value),
260 SvcParamKey::Alpn => parse_alpn(value),
261 SvcParamKey::NoDefaultAlpn => parse_no_default_alpn(value),
262 SvcParamKey::Port => parse_port(value),
263 SvcParamKey::Ipv4Hint => parse_ipv4_hint(value),
264 SvcParamKey::Ipv6Hint => parse_ipv6_hint(value),
265 SvcParamKey::EchConfigList => parse_ech_config(value),
266 SvcParamKey::Key(_) => parse_unknown(value),
267 SvcParamKey::Key65535 | SvcParamKey::Unknown(_) => Err(ParseError::Message(
268 "Bad Key type or unsupported, see generic key option, e.g. key1234",
269 )),
270 }
271}
272
273fn parse_char_data(value: &str) -> Result<String, ParseError> {
274 let mut lex = Lexer::new(value);
275 let ch_data = lex
276 .next_token()?
277 .ok_or(ParseError::Message("expected character data"))?;
278
279 match ch_data {
280 Token::CharData(data) => Ok(data),
281 _ => Err(ParseError::Message("expected character data")),
282 }
283}
284
285/// [RFC 9460 SVCB and HTTPS Resource Records, Nov 2023](https://datatracker.ietf.org/doc/html/rfc9460#section-8)
286///
287/// ```text
288/// The presentation value SHALL be a comma-separated list
289/// (Appendix A.1) of one or more valid SvcParamKeys, either by their
290/// registered name or in the unknown-key format (Section 2.1). Keys MAY
291/// appear in any order, but MUST NOT appear more than once. For self-
292/// consistency (Section 2.4.3), listed keys MUST also appear in the
293/// SvcParams.
294///
295/// To enable simpler parsing, this SvcParamValue MUST NOT contain escape
296/// sequences.
297///
298/// For example, the following is a valid list of SvcParams:
299///
300/// ipv6hint=... key65333=ex1 key65444=ex2 mandatory=key65444,ipv6hint
301/// ```
302///
303/// Currently this does not validate that the mandatory section matches the other keys
304fn parse_mandatory(value: Option<&str>) -> Result<SvcParamValue, ParseError> {
305 let value = value.ok_or(ParseError::Message("expected at least one Mandatory field"))?;
306
307 let mandatories = parse_list::<SvcParamKey>(value)?;
308 Ok(SvcParamValue::Mandatory(Mandatory(mandatories)))
309}
310
311/// [RFC 9460 SVCB and HTTPS Resource Records, Nov 2023](https://datatracker.ietf.org/doc/html/rfc9460#section-7.1.1)
312///
313/// ```text
314/// ALPNs are identified by their registered "Identification Sequence"
315/// (alpn-id), which is a sequence of 1-255 octets.
316///
317/// alpn-id = 1*255OCTET
318///
319/// For "alpn", the presentation value SHALL be a comma-separated list
320/// (Appendix A.1) of one or more alpn-ids.
321/// ```
322///
323/// This does not currently check to see if the ALPN code is legitimate
324fn parse_alpn(value: Option<&str>) -> Result<SvcParamValue, ParseError> {
325 let value = value.ok_or(ParseError::Message("expected at least one ALPN code"))?;
326
327 let alpns = parse_list::<String>(value).expect("infallible");
328 Ok(SvcParamValue::Alpn(Alpn(alpns)))
329}
330
331/// [RFC 9460 SVCB and HTTPS Resource Records, Nov 2023](https://datatracker.ietf.org/doc/html/rfc9460#section-7.1.1)
332///
333/// ```text
334/// For "no-default-alpn", the presentation and wire format values MUST
335/// be empty. When "no-default-alpn" is specified in an RR, "alpn" must
336/// also be specified in order for the RR to be "self-consistent"
337/// (Section 2.4.3).
338/// ```
339fn parse_no_default_alpn(value: Option<&str>) -> Result<SvcParamValue, ParseError> {
340 if value.is_some() {
341 return Err(ParseError::Message("no value expected for NoDefaultAlpn"));
342 }
343
344 Ok(SvcParamValue::NoDefaultAlpn)
345}
346
347/// [RFC 9460 SVCB and HTTPS Resource Records, Nov 2023](https://datatracker.ietf.org/doc/html/rfc9460#section-7.2)
348///
349/// ```text
350/// The presentation value of the SvcParamValue is a single decimal
351/// integer between 0 and 65535 in ASCII. Any other value (e.g. an
352/// empty value) is a syntax error. To enable simpler parsing, this
353/// SvcParam MUST NOT contain escape sequences.
354/// ```
355fn parse_port(value: Option<&str>) -> Result<SvcParamValue, ParseError> {
356 let value = value.ok_or(ParseError::Message("a port number for the port option"))?;
357
358 let value = parse_char_data(value)?;
359 let port = u16::from_str(&value)?;
360 Ok(SvcParamValue::Port(port))
361}
362
363/// [RFC 9460 SVCB and HTTPS Resource Records, Nov 2023](https://datatracker.ietf.org/doc/html/rfc9460#section-7.3)
364///
365/// ```text
366/// The presentation value SHALL be a comma-separated list
367/// (Appendix A.1) of one or more IP addresses of the appropriate family
368/// in standard textual format [RFC5952]. To enable simpler parsing,
369/// this SvcParamValue MUST NOT contain escape sequences.
370/// ```
371fn parse_ipv4_hint(value: Option<&str>) -> Result<SvcParamValue, ParseError> {
372 let value = value.ok_or(ParseError::Message("expected at least one ipv4 hint"))?;
373
374 let hints = parse_list::<A>(value)?;
375 Ok(SvcParamValue::Ipv4Hint(IpHint(hints)))
376}
377
378/// [RFC 9460 SVCB and HTTPS Resource Records, Nov 2023](https://datatracker.ietf.org/doc/html/rfc9460#section-7.3)
379///
380/// ```text
381/// The presentation value SHALL be a comma-separated list
382/// (Appendix A.1) of one or more IP addresses of the appropriate family
383/// in standard textual format [RFC5952]. To enable simpler parsing,
384/// this SvcParamValue MUST NOT contain escape sequences.
385/// ```
386fn parse_ipv6_hint(value: Option<&str>) -> Result<SvcParamValue, ParseError> {
387 let value = value.ok_or(ParseError::Message("expected at least one ipv6 hint"))?;
388
389 let hints = parse_list::<AAAA>(value)?;
390 Ok(SvcParamValue::Ipv6Hint(IpHint(hints)))
391}
392
393/// As the documentation states, the presentation format (what this function outputs) must be a BASE64 encoded string.
394/// hickory-dns will encode to BASE64 during formatting of the internal data, and output the BASE64 value.
395///
396/// [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)
397/// ```text
398/// In presentation format, the value is the ECHConfigList in Base 64 Encoding
399/// (Section 4 of [RFC4648]). Base 64 is used here to simplify integration with
400/// TLS server software. To enable simpler parsing, this SvcParam MUST NOT
401/// contain escape sequences.
402/// ```
403fn parse_ech_config(value: Option<&str>) -> Result<SvcParamValue, ParseError> {
404 let value = value.ok_or(ParseError::Message(
405 "expected a base64 encoded string for EchConfig",
406 ))?;
407
408 let value = parse_char_data(value)?;
409 let ech_config_bytes = data_encoding::BASE64.decode(value.as_bytes())?;
410 Ok(SvcParamValue::EchConfigList(EchConfigList(
411 ech_config_bytes,
412 )))
413}
414
415/// [RFC 9460 SVCB and HTTPS Resource Records, Nov 2023](https://datatracker.ietf.org/doc/html/rfc9460#section-2.1)
416///
417/// ```text
418/// Arbitrary keys can be represented using the unknown-key presentation
419/// format "keyNNNNN" where NNNNN is the numeric value of the key type
420/// without leading zeros. A SvcParam in this form SHALL be parsed as specified
421/// above, and the decoded value SHALL be used as its wire-format encoding.
422///
423/// For some SvcParamKeys, the value corresponds to a list or set of
424/// items. Presentation formats for such keys SHOULD use a comma-
425/// separated list (Appendix A.1).
426///
427/// SvcParams in presentation format MAY appear in any order, but keys
428/// MUST NOT be repeated.
429/// ```
430fn parse_unknown(value: Option<&str>) -> Result<SvcParamValue, ParseError> {
431 let unknown: Vec<u8> = if let Some(value) = value {
432 value.as_bytes().to_vec()
433 } else {
434 Vec::new()
435 };
436
437 Ok(SvcParamValue::Unknown(Unknown(unknown)))
438}
439
440fn parse_list<T>(value: &str) -> Result<Vec<T>, ParseError>
441where
442 T: FromStr,
443 T::Err: Into<ParseError>,
444{
445 let mut result = Vec::new();
446 let mut current_value = String::new();
447 let mut escaping = false;
448
449 for c in value.chars() {
450 match (c, escaping) {
451 // End of value
452 (',', false) => {
453 result.push(T::from_str(&parse_char_data(¤t_value)?).map_err(Into::into)?);
454 current_value.clear()
455 }
456 // Start of escape sequence
457 ('\\', false) => escaping = true,
458 // Comma inside escape sequence
459 (',', true) => {
460 current_value.push(',');
461 escaping = false
462 }
463 // Regular character inside escape sequence
464 (_, true) => {
465 current_value.push(c);
466 escaping = false
467 }
468 // Regular character
469 (_, false) => current_value.push(c),
470 }
471 }
472
473 // Push the remaining value if there's any
474 if !current_value.is_empty() {
475 result.push(T::from_str(&parse_char_data(¤t_value)?).map_err(Into::into)?);
476 }
477
478 Ok(result)
479}
480
481/// [RFC 9460 SVCB and HTTPS Resource Records, Nov 2023](https://datatracker.ietf.org/doc/html/rfc9460#section-14.3.2)
482///
483/// ```text
484/// 14.3.2. Initial Contents
485///
486/// The "Service Parameter Keys (SvcParamKeys)" registry has been
487/// populated with the following initial registrations:
488///
489/// +===========+=================+================+=========+==========+
490/// | Number | Name | Meaning |Reference|Change |
491/// | | | | |Controller|
492/// +===========+=================+================+=========+==========+
493/// | 0 | mandatory | Mandatory |RFC 9460,|IETF |
494/// | | | keys in this |Section 8| |
495/// | | | RR | | |
496/// +-----------+-----------------+----------------+---------+----------+
497/// | 1 | alpn | Additional |RFC 9460,|IETF |
498/// | | | supported |Section | |
499/// | | | protocols |7.1 | |
500/// +-----------+-----------------+----------------+---------+----------+
501/// | 2 | no-default-alpn | No support |RFC 9460,|IETF |
502/// | | | for default |Section | |
503/// | | | protocol |7.1 | |
504/// +-----------+-----------------+----------------+---------+----------+
505/// | 3 | port | Port for |RFC 9460,|IETF |
506/// | | | alternative |Section | |
507/// | | | endpoint |7.2 | |
508/// +-----------+-----------------+----------------+---------+----------+
509/// | 4 | ipv4hint | IPv4 address |RFC 9460,|IETF |
510/// | | | hints |Section | |
511/// | | | |7.3 | |
512/// +-----------+-----------------+----------------+---------+----------+
513/// | 5 | ech | RESERVED |N/A |IETF |
514/// | | | (held for | | |
515/// | | | Encrypted | | |
516/// | | | ClientHello) | | |
517/// +-----------+-----------------+----------------+---------+----------+
518/// | 6 | ipv6hint | IPv6 address |RFC 9460,|IETF |
519/// | | | hints |Section | |
520/// | | | |7.3 | |
521/// +-----------+-----------------+----------------+---------+----------+
522/// |65280-65534| N/A | Reserved for |RFC 9460 |IETF |
523/// | | | Private Use | | |
524/// +-----------+-----------------+----------------+---------+----------+
525/// | 65535 | N/A | Reserved |RFC 9460 |IETF |
526/// | | | ("Invalid | | |
527/// | | | key") | | |
528/// +-----------+-----------------+----------------+---------+----------+
529///
530/// parsing done via:
531/// * a 2 octet field containing the SvcParamKey as an integer in
532/// network byte order. (See Section 14.3.2 for the defined values.)
533/// ```
534#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
535#[derive(Debug, PartialEq, Eq, Hash, Clone, Copy)]
536pub enum SvcParamKey {
537 /// Mandatory keys in this RR
538 #[cfg_attr(feature = "serde", serde(rename = "mandatory"))]
539 Mandatory,
540 /// Additional supported protocols
541 #[cfg_attr(feature = "serde", serde(rename = "alpn"))]
542 Alpn,
543 /// No support for default protocol
544 #[cfg_attr(feature = "serde", serde(rename = "no-default-alpn"))]
545 NoDefaultAlpn,
546 /// Port for alternative endpoint
547 #[cfg_attr(feature = "serde", serde(rename = "port"))]
548 Port,
549 /// IPv4 address hints
550 #[cfg_attr(feature = "serde", serde(rename = "ipv4hint"))]
551 Ipv4Hint,
552 /// Encrypted Client Hello configuration list
553 #[cfg_attr(feature = "serde", serde(rename = "ech"))]
554 EchConfigList,
555 /// IPv6 address hints
556 #[cfg_attr(feature = "serde", serde(rename = "ipv6hint"))]
557 Ipv6Hint,
558 /// Private Use
559 Key(u16),
560 /// Reserved ("Invalid key")
561 Key65535,
562 /// Unknown
563 Unknown(u16),
564}
565
566impl From<u16> for SvcParamKey {
567 fn from(val: u16) -> Self {
568 match val {
569 0 => Self::Mandatory,
570 1 => Self::Alpn,
571 2 => Self::NoDefaultAlpn,
572 3 => Self::Port,
573 4 => Self::Ipv4Hint,
574 5 => Self::EchConfigList,
575 6 => Self::Ipv6Hint,
576 65280..=65534 => Self::Key(val),
577 65535 => Self::Key65535,
578 _ => Self::Unknown(val),
579 }
580 }
581}
582
583impl From<SvcParamKey> for u16 {
584 fn from(val: SvcParamKey) -> Self {
585 match val {
586 SvcParamKey::Mandatory => 0,
587 SvcParamKey::Alpn => 1,
588 SvcParamKey::NoDefaultAlpn => 2,
589 SvcParamKey::Port => 3,
590 SvcParamKey::Ipv4Hint => 4,
591 SvcParamKey::EchConfigList => 5,
592 SvcParamKey::Ipv6Hint => 6,
593 SvcParamKey::Key(val) => val,
594 SvcParamKey::Key65535 => 65535,
595 SvcParamKey::Unknown(val) => val,
596 }
597 }
598}
599
600impl<'r> BinDecodable<'r> for SvcParamKey {
601 // a 2 octet field containing the SvcParamKey as an integer in
602 // network byte order. (See Section 14.3.2 for the defined values.)
603 fn read(decoder: &mut BinDecoder<'r>) -> Result<Self, DecodeError> {
604 Ok(decoder.read_u16()?.unverified(/*any u16 is valid*/).into())
605 }
606}
607
608impl BinEncodable for SvcParamKey {
609 // a 2 octet field containing the SvcParamKey as an integer in
610 // network byte order. (See Section 14.3.2 for the defined values.)
611 fn emit(&self, encoder: &mut BinEncoder<'_>) -> ProtoResult<()> {
612 encoder.emit_u16((*self).into())
613 }
614}
615
616impl fmt::Display for SvcParamKey {
617 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
618 match self {
619 Self::Mandatory => f.write_str("mandatory")?,
620 Self::Alpn => f.write_str("alpn")?,
621 Self::NoDefaultAlpn => f.write_str("no-default-alpn")?,
622 Self::Port => f.write_str("port")?,
623 Self::Ipv4Hint => f.write_str("ipv4hint")?,
624 Self::EchConfigList => f.write_str("ech")?,
625 Self::Ipv6Hint => f.write_str("ipv6hint")?,
626 Self::Key(val) => write!(f, "key{val}")?,
627 Self::Key65535 => f.write_str("key65535")?,
628 Self::Unknown(val) => write!(f, "unknown{val}")?,
629 }
630
631 Ok(())
632 }
633}
634
635impl FromStr for SvcParamKey {
636 type Err = ProtoError;
637
638 fn from_str(s: &str) -> Result<Self, Self::Err> {
639 /// keys are in the format of key#, e.g. key12344, with a max value of u16
640 fn parse_unknown_key(key: &str) -> Result<SvcParamKey, ProtoError> {
641 let key_value = key.strip_prefix("key").ok_or_else(|| {
642 ProtoError::Msg(format!("bad formatted key ({key}), expected key1234"))
643 })?;
644
645 Ok(SvcParamKey::Key(u16::from_str(key_value)?))
646 }
647
648 let key = match s {
649 "mandatory" => Self::Mandatory,
650 "alpn" => Self::Alpn,
651 "no-default-alpn" => Self::NoDefaultAlpn,
652 "port" => Self::Port,
653 "ipv4hint" => Self::Ipv4Hint,
654 "ech" => Self::EchConfigList,
655 "ipv6hint" => Self::Ipv6Hint,
656 "key65535" => Self::Key65535,
657 _ => parse_unknown_key(s)?,
658 };
659
660 Ok(key)
661 }
662}
663
664impl Ord for SvcParamKey {
665 fn cmp(&self, other: &Self) -> Ordering {
666 u16::from(*self).cmp(&u16::from(*other))
667 }
668}
669
670impl PartialOrd for SvcParamKey {
671 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
672 Some(self.cmp(other))
673 }
674}
675
676/// Warning, it is currently up to users of this type to validate the data against that expected by the key
677///
678/// ```text
679/// * a 2 octet field containing the length of the SvcParamValue as an
680/// integer between 0 and 65535 in network byte order (but constrained
681/// by the RDATA and DNS message sizes).
682/// * an octet string of this length whose contents are in a format
683/// determined by the SvcParamKey.
684/// ```
685#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
686#[derive(Debug, PartialEq, Eq, Hash, Clone)]
687pub enum SvcParamValue {
688 /// In a ServiceMode RR, a SvcParamKey is considered "mandatory" if the
689 /// RR will not function correctly for clients that ignore this
690 /// SvcParamKey. Each SVCB protocol mapping SHOULD specify a set of keys
691 /// that are "automatically mandatory", i.e. mandatory if they are
692 /// present in an RR. The SvcParamKey "mandatory" is used to indicate
693 /// any mandatory keys for this RR, in addition to any automatically
694 /// mandatory keys that are present.
695 ///
696 /// see `Mandatory`
697 #[cfg_attr(feature = "serde", serde(rename = "mandatory"))]
698 Mandatory(Mandatory),
699 /// [RFC 9460 SVCB and HTTPS Resource Records, Nov 2023](https://datatracker.ietf.org/doc/html/rfc9460#section-7.1)
700 ///
701 /// ```text
702 /// The "alpn" and "no-default-alpn" SvcParamKeys together indicate the
703 /// set of Application Layer Protocol Negotiation (ALPN) protocol
704 /// identifiers [Alpn] and associated transport protocols supported by
705 /// this service endpoint (the "SVCB ALPN set").
706 /// ```
707 #[cfg_attr(feature = "serde", serde(rename = "alpn"))]
708 Alpn(Alpn),
709 /// For "no-default-alpn", the presentation and wire format values MUST
710 /// be empty.
711 /// See also `Alpn`
712 #[cfg_attr(feature = "serde", serde(rename = "no-default-alpn"))]
713 NoDefaultAlpn,
714 /// [RFC 9460 SVCB and HTTPS Resource Records, Nov 2023](https://datatracker.ietf.org/doc/html/rfc9460#section-7.2)
715 ///
716 /// ```text
717 /// 7.2. "port"
718 ///
719 /// The "port" SvcParamKey defines the TCP or UDP port that should be
720 /// used to reach this alternative endpoint. If this key is not present,
721 /// clients SHALL use the authority endpoint's port number.
722 ///
723 /// The presentation value of the SvcParamValue is a single decimal
724 /// integer between 0 and 65535 in ASCII. Any other value (e.g. an
725 /// empty value) is a syntax error. To enable simpler parsing, this
726 /// SvcParam MUST NOT contain escape sequences.
727 ///
728 /// The wire format of the SvcParamValue is the corresponding 2 octet
729 /// numeric value in network byte order.
730 ///
731 /// If a port-restricting firewall is in place between some client and
732 /// the service endpoint, changing the port number might cause that
733 /// client to lose access to the service, so operators should exercise
734 /// caution when using this SvcParamKey to specify a non-default port.
735 /// ```
736 #[cfg_attr(feature = "serde", serde(rename = "port"))]
737 Port(u16),
738 /// [RFC 9460 SVCB and HTTPS Resource Records, Nov 2023](https://datatracker.ietf.org/doc/html/rfc9460#section-7.2)
739 ///
740 /// The "ipv4hint" and "ipv6hint" keys convey IP addresses that clients
741 /// MAY use to reach the service. If A and AAAA records for TargetName
742 /// are locally available, the client SHOULD ignore these hints.
743 /// Otherwise, clients SHOULD perform A and/or AAAA queries for
744 /// TargetName as in Section 3, and clients SHOULD use the IP address in
745 /// those responses for future connections. Clients MAY opt to terminate
746 /// any connections using the addresses in hints and instead switch to
747 /// the addresses in response to the TargetName query. Failure to use A
748 /// and/or AAAA response addresses could negatively impact load balancing
749 /// or other geo-aware features and thereby degrade client performance.
750 ///
751 /// see `IpHint`
752 #[cfg_attr(feature = "serde", serde(rename = "ipv4hint"))]
753 Ipv4Hint(IpHint<A>),
754 /// [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)
755 ///
756 /// ```text
757 /// 2. "SvcParam for ECH configuration"
758 ///
759 /// The "ech" SvcParamKey is defined for conveying the ECH configuration
760 /// of an alternative endpoint. It is applicable to all TLS-based protocols
761 /// (including DTLS [RFC9147] and QUIC version 1 [RFC9001]) unless otherwise
762 /// specified.
763 /// ```
764 #[cfg_attr(feature = "serde", serde(rename = "ech"))]
765 EchConfigList(EchConfigList),
766 /// See `IpHint`
767 #[cfg_attr(feature = "serde", serde(rename = "ipv6hint"))]
768 Ipv6Hint(IpHint<AAAA>),
769 /// Unparsed network data. Refer to documents on the associated key value
770 ///
771 /// This will be left as is when read off the wire, and encoded in bas64
772 /// for presentation.
773 Unknown(Unknown),
774}
775
776impl SvcParamValue {
777 // a 2 octet field containing the length of the SvcParamValue as an
778 // integer between 0 and 65535 in network byte order (but constrained
779 // by the RDATA and DNS message sizes).
780 fn read(key: SvcParamKey, decoder: &mut BinDecoder<'_>) -> Result<Self, DecodeError> {
781 let len: usize = decoder
782 .read_u16()?
783 .verify_unwrap(|len| *len as usize <= decoder.len())
784 .map(|len| len as usize)
785 .map_err(|u| DecodeError::IncorrectRDataLengthRead {
786 read: decoder.len(),
787 len: u as usize,
788 })?;
789
790 let param_data = decoder.read_slice(len)?.unverified(/*verification to be done by individual param types*/);
791 let mut decoder = BinDecoder::new(param_data);
792
793 let value = match key {
794 SvcParamKey::Mandatory => Self::Mandatory(Mandatory::read(&mut decoder)?),
795 SvcParamKey::Alpn => Self::Alpn(Alpn::read(&mut decoder)?),
796 // should always be empty
797 SvcParamKey::NoDefaultAlpn => {
798 if len > 0 {
799 return Err(DecodeError::IncorrectRDataLengthRead { read: len, len: 0 });
800 }
801
802 Self::NoDefaultAlpn
803 }
804 // The wire format of the SvcParamValue is the corresponding 2 octet
805 // numeric value in network byte order.
806 SvcParamKey::Port => {
807 let port = decoder.read_u16()?.unverified(/*all values are legal ports*/);
808 Self::Port(port)
809 }
810 SvcParamKey::Ipv4Hint => Self::Ipv4Hint(IpHint::<A>::read(&mut decoder)?),
811 SvcParamKey::EchConfigList => Self::EchConfigList(EchConfigList::read(&mut decoder)?),
812 SvcParamKey::Ipv6Hint => Self::Ipv6Hint(IpHint::<AAAA>::read(&mut decoder)?),
813 SvcParamKey::Key(_) | SvcParamKey::Key65535 | SvcParamKey::Unknown(_) => {
814 Self::Unknown(Unknown::read(&mut decoder)?)
815 }
816 };
817
818 Ok(value)
819 }
820}
821
822impl BinEncodable for SvcParamValue {
823 // a 2 octet field containing the length of the SvcParamValue as an
824 // integer between 0 and 65535 in network byte order (but constrained
825 // by the RDATA and DNS message sizes).
826 fn emit(&self, encoder: &mut BinEncoder<'_>) -> ProtoResult<()> {
827 // set the place for the length...
828 let place = encoder.place::<u16>()?;
829
830 match self {
831 Self::Mandatory(mandatory) => mandatory.emit(encoder)?,
832 Self::Alpn(alpn) => alpn.emit(encoder)?,
833 Self::NoDefaultAlpn => (),
834 Self::Port(port) => encoder.emit_u16(*port)?,
835 Self::Ipv4Hint(ip_hint) => ip_hint.emit(encoder)?,
836 Self::EchConfigList(ech_config) => ech_config.emit(encoder)?,
837 Self::Ipv6Hint(ip_hint) => ip_hint.emit(encoder)?,
838 Self::Unknown(unknown) => unknown.emit(encoder)?,
839 }
840
841 // go back and set the length
842 let len = u16::try_from(encoder.len_since_place(&place))
843 .map_err(|_| ProtoError::from("Total length of SvcParamValue exceeds u16::MAX"))?;
844 place.replace(encoder, len)?;
845
846 Ok(())
847 }
848}
849
850impl fmt::Display for SvcParamValue {
851 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
852 match self {
853 Self::Mandatory(mandatory) => write!(f, "{mandatory}")?,
854 Self::Alpn(alpn) => write!(f, "{alpn}")?,
855 Self::NoDefaultAlpn => (),
856 Self::Port(port) => write!(f, "{port}")?,
857 Self::Ipv4Hint(ip_hint) => write!(f, "{ip_hint}")?,
858 Self::EchConfigList(ech_config) => write!(f, "{ech_config}")?,
859 Self::Ipv6Hint(ip_hint) => write!(f, "{ip_hint}")?,
860 Self::Unknown(unknown) => write!(f, "{unknown}")?,
861 }
862
863 Ok(())
864 }
865}
866
867/// [RFC 9460 SVCB and HTTPS Resource Records, Nov 2023](https://datatracker.ietf.org/doc/html/rfc9460#section-8)
868///
869/// ```text
870/// 8. ServiceMode RR compatibility and mandatory keys
871///
872/// In a ServiceMode RR, a SvcParamKey is considered "mandatory" if the
873/// RR will not function correctly for clients that ignore this
874/// SvcParamKey. Each SVCB protocol mapping SHOULD specify a set of keys
875/// that are "automatically mandatory", i.e. mandatory if they are
876/// present in an RR. The SvcParamKey "mandatory" is used to indicate
877/// any mandatory keys for this RR, in addition to any automatically
878/// mandatory keys that are present.
879///
880/// A ServiceMode RR is considered "compatible" with a client if the
881/// client recognizes all the mandatory keys, and their values indicate
882/// that successful connection establishment is possible. Incompatible RRs
883/// are ignored (see step 5 of the procedure defined in Section 3)
884///
885/// The presentation value SHALL be a comma-separated list
886/// (Appendix A.1) of one or more valid SvcParamKeys, either by their
887/// registered name or in the unknown-key format (Section 2.1). Keys MAY
888/// appear in any order, but MUST NOT appear more than once. For self-
889/// consistency (Section 2.4.3), listed keys MUST also appear in the
890/// SvcParams.
891///
892/// To enable simpler parsing, this SvcParamValue MUST NOT contain escape
893/// sequences.
894///
895/// For example, the following is a valid list of SvcParams:
896///
897/// ipv6hint=... key65333=ex1 key65444=ex2 mandatory=key65444,ipv6hint
898///
899/// In wire format, the keys are represented by their numeric values in
900/// network byte order, concatenated in strictly increasing numeric order.
901///
902/// This SvcParamKey is always automatically mandatory, and MUST NOT
903/// appear in its own value-list. Other automatically mandatory keys
904/// SHOULD NOT appear in the list either. (Including them wastes space
905/// and otherwise has no effect.)
906/// ```
907#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
908#[derive(Debug, PartialEq, Eq, Hash, Clone)]
909#[repr(transparent)]
910pub struct Mandatory(pub Vec<SvcParamKey>);
911
912impl<'r> BinDecodable<'r> for Mandatory {
913 /// This expects the decoder to be limited to only this field, i.e. the end of input for the decoder
914 /// is the end of input for the fields
915 ///
916 /// ```text
917 /// In wire format, the keys are represented by their numeric values in
918 /// network byte order, concatenated in strictly increasing numeric order.
919 /// ```
920 fn read(decoder: &mut BinDecoder<'r>) -> Result<Self, DecodeError> {
921 let mut keys = Vec::with_capacity(1);
922
923 while decoder.peek().is_some() {
924 keys.push(SvcParamKey::read(decoder)?);
925 }
926
927 if keys.is_empty() {
928 return Err(DecodeError::SvcParamMissingValue);
929 }
930
931 Ok(Self(keys))
932 }
933}
934
935impl BinEncodable for Mandatory {
936 /// This expects the decoder to be limited to only this field, i.e. the end of input for the decoder
937 /// is the end of input for the fields
938 ///
939 /// ```text
940 /// In wire format, the keys are represented by their numeric values in
941 /// network byte order, concatenated in strictly increasing numeric order.
942 /// ```
943 fn emit(&self, encoder: &mut BinEncoder<'_>) -> ProtoResult<()> {
944 if self.0.is_empty() {
945 return Err(ProtoError::from("Alpn expects at least one value"));
946 }
947
948 // TODO: order by key value
949 for key in self.0.iter() {
950 key.emit(encoder)?
951 }
952
953 Ok(())
954 }
955}
956
957impl fmt::Display for Mandatory {
958 /// [RFC 9460 SVCB and HTTPS Resource Records, Nov 2023](https://datatracker.ietf.org/doc/html/rfc9460#section-8)
959 ///
960 /// The presentation value SHALL be a comma-separated list
961 /// (Appendix A.1) of one or more valid SvcParamKeys, either by their
962 /// registered name or in the unknown-key format (Section 2.1). Keys MAY
963 /// appear in any order, but MUST NOT appear more than once. For self-
964 /// consistency (Section 2.4.3), listed keys MUST also appear in the
965 /// SvcParams.
966 ///
967 /// To enable simpler parsing, this SvcParamValue MUST NOT contain escape
968 /// sequences.
969 ///
970 /// For example, the following is a valid list of SvcParams:
971 ///
972 /// ipv6hint=... key65333=ex1 key65444=ex2 mandatory=key65444,ipv6hint
973 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
974 for key in self.0.iter() {
975 // TODO: confirm in the RFC that trailing commas are ok
976 write!(f, "{key},")?;
977 }
978
979 Ok(())
980 }
981}
982
983/// [RFC 9460 SVCB and HTTPS Resource Records, Nov 2023](https://datatracker.ietf.org/doc/html/rfc9460#section-7.1)
984///
985/// ```text
986/// 7.1. "alpn" and "no-default-alpn"
987///
988/// The "alpn" and "no-default-alpn" SvcParamKeys together indicate the
989/// set of Application-Layer Protocol Negotiation (ALPN) protocol
990/// identifiers [ALPN] and associated transport protocols supported by
991/// this service endpoint (the "SVCB ALPN set").
992///
993/// As with Alt-Svc [AltSvc], each ALPN protocol identifier is used to
994/// identify the application protocol and associated suite of protocols
995/// supported by the endpoint (the "protocol suite"). The presence of an
996/// ALPN protocol identifier in the SVCB ALPN set indicates that this
997/// service endpoint, described by TargetName and the other parameters
998/// (e.g., "port"), offers service with the protocol suite associated
999/// with this ALPN identifier.
1000///
1001/// Clients filter the set of ALPN identifiers to match the protocol
1002/// suites they support, and this informs the underlying transport
1003/// protocol used (such as QUIC over UDP or TLS over TCP). ALPN protocol
1004/// identifiers that do not uniquely identify a protocol suite (e.g., an
1005/// Identification Sequence that can be used with both TLS and DTLS) are
1006/// not compatible with this SvcParamKey and MUST NOT be included in the
1007/// SVCB ALPN set.
1008///
1009/// 7.1.1. Representation
1010///
1011/// ALPNs are identified by their registered "Identification Sequence"
1012/// (alpn-id), which is a sequence of 1-255 octets.
1013///
1014/// alpn-id = 1*255OCTET
1015///
1016/// For "alpn", the presentation value SHALL be a comma-separated list
1017/// (Appendix A.1) of one or more alpn-ids. Zone-file implementations
1018/// MAY disallow the "," and "\" characters in ALPN IDs instead of
1019/// implementing the value-list escaping procedure, relying on the opaque
1020/// key format (e.g., key1=\002h2) in the event that these characters are
1021/// needed.
1022///
1023/// The wire-format value for "alpn" consists of at least one alpn-id
1024/// prefixed by its length as a single octet, and these length-value
1025/// pairs are concatenated to form the SvcParamValue. These pairs MUST
1026/// exactly fill the SvcParamValue; otherwise, the SvcParamValue is
1027/// malformed.
1028///
1029/// For "no-default-alpn", the presentation and wire-format values MUST
1030/// be empty. When "no-default-alpn" is specified in an RR, "alpn" must
1031/// also be specified in order for the RR to be "self-consistent"
1032/// (Section 2.4.3).
1033///
1034/// Each scheme that uses this SvcParamKey defines a "default set" of
1035/// ALPN IDs that are supported by nearly all clients and servers; this
1036/// set MAY be empty. To determine the SVCB ALPN set, the client starts
1037/// with the list of alpn-ids from the "alpn" SvcParamKey, and it adds
1038/// the default set unless the "no-default-alpn" SvcParamKey is present.
1039///
1040/// 7.1.2. Use
1041///
1042/// To establish a connection to the endpoint, clients MUST
1043///
1044/// 1. Let SVCB-ALPN-Intersection be the set of protocols in the SVCB
1045/// ALPN set that the client supports.
1046///
1047/// 2. Let Intersection-Transports be the set of transports (e.g., TLS,
1048/// DTLS, QUIC) implied by the protocols in SVCB-ALPN-Intersection.
1049///
1050/// 3. For each transport in Intersection-Transports, construct a
1051/// ProtocolNameList containing the Identification Sequences of all
1052/// the client's supported ALPN protocols for that transport, without
1053/// regard to the SVCB ALPN set.
1054///
1055/// For example, if the SVCB ALPN set is ["http/1.1", "h3"] and the
1056/// client supports HTTP/1.1, HTTP/2, and HTTP/3, the client could
1057/// attempt to connect using TLS over TCP with a ProtocolNameList of
1058/// ["http/1.1", "h2"] and could also attempt a connection using QUIC
1059/// with a ProtocolNameList of ["h3"].
1060///
1061/// Once the client has constructed a ClientHello, protocol negotiation
1062/// in that handshake proceeds as specified in [ALPN], without regard to
1063/// the SVCB ALPN set.
1064///
1065/// Clients MAY implement a fallback procedure, using a less-preferred
1066/// transport if more-preferred transports fail to connect. This
1067/// fallback behavior is vulnerable to manipulation by a network attacker
1068/// who blocks the more-preferred transports, but it may be necessary for
1069/// compatibility with existing networks.
1070///
1071/// With this procedure in place, an attacker who can modify DNS and
1072/// network traffic can prevent a successful transport connection but
1073/// cannot otherwise interfere with ALPN protocol selection. This
1074/// procedure also ensures that each ProtocolNameList includes at least
1075/// one protocol from the SVCB ALPN set.
1076///
1077/// Clients SHOULD NOT attempt connection to a service endpoint whose
1078/// SVCB ALPN set does not contain any supported protocols.
1079///
1080/// To ensure consistency of behavior, clients MAY reject the entire SVCB
1081/// RRset and fall back to basic connection establishment if all of the
1082/// compatible RRs indicate "no-default-alpn", even if connection could
1083/// have succeeded using a non-default ALPN protocol.
1084///
1085/// Zone operators SHOULD ensure that at least one RR in each RRset
1086/// supports the default transports. This enables compatibility with the
1087/// greatest number of clients.
1088/// ```
1089#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
1090#[derive(Debug, PartialEq, Eq, Hash, Clone)]
1091#[repr(transparent)]
1092pub struct Alpn(pub Vec<String>);
1093
1094impl<'r> BinDecodable<'r> for Alpn {
1095 /// This expects the decoder to be limited to only this field, i.e. the end of input for the decoder
1096 /// is the end of input for the fields
1097 ///
1098 /// ```text
1099 /// The wire format value for "alpn" consists of at least one alpn-id
1100 /// prefixed by its length as a single octet, and these length-value
1101 /// pairs are concatenated to form the SvcParamValue. These pairs MUST
1102 /// exactly fill the SvcParamValue; otherwise, the SvcParamValue is
1103 /// malformed.
1104 /// ```
1105 fn read(decoder: &mut BinDecoder<'r>) -> Result<Self, DecodeError> {
1106 let mut alpns = Vec::with_capacity(1);
1107
1108 while decoder.peek().is_some() {
1109 let alpn = decoder.read_character_data()?.unverified(/*will rely on string parser*/);
1110 let alpn = String::from_utf8(alpn.to_vec())?;
1111 alpns.push(alpn);
1112 }
1113
1114 if alpns.is_empty() {
1115 return Err(DecodeError::SvcParamMissingValue);
1116 }
1117
1118 Ok(Self(alpns))
1119 }
1120}
1121
1122impl BinEncodable for Alpn {
1123 /// The wire format value for "alpn" consists of at least one alpn-id
1124 /// prefixed by its length as a single octet, and these length-value
1125 /// pairs are concatenated to form the SvcParamValue. These pairs MUST
1126 /// exactly fill the SvcParamValue; otherwise, the SvcParamValue is
1127 /// malformed.
1128 fn emit(&self, encoder: &mut BinEncoder<'_>) -> ProtoResult<()> {
1129 if self.0.is_empty() {
1130 return Err(ProtoError::from("Alpn expects at least one value"));
1131 }
1132
1133 for alpn in self.0.iter() {
1134 encoder.emit_character_data(alpn)?
1135 }
1136
1137 Ok(())
1138 }
1139}
1140
1141impl fmt::Display for Alpn {
1142 /// The presentation value SHALL be a comma-separated list
1143 /// (Appendix A.1) of one or more "alpn-id"s.
1144 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
1145 for alpn in self.0.iter() {
1146 // TODO: confirm in the RFC that trailing commas are ok
1147 write!(f, "{alpn},")?;
1148 }
1149
1150 Ok(())
1151 }
1152}
1153
1154/// [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)
1155///
1156/// ```text
1157/// 2. "SvcParam for ECH configuration"
1158///
1159/// The "ech" SvcParamKey is defined for conveying the ECH configuration
1160/// of an alternative endpoint. It is applicable to all TLS-based protocols
1161/// (including DTLS [RFC9147] and QUIC version 1 [RFC9001]) unless
1162/// otherwise specified.
1163///
1164/// In wire format, the value of the parameter is an ECHConfigList (Section 4 of draft-ietf-tls-esni-18),
1165/// including the redundant length prefix. In presentation format, the value is the ECHConfigList
1166/// in Base 64 Encoding (Section 4 of [RFC4648]). Base 64 is used here to simplify integration
1167/// with TLS server software. To enable simpler parsing, this SvcParam MUST NOT contain escape
1168/// sequences.
1169/// ```
1170#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
1171#[derive(PartialEq, Eq, Hash, Clone)]
1172#[repr(transparent)]
1173pub struct EchConfigList(pub Vec<u8>);
1174
1175impl<'r> BinDecodable<'r> for EchConfigList {
1176 /// In wire format, the value of the parameter is an ECHConfigList (Section 4 of draft-ietf-tls-esni-18),
1177 /// including the redundant length prefix. In presentation format, the value is the
1178 /// ECHConfigList in Base 64 Encoding (Section 4 of RFC4648).
1179 /// Base 64 is used here to simplify integration with TLS server software.
1180 /// To enable simpler parsing, this SvcParam MUST NOT contain escape sequences.
1181 fn read(decoder: &mut BinDecoder<'r>) -> Result<Self, DecodeError> {
1182 let data =
1183 decoder.read_vec(decoder.len())?.unverified(/*up to consumer to validate this data*/);
1184
1185 Ok(Self(data))
1186 }
1187}
1188
1189impl BinEncodable for EchConfigList {
1190 /// In wire format, the value of the parameter is an ECHConfigList (Section 4 of draft-ietf-tls-esni-18),
1191 /// including the redundant length prefix. In presentation format, the value is the
1192 /// ECHConfigList in Base 64 Encoding (Section 4 of RFC4648).
1193 /// Base 64 is used here to simplify integration with TLS server software.
1194 /// To enable simpler parsing, this SvcParam MUST NOT contain escape sequences.
1195 fn emit(&self, encoder: &mut BinEncoder<'_>) -> ProtoResult<()> {
1196 encoder.emit_vec(&self.0)?;
1197
1198 Ok(())
1199 }
1200}
1201
1202impl fmt::Display for EchConfigList {
1203 /// As the documentation states, the presentation format (what this function outputs) must be a BASE64 encoded string.
1204 /// hickory-dns will encode to BASE64 during formatting of the internal data, and output the BASE64 value.
1205 ///
1206 /// [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)
1207 /// ```text
1208 /// In presentation format, the value is the ECHConfigList in Base 64 Encoding
1209 /// (Section 4 of [RFC4648]). Base 64 is used here to simplify integration with
1210 /// TLS server software. To enable simpler parsing, this SvcParam MUST NOT
1211 /// contain escape sequences.
1212 /// ```
1213 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
1214 write!(f, "\"{}\"", data_encoding::BASE64.encode(&self.0))
1215 }
1216}
1217
1218impl fmt::Debug for EchConfigList {
1219 /// The debug format for EchConfig will output the value in BASE64 like Display, but will the addition of the type-name.
1220 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
1221 write!(
1222 f,
1223 "\"EchConfig ({})\"",
1224 data_encoding::BASE64.encode(&self.0)
1225 )
1226 }
1227}
1228
1229/// [RFC 9460 SVCB and HTTPS Resource Records, Nov 2023](https://datatracker.ietf.org/doc/html/rfc9460#section-7.3)
1230///
1231/// ```text
1232/// 7.3. "ipv4hint" and "ipv6hint"
1233///
1234/// The "ipv4hint" and "ipv6hint" keys convey IP addresses that clients
1235/// MAY use to reach the service. If A and AAAA records for TargetName
1236/// are locally available, the client SHOULD ignore these hints.
1237/// Otherwise, clients SHOULD perform A and/or AAAA queries for
1238/// TargetName per Section 3, and clients SHOULD use the IP address in
1239/// those responses for future connections. Clients MAY opt to terminate
1240/// any connections using the addresses in hints and instead switch to
1241/// the addresses in response to the TargetName query. Failure to use A
1242/// and/or AAAA response addresses could negatively impact load balancing
1243/// or other geo-aware features and thereby degrade client performance.
1244///
1245/// The presentation value SHALL be a comma-separated list (Appendix A.1)
1246/// of one or more IP addresses of the appropriate family in standard
1247/// textual format [RFC5952] [RFC4001]. To enable simpler parsing, this
1248/// SvcParamValue MUST NOT contain escape sequences.
1249///
1250/// The wire format for each parameter is a sequence of IP addresses in
1251/// network byte order (for the respective address family). Like an A or
1252/// AAAA RRset, the list of addresses represents an unordered collection,
1253/// and clients SHOULD pick addresses to use in a random order. An empty
1254/// list of addresses is invalid.
1255///
1256/// When selecting between IPv4 and IPv6 addresses to use, clients may
1257/// use an approach such as Happy Eyeballs [HappyEyeballsV2]. When only
1258/// "ipv4hint" is present, NAT64 clients may synthesize IPv6 addresses as
1259/// specified in [RFC7050] or ignore the "ipv4hint" key and wait for AAAA
1260/// resolution (Section 3). For best performance, server operators
1261/// SHOULD include an "ipv6hint" parameter whenever they include an
1262/// "ipv4hint" parameter.
1263///
1264/// These parameters are intended to minimize additional connection
1265/// latency when a recursive resolver is not compliant with the
1266/// requirements in Section 4 and SHOULD NOT be included if most clients
1267/// are using compliant recursive resolvers. When TargetName is the
1268/// service name or the owner name (which can be written as "."), server
1269/// operators SHOULD NOT include these hints, because they are unlikely
1270/// to convey any performance benefit.
1271/// ```
1272#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
1273#[derive(Debug, PartialEq, Eq, Hash, Clone)]
1274#[repr(transparent)]
1275pub struct IpHint<T>(pub Vec<T>);
1276
1277impl<'r, T> BinDecodable<'r> for IpHint<T>
1278where
1279 T: BinDecodable<'r>,
1280{
1281 /// The wire format for each parameter is a sequence of IP addresses in
1282 /// network byte order (for the respective address family). Like an A or
1283 /// AAAA RRSet, the list of addresses represents an unordered collection,
1284 /// and clients SHOULD pick addresses to use in a random order. An empty
1285 /// list of addresses is invalid.
1286 fn read(decoder: &mut BinDecoder<'r>) -> Result<Self, DecodeError> {
1287 let mut ips = Vec::new();
1288
1289 while decoder.peek().is_some() {
1290 ips.push(T::read(decoder)?)
1291 }
1292
1293 Ok(Self(ips))
1294 }
1295}
1296
1297impl<T> BinEncodable for IpHint<T>
1298where
1299 T: BinEncodable,
1300{
1301 /// The wire format for each parameter is a sequence of IP addresses in
1302 /// network byte order (for the respective address family). Like an A or
1303 /// AAAA RRSet, the list of addresses represents an unordered collection,
1304 /// and clients SHOULD pick addresses to use in a random order. An empty
1305 /// list of addresses is invalid.
1306 fn emit(&self, encoder: &mut BinEncoder<'_>) -> ProtoResult<()> {
1307 for ip in self.0.iter() {
1308 ip.emit(encoder)?;
1309 }
1310
1311 Ok(())
1312 }
1313}
1314
1315impl<T> fmt::Display for IpHint<T>
1316where
1317 T: fmt::Display,
1318{
1319 /// The presentation value SHALL be a comma-separated list
1320 /// (Appendix A.1) of one or more IP addresses of the appropriate family
1321 /// in standard textual format [RFC 5952](https://tools.ietf.org/html/rfc5952). To enable simpler parsing,
1322 /// this SvcParamValue MUST NOT contain escape sequences.
1323 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
1324 for ip in self.0.iter() {
1325 write!(f, "{ip},")?;
1326 }
1327
1328 Ok(())
1329 }
1330}
1331
1332/// [RFC 9460 SVCB and HTTPS Resource Records, Nov 2023](https://datatracker.ietf.org/doc/html/rfc9460#section-2.1)
1333///
1334/// ```text
1335/// Arbitrary keys can be represented using the unknown-key presentation
1336/// format "keyNNNNN" where NNNNN is the numeric value of the key type
1337/// without leading zeros. A SvcParam in this form SHALL be parsed as specified
1338/// above, and the decoded value SHALL be used as its wire-format encoding.
1339///
1340/// For some SvcParamKeys, the value corresponds to a list or set of
1341/// items. Presentation formats for such keys SHOULD use a comma-
1342/// separated list (Appendix A.1).
1343///
1344/// SvcParams in presentation format MAY appear in any order, but keys
1345/// MUST NOT be repeated.
1346/// ```
1347#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
1348#[derive(Debug, PartialEq, Eq, Hash, Clone)]
1349#[repr(transparent)]
1350pub struct Unknown(pub Vec<u8>);
1351
1352impl<'r> BinDecodable<'r> for Unknown {
1353 fn read(decoder: &mut BinDecoder<'r>) -> Result<Self, DecodeError> {
1354 // The passed slice is already length delimited, and we cannot
1355 // assume it's a collection of anything.
1356 let len = decoder.len();
1357
1358 let data = decoder.read_vec(len)?;
1359 let unknowns = data.unverified(/*any data is valid here*/).to_vec();
1360
1361 Ok(Self(unknowns))
1362 }
1363}
1364
1365impl BinEncodable for Unknown {
1366 fn emit(&self, encoder: &mut BinEncoder<'_>) -> ProtoResult<()> {
1367 encoder.emit_vec(&self.0)?;
1368
1369 Ok(())
1370 }
1371}
1372
1373impl fmt::Display for Unknown {
1374 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
1375 // TODO: this needs to be properly encoded
1376 write!(f, "\"{}\",", String::from_utf8_lossy(&self.0))?;
1377
1378 Ok(())
1379 }
1380}
1381
1382impl BinEncodable for SVCB {
1383 fn emit(&self, encoder: &mut BinEncoder<'_>) -> ProtoResult<()> {
1384 let mut encoder = encoder.with_rdata_behavior(RDataEncoding::Other);
1385
1386 self.svc_priority.emit(&mut encoder)?;
1387 self.target_name.emit(&mut encoder)?;
1388
1389 let mut last_key: Option<SvcParamKey> = None;
1390 for (key, param) in self.svc_params.iter() {
1391 if let Some(last_key) = last_key {
1392 if key <= &last_key {
1393 return Err(ProtoError::from("SvcParams out of order"));
1394 }
1395 }
1396
1397 key.emit(&mut encoder)?;
1398 param.emit(&mut encoder)?;
1399
1400 last_key = Some(*key);
1401 }
1402
1403 Ok(())
1404 }
1405}
1406
1407impl RecordDataDecodable<'_> for SVCB {
1408 /// Reads the SVCB record from the decoder.
1409 ///
1410 /// [RFC 9460 SVCB and HTTPS Resource Records, Nov 2023](https://datatracker.ietf.org/doc/html/rfc9460#section-2.2)
1411 ///
1412 /// ```text
1413 /// Clients MUST consider an RR malformed if:
1414 ///
1415 /// * the end of the RDATA occurs within a SvcParam.
1416 /// * SvcParamKeys are not in strictly increasing numeric order.
1417 /// * the SvcParamValue for an SvcParamKey does not have the expected
1418 /// format.
1419 ///
1420 /// Note that the second condition implies that there are no duplicate
1421 /// SvcParamKeys.
1422 ///
1423 /// If any RRs are malformed, the client MUST reject the entire RRSet and
1424 /// fall back to non-SVCB connection establishment.
1425 /// ```
1426 fn read_data(
1427 decoder: &mut BinDecoder<'_>,
1428 rdata_length: Restrict<u16>,
1429 ) -> Result<Self, DecodeError> {
1430 let start_index = decoder.index();
1431
1432 let svc_priority = decoder.read_u16()?.unverified(/*any u16 is valid*/);
1433 let target_name = Name::read(decoder)?;
1434
1435 let mut remainder_len = rdata_length
1436 .map(|len| len as usize)
1437 .checked_sub(decoder.index() - start_index)
1438 .map_err(|len| DecodeError::IncorrectRDataLengthRead {
1439 read: decoder.index() - start_index,
1440 len,
1441 })?
1442 .unverified(); // valid len
1443 let mut svc_params: Vec<(SvcParamKey, SvcParamValue)> = Vec::new();
1444
1445 // must have at least 4 bytes left for the key and the length
1446 while remainder_len >= 4 {
1447 // a 2 octet field containing the SvcParamKey as an integer in
1448 // network byte order. (See Section 14.3.2 for the defined values.)
1449 let key = SvcParamKey::read(decoder)?;
1450
1451 // a 2 octet field containing the length of the SvcParamValue as an
1452 // integer between 0 and 65535 in network byte order (but constrained
1453 // by the RDATA and DNS message sizes).
1454 let value = SvcParamValue::read(key, decoder)?;
1455
1456 if let Some(last_key) = svc_params.last().map(|(key, _)| key) {
1457 if last_key >= &key {
1458 return Err(DecodeError::SvcParamsOutOfOrder);
1459 }
1460 }
1461
1462 svc_params.push((key, value));
1463 remainder_len = rdata_length
1464 .map(|len| len as usize)
1465 .checked_sub(decoder.index() - start_index)
1466 .map_err(|len| DecodeError::IncorrectRDataLengthRead {
1467 read: decoder.index() - start_index,
1468 len,
1469 })?
1470 .unverified(); // valid len
1471 }
1472
1473 Ok(Self {
1474 svc_priority,
1475 target_name,
1476 svc_params,
1477 })
1478 }
1479}
1480
1481impl RecordData for SVCB {
1482 fn try_borrow(data: &RData) -> Option<&Self> {
1483 match data {
1484 RData::SVCB(data) => Some(data),
1485 _ => None,
1486 }
1487 }
1488
1489 fn record_type(&self) -> RecordType {
1490 RecordType::SVCB
1491 }
1492
1493 fn into_rdata(self) -> RData {
1494 RData::SVCB(self)
1495 }
1496}
1497
1498/// [RFC 9460 SVCB and HTTPS Resource Records, Nov 2023](https://datatracker.ietf.org/doc/html/rfc9460#section-10.4)
1499///
1500/// ```text
1501/// simple.example. 7200 IN HTTPS 1 . alpn=h3
1502/// pool 7200 IN HTTPS 1 h3pool alpn=h2,h3 ech="123..."
1503/// HTTPS 2 . alpn=h2 ech="abc..."
1504/// @ 7200 IN HTTPS 0 www
1505/// _8765._baz.api.example.com. 7200 IN SVCB 0 svc4-baz.example.net.
1506/// ```
1507impl fmt::Display for SVCB {
1508 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
1509 write!(
1510 f,
1511 "{svc_priority} {target_name}",
1512 svc_priority = self.svc_priority,
1513 target_name = self.target_name,
1514 )?;
1515
1516 for (key, param) in self.svc_params.iter() {
1517 write!(f, " {key}={param}")?
1518 }
1519
1520 Ok(())
1521 }
1522}
1523
1524#[cfg(test)]
1525mod tests {
1526 use alloc::{borrow::ToOwned, string::ToString};
1527
1528 use crate::{rr::rdata::HTTPS, serialize::txt::Parser};
1529
1530 use super::*;
1531
1532 #[test]
1533 fn read_svcb_key() {
1534 assert_eq!(SvcParamKey::Mandatory, 0.into());
1535 assert_eq!(SvcParamKey::Alpn, 1.into());
1536 assert_eq!(SvcParamKey::NoDefaultAlpn, 2.into());
1537 assert_eq!(SvcParamKey::Port, 3.into());
1538 assert_eq!(SvcParamKey::Ipv4Hint, 4.into());
1539 assert_eq!(SvcParamKey::EchConfigList, 5.into());
1540 assert_eq!(SvcParamKey::Ipv6Hint, 6.into());
1541 assert_eq!(SvcParamKey::Key(65280), 65280.into());
1542 assert_eq!(SvcParamKey::Key(65534), 65534.into());
1543 assert_eq!(SvcParamKey::Key65535, 65535.into());
1544 assert_eq!(SvcParamKey::Unknown(65279), 65279.into());
1545 }
1546
1547 #[test]
1548 fn read_svcb_key_to_u16() {
1549 assert_eq!(u16::from(SvcParamKey::Mandatory), 0);
1550 assert_eq!(u16::from(SvcParamKey::Alpn), 1);
1551 assert_eq!(u16::from(SvcParamKey::NoDefaultAlpn), 2);
1552 assert_eq!(u16::from(SvcParamKey::Port), 3);
1553 assert_eq!(u16::from(SvcParamKey::Ipv4Hint), 4);
1554 assert_eq!(u16::from(SvcParamKey::EchConfigList), 5);
1555 assert_eq!(u16::from(SvcParamKey::Ipv6Hint), 6);
1556 assert_eq!(u16::from(SvcParamKey::Key(65280)), 65280);
1557 assert_eq!(u16::from(SvcParamKey::Key(65534)), 65534);
1558 assert_eq!(u16::from(SvcParamKey::Key65535), 65535);
1559 assert_eq!(u16::from(SvcParamKey::Unknown(65279)), 65279);
1560 }
1561
1562 #[track_caller]
1563 fn test_encode_decode(rdata: SVCB) {
1564 let mut bytes = Vec::new();
1565 let mut encoder = BinEncoder::new(&mut bytes);
1566 rdata.emit(&mut encoder).expect("failed to emit SVCB");
1567 let bytes = encoder.into_bytes();
1568
1569 let mut decoder = BinDecoder::new(bytes);
1570 let read_rdata = SVCB::read_data(&mut decoder, Restrict::new(bytes.len() as u16))
1571 .expect("failed to read back");
1572 assert_eq!(rdata, read_rdata);
1573 }
1574
1575 #[test]
1576 fn test_encode_decode_svcb() {
1577 test_encode_decode(SVCB::new(
1578 0,
1579 Name::from_utf8("www.example.com.").unwrap(),
1580 vec![],
1581 ));
1582 test_encode_decode(SVCB::new(
1583 0,
1584 Name::from_utf8(".").unwrap(),
1585 vec![(
1586 SvcParamKey::Alpn,
1587 SvcParamValue::Alpn(Alpn(vec!["h2".to_string()])),
1588 )],
1589 ));
1590 test_encode_decode(SVCB::new(
1591 0,
1592 Name::from_utf8("example.com.").unwrap(),
1593 vec![
1594 (
1595 SvcParamKey::Mandatory,
1596 SvcParamValue::Mandatory(Mandatory(vec![SvcParamKey::Alpn])),
1597 ),
1598 (
1599 SvcParamKey::Alpn,
1600 SvcParamValue::Alpn(Alpn(vec!["h2".to_string()])),
1601 ),
1602 ],
1603 ));
1604 }
1605
1606 #[test]
1607 #[should_panic]
1608 fn test_encode_decode_svcb_bad_order() {
1609 test_encode_decode(SVCB::new(
1610 0,
1611 Name::from_utf8(".").unwrap(),
1612 vec![
1613 (
1614 SvcParamKey::Alpn,
1615 SvcParamValue::Alpn(Alpn(vec!["h2".to_string()])),
1616 ),
1617 (
1618 SvcParamKey::Mandatory,
1619 SvcParamValue::Mandatory(Mandatory(vec![SvcParamKey::Alpn])),
1620 ),
1621 ],
1622 ));
1623 }
1624
1625 #[test]
1626 fn test_no_panic() {
1627 const BUF: &[u8] = &[
1628 255, 121, 0, 0, 0, 0, 40, 255, 255, 160, 160, 0, 0, 0, 64, 0, 1, 255, 158, 0, 0, 0, 8,
1629 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
1630 ];
1631 assert!(crate::op::Message::from_vec(BUF).is_err());
1632 }
1633
1634 #[test]
1635 fn test_unrestricted_output_size() {
1636 let svcb = SVCB::new(
1637 8224,
1638 Name::from_utf8(".").unwrap(),
1639 vec![(
1640 SvcParamKey::Unknown(8224),
1641 SvcParamValue::Unknown(Unknown(vec![32; 257])),
1642 )],
1643 );
1644
1645 let mut buf = Vec::new();
1646 let mut encoder = BinEncoder::new(&mut buf);
1647 svcb.emit(&mut encoder).unwrap();
1648 }
1649
1650 #[test]
1651 fn test_unknown_value_round_trip() {
1652 let svcb = SVCB::new(
1653 8224,
1654 Name::from_utf8(".").unwrap(),
1655 vec![(
1656 SvcParamKey::Unknown(8224),
1657 SvcParamValue::Unknown(Unknown(vec![32; 10])),
1658 )],
1659 );
1660
1661 let mut buf = Vec::new();
1662 let mut encoder = BinEncoder::new(&mut buf);
1663 svcb.emit(&mut encoder).unwrap();
1664
1665 let mut decoder = BinDecoder::new(&buf);
1666 let decoded = SVCB::read_data(
1667 &mut decoder,
1668 Restrict::new(u16::try_from(buf.len()).unwrap()),
1669 )
1670 .unwrap();
1671
1672 assert_eq!(svcb, decoded);
1673 }
1674
1675 // this assumes that only a single record is parsed
1676 // TODO: make Parser return an iterator over all records in a stream.
1677 fn parse_record<D: RecordData>(txt: &str) -> D {
1678 let records = Parser::new(txt, None, Some(Name::root()))
1679 .parse()
1680 .expect("failed to parse record")
1681 .1;
1682 let record_set = records.into_iter().next().expect("no record found").1;
1683 D::try_borrow(&record_set.into_iter().next().unwrap().data)
1684 .expect("Not the correct record")
1685 .clone()
1686 }
1687
1688 #[test]
1689 fn test_parsing() {
1690 let svcb: HTTPS = parse_record(CF_HTTPS_RECORD);
1691
1692 assert_eq!(svcb.svc_priority, 1);
1693 assert_eq!(svcb.target_name, Name::root());
1694
1695 let mut params = svcb.svc_params.iter();
1696
1697 // alpn
1698 let param = params.next().expect("not alpn");
1699 assert_eq!(param.0, SvcParamKey::Alpn);
1700 let SvcParamValue::Alpn(value) = ¶m.1 else {
1701 panic!("expected alpn");
1702 };
1703 assert_eq!(value.0, &["http/1.1", "h2"]);
1704
1705 // ipv4 hint
1706 let param = params.next().expect("ipv4hint");
1707 assert_eq!(SvcParamKey::Ipv4Hint, param.0);
1708 let SvcParamValue::Ipv4Hint(value) = ¶m.1 else {
1709 panic!("expected ipv4hint");
1710 };
1711 assert_eq!(
1712 value.0,
1713 &[A::new(162, 159, 137, 85), A::new(162, 159, 138, 85)]
1714 );
1715
1716 // echconfig
1717 let param = params.next().expect("echconfig");
1718 assert_eq!(SvcParamKey::EchConfigList, param.0);
1719 let SvcParamValue::EchConfigList(value) = ¶m.1 else {
1720 panic!("expected echconfig");
1721 };
1722 assert_eq!(
1723 value.0,
1724 data_encoding::BASE64.decode(b"AEX+DQBBtgAgACBMmGJQR02doup+5VPMjYpe5HQQ/bpntFCxDa8LT2PLAgAEAAEAAQASY2xvdWRmbGFyZS1lY2guY29tAAA=").unwrap()
1725 );
1726
1727 // ipv6 hint
1728 let param = params.next().expect("ipv6hint");
1729 assert_eq!(SvcParamKey::Ipv6Hint, param.0);
1730 let SvcParamValue::Ipv6Hint(value) = ¶m.1 else {
1731 panic!("expected ipv6hint");
1732 };
1733 assert_eq!(
1734 value.0,
1735 &[
1736 AAAA::new(0x2606, 0x4700, 0x7, 0, 0, 0, 0xa29f, 0x8955),
1737 AAAA::new(0x2606, 0x4700, 0x7, 0, 0, 0, 0xa29f, 0x8a5)
1738 ]
1739 );
1740 }
1741
1742 #[test]
1743 fn test_parse_display() {
1744 let svcb: SVCB = parse_record(CF_SVCB_RECORD);
1745
1746 let svcb_display = svcb.to_string();
1747
1748 // add back the name, etc...
1749 let svcb_display = format!("crypto.cloudflare.com. 299 IN SVCB {svcb_display}");
1750 let svcb_display = parse_record(&svcb_display);
1751
1752 assert_eq!(svcb, svcb_display);
1753 }
1754
1755 /// sanity check for https
1756 #[test]
1757 fn test_parsing_https() {
1758 let records = [GOOGLE_HTTPS_RECORD, CF_HTTPS_RECORD];
1759 for record in records.iter() {
1760 let svcb: HTTPS = parse_record(record);
1761
1762 assert_eq!(svcb.svc_priority, 1);
1763 assert_eq!(svcb.target_name, Name::root());
1764 }
1765 }
1766
1767 /// Test with RFC 9460 Appendix D test vectors
1768 /// <https://datatracker.ietf.org/doc/html/rfc9460#appendix-D>
1769 // TODO(XXX): Consider adding the negative "Failure Cases" from D.3.
1770 #[test]
1771 fn test_rfc9460_vectors() {
1772 #[derive(Debug)]
1773 struct TestVector {
1774 record: &'static str,
1775 record_type: RecordType,
1776 target_name: Name,
1777 priority: u16,
1778 params: Vec<(SvcParamKey, SvcParamValue)>,
1779 }
1780
1781 #[derive(Debug)]
1782 enum RecordType {
1783 SVCB,
1784 HTTPS,
1785 }
1786
1787 // NOTE: In each case the test vector from the RFC was augmented with a TTL (42 in each
1788 // case). The parser requires this but the test vectors do not include it.
1789 let vectors: [TestVector; 9] = [
1790 // https://datatracker.ietf.org/doc/html/rfc9460#appendix-D.1
1791 // Figure 2: AliasMode
1792 TestVector {
1793 record: "example.com. 42 HTTPS 0 foo.example.com.",
1794 record_type: RecordType::HTTPS,
1795 target_name: Name::from_str("foo.example.com.").unwrap(),
1796 priority: 0,
1797 params: Vec::new(),
1798 },
1799 // https://datatracker.ietf.org/doc/html/rfc9460#appendix-D.2
1800 // Figure 3: TargetName Is "."
1801 TestVector {
1802 record: "example.com. 42 SVCB 1 .",
1803 record_type: RecordType::SVCB,
1804 target_name: Name::from_str(".").unwrap(),
1805 priority: 1,
1806 params: Vec::new(),
1807 },
1808 // Figure 4: Specifies a Port
1809 TestVector {
1810 record: "example.com. 42 SVCB 16 foo.example.com. port=53",
1811 record_type: RecordType::SVCB,
1812 target_name: Name::from_str("foo.example.com.").unwrap(),
1813 priority: 16,
1814 params: vec![(SvcParamKey::Port, SvcParamValue::Port(53))],
1815 },
1816 // Figure 5: A Generic Key and Unquoted Value
1817 TestVector {
1818 record: "example.com. 42 SVCB 1 foo.example.com. key667=hello",
1819 record_type: RecordType::SVCB,
1820 target_name: Name::from_str("foo.example.com.").unwrap(),
1821 priority: 1,
1822 params: vec![(
1823 SvcParamKey::Key(667),
1824 SvcParamValue::Unknown(Unknown(b"hello".into())),
1825 )],
1826 },
1827 // Figure 6: A Generic Key and Quoted Value with a Decimal Escape
1828 TestVector {
1829 record: r#"example.com. 42 SVCB 1 foo.example.com. key667="hello\210qoo""#,
1830 record_type: RecordType::SVCB,
1831 target_name: Name::from_str("foo.example.com.").unwrap(),
1832 priority: 1,
1833 params: vec![(
1834 SvcParamKey::Key(667),
1835 SvcParamValue::Unknown(Unknown(b"hello\\210qoo".into())),
1836 )],
1837 },
1838 // Figure 7: Two Quoted IPv6 Hints
1839 TestVector {
1840 record: r#"example.com. 42 SVCB 1 foo.example.com. (ipv6hint="2001:db8::1,2001:db8::53:1")"#,
1841 record_type: RecordType::SVCB,
1842 target_name: Name::from_str("foo.example.com.").unwrap(),
1843 priority: 1,
1844 params: vec![(
1845 SvcParamKey::Ipv6Hint,
1846 SvcParamValue::Ipv6Hint(IpHint(vec![
1847 AAAA::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 1),
1848 AAAA::new(0x2001, 0xdb8, 0, 0, 0, 0, 0x53, 1),
1849 ])),
1850 )],
1851 },
1852 // Figure 8: An IPv6 Hint Using the Embedded IPv4 Syntax
1853 TestVector {
1854 record: r#"example.com. 42 SVCB 1 example.com. (ipv6hint="2001:db8:122:344::192.0.2.33")"#,
1855 record_type: RecordType::SVCB,
1856 target_name: Name::from_str("example.com.").unwrap(),
1857 priority: 1,
1858 params: vec![(
1859 SvcParamKey::Ipv6Hint,
1860 SvcParamValue::Ipv6Hint(IpHint(vec![AAAA::new(
1861 0x2001, 0xdb8, 0x122, 0x344, 0, 0, 0xc000, 0x221,
1862 )])),
1863 )],
1864 },
1865 // Figure 9: SvcParamKey Ordering Is Arbitrary in Presentation Format but Sorted in Wire Format
1866 TestVector {
1867 record: r#"example.com. 42 SVCB 16 foo.example.org. (alpn=h2,h3-19 mandatory=ipv4hint,alpn ipv4hint=192.0.2.1)"#,
1868 record_type: RecordType::SVCB,
1869 target_name: Name::from_str("foo.example.org.").unwrap(),
1870 priority: 16,
1871 params: vec![
1872 (
1873 SvcParamKey::Alpn,
1874 SvcParamValue::Alpn(Alpn(vec!["h2".to_owned(), "h3-19".to_owned()])),
1875 ),
1876 (
1877 SvcParamKey::Mandatory,
1878 SvcParamValue::Mandatory(Mandatory(vec![
1879 SvcParamKey::Ipv4Hint,
1880 SvcParamKey::Alpn,
1881 ])),
1882 ),
1883 (
1884 SvcParamKey::Ipv4Hint,
1885 SvcParamValue::Ipv4Hint(IpHint(vec![A::new(192, 0, 2, 1)])),
1886 ),
1887 ],
1888 },
1889 // Figure 10: An "alpn" Value with an Escaped Comma and an Escaped Backslash in Two Presentation Formats
1890 TestVector {
1891 record: r#"example.com. 42 SVCB 16 foo.example.org. alpn="f\\\\oo\,bar,h2""#,
1892 record_type: RecordType::SVCB,
1893 target_name: Name::from_str("foo.example.org.").unwrap(),
1894 priority: 16,
1895 params: vec![(
1896 SvcParamKey::Alpn,
1897 SvcParamValue::Alpn(Alpn(vec![r#"f\\oo,bar"#.to_owned(), "h2".to_owned()])),
1898 )],
1899 },
1900 /*
1901 * TODO(XXX): Parser does not replace escaped characters, does not see "\092," as
1902 * an escaped delim.
1903 TestVector {
1904 record: r#"example.com. 42 SVCB 116 foo.example.org. alpn=f\\\092oo\092,bar,h2""#,
1905 record_type: RecordType::SVCB,
1906 target_name: Name::from_str("foo.example.org.").unwrap(),
1907 priority: 16,
1908 params: vec![(
1909 SvcParamKey::Alpn,
1910 SvcParamValue::Alpn(Alpn(vec![r#"f\\oo,bar"#.to_owned(), "h2".to_owned()])),
1911 )],
1912 },
1913 */
1914 ];
1915
1916 for record in vectors {
1917 let expected_scvb = SVCB::new(record.priority, record.target_name, record.params);
1918 match record.record_type {
1919 RecordType::SVCB => {
1920 let parsed: SVCB = parse_record(record.record);
1921 assert_eq!(parsed, expected_scvb);
1922 }
1923 RecordType::HTTPS => {
1924 let parsed: HTTPS = parse_record(record.record);
1925 assert_eq!(parsed, HTTPS(expected_scvb));
1926 }
1927 };
1928 }
1929 }
1930
1931 const CF_SVCB_RECORD: &str = "crypto.cloudflare.com. 1664 IN SVCB 1 . alpn=\"http/1.1,h2\" ipv4hint=162.159.137.85,162.159.138.85 ech=AEX+DQBBtgAgACBMmGJQR02doup+5VPMjYpe5HQQ/bpntFCxDa8LT2PLAgAEAAEAAQASY2xvdWRmbGFyZS1lY2guY29tAAA= ipv6hint=2606:4700:7::a29f:8955,2606:4700:7::a29f:8a5";
1932 const CF_HTTPS_RECORD: &str = "crypto.cloudflare.com. 1664 IN HTTPS 1 . alpn=\"http/1.1,h2\" ipv4hint=162.159.137.85,162.159.138.85 ech=AEX+DQBBtgAgACBMmGJQR02doup+5VPMjYpe5HQQ/bpntFCxDa8LT2PLAgAEAAEAAQASY2xvdWRmbGFyZS1lY2guY29tAAA= ipv6hint=2606:4700:7::a29f:8955,2606:4700:7::a29f:8a5";
1933 const GOOGLE_HTTPS_RECORD: &str = "google.com 21132 IN HTTPS 1 . alpn=\"h2,h3\"";
1934}