### SVCB Record Data Examples Source: https://docs.rs/hickory-proto/latest/hickory_proto/rr/rdata/svcb/struct.SVCB.html Examples of SVCB and HTTPS resource records as they might appear in DNS. ```dns simple.example. 7200 IN HTTPS 1 . alpn=h3 pool 7200 IN HTTPS 1 h3pool alpn=h2,h3 ech="123..." HTTPS 2 . alpn=h2 ech="abc..." @ 7200 IN HTTPS 0 www _8765._baz.api.example.com. 7200 IN SVCB 0 svc4-baz.example.net. ``` -------------------------------- ### SIG RR Presentation Example Source: https://docs.rs/hickory-proto/latest/hickory_proto/dnssec/rdata/sig/struct.SIG.html An example illustrating the presentation format of a SIG RR, including canonical RR form and base64 encoded signature. ```dns foo.nil. SIG NXT 1 2 ( 19970102030405 ;signature expiration 19961211100908 ;signature inception 2143 ;key identifier foo.nil. ;signer AIYADP8d3zYNyQwW2EM4wXVFdslEJcUx/fxkfBeH1El4ixPFhpfHFElxbvKoWmvjDTCm fiYy2X+8XpFjwICHc398kzWsTMKlxovpz2FnCTM= ;signature (640 bits) ) ``` -------------------------------- ### NSEC RR Presentation Format and Example Source: https://docs.rs/hickory-proto/latest/hickory_proto/dnssec/rdata/nsec/struct.NSEC.html Illustrates the presentation format of the NSEC RDATA, including the Next Domain Name and Type Bit Maps fields. Provides a practical example of an NSEC record for alfa.example.com. ```dns alfa.example.com. 86400 IN NSEC host.example.com. ( A MX RRSIG NSEC TYPE1234 ) ``` -------------------------------- ### BinDecoder Length Example Source: https://docs.rs/hickory-proto/latest/hickory_proto/serialize/binary/struct.BinDecoder.html Demonstrates how to create a BinDecoder and check its length before and after reading data. ```rust use hickory_proto::serialize::binary::BinDecoder; let deadbeef = b"deadbeef"; let mut decoder = BinDecoder::new(deadbeef); assert_eq!(decoder.len(), 8); deployer.read_slice(7).unwrap(); assert_eq!(decoder.len(), 1); ``` -------------------------------- ### ZoneUsage for .example. Zone Source: https://docs.rs/hickory-proto/latest/hickory_proto/rr/domain/usage/struct.ZoneUsage.html Creates a ZoneUsage instance for the .example. domain, reserved for documentation and examples. ```rust pub fn example(name: Name) -> Self ``` -------------------------------- ### TLSA RR Examples Source: https://docs.rs/hickory-proto/latest/src/hickory_proto/rr/rdata/tlsa.rs.html Provides examples of TLSA RDATA for different certificate association scenarios, including hashed PKIX CA certificates and subject public keys, as well as full certificate associations. ```text 2.3. TLSA RR Examples In the following examples, the domain name is formed using the rules in Section 3. An example of a hashed (SHA-256) association of a PKIX CA certificate: _443._tcp.www.example.com. IN TLSA ( 0 0 1 d2abde240d7cd3ee6b4b28c54df034b9 7983a1d16e8a410e4561cb106618e971 ) An example of a hashed (SHA-512) subject public key association of a PKIX end entity certificate: _443._tcp.www.example.com. IN TLSA ( 1 1 2 92003ba34942dc74152e2f2c408d29ec a5a520e7f2e06bb944f4dca346baf63c 1b177615d466f6c4b71c216a50292bd5 8c9ebdd2f74e38fe51ffd48c43326cbc ) An example of a full certificate association of a PKIX end entity certificate: _443._tcp.www.example.com. IN TLSA ( 3 0 0 30820307308201efa003020102020... ) ``` -------------------------------- ### NAPTR Record Master File Format Example Source: https://docs.rs/hickory-proto/latest/hickory_proto/rr/rdata/naptr/struct.NAPTR.html Illustrates the master file format for NAPTR records as defined in RFC 2915. It shows the order, preference, flags, services, regexp, and replacement fields with example values. The regexp field requires careful handling due to potential backslashes. ```dns ;; order pflags service regexp replacement IN NAPTR 100 50 "a" "z3950+N2L+N2C" "" cidserver.example.com. IN NAPTR 100 50 "a" "rcds+N2C" "" cidserver.example.com. IN NAPTR 100 50 "s" "http+N2L+N2C+N2R" "" www.example.com. ``` -------------------------------- ### ZoneUsage::example Source: https://docs.rs/hickory-proto/latest/hickory_proto/rr/domain/usage/struct.ZoneUsage.html Creates a ZoneUsage configuration for the '.example.' zone. ```APIDOC ## ZoneUsage::example ### Description Provides restrictions for the `.example.` zone. ### Signature ```rust pub fn example(name: Name) -> Self ``` ### Parameters * **name**: `Name` - The name of the example zone. ### Returns A `ZoneUsage` instance configured for the `.example.` zone. ``` -------------------------------- ### Get Slice from Specific Position Source: https://docs.rs/hickory-proto/latest/src/hickory_proto/serialize/binary/decoder.rs.html Retrieves a slice of data from the binary decoder starting from a given offset. This is useful for accessing data without consuming it from the decoder's current position. An error occurs if the offset is out of bounds. ```rust let deadbeef = b"deadbeef"; let mut decoder = BinDecoder::new(deadbeef); decoder.read_slice(4).expect("failed to read dead"); let read = decoder.slice_from(0).expect("failed to get slice"); assert_eq!(&read, b"dead"); decoder.read_slice(2).expect("failed to read be"); let read = decoder.slice_from(4).expect("failed to get slice"); assert_eq!(&read, b"be"); decoder.read_slice(0).expect("failed to read nothing"); let read = decoder.slice_from(4).expect("failed to get slice"); assert_eq!(&read, b"be"); // this should fail assert!(decoder.slice_from(10).is_err()); ``` -------------------------------- ### Get TypeId of RsaSigningKey Source: https://docs.rs/hickory-proto/latest/hickory_proto/dnssec/crypto/struct.RsaSigningKey.html Gets the TypeId of RsaSigningKey, a blanket implementation from the Any trait. ```rust fn type_id(&self) -> TypeId ``` -------------------------------- ### Create a SupportedAlgorithms set with all algorithms Source: https://docs.rs/hickory-proto/latest/hickory_proto/dnssec/struct.SupportedAlgorithms.html Initializes a SupportedAlgorithms set that includes all possible DNSSEC algorithms. This is a convenient way to indicate full support. ```rust pub fn all() -> Self ``` -------------------------------- ### Create and Initialize DnssecSigner Source: https://docs.rs/hickory-proto/latest/src/hickory_proto/dnssec/signer.rs.html Demonstrates the creation of a DnssecSigner instance with a private key and root name. ```rust let key = RsaSigningKey::from_pkcs8(&PrivatePkcs8KeyDer::from(RSA_KEY), Algorithm::RSASHA256).unwrap(); let pub_key = key.to_public_key().unwrap(); let dnskey = DNSKEY::from_key(&pub_key); let signer = DnssecSigner::new( dnskey, Box::new(key), Name::root(), Duration::from_secs(300), ); ``` -------------------------------- ### TXT Record Creation and Binary Encoding/Decoding Source: https://docs.rs/hickory-proto/latest/src/hickory_proto/rr/rdata/txt.rs.html Shows how to create a TXT record from string data, encode it into a binary format using BinEncoder, and then decode it back into a TXT record using BinDecoder. Asserts that the decoded record matches the original. ```rust let rdata = TXT::new(vec!["Test me some".to_string(), "more please".to_string()]); let mut bytes = Vec::new(); let mut encoder: BinEncoder<'_> = BinEncoder::new(&mut bytes); assert!(rdata.emit(&mut encoder).is_ok()); let bytes = encoder.into_bytes(); #[cfg(feature = "std")] println!("bytes: {:?}", bytes); let mut decoder: BinDecoder<'_> = BinDecoder::new(bytes); let restrict = Restrict::new(bytes.len() as u16); let read_rdata = TXT::read_data(&mut decoder, restrict).expect("Decoding error"); assert_eq!(rdata, read_rdata); ``` -------------------------------- ### Get Ipv4Addr as octets (Nightly) Source: https://docs.rs/hickory-proto/latest/hickory_proto/rr/rdata/a/struct.A.html This is a nightly-only experimental API to get the four eight-bit integers of an IPv4 address as a slice. ```rust #![feature(ip_as_octets)] use std::net::Ipv4Addr; let addr = Ipv4Addr::new(127, 0, 0, 1); assert_eq!(addr.as_octets(), &[127, 0, 0, 1]); ``` -------------------------------- ### Unsafe Undefined Behavior Example Source: https://docs.rs/hickory-proto/latest/hickory_proto/dnssec/type.DnsSecResult.html An example illustrating the undefined behavior that occurs when `unsafe unwrap_unchecked` is called on an `Err` variant. ```rust let x: Result = Err("emergency failure"); unsafe { x.unwrap_unchecked() }; // Undefined behavior! ``` -------------------------------- ### Iterating Through All Supported Algorithms Source: https://docs.rs/hickory-proto/latest/src/hickory_proto/dnssec/supported_algorithm.rs.html Shows how to iterate through all available DNSSEC algorithms using `SupportedAlgorithms::all()` and verify the count and order of algorithms returned by the iterator. Also demonstrates iterating over a custom set of algorithms. ```rust let supported = SupportedAlgorithms::all(); assert_eq!(supported.iter().count(), 7); // it just so happens that the iterator has a fixed order... let supported = SupportedAlgorithms::all(); let mut iter = supported.iter(); assert_eq!(iter.next(), Some(Algorithm::RSASHA1)); assert_eq!(iter.next(), Some(Algorithm::RSASHA256)); assert_eq!(iter.next(), Some(Algorithm::RSASHA1NSEC3SHA1)); assert_eq!(iter.next(), Some(Algorithm::RSASHA512)); assert_eq!(iter.next(), Some(Algorithm::ECDSAP256SHA256)); assert_eq!(iter.next(), Some(Algorithm::ECDSAP384SHA384)); assert_eq!(iter.next(), Some(Algorithm::ED25519)); let mut supported = SupportedAlgorithms::new(); supported.set(Algorithm::RSASHA256); supported.set(Algorithm::RSASHA512); let mut iter = supported.iter(); assert_eq!(iter.next(), Some(Algorithm::RSASHA256)); assert_eq!(iter.next(), Some(Algorithm::RSASHA512)); ``` -------------------------------- ### Create a new SupportedAlgorithms set Source: https://docs.rs/hickory-proto/latest/hickory_proto/dnssec/struct.SupportedAlgorithms.html Initializes a new, empty set of SupportedAlgorithms. This is useful when you need to start with a clean slate and add algorithms individually. ```rust pub fn new() -> Self ``` -------------------------------- ### TLSA RR Example: Full Certificate Association Source: https://docs.rs/hickory-proto/latest/hickory_proto/rr/rdata/tlsa/struct.TLSA.html An example of a TLSA record representing a full certificate association of a PKIX end entity certificate. ```dns _443._tcp.www.example.com. IN TLSA ( 3 0 0 30820307308201efa003020102020... ) ``` -------------------------------- ### Create and check localhost IPv6 address Source: https://docs.rs/hickory-proto/latest/hickory_proto/rr/rdata/aaaa/struct.Ipv6Addr.html Demonstrates creating an IPv6 localhost address using `Ipv6Addr::new` and verifying it with `is_loopback()`. ```rust use std::net::Ipv6Addr; let localhost = Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1); assert_eq!("::1".parse(), Ok(localhost)); assert_eq!(localhost.is_loopback(), true); ``` -------------------------------- ### store_label_pointer Source: https://docs.rs/hickory-proto/latest/src/hickory_proto/serialize/binary/encoder.rs.html Stores a pointer to a label that has already been written into the buffer. The location of this pointer is the current position in the buffer, and it refers to a label starting at the specified `start` index. ```APIDOC ## store_label_pointer ### Description Records a reference to a previously encoded label within the buffer. This is used for name compression, allowing subsequent references to the same label to point back to its first occurrence. ### Method `&mut self` ### Parameters * `start` (usize) - The starting index of the label in the buffer. * `end` (usize) - The ending index of the label in the buffer. ``` -------------------------------- ### Building Access Control Sets Source: https://docs.rs/hickory-proto/latest/src/hickory_proto/access_control.rs.html Demonstrates how to build an AccessControlSet using AccessControlSetBuilder, applying deny and allow rules for IPv4 and IPv6 networks. Includes error handling for the build process and assertions for denied IPs. ```rust let mut builder = AccessControlSetBuilder::new(tc.name); if tc.in_deny { builder = builder.deny([test_v4_net, test_v6_net].iter()); } if tc.in_allow { builder = builder.allow([test_v4_net, test_v6_net].iter()); } let Ok(acs) = builder.build() else { match tc.expected_build_err { true => continue, false => panic!("unexpected builder error"), } }; assert_eq!( acs.denied(test_v4), tc.expected_denied, "IPv4 case '{}' failed", tc.name ); assert_eq!( acs.denied(test_v6), tc.expected_denied, "IPv6 case '{}' failed", tc.name ); ``` -------------------------------- ### Setting Environment Variable with expect Source: https://docs.rs/hickory-proto/latest/hickory_proto/dnssec/type.DnsSecResult.html Provides an example of using expect to ensure an environment variable is set, with a descriptive panic message if it's missing. ```rust let path = std::env::var("IMPORTANT_PATH") .expect("env variable `IMPORTANT_PATH` should be set by `wrapper_script.sh`"); ``` -------------------------------- ### Get Records with or without RRSIGs Source: https://docs.rs/hickory-proto/latest/src/hickory_proto/rr/rr_set.rs.html Retrieves all records within an RRset. Use `records_with_rrsigs` to include DNSSEC RRSIG records if they exist, or `records_without_rrsigs` to get only the primary records. ```rust pub fn records(&self, and_rrsigs: bool) -> RrsetRecords<'_> { if and_rrsigs { self.records_with_rrsigs() } else { self.records_without_rrsigs() } } ``` ```rust pub fn records_with_rrsigs(&self) -> RrsetRecords<'_> { if self.records.is_empty() { RrsetRecords::Empty } else { RrsetRecords::RecordsAndRrsigs(RecordsAndRrsigsIter( self.records.iter().chain(self.rrsigs.iter()), )) } } ``` ```rust pub fn records_without_rrsigs(&self) -> RrsetRecords<'_> { if self.records.is_empty() { RrsetRecords::Empty } else { RrsetRecords::RecordsOnly(self.records.iter()) } } ``` -------------------------------- ### TLSA RR Example: Hashed PKIX CA Certificate (SHA-256) Source: https://docs.rs/hickory-proto/latest/hickory_proto/rr/rdata/tlsa/struct.TLSA.html An example of a TLSA record representing a hashed association of a PKIX CA certificate using SHA-256. ```dns _443._tcp.www.example.com. IN TLSA ( 0 0 1 d2abde240d7cd3ee6b4b28c54df034b9 7983a1d16e8a410e4561cb106618e971 ) ``` -------------------------------- ### SVCB Zone File Presentation Format Example Source: https://docs.rs/hickory-proto/latest/src/hickory_proto/rr/rdata/svcb.rs.html Illustrates how SVCB records are represented in a zone file, showing the service priority, target name, and service parameters like port. ```dns example.com. 7200 IN HTTPS 0 svc.example.net. svc.example.net. 7200 IN CNAME svc2.example.net. svc2.example.net. 7200 IN HTTPS 1 . port=8002 svc2.example.net. 300 IN A 192.0.2.2 svc2.example.net. 300 IN AAAA 2001:db8::2 ``` -------------------------------- ### Get Iterator Size Hint Source: https://docs.rs/hickory-proto/latest/src/hickory_proto/rr/domain/name.rs.html Illustrates how to use `size_hint()` on a domain name iterator to get an estimate of the number of remaining elements. Shows the hint before and after consuming one element. ```rust fn test_size_hint() { let name = Name::from_ascii("www.example.com").unwrap(); let mut iter = name.iter(); assert_eq!(iter.size_hint().0, 3); assert_eq!(iter.next().unwrap(), b"www"); assert_eq!(iter.size_hint().0, 2); } ``` -------------------------------- ### DNS Header Encoding Example Source: https://docs.rs/hickory-proto/latest/src/hickory_proto/op/header.rs.html Demonstrates encoding a DNS header structure into a byte vector using BinEncoder. Verifies the output against an expected byte sequence. ```rust let mut header = Header { id: 0x1234, flags: Flags { qr: false, opcode: OpCode::Query, aa: false, tc: false, rd: true, ra: false, z: 0, rcode: ResponseCode::NoError, }, counts: HeaderCounts { queries: 0x0001, answers: 0x0000, authorities: 0x0000, additionals: 0x0000, }, }; let expect = vec![ 0x12, 0x34, 0x00, 0x00, // Flags: QR=0, OpCode=0, AA=0, TC=0, RD=1, RA=0, Z=0, RCODE=0 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, ]; let mut bytes = Vec::with_capacity(512); { let mut encoder = BinEncoder::new(&mut bytes); header.emit(&mut encoder).unwrap(); } assert_eq!(bytes, expect); ``` -------------------------------- ### Display Format Example for Flags Source: https://docs.rs/hickory-proto/latest/hickory_proto/op/struct.Flags.html Illustrates the display format for header flags, following the 'dig' command's convention. For example, 'RD,AA,RA;' signifies Recursion-Desired, Authoritative-Answer, and Recursion-Available. ```rust Example: “RD,AA,RA;” is Recursion-Desired, Authoritative-Answer, Recursion-Available. ``` -------------------------------- ### ProofFlags Initialization Methods Source: https://docs.rs/hickory-proto/latest/hickory_proto/dnssec/struct.ProofFlags.html Provides methods to create new ProofFlags instances, including an empty set, a set with all known bits, and conversion from raw bit values or flag names. ```rust pub const fn empty() -> Self ``` ```rust pub const fn all() -> Self ``` ```rust pub const fn from_bits(bits: u32) -> Option ``` ```rust pub const fn from_bits_truncate(bits: u32) -> Self ``` ```rust pub const fn from_bits_retain(bits: u32) -> Self ``` ```rust pub fn from_name(name: &str) -> Option ``` -------------------------------- ### Store Label Pointer Source: https://docs.rs/hickory-proto/latest/src/hickory_proto/serialize/binary/encoder.rs.html Stores a pointer to a label within the buffer. The pointer consists of a start and end index. Asserts that indices are within u16::MAX and that start is less than or equal to end. ```rust pub fn store_label_pointer(&mut self, start: usize, end: usize) { assert!(start <= (u16::MAX as usize)); assert!(end <= (u16::MAX as usize)); assert!(start <= end); } ``` -------------------------------- ### Borrow Slice from Buffer Source: https://docs.rs/hickory-proto/latest/src/hickory_proto/serialize/binary/encoder.rs.html Returns a slice of the buffer from a start index to an end index. Asserts that the start index is less than the current offset and the end index is within the buffer's bounds. ```rust pub fn slice_of(&self, start: usize, end: usize) -> &[u8] { assert!(start < self.offset); assert!(end <= self.buffer.len()); &self.buffer.buffer()[start..end] } ``` -------------------------------- ### HINFO Record Example (RFC 1033) Source: https://docs.rs/hickory-proto/latest/hickory_proto/rr/rdata/hinfo/struct.HINFO.html Provides sample HINFO records demonstrating the format for hardware and software descriptions. ```text SRI-NIC.ARPA. HINFO DEC-2060 TOPS20 UCBARPA.Berkeley.EDU. HINFO VAX-11/780 UNIX ``` -------------------------------- ### CAA Issue Property Examples Source: https://docs.rs/hickory-proto/latest/src/hickory_proto/rr/rdata/caa.rs.html Illustrates the usage of the CAA 'issue' property tag for restricting certificate issuance. Includes examples for specifying authorized issuers, forbidding all issuance, and handling malformed values. ```text certs.example.com CAA 0 issue "ca1.example.net" certs.example.com CAA 0 issue "ca2.example.org" ``` ```text nocerts.example.com CAA 0 issue ";" ``` ```text malformed.example.com CAA 0 issue "%%%%%" ``` ```text account.example.com CAA 0 issue "ca1.example.net; account=230123" ``` -------------------------------- ### Creating Domain Names from ASCII and Labels Source: https://docs.rs/hickory-proto/latest/hickory_proto/rr/domain/struct.Name.html Shows how to create `Name` objects from ASCII strings and from a vector of labels. This includes examples of case preservation and handling escaped characters like '.' and '\056'. ```rust use hickory_proto::rr::Name; let bytes_name = Name::from_labels(vec!["WWW".as_bytes(), "example".as_bytes(), "COM".as_bytes()]).unwrap(); let ascii_name = Name::from_ascii("WWW.example.COM.").unwrap(); let lower_name = Name::from_ascii("www.example.com.").unwrap(); assert!(bytes_name.eq_case(&ascii_name)); assert!(!lower_name.eq_case(&ascii_name)); // escaped values let bytes_name = Name::from_labels(vec!["email.name".as_bytes(), "example".as_bytes(), "com".as_bytes()]).unwrap(); let name = Name::from_ascii("email\\.name.example.com.").unwrap(); assert_eq!(bytes_name, name); let bytes_name = Name::from_labels(vec!["bad.char".as_bytes(), "example".as_bytes(), "com".as_bytes()]).unwrap(); let name = Name::from_ascii("bad\\056char.example.com.").unwrap(); assert_eq!(bytes_name, name); ``` -------------------------------- ### SupportedAlgorithms::all() Source: https://docs.rs/hickory-proto/latest/src/hickory_proto/dnssec/supported_algorithm.rs.html Creates a SupportedAlgorithms set where all currently recognized algorithms are marked as supported. This is useful for indicating full support. ```rust pub fn all() -> Self { Self { bit_map: 0b0111_1111, } } ``` -------------------------------- ### TLSA RR Example: Hashed Subject Public Key (SHA-512) Source: https://docs.rs/hickory-proto/latest/hickory_proto/rr/rdata/tlsa/struct.TLSA.html An example of a TLSA record representing a hashed association of a PKIX end entity certificate's subject public key using SHA-512. ```dns _443._tcp.www.example.com. IN TLSA ( 1 1 2 92003ba34942dc74152e2f2c408d29ec a5a520e7f2e06bb944f4dca346baf63c 1b177615d466f6c4b71c216a50292bd5 8c9ebdd2f74e38fe51ffd48c43326cbc ) ``` -------------------------------- ### Creating Name from Labels and Strings Source: https://docs.rs/hickory-proto/latest/hickory_proto/rr/domain/struct.Name.html Demonstrates creating Name instances from byte labels and UTF-8 strings. Shows case-sensitive comparison differences. ```rust use std::str::FromStr; use hickory_proto::rr::Name; let bytes_name = Name::from_labels(vec!["WWW".as_bytes(), "example".as_bytes(), "COM".as_bytes()]).unwrap(); // from_str calls through to from_utf8 let utf8_name = Name::from_str("WWW.example.COM.").unwrap(); let lower_name = Name::from_str("www.example.com.").unwrap(); assert!(!bytes_name.eq_case(&utf8_name)); assert!(lower_name.eq_case(&utf8_name)); ``` -------------------------------- ### Creating and Checking a DNS Response with an Answer Source: https://docs.rs/hickory-proto/latest/src/hickory_proto/op/dns_response.rs.html Demonstrates how to construct a DNS message, add an A record as an answer, convert it to a DnsResponse, and assert that it contains an answer. ```rust #[test] fn contains_answer() { let mut message = Message::query(); message.add_answer(Record::from_rdata( Name::root(), 88640, RData::A(A::new(127, 0, 0, 2)), )); let response = DnsResponse::from_message(message.into_response()).unwrap(); assert!(response.contains_answer()) } ``` -------------------------------- ### DS RR Presentation Format and Example Source: https://docs.rs/hickory-proto/latest/hickory_proto/dnssec/rdata/ds/struct.DS.html Illustrates the presentation format for DS RDATA, including key tag, algorithm, digest type, and digest. Provides a concrete example of a DS record corresponding to a DNSKEY record. ```text 5.3. The DS RR Presentation Format The presentation format of the RDATA portion is as follows: The Key Tag field MUST be represented as an unsigned decimal integer. The Algorithm field MUST be represented either as an unsigned decimal integer or as an algorithm mnemonic specified in Appendix A.1. The Digest Type field MUST be represented as an unsigned decimal integer. The Digest MUST be represented as a sequence of case-insensitive hexadecimal digits. Whitespace is allowed within the hexadecimal text. 5.4. DS RR Example The following example shows a DNSKEY RR and its corresponding DS RR. dskey.example.com. 86400 IN DNSKEY 256 3 5 ( AQOeiiR0GOMYkDshWoSKz9Xz fwJr1AYtsmx3TGkJaNXVbfi/ 2pHm822aJ5iI9BMzNXxeYCmZ DRD99WYwYqUSdjMmmAphXdvx egXd/M5+X7OrzKBaMbCVdFLU Uh6DhweJBjEVv5f2wwjM9Xzc nOf+EPbtG9DMBmADjFDc2w/r ljwvFw== ) ; key id = 60485 dskey.example.com. 86400 IN DS 60485 5 1 ( 2BB183AF5F22588179A53B0A 98631FAD1A292118 ) The first four text fields specify the name, TTL, Class, and RR type (DS). Value 60485 is the key tag for the corresponding "dskey.example.com." DNSKEY RR, and value 5 denotes the algorithm used by this "dskey.example.com." DNSKEY RR. The value 1 is the algorithm used to construct the digest, and the rest of the RDATA text is the digest in hexadecimal. ``` -------------------------------- ### Get RegistryUsage Source: https://docs.rs/hickory-proto/latest/hickory_proto/rr/domain/usage/struct.ZoneUsage.html Returns the RegistryUsage configuration for this zone. ```rust pub fn registry(&self) -> RegistryUsage ``` -------------------------------- ### Zone Lexer Tokenization Examples Source: https://docs.rs/hickory-proto/latest/src/hickory_proto/serialize/txt/zone_lex.rs.html Demonstrates the tokenization of various zone file elements including blank tokens, character data, IP addresses, end-of-line markers, include directives, and subsystem references. ```rust assert_eq!(next_token(&mut lexer).unwrap(), Token::Blank); assert_eq!( next_token(&mut lexer).unwrap(), Token::CharData("A".to_string()) ); assert_eq!( next_token(&mut lexer).unwrap(), Token::CharData("128.9.0.32".to_string()) ); assert_eq!(next_token(&mut lexer).unwrap(), Token::EOL); assert_eq!(next_token(&mut lexer).unwrap(), Token::EOL); assert_eq!(next_token(&mut lexer).unwrap(), Token::Include); assert_eq!( next_token(&mut lexer).unwrap(), Token::CharData("ISI-MAILBOXES.TXT".to_string()) ); assert!(next_token(&mut lexer).is_none()); ``` -------------------------------- ### Checking Algorithm Support Source: https://docs.rs/hickory-proto/latest/src/hickory_proto/dnssec/supported_algorithm.rs.html Demonstrates how to check if a specific DNSSEC algorithm is supported by the `SupportedAlgorithms` set. Initializes a set, adds an algorithm, and then asserts its presence and the absence of another. ```rust let mut supported = SupportedAlgorithms::new(); supported.set(Algorithm::RSASHA1); assert!(supported.has(Algorithm::RSASHA1)); assert!(!supported.has(Algorithm::RSASHA1NSEC3SHA1)); let mut supported = SupportedAlgorithms::new(); supported.set(Algorithm::RSASHA256); assert!(!supported.has(Algorithm::RSASHA1)); assert!(!supported.has(Algorithm::RSASHA1NSEC3SHA1)); assert!(supported.has(Algorithm::RSASHA256)); ``` -------------------------------- ### Get OpUsage Source: https://docs.rs/hickory-proto/latest/hickory_proto/rr/domain/usage/struct.ZoneUsage.html Returns the OpUsage configuration for this zone. ```rust pub fn op(&self) -> OpUsage ``` -------------------------------- ### Example: LowerName Number of Labels Source: https://docs.rs/hickory-proto/latest/src/hickory_proto/rr/lower_name.rs.html Demonstrates counting labels for different LowerName instances, including the root and multi-label names. ```rust use std::str::FromStr; use hickory_proto::rr::{LowerName, Name}; let root = LowerName::from(Name::root()); assert_eq!(root.num_labels(), 0); let example_com = LowerName::from(Name::from_str("example.com").unwrap()); assert_eq!(example_com.num_labels(), 2); let star_example_com = LowerName::from(Name::from_str("*.example.com").unwrap()); ``` -------------------------------- ### Get AuthUsage Source: https://docs.rs/hickory-proto/latest/hickory_proto/rr/domain/usage/struct.ZoneUsage.html Returns the AuthUsage configuration for this zone. ```rust pub fn auth(&self) -> AuthUsage ``` -------------------------------- ### Get CacheUsage Source: https://docs.rs/hickory-proto/latest/hickory_proto/rr/domain/usage/struct.ZoneUsage.html Returns the CacheUsage configuration for this zone. ```rust pub fn cache(&self) -> CacheUsage ``` -------------------------------- ### Create and Use TSIG Signer Source: https://docs.rs/hickory-proto/latest/src/hickory_proto/rr/tsig.rs.html Demonstrates creating a TSIG signer with a secret key, algorithm, key name, and fudge value, then signing a DNS question and verifying its integrity. ```rust let sig_key = b"some_key".to_vec(); let signer = TSigner::new(sig_key, TsigAlgorithm::HmacSha512, key_name, fudge as u16).unwrap(); assert!(question.signature().is_none()); question .finalize(&signer, time_begin) .expect("should have signed"); assert!(question.signature().is_some()); // this should be ok, it has not been tampered with assert!( signer .verify_message_byte(&question.to_bytes().unwrap(), None, true) .is_ok() ); (question, signer) ``` -------------------------------- ### RFC 4034 Canonical Ordering Example Source: https://docs.rs/hickory-proto/latest/src/hickory_proto/rr/domain/name.rs.html Illustrates the canonical ordering of domain names as specified in RFC 4034, section 6.1. It creates a vector of names with varying labels and casing, sorts them, and asserts that the original and sorted vectors are identical, demonstrating correct sorting behavior. ```rust let names = Vec::from([ Name::from_labels::<_, &[u8]>([b"example".as_slice()]).unwrap(), Name::from_labels::<_, &[u8]>([b"a".as_slice(), b"example".as_slice()]).unwrap(), Name::from_labels::<_, &[u8]>([ b"yljkjljk".as_slice(), b"a".as_slice(), b"example".as_slice(), ]) .unwrap(), Name::from_labels::<_, &[u8]>([ b"Z".as_slice(), b"a".as_slice(), b"example".as_slice(), ]) .unwrap(), Name::from_labels::<_, &[u8]>([ b"zABC".as_slice(), b"a".as_slice(), b"EXAMPLE".as_slice(), ]) .unwrap(), Name::from_labels::<_, &[u8]>([b"z".as_slice(), b"example".as_slice()]).unwrap(), Name::from_labels::<_, &[u8]>([ b"\x01".as_slice(), b"z".as_slice(), b"example".as_slice(), ]) .unwrap(), Name::from_labels::<_, &[u8]>([ b"*".as_slice(), b"z".as_slice(), b"example".as_slice(), ]) .unwrap(), Name::from_labels::<_, &[u8]>([ b"\x80".as_slice(), b"z".as_slice(), b"example".as_slice(), ]) .unwrap(), ]); let mut sorted = names.clone(); sorted.sort(); assert_eq!(names, sorted); ``` -------------------------------- ### Get ResolverUsage Source: https://docs.rs/hickory-proto/latest/hickory_proto/rr/domain/usage/struct.ZoneUsage.html Returns the ResolverUsage configuration for this zone. ```rust pub fn resolver(&self) -> ResolverUsage ``` -------------------------------- ### Get AppUsage Source: https://docs.rs/hickory-proto/latest/hickory_proto/rr/domain/usage/struct.ZoneUsage.html Returns the AppUsage configuration for this zone. ```rust pub fn app(&self) -> AppUsage ``` -------------------------------- ### Enable DNSSEC with Default Algorithms Source: https://docs.rs/hickory-proto/latest/src/hickory_proto/op/edns.rs.html Prepares the EDNS object for DNSSEC by setting the DNSSEC OK flag and adding default supported algorithms (DAU option). This is a common setup for DNSSEC. ```rust let mut edns = Edns::new(); edns.enable_dnssec(); ``` -------------------------------- ### NAPTR Record Parsing Example Source: https://docs.rs/hickory-proto/latest/src/hickory_proto/rr/rdata/naptr.rs.html Demonstrates parsing NAPTR records from a sequence of tokens, extracting order, preference, flags, services, regexp, and replacement. This is useful for reading DNS records. ```rust pub(crate) fn from_tokens<'i, I: Iterator>( mut tokens: I, origin: Option<&Name>, ) -> Result { let order: u16 = tokens .next() .ok_or_else(|| ParseError::MissingToken("order".to_string())) .and_then(|s| u16::from_str(s).map_err(Into::into))?; let preference: u16 = tokens .next() ``` -------------------------------- ### Get UserUsage Source: https://docs.rs/hickory-proto/latest/hickory_proto/rr/domain/usage/struct.ZoneUsage.html Returns the UserUsage configuration for this zone. ```rust pub fn user(&self) -> UserUsage ``` -------------------------------- ### Sign a DNS Message with TSIG Source: https://docs.rs/hickory-proto/latest/src/hickory_proto/rr/tsig.rs.html Illustrates how to sign a DNS message using a TSigner. This involves finalizing the message with a signature generated based on the message content, TSIG key, and algorithm. ```rust let time_begin = 1609459200u64; let fudge = 300u64; let origin: Name = Name::parse("example.com.", None).unwrap(); let key_name: Name = Name::from_ascii("key_name.").unwrap(); let mut question = Message::query(); let mut query: Query = Query::new(); query.set_name(origin); question.add_query(query); let sig_key = b"some_key".to_vec(); let signer = TSigner::new(sig_key, TsigAlgorithm::HmacSha512, key_name, fudge as u16).unwrap(); assert!(question.signature().is_none()); question .finalize(&signer, time_begin) .expect("should have signed"); assert!(question.signature().is_some()); ``` -------------------------------- ### Get Query Type Source: https://docs.rs/hickory-proto/latest/hickory_proto/op/struct.Query.html Returns the RecordType being queried. ```rust pub fn query_type(&self) -> RecordType ``` -------------------------------- ### RFC 4034 NSEC Record Example Source: https://docs.rs/hickory-proto/latest/src/hickory_proto/dnssec/rdata/nsec.rs.html Implements and verifies an NSEC record based on the example provided in section 4.3 of RFC 4034. This snippet ensures correct encoding and decoding of a specific NSEC record structure with various record types. ```rust use std::println; use alloc::vec::Vec; use super::* #[test] fn rfc4034_example_rdata() { // From section 4.3 of RFC 4034 let bytes = b"\x04host\ \x07example\ \x03com\x00\ \x00\x06\x40\x01\x00\x00\x00\x03\ \x04\x1b\x00\x00\x00\x00\x00\x00\ \x00\x00\x00\x00\x00\x00\x00\x00\ \x00\x00\x00\x00\x00\x00\x00\x00\ \x00\x00\x00\x00\x20"; let rdata = NSEC::new( Name::parse("host.example.com.", None).unwrap(), [ RecordType::A, RecordType::MX, RecordType::RRSIG, RecordType::NSEC, RecordType::Unknown(1234), ], ); let mut buffer = Vec::new(); let mut encoder = BinEncoder::new(&mut buffer); rdata.emit(&mut encoder).expect("Encoding error"); assert_eq!(encoder.into_bytes(), bytes); let mut decoder = BinDecoder::new(bytes); let decoded = NSEC::read_data(&mut decoder, Restrict::new(bytes.len() as u16)) .expect("Decoding error"); assert_eq!(decoded, rdata); } ``` -------------------------------- ### Parsing SVCB Parameters Source: https://docs.rs/hickory-proto/latest/src/hickory_proto/rr/rdata/svcb.rs.html Demonstrates parsing of various SVCB parameters including ALPN, IPv4 hints, ECH configuration, and IPv6 hints from a DNS record. ```rust assert_eq!(param.0, SvcParamKey::Alpn); let SvcParamValue::Alpn(value) = ¶m.1 else { panic!("expected alpn"); }; assert_eq!(value.0, &["http/1.1", "h2"]); // ipv4 hint let param = params.next().expect("ipv4hint"); assert_eq!(SvcParamKey::Ipv4Hint, param.0); let SvcParamValue::Ipv4Hint(value) = ¶m.1 else { panic!("expected ipv4hint"); }; assert_eq!( value.0, &[A::new(162, 159, 137, 85), A::new(162, 159, 138, 85)] ); // echconfig let param = params.next().expect("echconfig"); assert_eq!(SvcParamKey::EchConfigList, param.0); let SvcParamValue::EchConfigList(value) = ¶m.1 else { panic!("expected echconfig"); }; assert_eq!( value.0, data_encoding::BASE64.decode(b"AEX+DQBBtgAgACBMmGJQR02doup+5VPMjYpe5HQQ/bpntFCxDa8LT2PLAgAEAAEAAQASY2xvdWRmbGFyZS1lY2guY29tAAA=").unwrap() ); // ipv6 hint let param = params.next().expect("ipv6hint"); assert_eq!(SvcParamKey::Ipv6Hint, param.0); let SvcParamValue::Ipv6Hint(value) = ¶m.1 else { panic!("expected ipv6hint"); }; assert_eq!( value.0, &[ AAAA::new(0x2606, 0x4700, 0x7, 0, 0, 0, 0xa29f, 0x8955), AAAA::new(0x2606, 0x4700, 0x7, 0, 0, 0, 0xa29f, 0x8a5) ] ); ``` -------------------------------- ### ZoneUsage for .example. Zone Source: https://docs.rs/hickory-proto/latest/src/hickory_proto/rr/domain/usage.rs.html Creates a ZoneUsage with restrictions for the '.example.' zone, typically used for documentation and examples. All usage types are set to Normal. ```rust pub fn example(name: Name) -> Self { Self::new( name, UserUsage::Normal, AppUsage::Normal, ResolverUsage::Normal, CacheUsage::Normal, AuthUsage::Normal, OpUsage::Normal, RegistryUsage::Reserved, ) } ``` -------------------------------- ### Get Current Offset Source: https://docs.rs/hickory-proto/latest/src/hickory_proto/serialize/binary/encoder.rs.html Returns the current offset into the buffer. ```rust pub fn offset(&self) -> usize { self.offset } ``` -------------------------------- ### Get Buffer Length Source: https://docs.rs/hickory-proto/latest/src/hickory_proto/serialize/binary/encoder.rs.html Returns the current length of the buffer. ```rust pub fn len(&self) -> usize { self.buffer.len() } ``` -------------------------------- ### Converting Supported Algorithms to and from Vec Source: https://docs.rs/hickory-proto/latest/src/hickory_proto/dnssec/supported_algorithm.rs.html Illustrates the conversion of `SupportedAlgorithms` to a `Vec` and back. This is useful for serialization and deserialization. It first converts all algorithms, then a custom subset, and verifies the decoded result. ```rust let supported = SupportedAlgorithms::all(); let array: Vec = (&supported).into(); let decoded: SupportedAlgorithms = (&array as &[_]).into(); assert_eq!(supported, decoded); let mut supported = SupportedAlgorithms::new(); supported.set(Algorithm::RSASHA256); supported.set(Algorithm::ECDSAP256SHA256); supported.set(Algorithm::ECDSAP384SHA384); supported.set(Algorithm::ED25519); let array: Vec = (&supported).into(); let decoded: SupportedAlgorithms = (&array as &[_]).into(); assert_eq!(supported, decoded); assert!(!supported.has(Algorithm::RSASHA1)); assert!(!supported.has(Algorithm::RSASHA1NSEC3SHA1)); assert!(supported.has(Algorithm::RSASHA256)); assert!(supported.has(Algorithm::ECDSAP256SHA256)); assert!(supported.has(Algorithm::ECDSAP384SHA384)); assert!(supported.has(Algorithm::ED25519)); ``` -------------------------------- ### SupportedAlgorithms::new() Source: https://docs.rs/hickory-proto/latest/src/hickory_proto/dnssec/supported_algorithm.rs.html Creates a new, empty SupportedAlgorithms set. Use this when initializing a new set. ```rust pub fn new() -> Self { Self { bit_map: 0 } } ``` -------------------------------- ### Get Label Length Source: https://docs.rs/hickory-proto/latest/src/hickory_proto/rr/domain/label.rs.html Returns the length of the label in bytes. ```rust pub fn len(&self) -> usize { self.0.len() } ``` -------------------------------- ### Cloudflare SVCB Record Example Source: https://docs.rs/hickory-proto/latest/src/hickory_proto/rr/rdata/svcb.rs.html A constant string representing a Cloudflare SVCB record, including service priority, target, and hints. ```rust 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"; ``` -------------------------------- ### Get Query Class Source: https://docs.rs/hickory-proto/latest/hickory_proto/op/struct.Query.html Returns the DNS class of the query. ```rust pub fn query_class(&self) -> DNSClass ``` -------------------------------- ### Get the EDNS version Source: https://docs.rs/hickory-proto/latest/hickory_proto/op/struct.Edns.html Returns the EDNS version number. ```rust pub fn version(&self) -> u8 ``` -------------------------------- ### Zone Lexer Initialization Source: https://docs.rs/hickory-proto/latest/src/hickory_proto/serialize/txt/zone_lex.rs.html Creates a new lexer instance for parsing Zone file data. It initializes the lexer with the provided text and sets the initial state to StartLine. ```Rust pub(crate) fn new(txt: impl Into>) -> Self { Lexer { txt: CowChars { data: txt.into(), offset: 0, } .peekable(), state: State::StartLine, } } ``` -------------------------------- ### Get Name Encoding Source: https://docs.rs/hickory-proto/latest/src/hickory_proto/serialize/binary/encoder.rs.html Returns the current name encoding mode. ```rust pub fn name_encoding(&self) -> NameEncoding { self.name_encoding } ``` -------------------------------- ### New Parser Initialization Source: https://docs.rs/hickory-proto/latest/src/hickory_proto/serialize/txt/zone.rs.html Creates a new `Parser` instance for a given input string and optional path. The origin name is set to fully qualified if provided. ```rust impl<'a> Parser<'a> { /// Returns a new Zone file parser /// /// The `path` argument's parent directory is used to resolve relative `$INCLUDE` paths. /// Relative `$INCLUDE` paths will yield an error if `path` is `None`. pub fn new( input: impl Into>, path: Option, mut origin: Option, ) -> Self { if let Some(origin) = &mut origin { origin.set_fqdn(true); } Self { lexers: vec![(Lexer::new(input), path)], origin, } } ``` -------------------------------- ### Get TSigner Algorithm Source: https://docs.rs/hickory-proto/latest/hickory_proto/rr/struct.TSigner.html Returns the algorithm used for message authentication. ```rust pub fn algorithm(&self) -> &TsigAlgorithm ``` -------------------------------- ### CSYNC::new Source: https://docs.rs/hickory-proto/latest/hickory_proto/rr/rdata/csync/struct.CSYNC.html Creates a new CSYNC record data instance. ```APIDOC ## Function CSYNC::new Creates a new CSYNC record data. ### Arguments - `soa_serial` (u32): A serial number for the zone. - `immediate` (bool): A flag signalling if the change should happen immediately. - `soa_minimum` (bool): A flag to used to signal if the soa_serial should be validated. - `type_bit_maps` (impl IntoIterator): An iterator over `RecordType` that specifies the types to synchronize. ### Returns A new `CSYNC` record data instance. ``` -------------------------------- ### Get Zone Name Source: https://docs.rs/hickory-proto/latest/hickory_proto/rr/domain/usage/struct.ZoneUsage.html Retrieves a reference to the Name associated with this ZoneUsage. ```rust pub fn name(&self) -> &Name ``` -------------------------------- ### Name Comparison and Hashing Source: https://docs.rs/hickory-proto/latest/src/hickory_proto/rr/domain/name.rs.html Demonstrates the creation of domain names with and without a trailing dot and their subsequent hashing. It asserts that names with and without a trailing dot are not equal and produce different hash values. ```rust let mut hasher = DefaultHasher::new(); let with_dot = Name::from_utf8("com.").unwrap(); with_dot.hash(&mut hasher); let hash_with_dot = hasher.finish(); let without_dot = Name::from_utf8("com").unwrap(); without_dot.hash(&mut hasher); let hash_without_dot = hasher.finish(); assert_ne!(with_dot, without_dot); assert_ne!(hash_with_dot, hash_without_dot); ``` -------------------------------- ### Get DnsRequest Options Source: https://docs.rs/hickory-proto/latest/hickory_proto/op/struct.DnsRequest.html Retrieves a reference to the DnsRequestOptions associated with this request. ```rust pub fn options(&self) -> &DnsRequestOptions ``` -------------------------------- ### Get KEY RData Protocol Source: https://docs.rs/hickory-proto/latest/hickory_proto/dnssec/rdata/key/struct.KEY.html Returns the protocol that this key can be used with. ```rust pub fn protocol(&self) -> Protocol ``` -------------------------------- ### TXT Record from Bytes with Binary Encoding/Decoding Source: https://docs.rs/hickory-proto/latest/src/hickory_proto/rr/rdata/txt.rs.html Demonstrates creating a TXT record from a mix of string slices and byte slices, then encoding and decoding it. This is useful for TXT records containing non-UTF8 binary data. ```rust let bin_data = vec![0, 1, 2, 3, 4, 5, 6, 7, 8]; let rdata = TXT::from_bytes(vec![b"Test me some", &bin_data]); let mut bytes = Vec::new(); let mut encoder: BinEncoder<'_> = BinEncoder::new(&mut bytes); assert!(rdata.emit(&mut encoder).is_ok()); let bytes = encoder.into_bytes(); #[cfg(feature = "std")] println!("bytes: {:?}", bytes); let mut decoder: BinDecoder<'_> = BinDecoder::new(bytes); let restrict = Restrict::new(bytes.len() as u16); let read_rdata = TXT::read_data(&mut decoder, restrict).expect("Decoding error"); assert_eq!(rdata, read_rdata); ```