hickory-recursor-0.24.1/.cargo_vcs_info.json0000644000000001550000000000100144330ustar { "git": { "sha1": "e56a18ee241edf9c8a4ee17508cfc727617ffbb9" }, "path_in_vcs": "crates/recursor" }hickory-recursor-0.24.1/Cargo.toml0000644000000076230000000000100124400ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2021" rust-version = "1.67.0" name = "hickory-recursor" version = "0.24.1" authors = ["The contributors to Hickory DNS"] description = """ *WARNING* This library is experimental Hickory DNS Recursor is a safe and secure DNS recursive resolver with DNSSEC support. Hickory DNS is based on the Tokio and Futures libraries, which means it should be easily integrated into other software that also use those libraries. This library can be used as in the server and binary for performing recursive lookups. """ homepage = "https://hickory-dns.org/" documentation = "https://docs.rs/hickory-recursor" readme = "README.md" keywords = [ "DNS", "BIND", "dig", "named", "dnssec", ] categories = ["network-programming"] license = "MIT OR Apache-2.0" repository = "https://github.com/hickory-dns/hickory-dns" [package.metadata.docs.rs] all-features = true default-target = "x86_64-unknown-linux-gnu" rustdoc-args = [ "--cfg", "docsrs", ] targets = [ "x86_64-apple-darwin", "x86_64-pc-windows-msvc", ] [lib] name = "hickory_recursor" path = "src/lib.rs" [dependencies.async-recursion] version = "1.0.0" [dependencies.async-trait] version = "0.1.43" [dependencies.bytes] version = "1" [dependencies.cfg-if] version = "1" [dependencies.enum-as-inner] version = "0.6" [dependencies.futures-util] version = "0.3.5" features = ["std"] default-features = false [dependencies.hickory-proto] version = "0.24.0" default-features = false [dependencies.hickory-resolver] version = "0.24.0" features = ["tokio-runtime"] default-features = false [dependencies.lru-cache] version = "0.1.2" [dependencies.parking_lot] version = "0.12" [dependencies.serde] version = "1.0" features = ["derive"] optional = true [dependencies.thiserror] version = "1.0.20" [dependencies.tokio] version = "1.21" features = ["net"] [dependencies.tracing] version = "0.1.30" [dev-dependencies.tokio] version = "1.21" features = [ "macros", "rt", ] [dev-dependencies.tracing-subscriber] version = "0.3" features = [ "std", "fmt", "env-filter", ] [features] dns-over-h3 = [ "dns-over-rustls", "hickory-proto/dns-over-h3", "hickory-resolver/dns-over-h3", ] dns-over-https = ["hickory-proto/dns-over-https"] dns-over-https-rustls = [ "dns-over-https", "hickory-proto/dns-over-https-rustls", "hickory-resolver/dns-over-https-rustls", "dns-over-rustls", ] dns-over-native-tls = [ "dns-over-tls", "hickory-proto/dns-over-native-tls", "hickory-resolver/dns-over-native-tls", ] dns-over-openssl = [ "dns-over-tls", "dnssec-openssl", "hickory-proto/dns-over-openssl", "hickory-resolver/dns-over-openssl", ] dns-over-quic = [ "dns-over-rustls", "hickory-proto/dns-over-quic", "hickory-resolver/dns-over-quic", ] dns-over-rustls = [ "dns-over-tls", "dnssec-ring", "hickory-proto/dns-over-rustls", "hickory-resolver/dns-over-rustls", ] dns-over-tls = [] dnssec = [] dnssec-openssl = [ "dnssec", "hickory-proto/dnssec-openssl", "hickory-resolver/dnssec-openssl", ] dnssec-ring = [ "dnssec", "hickory-proto/dnssec-ring", "hickory-resolver/dnssec-ring", ] serde-config = [ "serde", "hickory-proto/serde-config", "hickory-resolver/serde-config", ] testing = [] tls = ["dns-over-openssl"] tls-openssl = ["dns-over-openssl"] [badges.codecov] branch = "main" repository = "hickory-dns/hickory-dns" service = "github" [badges.maintenance] status = "actively-developed" hickory-recursor-0.24.1/Cargo.toml.orig000064400000000000000000000073441046102023000161210ustar 00000000000000[package] name = "hickory-recursor" # A short blurb about the package. This is not rendered in any format when # uploaded to crates.io (aka this is not markdown) description = """ *WARNING* This library is experimental Hickory DNS Recursor is a safe and secure DNS recursive resolver with DNSSEC support. Hickory DNS is based on the Tokio and Futures libraries, which means it should be easily integrated into other software that also use those libraries. This library can be used as in the server and binary for performing recursive lookups. """ # These URLs point to more information about the repository documentation = "https://docs.rs/hickory-recursor" # This points to a file in the repository (relative to this Cargo.toml). The # contents of this file are stored and indexed in the registry. readme = "README.md" version.workspace = true authors.workspace = true edition.workspace = true rust-version.workspace = true homepage.workspace = true repository.workspace = true keywords.workspace = true categories.workspace = true license.workspace = true [badges] codecov = { repository = "hickory-dns/hickory-dns", branch = "main", service = "github" } maintenance = { status = "actively-developed" } [features] #backtrace = ["dep:backtrace", "hickory-proto/backtrace", "hickory-resolver/backtrace"] dnssec-openssl = [ "dnssec", "hickory-proto/dnssec-openssl", "hickory-resolver/dnssec-openssl", ] dnssec-ring = [ "dnssec", "hickory-proto/dnssec-ring", "hickory-resolver/dnssec-ring", ] dnssec = [] # TODO: Need to figure out how to be consistent with ring/openssl usage... dns-over-https-rustls = [ "dns-over-https", "hickory-proto/dns-over-https-rustls", "hickory-resolver/dns-over-https-rustls", "dns-over-rustls", ] dns-over-https = ["hickory-proto/dns-over-https"] dns-over-quic = [ "dns-over-rustls", "hickory-proto/dns-over-quic", "hickory-resolver/dns-over-quic", ] dns-over-h3 = [ "dns-over-rustls", "hickory-proto/dns-over-h3", "hickory-resolver/dns-over-h3", ] # TODO: migrate all tls and tls-openssl features to dns-over-tls, et al dns-over-native-tls = [ "dns-over-tls", "hickory-proto/dns-over-native-tls", "hickory-resolver/dns-over-native-tls", ] dns-over-openssl = [ "dns-over-tls", "dnssec-openssl", "hickory-proto/dns-over-openssl", "hickory-resolver/dns-over-openssl", ] dns-over-rustls = [ "dns-over-tls", "dnssec-ring", "hickory-proto/dns-over-rustls", "hickory-resolver/dns-over-rustls", ] dns-over-tls = [] # This is a deprecated feature... tls-openssl = ["dns-over-openssl"] tls = ["dns-over-openssl"] serde-config = [ "serde", "hickory-proto/serde-config", "hickory-resolver/serde-config", ] testing = [] [lib] name = "hickory_recursor" path = "src/lib.rs" [dependencies] async-trait.workspace = true async-recursion.workspace = true #backtrace = { version = "0.3.50", optional = true } bytes.workspace = true cfg-if.workspace = true enum-as-inner.workspace = true futures-util = { workspace = true, default-features = false, features = [ "std", ] } lru-cache.workspace = true parking_lot.workspace = true serde = { workspace = true, features = ["derive"], optional = true } thiserror.workspace = true tracing.workspace = true tokio = { workspace = true, features = ["net"] } hickory-proto.workspace = true hickory-resolver = { workspace = true, features = ["tokio-runtime"] } [dev-dependencies] tokio = { workspace = true, features = ["macros", "rt"] } tracing-subscriber = { workspace = true, features = [ "std", "fmt", "env-filter", ] } [package.metadata.docs.rs] all-features = true default-target = "x86_64-unknown-linux-gnu" targets = ["x86_64-apple-darwin", "x86_64-pc-windows-msvc"] rustdoc-args = ["--cfg", "docsrs"] hickory-recursor-0.24.1/LICENSE-APACHE000064400000000000000000000261401046102023000151510ustar 00000000000000 Apache License Version 2.0, January 2004 https://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "{}" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright {yyyy} {name of copyright owner} Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. hickory-recursor-0.24.1/LICENSE-MIT000064400000000000000000000021151046102023000146550ustar 00000000000000Copyright (c) 2022 The Hickory DNS Developers Copyright (c) 2017 Google LLC. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. hickory-recursor-0.24.1/README.md000064400000000000000000000030121046102023000144750ustar 00000000000000# Overview Hickory DNS Recursor is a library which implements recursive resolution for DNS. This is currently experimental, test coverage is low and full scope of tests haven't been determined yet. This library can be used to perform DNS resolution beginning with a set of root (hints) authorities. It does not require an upstream recursive resolver to find records in DNS. **NOTICE** This project was rebranded from Trust-DNS to Hickory DNS and has been moved to the https://github.com/hickory-dns/hickory-dns organization and repo, this crate/binary has been moved to [hickory-recursor](https://crates.io/crates/hickory-recursor), from `0.24` and onward, for prior versions see [trust-dns-recursor](https://crates.io/crates/trust-dns-recursor). ## Minimum Rust Version The current minimum rustc version for this project is `1.67` ## Versioning Hickory DNS does it's best job to follow semver. Hickory DNS will be promoted to 1.0 upon stabilization of the publicly exposed APIs. This does not mean that Hickory DNS will necessarily break on upgrades between 0.x updates. Whenever possible, old APIs will be deprecated with notes on what replaced those deprecations. Hickory DNS will make a best effort to never break software which depends on it due to API changes, though this can not be guaranteed. Deprecated interfaces will be maintained for at minimum one major release after that in which they were deprecated (where possible), with the exception of the upgrade to 1.0 where all deprecated interfaces will be planned to be removed. hickory-recursor-0.24.1/src/error.rs000064400000000000000000000106601046102023000155130ustar 00000000000000// Copyright 2015-2020 Benjamin Fry // // Licensed under the Apache License, Version 2.0, or the MIT license , at your option. This file may not be // copied, modified, or distributed except according to those terms. //! Error types for the crate #![deny(missing_docs)] use std::{fmt, io}; use enum_as_inner::EnumAsInner; use hickory_resolver::Name; use thiserror::Error; #[cfg(feature = "backtrace")] use crate::proto::{trace, ExtBacktrace}; use crate::{ proto::error::ProtoError, resolver::error::{ResolveError, ResolveErrorKind}, }; /// The error kind for errors that get returned in the crate #[derive(Debug, EnumAsInner, Error)] #[non_exhaustive] pub enum ErrorKind { /// An error with an arbitrary message, referenced as &'static str #[error("{0}")] Message(&'static str), /// An error with an arbitrary message, stored as String #[error("{0}")] Msg(String), /// Upstream DNS authority returned a Referral to another nameserver #[error("forward response: {0}")] Forward(Name), /// An error got returned from IO #[error("io error: {0}")] Io(#[from] std::io::Error), /// An error got returned by the hickory-proto crate #[error("proto error: {0}")] Proto(#[from] ProtoError), /// An error got returned by the hickory-proto crate #[error("proto error: {0}")] Resolve(ResolveError), /// A request timed out #[error("request timed out")] Timeout, } /// The error type for errors that get returned in the crate #[derive(Error, Clone, Debug)] #[non_exhaustive] pub struct Error { /// Kind of error that ocurred pub kind: Box, /// Backtrace to the source of the error #[cfg(feature = "backtrace")] pub backtrack: Option, } impl Error { /// Get the kind of the error pub fn kind(&self) -> &ErrorKind { &self.kind } } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { cfg_if::cfg_if! { if #[cfg(feature = "backtrace")] { if let Some(ref backtrace) = self.backtrack { fmt::Display::fmt(&self.kind, f)?; fmt::Debug::fmt(backtrace, f) } else { fmt::Display::fmt(&self.kind, f) } } else { fmt::Display::fmt(&self.kind, f) } } } } impl From for Error where E: Into, { fn from(error: E) -> Self { let kind: ErrorKind = error.into(); Self { kind: Box::new(kind), #[cfg(feature = "backtrace")] backtrack: trace!(), } } } impl From<&'static str> for Error { fn from(msg: &'static str) -> Self { ErrorKind::Message(msg).into() } } impl From for Error { fn from(msg: String) -> Self { ErrorKind::Msg(msg).into() } } impl From for io::Error { fn from(e: Error) -> Self { match *e.kind() { ErrorKind::Timeout => Self::new(io::ErrorKind::TimedOut, e), _ => Self::new(io::ErrorKind::Other, e), } } } impl From for String { fn from(e: Error) -> Self { e.to_string() } } impl From for Error { fn from(e: ResolveError) -> Self { if let ResolveErrorKind::NoRecordsFound { soa, .. } = e.kind() { match soa { Some(soa) => ErrorKind::Forward(soa.name().clone()).into(), _ => ErrorKind::Resolve(e).into(), } } else { ErrorKind::Resolve(e).into() } } } impl Clone for ErrorKind { fn clone(&self) -> Self { use self::ErrorKind::*; match *self { Message(msg) => Message(msg), Msg(ref msg) => Msg(msg.clone()), Forward(ref ns) => Forward(ns.clone()), Io(ref io) => Io(std::io::Error::from(io.kind())), Proto(ref proto) => Proto(proto.clone()), Resolve(ref resolve) => Resolve(resolve.clone()), Timeout => Self::Timeout, } } } /// A trait marking a type which implements From and /// std::error::Error types as well as Clone + Send pub trait FromError: From + std::error::Error + Clone {} impl FromError for E where E: From + std::error::Error + Clone {} hickory-recursor-0.24.1/src/lib.rs000064400000000000000000000021651046102023000151310ustar 00000000000000// Copyright 2015-2022 Benjamin Fry // // Licensed under the Apache License, Version 2.0, or the MIT license , at your option. This file may not be // copied, modified, or distributed except according to those terms. //! A recursive DNS resolver based on the Hickory DNS (stub) resolver #![warn( clippy::default_trait_access, clippy::dbg_macro, clippy::print_stdout, clippy::unimplemented, missing_copy_implementations, missing_docs, non_snake_case, non_upper_case_globals, rust_2018_idioms, unreachable_pub )] #![allow( clippy::single_component_path_imports, clippy::upper_case_acronyms, // can be removed on a major release boundary )] #![recursion_limit = "2048"] #![cfg_attr(docsrs, feature(doc_cfg))] pub mod error; mod recursor; pub(crate) mod recursor_pool; pub use error::{Error, ErrorKind}; pub use hickory_proto as proto; pub use hickory_resolver as resolver; pub use hickory_resolver::config::NameServerConfig; pub use recursor::Recursor; hickory-recursor-0.24.1/src/recursor.rs000064400000000000000000000472751046102023000162420ustar 00000000000000// Copyright 2015-2023 Benjamin Fry // // Licensed under the Apache License, Version 2.0, or the MIT license , at your option. This file may not be // copied, modified, or distributed except according to those terms. use std::{net::SocketAddr, time::Instant}; use async_recursion::async_recursion; use futures_util::{future::select_all, FutureExt}; use hickory_resolver::name_server::TokioConnectionProvider; use lru_cache::LruCache; use parking_lot::Mutex; use tracing::{debug, info, warn}; use crate::{ proto::{ op::Query, rr::{RData, RecordType}, }, recursor_pool::RecursorPool, resolver::{ config::{NameServerConfig, NameServerConfigGroup, Protocol, ResolverOpts}, dns_lru::{DnsLru, TtlConfig}, error::ResolveError, lookup::Lookup, name_server::{GenericNameServerPool, TokioRuntimeProvider}, Name, }, Error, ErrorKind, }; /// Set of nameservers by the zone name type NameServerCache

= LruCache>; /// A top down recursive resolver which operates off a list of roots for initial recursive requests. /// /// This is the well known root nodes, referred to as hints in RFCs. See the IANA [Root Servers](https://www.iana.org/domains/root/servers) list. pub struct Recursor { roots: RecursorPool, name_server_cache: Mutex>, record_cache: DnsLru, } impl Recursor { /// Construct a new recursor using the list of NameServerConfigs for the root node list /// /// # Panics /// /// This will panic if the roots are empty. pub fn new(roots: impl Into) -> Result { // configure the hickory-resolver let roots: NameServerConfigGroup = roots.into(); assert!(!roots.is_empty(), "roots must not be empty"); let opts = recursor_opts(); let roots = GenericNameServerPool::from_config(roots, opts, TokioConnectionProvider::default()); let roots = RecursorPool::from(Name::root(), roots); let name_server_cache = Mutex::new(NameServerCache::new(100)); // TODO: make this configurable let record_cache = DnsLru::new(100, TtlConfig::default()); Ok(Self { roots, name_server_cache, record_cache, }) } /// Perform a recursive resolution /// /// [RFC 1034](https://datatracker.ietf.org/doc/html/rfc1034#section-5.3.3), Domain Concepts and Facilities, November 1987 /// /// ```text /// 5.3.3. Algorithm /// /// The top level algorithm has four steps: /// /// 1. See if the answer is in local information, and if so return /// it to the client. /// /// 2. Find the best servers to ask. /// /// 3. Send them queries until one returns a response. /// /// 4. Analyze the response, either: /// /// a. if the response answers the question or contains a name /// error, cache the data as well as returning it back to /// the client. /// /// b. if the response contains a better delegation to other /// servers, cache the delegation information, and go to /// step 2. /// /// c. if the response shows a CNAME and that is not the /// answer itself, cache the CNAME, change the SNAME to the /// canonical name in the CNAME RR and go to step 1. /// /// d. if the response shows a servers failure or other /// bizarre contents, delete the server from the SLIST and /// go back to step 3. /// /// Step 1 searches the cache for the desired data. If the data is in the /// cache, it is assumed to be good enough for normal use. Some resolvers /// have an option at the user interface which will force the resolver to /// ignore the cached data and consult with an authoritative server. This /// is not recommended as the default. If the resolver has direct access to /// a name server's zones, it should check to see if the desired data is /// present in authoritative form, and if so, use the authoritative data in /// preference to cached data. /// /// Step 2 looks for a name server to ask for the required data. The /// general strategy is to look for locally-available name server RRs, /// starting at SNAME, then the parent domain name of SNAME, the /// grandparent, and so on toward the root. Thus if SNAME were /// Mockapetris.ISI.EDU, this step would look for NS RRs for /// Mockapetris.ISI.EDU, then ISI.EDU, then EDU, and then . (the root). /// These NS RRs list the names of hosts for a zone at or above SNAME. Copy /// the names into SLIST. Set up their addresses using local data. It may /// be the case that the addresses are not available. The resolver has many /// choices here; the best is to start parallel resolver processes looking /// for the addresses while continuing onward with the addresses which are /// available. Obviously, the design choices and options are complicated /// and a function of the local host's capabilities. The recommended /// priorities for the resolver designer are: /// /// 1. Bound the amount of work (packets sent, parallel processes /// started) so that a request can't get into an infinite loop or /// start off a chain reaction of requests or queries with other /// implementations EVEN IF SOMEONE HAS INCORRECTLY CONFIGURED /// SOME DATA. /// /// 2. Get back an answer if at all possible. /// /// 3. Avoid unnecessary transmissions. /// /// 4. Get the answer as quickly as possible. /// /// If the search for NS RRs fails, then the resolver initializes SLIST from /// the safety belt SBELT. The basic idea is that when the resolver has no /// idea what servers to ask, it should use information from a configuration /// file that lists several servers which are expected to be helpful. /// Although there are special situations, the usual choice is two of the /// root servers and two of the servers for the host's domain. The reason /// for two of each is for redundancy. The root servers will provide /// eventual access to all of the domain space. The two local servers will /// allow the resolver to continue to resolve local names if the local /// network becomes isolated from the internet due to gateway or link /// failure. /// /// In addition to the names and addresses of the servers, the SLIST data /// structure can be sorted to use the best servers first, and to insure /// that all addresses of all servers are used in a round-robin manner. The /// sorting can be a simple function of preferring addresses on the local /// network over others, or may involve statistics from past events, such as /// previous response times and batting averages. /// /// Step 3 sends out queries until a response is received. The strategy is /// to cycle around all of the addresses for all of the servers with a /// timeout between each transmission. In practice it is important to use /// all addresses of a multihomed host, and too aggressive a retransmission /// policy actually slows response when used by multiple resolvers /// contending for the same name server and even occasionally for a single /// resolver. SLIST typically contains data values to control the timeouts /// and keep track of previous transmissions. /// /// Step 4 involves analyzing responses. The resolver should be highly /// paranoid in its parsing of responses. It should also check that the /// response matches the query it sent using the ID field in the response. /// /// The ideal answer is one from a server authoritative for the query which /// either gives the required data or a name error. The data is passed back /// to the user and entered in the cache for future use if its TTL is /// greater than zero. /// /// If the response shows a delegation, the resolver should check to see /// that the delegation is "closer" to the answer than the servers in SLIST /// are. This can be done by comparing the match count in SLIST with that /// computed from SNAME and the NS RRs in the delegation. If not, the reply /// is bogus and should be ignored. If the delegation is valid the NS /// delegation RRs and any address RRs for the servers should be cached. /// The name servers are entered in the SLIST, and the search is restarted. /// /// If the response contains a CNAME, the search is restarted at the CNAME /// unless the response has the data for the canonical name or if the CNAME /// is the answer itself. /// /// Details and implementation hints can be found in [RFC-1035]. /// /// 6. A SCENARIO /// /// In our sample domain space, suppose we wanted separate administrative /// control for the root, MIL, EDU, MIT.EDU and ISI.EDU zones. We might /// allocate name servers as follows: /// /// /// |(C.ISI.EDU,SRI-NIC.ARPA /// | A.ISI.EDU) /// +---------------------+------------------+ /// | | | /// MIL EDU ARPA /// |(SRI-NIC.ARPA, |(SRI-NIC.ARPA, | /// | A.ISI.EDU | C.ISI.EDU) | /// +-----+-----+ | +------+-----+-----+ /// | | | | | | | /// BRL NOSC DARPA | IN-ADDR SRI-NIC ACC /// | /// +--------+------------------+---------------+--------+ /// | | | | | /// UCI MIT | UDEL YALE /// |(XX.LCS.MIT.EDU, ISI /// |ACHILLES.MIT.EDU) |(VAXA.ISI.EDU,VENERA.ISI.EDU, /// +---+---+ | A.ISI.EDU) /// | | | /// LCS ACHILLES +--+-----+-----+--------+ /// | | | | | | /// XX A C VAXA VENERA Mockapetris /// /// In this example, the authoritative name server is shown in parentheses /// at the point in the domain tree at which is assumes control. /// /// Thus the root name servers are on C.ISI.EDU, SRI-NIC.ARPA, and /// A.ISI.EDU. The MIL domain is served by SRI-NIC.ARPA and A.ISI.EDU. The /// EDU domain is served by SRI-NIC.ARPA. and C.ISI.EDU. Note that servers /// may have zones which are contiguous or disjoint. In this scenario, /// C.ISI.EDU has contiguous zones at the root and EDU domains. A.ISI.EDU /// has contiguous zones at the root and MIL domains, but also has a non- /// contiguous zone at ISI.EDU. /// ``` pub async fn resolve(&self, query: Query, request_time: Instant) -> Result { if let Some(lookup) = self.record_cache.get(&query, request_time) { return lookup.map_err(Into::into); } // not in cache, let's look for an ns record for lookup let zone = match query.query_type() { RecordType::NS => query.name().base_name(), // look for the NS records "inside" the zone _ => query.name().clone(), }; let mut zone = zone; let mut ns = None; // max number of forwarding processes 'max_forward: for _ in 0..20 { match self.ns_pool_for_zone(zone.clone(), request_time).await { Ok(found) => { // found the nameserver ns = Some(found); break 'max_forward; } Err(e) => match e.kind() { ErrorKind::Forward(name) => { // if we already had this name, don't try again if &zone == name { debug!("zone previously searched for {}", name); break 'max_forward; }; debug!("ns forwarded to {}", name); zone = name.clone(); } _ => return Err(e), }, } } let ns = ns.ok_or_else(|| Error::from(format!("no nameserver found for {zone}")))?; debug!("found zone {} for {}", ns.zone(), query); let response = self.lookup(query, ns, request_time).await?; Ok(response) } async fn lookup( &self, query: Query, ns: RecursorPool, now: Instant, ) -> Result { if let Some(lookup) = self.record_cache.get(&query, now) { debug!("cached data {lookup:?}"); return lookup.map_err(Into::into); } let response = ns.lookup(query.clone()); // TODO: we are only expecting one response // TODO: should we change DnsHandle to always be a single response? And build a totally custom handler for other situations? // TODO: check if data is "authentic" match response.await { Ok(r) => { let mut r = r.into_message(); info!("response: {}", r.header()); let records = r .take_answers() .into_iter() .chain(r.take_name_servers()) .chain(r.take_additionals()); let lookup = self.record_cache.insert_records(query, records, now); lookup.ok_or_else(|| Error::from("no records found")) } Err(e) => { warn!("lookup error: {e}"); Err(Error::from(e)) } } } #[async_recursion] async fn ns_pool_for_zone( &self, zone: Name, request_time: Instant, ) -> Result, Error> { // TODO: need to check TTLs here. if let Some(ns) = self.name_server_cache.lock().get_mut(&zone) { return Ok(ns.clone()); }; let parent_zone = zone.base_name(); let nameserver_pool = if parent_zone.is_root() { debug!("using roots for {zone} nameservers"); self.roots.clone() } else { self.ns_pool_for_zone(parent_zone, request_time).await? }; // TODO: check for cached ns pool for this zone let lookup = Query::query(zone.clone(), RecordType::NS); let response = self .lookup(lookup.clone(), nameserver_pool.clone(), request_time) .await?; // let zone_nameservers = response.name_servers(); // let glue = response.additionals(); // TODO: grab TTL and use for cache // get all the NS records and glue let mut config_group = NameServerConfigGroup::new(); let mut need_ips_for_names = Vec::new(); // unpack all glued records for zns in response.record_iter() { if let Some(ns_data) = zns.data().and_then(RData::as_ns) { // let glue_ips = glue // .iter() // .filter(|g| g.name() == ns_data) // .filter_map(Record::data) // .filter_map(RData::to_ip_addr); let cached_a = self.record_cache.get( &Query::query(ns_data.0.clone(), RecordType::A), request_time, ); let cached_aaaa = self.record_cache.get( &Query::query(ns_data.0.clone(), RecordType::AAAA), request_time, ); let cached_a = cached_a.and_then(Result::ok).map(Lookup::into_iter); let cached_aaaa = cached_aaaa.and_then(Result::ok).map(Lookup::into_iter); let glue_ips = cached_a .into_iter() .flatten() .chain(cached_aaaa.into_iter().flatten()) .filter_map(|r| RData::ip_addr(&r)); let mut had_glue = false; for ip in glue_ips { let mut udp = NameServerConfig::new(SocketAddr::from((ip, 53)), Protocol::Udp); let mut tcp = NameServerConfig::new(SocketAddr::from((ip, 53)), Protocol::Tcp); udp.trust_negative_responses = true; tcp.trust_negative_responses = true; config_group.push(udp); config_group.push(tcp); had_glue = true; } if !had_glue { debug!("glue not found for {}", ns_data); need_ips_for_names.push(ns_data); } } } // collect missing IP addresses, select over them all, get the addresses // make it configurable to query for all records? if config_group.is_empty() && !need_ips_for_names.is_empty() { debug!("need glue for {}", zone); let a_resolves = need_ips_for_names.iter().take(1).map(|name| { let a_query = Query::query(name.0.clone(), RecordType::A); self.resolve(a_query, request_time).boxed() }); let aaaa_resolves = need_ips_for_names.iter().take(1).map(|name| { let aaaa_query = Query::query(name.0.clone(), RecordType::AAAA); self.resolve(aaaa_query, request_time).boxed() }); let mut a_resolves: Vec<_> = a_resolves.chain(aaaa_resolves).collect(); while !a_resolves.is_empty() { let (next, _, rest) = select_all(a_resolves).await; a_resolves = rest; match next { Ok(response) => { debug!("A or AAAA response: {:?}", response); let ips = response.iter().filter_map(RData::ip_addr); for ip in ips { let udp = NameServerConfig::new(SocketAddr::from((ip, 53)), Protocol::Udp); let tcp = NameServerConfig::new(SocketAddr::from((ip, 53)), Protocol::Tcp); config_group.push(udp); config_group.push(tcp); } } Err(e) => { warn!("resolve failed {}", e); } } } } // now construct a namesever pool based off the NS and glue records let ns = GenericNameServerPool::from_config( config_group, recursor_opts(), TokioConnectionProvider::default(), ); let ns = RecursorPool::from(zone.clone(), ns); // store in cache for future usage debug!("found nameservers for {}", zone); self.name_server_cache.lock().insert(zone, ns.clone()); Ok(ns) } } fn recursor_opts() -> ResolverOpts { let mut options = ResolverOpts::default(); options.ndots = 0; options.edns0 = true; options.validate = false; // we'll need to do any dnssec validation differently in a recursor (top-down rather than bottom-up) options.preserve_intermediates = true; options.recursion_desired = false; options.num_concurrent_reqs = 1; options } hickory-recursor-0.24.1/src/recursor_pool.rs000064400000000000000000000064301046102023000172570ustar 00000000000000// Copyright 2015-2022 Benjamin Fry // // Licensed under the Apache License, Version 2.0, or the MIT license , at your option. This file may not be // copied, modified, or distributed except according to those terms. use std::{ collections::HashMap, pin::Pin, sync::Arc, task::{Context, Poll}, }; use futures_util::{future::Shared, Future, FutureExt, StreamExt}; use hickory_proto::{ op::Query, xfer::{DnsRequestOptions, DnsResponse}, DnsHandle, }; use hickory_resolver::name_server::{RuntimeProvider, TokioRuntimeProvider}; use hickory_resolver::{ error::{ResolveError, ResolveErrorKind}, name_server::GenericNameServerPool, Name, }; use parking_lot::Mutex; use tracing::info; /// Active request cache /// /// The futures are Shared so any waiting on these results will resolve to the same result type ActiveRequests = HashMap; type DnsResponseFuture = Box>> + Send + 'static>; #[derive(Clone)] pub(crate) struct SharedLookup(Shared>); impl Future for SharedLookup { type Output = Result; fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { self.0.poll_unpin(cx).map(|o| match o { Some(r) => r, None => Err(ResolveErrorKind::Message("no response from nameserver").into()), }) } } #[derive(Clone)] pub(crate) struct RecursorPool { zone: Name, ns: GenericNameServerPool

, active_requests: Arc>, } impl RecursorPool { pub(crate) fn from(zone: Name, ns: GenericNameServerPool) -> Self { let active_requests = Arc::new(Mutex::new(ActiveRequests::default())); Self { zone, ns, active_requests, } } } impl

RecursorPool

where P: RuntimeProvider + Send + 'static, { pub(crate) fn zone(&self) -> &Name { &self.zone } pub(crate) async fn lookup(&self, query: Query) -> Result { let ns = self.ns.clone(); let query_cpy = query.clone(); // block concurrent requests let lookup = self .active_requests .lock() .entry(query.clone()) .or_insert_with(move || { info!("querying {} for {}", self.zone, query_cpy); let mut options = DnsRequestOptions::default(); options.use_edns = false; // TODO: this should be configurable options.recursion_desired = false; // convert the lookup into a shared future let lookup = ns .lookup(query_cpy, options) .into_future() .map(|(next, _)| next) .boxed() .shared(); SharedLookup(lookup) }) .clone(); let result = lookup.await; // remove the concurrent request marker self.active_requests.lock().remove(&query); result } }