async-std-resolver-0.24.0/.cargo_vcs_info.json0000644000000001670000000000100146670ustar { "git": { "sha1": "408d0baca080d1b201cd33e616dc4abd160ef6c0" }, "path_in_vcs": "crates/async-std-resolver" }async-std-resolver-0.24.0/Cargo.toml0000644000000042230000000000100126620ustar # 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 = "async-std-resolver" version = "0.24.0" authors = ["The contributors to Hickory DNS"] description = """ Hickory DNS is a safe and secure DNS library, for async-std. This Resolver library uses the hickory-proto library to perform all DNS queries. The Resolver is intended to be a high-level library for any DNS record resolution see Resolver and AsyncResolver for supported resolution types. The Client can be used for other queries. """ homepage = "https://hickory-dns.org/" documentation = "https://docs.rs/async-std-resolver" 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" [lib] name = "async_std_resolver" path = "src/lib.rs" [dependencies.async-std] version = "1.6" features = ["unstable"] [dependencies.async-trait] version = "0.1.43" [dependencies.futures-io] version = "0.3.5" features = ["std"] default-features = false [dependencies.futures-util] version = "0.3.5" features = ["std"] default-features = false [dependencies.hickory-resolver] version = "0.24.0" default-features = false [dependencies.pin-utils] version = "0.1.0" [dependencies.socket2] version = "0.5" [dev-dependencies.async-std] version = "1.6" features = ["attributes"] [dev-dependencies.hickory-resolver] version = "0.24.0" features = ["testing"] default-features = false [features] default = ["system-config"] system-config = ["hickory-resolver/system-config"] [badges.codecov] branch = "main" repository = "hickory-dns/hickory-dns" service = "github" [badges.maintenance] status = "actively-developed" async-std-resolver-0.24.0/Cargo.toml.orig000064400000000000000000000053151046102023000163460ustar 00000000000000[package] name = "async-std-resolver" # A short blurb about the package. This is not rendered in any format when # uploaded to crates.io (aka this is not markdown) description = """ Hickory DNS is a safe and secure DNS library, for async-std. This Resolver library uses the hickory-proto library to perform all DNS queries. The Resolver is intended to be a high-level library for any DNS record resolution see Resolver and AsyncResolver for supported resolution types. The Client can be used for other queries. """ # These URLs point to more information about the repository documentation = "https://docs.rs/async-std-resolver" # 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] #github-actions = { repository = "bluejekyll/hickory", branch = "main", workflow = "test" } codecov = { repository = "hickory-dns/hickory-dns", branch = "main", service = "github" } maintenance = { status = "actively-developed" } [features] default = ["system-config"] # resolver configuration system-config = ["hickory-resolver/system-config"] #### # TODO: These next features are common across the hickory crates, but they are not ready for use here #### #dns-over-native-tls = ["dns-over-tls", "hickory-resolver/dns-over-native-tls"] # DNS over TLS with OpenSSL currently needs a good way to set default CAs, use rustls or native-tls #dns-over-openssl = ["dns-over-tls", "hickory-resolver/dns-over-openssl"] #dns-over-rustls = ["dns-over-tls", "hickory-resolver/dns-over-rustls"] #dns-over-tls = [] # This requires some TLS library, currently only rustls is supported #dns-over-https-rustls = ["hickory-resolver/dns-over-https-rustls"] #dns-over-https = [] #dnssec-openssl = ["dnssec", "hickory-resolver/dnssec-openssl"] #dnssec-ring = ["dnssec", "hickory-resolver/dnssec-ring"] #dnssec = [] [lib] name = "async_std_resolver" path = "src/lib.rs" [dependencies] async-std = { workspace = true, features = ["unstable"] } async-trait.workspace = true futures-io = { workspace = true, default-features = false, features = ["std"] } futures-util = { workspace = true, default-features = false, features = [ "std", ] } pin-utils.workspace = true hickory-resolver = { workspace = true, default-features = false } socket2.workspace = true [dev-dependencies] async-std = { workspace = true, features = ["attributes"] } hickory-resolver = { workspace = true, default-features = false, features = [ "testing", ] } async-std-resolver-0.24.0/LICENSE-APACHE000064400000000000000000000261401046102023000154020ustar 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. async-std-resolver-0.24.0/LICENSE-MIT000064400000000000000000000021151046102023000151060ustar 00000000000000Copyright (c) 2015 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. async-std-resolver-0.24.0/README.md000064400000000000000000000065301046102023000147360ustar 00000000000000# Overview Hickory DNS Async-Std Resolver is a library which implements the DNS resolver using the Hickory DNS Resolver library. This library contains implementations for IPv4 (A) and IPv6 (AAAA) resolution, more features are in the works. It is built on top of the [async-std](https://async.rs) async-io project, this allows it to be integrated into other systems using the async-std and futures libraries. The Hickory DNS [project](https://github.com/hickory-dns/hickory-dns) contains other libraries for DNS: a [client library](https://crates.io/crates/hickory-client) for raw protocol usage, a [server library](https://crates.io/crates/hickory-server) for hosting zones, and variations on the TLS implementation over [rustls](https://crates.io/crates/hickory-dns-rustls) and [native-tls](https://crates.io/crates/hickory-dns-native-tls). **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, from `0.24` and onward. ## Features - Various IPv4 and IPv6 lookup strategies - `/etc/resolv.conf` based configuration on Unix/Posix systems - NameServer pools with performance based priority usage - Caching of query results - NxDomain/NoData caching (negative caching) - TBD (in tokio impl): DNSSEC validation - Generic Record Type Lookup - CNAME chain resolution - _experimental_ mDNS support (enable with `mdns` feature) - TBD (in tokio impl): DNS over TLS (utilizing `native-tls`, `rustls`, and `openssl`; `native-tls` or `rustls` are recommended) - TBD (in tokio impl): DNS over HTTPS (currently only supports `rustls`) ## Example ```rust use std::net::*; use async_std::prelude::*; use async_std_resolver::{resolver, config}; #[async_std::main] async fn main() { // Construct a new Resolver with default configuration options let resolver = resolver( config::ResolverConfig::default(), config::ResolverOpts::default(), ).await; // Lookup the IP addresses associated with a name. // This returns a future that will lookup the IP addresses, it must be run in the Core to // to get the actual result. let mut response = resolver.lookup_ip("www.example.com.").await.unwrap(); // There can be many addresses associated with the name, // this can return IPv4 and/or IPv6 addresses let address = response.iter().next().expect("no addresses returned!"); if address.is_ipv4() { assert_eq!(address, IpAddr::V4(Ipv4Addr::new(93, 184, 216, 34))); } else { assert_eq!(address, IpAddr::V6(Ipv6Addr::new(0x2606, 0x2800, 0x220, 0x1, 0x248, 0x1893, 0x25c8, 0x1946))); } } ``` ## Minimum Rust Version The current minimum rustc version for this project is `1.67` ## Versioning Hickory DNS does its 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. async-std-resolver-0.24.0/src/lib.rs000064400000000000000000000126221046102023000153610ustar 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. // LIBRARY WARNINGS #![warn( clippy::default_trait_access, clippy::dbg_macro, clippy::print_stdout, clippy::unimplemented, clippy::use_self, missing_copy_implementations, missing_docs, non_snake_case, non_upper_case_globals, rust_2018_idioms, unreachable_pub )] #![allow(clippy::needless_doctest_main)] //! The Resolver is responsible for performing recursive queries to lookup domain names. //! //! This is a 100% in process DNS resolver. It *does not* use the Host OS' resolver. If what is desired is to use the Host OS' resolver, generally in the system's libc, then the `std::net::ToSocketAddrs` variant over `&str` should be used. //! //! Unlike the `hickory-client`, this tries to provide a simpler interface to perform DNS queries. For update options, i.e. Dynamic DNS, the `hickory-client` crate must be used instead. The Resolver library is capable of searching multiple domains (this can be disabled by using an FQDN during lookup), dual-stack IPv4/IPv6 lookups, performing chained CNAME lookups, and features connection metric tracking for attempting to pick the best upstream DNS resolver. //! //! Use [`AsyncResolver`](crate::AsyncResolver) for performing DNS queries. `AsyncResolver` is a `async-std` based async resolver, and can be used inside any `asyn-std` based system. //! //! This as best as possible attempts to abide by the DNS RFCs, please file issues at . //! //! # Usage //! //! ## Declare dependency //! //! ```toml //! [dependency] //! async-std-resolver = "*" //! ``` //! //! ## Using the async-std Resolver //! //! For more advanced asynchronous usage, the [`AsyncResolver`] is integrated with async-std. //! //! ```rust //! use std::net::*; //! use async_std::prelude::*; //! use async_std_resolver::{resolver, config}; //! //! #[async_std::main] //! async fn main() { //! // Construct a new Resolver with default configuration options //! let resolver = resolver( //! config::ResolverConfig::default(), //! config::ResolverOpts::default(), //! ).await; //! //! // Lookup the IP addresses associated with a name. //! // This returns a future that will lookup the IP addresses, it must be run in the Core to //! // to get the actual result. //! let mut response = resolver.lookup_ip("www.example.com.").await.unwrap(); //! //! // There can be many addresses associated with the name, //! // this can return IPv4 and/or IPv6 addresses //! let address = response.iter().next().expect("no addresses returned!"); //! if address.is_ipv4() { //! assert_eq!(address, IpAddr::V4(Ipv4Addr::new(93, 184, 216, 34))); //! } else { //! assert_eq!(address, IpAddr::V6(Ipv6Addr::new(0x2606, 0x2800, 0x220, 0x1, 0x248, 0x1893, 0x25c8, 0x1946))); //! } //! } //! ``` //! //! ## Using the host system config //! //! On Unix systems, the `/etc/resolv.conf` can be used for configuration. Not all options specified in the host systems `resolv.conf` are applicable or compatible with this software. In addition there may be additional options supported which the host system does not. Example: //! //! ``` //! use std::net::*; //! use async_std::prelude::*; //! # #[cfg(feature = "system-config")] //! use async_std_resolver::{resolver_from_system_conf, config}; //! //! #[async_std::main] //! async fn main() { //! # #[cfg(feature = "system-config")] //! # { //! // Use the host OS'es `/etc/resolv.conf` //! let resolver = resolver_from_system_conf().await.unwrap(); //! let response = resolver.lookup_ip("www.example.com.").await.unwrap(); //! # } //! } //! ``` use hickory_resolver::AsyncResolver; use crate::runtime::AsyncStdConnectionProvider; mod net; mod runtime; #[cfg(test)] mod tests; mod time; pub use hickory_resolver::config; pub use hickory_resolver::error::ResolveError; pub use hickory_resolver::lookup; pub use hickory_resolver::lookup_ip; pub use hickory_resolver::proto; /// An AsyncResolver used with async_std pub type AsyncStdResolver = AsyncResolver; /// Construct a new async-std based `AsyncResolver` with the provided configuration. /// /// # Arguments /// /// * `config` - configuration, name_servers, etc. for the Resolver /// * `options` - basic lookup options for the resolver /// /// # Returns /// /// A tuple containing the new `AsyncResolver` and a future that drives the /// background task that runs resolutions for the `AsyncResolver`. See the /// documentation for `AsyncResolver` for more information on how to use /// the background future. pub async fn resolver( config: config::ResolverConfig, options: config::ResolverOpts, ) -> AsyncStdResolver { AsyncStdResolver::new(config, options, AsyncStdConnectionProvider::default()) } /// Constructs a new async-std based Resolver with the system configuration. /// /// This will use `/etc/resolv.conf` on Unix OSes and the registry on Windows. #[cfg(any(unix, target_os = "windows"))] #[cfg(feature = "system-config")] pub async fn resolver_from_system_conf() -> Result { AsyncStdResolver::from_system_conf(AsyncStdConnectionProvider::default()) } async-std-resolver-0.24.0/src/net.rs000064400000000000000000000116261046102023000154040ustar 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. use std::io; use std::net::{Ipv4Addr, Ipv6Addr, SocketAddr}; use std::pin::Pin; use std::task::{Context, Poll}; use async_std::task::spawn_blocking; use async_trait::async_trait; use futures_io::{AsyncRead, AsyncWrite}; use futures_util::future::FutureExt; use hickory_resolver::proto::tcp::{Connect, DnsTcpStream}; use hickory_resolver::proto::udp::{DnsUdpSocket, QuicLocalAddr, UdpSocket}; use pin_utils::pin_mut; use socket2::{Domain, Protocol, Socket, Type}; use crate::time::AsyncStdTime; pub struct AsyncStdUdpSocket(async_std::net::UdpSocket); #[async_trait] impl DnsUdpSocket for AsyncStdUdpSocket { type Time = AsyncStdTime; fn poll_recv_from( &self, cx: &mut Context<'_>, buf: &mut [u8], ) -> Poll> { let fut = self.0.recv_from(buf); pin_mut!(fut); fut.poll_unpin(cx) } async fn recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> { self.0.recv_from(buf).await } fn poll_send_to( &self, cx: &mut Context<'_>, buf: &[u8], target: SocketAddr, ) -> Poll> { let fut = self.0.send_to(buf, target); pin_mut!(fut); fut.poll_unpin(cx) } async fn send_to(&self, buf: &[u8], target: SocketAddr) -> io::Result { self.0.send_to(buf, target).await } } impl QuicLocalAddr for AsyncStdUdpSocket { fn local_addr(&self) -> io::Result { self.0.local_addr() } } #[async_trait] impl UdpSocket for AsyncStdUdpSocket { async fn connect(addr: SocketAddr) -> io::Result { let bind_addr: SocketAddr = match addr { SocketAddr::V4(_addr) => (Ipv4Addr::UNSPECIFIED, 0).into(), SocketAddr::V6(_addr) => (Ipv6Addr::UNSPECIFIED, 0).into(), }; Self::connect_with_bind(addr, bind_addr).await } async fn connect_with_bind(_addr: SocketAddr, bind_addr: SocketAddr) -> io::Result { let socket = async_std::net::UdpSocket::bind(bind_addr).await?; // TODO: research connect more, it appears to break receive tests on UDP // socket.connect(addr).await?; Ok(Self(socket)) } async fn bind(addr: SocketAddr) -> io::Result { async_std::net::UdpSocket::bind(addr) .await .map(AsyncStdUdpSocket) } } pub struct AsyncStdTcpStream(async_std::net::TcpStream); impl DnsTcpStream for AsyncStdTcpStream { type Time = AsyncStdTime; } #[async_trait] impl Connect for AsyncStdTcpStream { async fn connect_with_bind( addr: SocketAddr, bind_addr: Option, ) -> io::Result { let stream = match bind_addr { Some(bind_addr) => { spawn_blocking(move || { let domain = match bind_addr { SocketAddr::V4(_) => Domain::IPV4, SocketAddr::V6(_) => Domain::IPV6, }; let socket = Socket::new(domain, Type::STREAM, Some(Protocol::TCP))?; socket.bind(&bind_addr.into())?; socket.connect(&addr.into())?; let std_stream: std::net::TcpStream = socket.into(); let stream = async_std::net::TcpStream::from(std_stream); Ok::<_, io::Error>(stream) }) .await? } None => async_std::net::TcpStream::connect(addr).await?, }; stream.set_nodelay(true)?; Ok(Self(stream)) } } impl AsyncWrite for AsyncStdTcpStream { fn poll_write( mut self: std::pin::Pin<&mut Self>, cx: &mut std::task::Context<'_>, bytes: &[u8], ) -> std::task::Poll> { Pin::new(&mut self.0).poll_write(cx, bytes) } fn poll_flush( mut self: std::pin::Pin<&mut Self>, cx: &mut std::task::Context<'_>, ) -> std::task::Poll> { Pin::new(&mut self.0).poll_flush(cx) } fn poll_close( mut self: std::pin::Pin<&mut Self>, cx: &mut std::task::Context<'_>, ) -> std::task::Poll> { Pin::new(&mut self.0).poll_close(cx) } } impl AsyncRead for AsyncStdTcpStream { fn poll_read( mut self: std::pin::Pin<&mut Self>, cx: &mut std::task::Context<'_>, bytes: &mut [u8], ) -> std::task::Poll> { Pin::new(&mut self.0).poll_read(cx, bytes) } } async-std-resolver-0.24.0/src/runtime.rs000064400000000000000000000100371046102023000162740ustar 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. use hickory_resolver::config::{NameServerConfig, ResolverOpts}; use std::future::Future; use std::net::SocketAddr; use std::pin::Pin; use hickory_resolver::proto::error::ProtoError; use hickory_resolver::proto::Executor; use hickory_resolver::name_server::{ConnectionProvider, GenericConnector, RuntimeProvider, Spawn}; use crate::net::{AsyncStdTcpStream, AsyncStdUdpSocket}; use crate::proto::tcp::Connect; use crate::proto::udp::UdpSocket; use crate::time::AsyncStdTime; /// The async_std runtime. /// /// The runtime provides an I/O [driver], task scheduler, [timer], and blocking /// pool, necessary for running asynchronous tasks. /// /// Instances of `AsyncStdRuntime` can be created using [`new`]. However, most /// users will use the `#[async_std::main]` annotation on their entry point instead. /// /// See [module level][mod] documentation for more details. /// /// # Shutdown /// /// Shutting down the runtime is done by dropping the value. The current thread /// will block until the shut down operation has completed. /// /// * Drain any scheduled work queues. /// * Drop any futures that have not yet completed. /// * Drop the reactor. /// /// Once the reactor has dropped, any outstanding I/O resources bound to /// that reactor will no longer function. Calling any method on them will /// result in an error. /// /// [driver]: crate::io::driver /// [timer]: crate::time /// [mod]: index.html /// [`new`]: #method.new #[derive(Clone, Copy, Default)] pub struct AsyncStdRuntimeProvider; impl Executor for AsyncStdRuntimeProvider { fn new() -> Self { Self {} } fn block_on(&mut self, future: F) -> F::Output { async_std::task::block_on(future) } } #[derive(Clone, Copy)] pub struct AsyncStdRuntimeHandle; impl Spawn for AsyncStdRuntimeHandle { fn spawn_bg(&mut self, future: F) where F: Future> + Send + 'static, { let _join = async_std::task::spawn(future); } } impl RuntimeProvider for AsyncStdRuntimeProvider { type Handle = AsyncStdRuntimeHandle; type Timer = AsyncStdTime; type Udp = AsyncStdUdpSocket; type Tcp = AsyncStdTcpStream; fn create_handle(&self) -> Self::Handle { AsyncStdRuntimeHandle {} } fn connect_tcp( &self, server_addr: SocketAddr, ) -> Pin>>> { Box::pin(AsyncStdTcpStream::connect(server_addr)) } fn bind_udp( &self, local_addr: SocketAddr, _server_addr: SocketAddr, ) -> Pin>>> { Box::pin(AsyncStdUdpSocket::bind(local_addr)) } } #[derive(Clone, Default)] pub struct AsyncStdConnectionProvider { runtime_provider: AsyncStdRuntimeProvider, connection_provider: GenericConnector, } impl Executor for AsyncStdConnectionProvider { fn new() -> Self { let p = AsyncStdRuntimeProvider::new(); Self { runtime_provider: p, connection_provider: GenericConnector::new(p), } } fn block_on(&mut self, future: F) -> F::Output { self.runtime_provider.block_on(future) } } impl ConnectionProvider for AsyncStdConnectionProvider { type Conn = as ConnectionProvider>::Conn; type FutureConn = as ConnectionProvider>::FutureConn; type RuntimeProvider = AsyncStdRuntimeProvider; fn new_connection( &self, config: &NameServerConfig, options: &ResolverOpts, ) -> Self::FutureConn { self.connection_provider.new_connection(config, options) } } async-std-resolver-0.24.0/src/tests.rs000064400000000000000000000144411046102023000157560ustar 00000000000000#![allow(clippy::extra_unused_type_parameters)] use hickory_resolver::name_server::GenericConnection; use hickory_resolver::testing; use crate::config::{ResolverConfig, ResolverOpts}; use crate::lookup::LookupFuture; use crate::lookup_ip::LookupIpFuture; use crate::proto::xfer::DnsRequest; use crate::proto::Executor; use crate::runtime::AsyncStdConnectionProvider; use crate::AsyncStdResolver; use crate::ResolveError; fn is_send_t() -> bool { true } fn is_sync_t() -> bool { true } #[test] fn test_send_sync() { assert!(is_send_t::()); assert!(is_sync_t::()); assert!(is_send_t::()); assert!(is_sync_t::()); assert!(is_send_t::()); assert!(is_sync_t::()); assert!(is_send_t::()); assert!(is_send_t::>()); assert!(is_send_t::>()); } #[test] fn test_lookup_google() { use testing::lookup_test; let io_loop = AsyncStdConnectionProvider::new(); lookup_test::( ResolverConfig::google(), io_loop.clone(), io_loop, ) } #[test] fn test_lookup_cloudflare() { use testing::lookup_test; let io_loop = AsyncStdConnectionProvider::new(); lookup_test::( ResolverConfig::cloudflare(), io_loop.clone(), io_loop, ) } #[test] fn test_lookup_quad9() { use testing::lookup_test; let io_loop = AsyncStdConnectionProvider::new(); lookup_test::( ResolverConfig::quad9(), io_loop.clone(), io_loop, ) } #[test] fn test_ip_lookup() { use testing::ip_lookup_test; let io_loop = AsyncStdConnectionProvider::new(); ip_lookup_test::( io_loop.clone(), io_loop, ) } #[test] fn test_ip_lookup_across_threads() { use testing::ip_lookup_across_threads_test; let io_loop = AsyncStdConnectionProvider::new(); ip_lookup_across_threads_test::(io_loop) } #[test] #[cfg(feature = "dnssec")] fn test_sec_lookup() { use testing::sec_lookup_test; let io_loop = AsyncStdConnectionProvider::new(); sec_lookup_test::( io_loop.clone(), io_loop, ); } #[test] #[cfg(feature = "dnssec")] fn test_sec_lookup_fails() { use testing::sec_lookup_fails_test; let io_loop = AsyncStdConnectionProvider::new(); sec_lookup_fails_test::( io_loop.clone(), io_loop, ); } #[test] #[ignore] #[cfg(any(unix, target_os = "windows"))] #[cfg(feature = "system-config")] fn test_system_lookup() { use testing::system_lookup_test; let io_loop = AsyncStdConnectionProvider::new(); system_lookup_test::( io_loop.clone(), io_loop, ); } #[test] #[ignore] #[cfg(feature = "system-config")] // these appear to not work on CI, test on macos with `10.1.0.104 a.com` #[cfg(unix)] fn test_hosts_lookup() { use testing::hosts_lookup_test; let io_loop = AsyncStdConnectionProvider::new(); hosts_lookup_test::( io_loop.clone(), io_loop, ); } #[test] fn test_fqdn() { use testing::fqdn_test; let io_loop = AsyncStdConnectionProvider::new(); fqdn_test::(io_loop.clone(), io_loop); } #[test] fn test_ndots() { use testing::ndots_test; let io_loop = AsyncStdConnectionProvider::new(); ndots_test::(io_loop.clone(), io_loop); } #[test] fn test_large_ndots() { use testing::large_ndots_test; let io_loop = AsyncStdConnectionProvider::new(); large_ndots_test::( io_loop.clone(), io_loop, ); } #[test] fn test_domain_search() { use testing::domain_search_test; let io_loop = AsyncStdConnectionProvider::new(); domain_search_test::( io_loop.clone(), io_loop, ); } #[test] fn test_search_list() { use testing::search_list_test; let io_loop = AsyncStdConnectionProvider::new(); search_list_test::( io_loop.clone(), io_loop, ); } #[test] fn test_idna() { use testing::idna_test; let io_loop = AsyncStdConnectionProvider::new(); idna_test::(io_loop.clone(), io_loop); } #[test] fn test_localhost_ipv4() { use testing::localhost_ipv4_test; let io_loop = AsyncStdConnectionProvider::new(); localhost_ipv4_test::( io_loop.clone(), io_loop, ); } #[test] fn test_localhost_ipv6() { use testing::localhost_ipv6_test; let io_loop = AsyncStdConnectionProvider::new(); localhost_ipv6_test::( io_loop.clone(), io_loop, ); } #[test] fn test_search_ipv4_large_ndots() { use testing::search_ipv4_large_ndots_test; let io_loop = AsyncStdConnectionProvider::new(); search_ipv4_large_ndots_test::( io_loop.clone(), io_loop, ); } #[test] fn test_search_ipv6_large_ndots() { use testing::search_ipv6_large_ndots_test; let io_loop = AsyncStdConnectionProvider::new(); search_ipv6_large_ndots_test::( io_loop.clone(), io_loop, ); } #[test] fn test_search_ipv6_name_parse_fails() { use testing::search_ipv6_name_parse_fails_test; let io_loop = AsyncStdConnectionProvider::new(); search_ipv6_name_parse_fails_test::( io_loop.clone(), io_loop, ); } async-std-resolver-0.24.0/src/time.rs000064400000000000000000000020061046102023000155440ustar 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. use std::future::Future; use std::time::Duration; use async_trait::async_trait; use hickory_resolver::proto::Time; /// AsyncStd backed timer implementation #[derive(Clone, Copy)] pub struct AsyncStdTime; #[async_trait] impl Time for AsyncStdTime { async fn delay_for(duration: Duration) { async_std::task::sleep(duration).await } async fn timeout( duration: Duration, future: F, ) -> Result { async_std::future::timeout(duration, future) .await .map_err(move |_| std::io::Error::new(std::io::ErrorKind::TimedOut, "future timed out")) } }