├── .gitignore ├── .travis.yml ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md ├── examples ├── basic.rs ├── custom_resolve.rs └── listener.rs └── src ├── endpoint.rs ├── lib.rs ├── net.rs └── resolver.rs /.gitignore: -------------------------------------------------------------------------------- 1 | target 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: rust 2 | 3 | rust: 4 | - nightly 5 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "tokio-dns-unofficial" 3 | version = "0.4.0" 4 | authors = ["Simon Bernier St-Pierre "] 5 | description = "Unofficial extension to tokio to provide asynchronous DNS resolution" 6 | documentation = "https://docs.rs/tokio-dns-unofficial" 7 | homepage = "https://github.com/sbstp/tokio-dns" 8 | repository = "https://github.com/sbstp/tokio-dns" 9 | readme = "README.md" 10 | keywords = ["tokio", "async", "dns"] 11 | license = "Apache-2.0/MIT" 12 | exclude = [".travis.yml"] 13 | edition = "2018" 14 | 15 | [lib] 16 | name = "tokio_dns" 17 | path = "src/lib.rs" 18 | 19 | [dependencies] 20 | futures-preview = "0.3.0-alpha.18" 21 | lazy_static = "1.0" 22 | tokio = "0.2.0-alpha.3" 23 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Copyright (c) 2016 Simon Bernier St-Pierre 2 | 3 | Permission is hereby granted, free of charge, to any 4 | person obtaining a copy of this software and associated 5 | documentation files (the "Software"), to deal in the 6 | Software without restriction, including without 7 | limitation the rights to use, copy, modify, merge, 8 | publish, distribute, sublicense, and/or sell copies of 9 | the Software, and to permit persons to whom the Software 10 | is furnished to do so, subject to the following 11 | conditions: 12 | 13 | The above copyright notice and this permission notice 14 | shall be included in all copies or substantial portions 15 | of the Software. 16 | 17 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF 18 | ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 19 | TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 20 | PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT 21 | SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 22 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 23 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR 24 | IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 25 | DEALINGS IN THE SOFTWARE. 26 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Attention! 2 | This repository is how archived because both tokio and async-std provide their own asynchronous resolvers. 3 | 4 | # tokio-dns 5 | Asynchronous name resolution utilities for the `futures` and `tokio` crates. Look at the crate-level documentation for more details. 6 | 7 | [![BuildStatus](https://api.travis-ci.org/sbstp/tokio-dns.svg?branch=master)](https://travis-ci.org/sbstp/tokio-dns) 8 | 9 | [Documentation](https://docs.rs/tokio-dns-unofficial) 10 | 11 | This library [has been packaged to crates.io](https://crates.io/crates/tokio-dns-unofficial). Note that its name on crates.io is `tokio-dns-unofficial`, but the crate's name is `tokio_dns` (when using `extern crate ...`). 12 | 13 | ## Changelog 14 | 15 | ### 0.4.0 16 | * Added a ton of combinations of `IpAdrr`, `SocketAddr`, and `port` to the `ToEndpoint` trait. 17 | * Added new free functions to resolve a host/endpoint to a sequence of ip addresses or socket addresses, thanks @Fedcomp . 18 | * Small docs changes and new examples. 19 | 20 | 21 | ### 0.3.1 22 | * Fix a `rustc` regression, thanks @mehcode . 23 | 24 | ### 0.3.0 25 | * Update to the new `tokio` crate. 26 | * Change the API to look more like `tokio`'s API. 27 | * New `resolve` free function to resolve a hostname asynchronously using the default resolver. 28 | 29 | 30 | ## Demo 31 | ```rust 32 | // Taken from examples/basic.rs 33 | use tokio_dns::TcpStream; 34 | 35 | // connect using the built-in resolver. 36 | let conn = TcpStream::connect("rust-lang.org:80").and_then(|sock| { 37 | println!("conncted to {}", sock.peer_addr().unwrap()); 38 | Ok(()) 39 | }); 40 | ``` 41 | 42 | ## License 43 | [MIT](LICENSE-MIT) or [Apache](LICENSE-APACHE) 44 | -------------------------------------------------------------------------------- /examples/basic.rs: -------------------------------------------------------------------------------- 1 | use tokio_dns::TcpStream; 2 | 3 | #[tokio::main] 4 | async fn main() { 5 | // connect using the built-in resolver. 6 | match TcpStream::connect("rust-lang.org:80").await { 7 | Ok(sock) => println!("Connected to {}", sock.peer_addr().unwrap()), 8 | Err(err) => println!("Error connecting {:?}", err), 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /examples/custom_resolve.rs: -------------------------------------------------------------------------------- 1 | use tokio_dns::CpuPoolResolver; 2 | 3 | #[tokio::main] 4 | async fn main() { 5 | // create a custom, 10 thread CpuPoolResolver 6 | let resolver = CpuPoolResolver::new(10); 7 | 8 | match tokio_dns::resolve_sock_addr_with("rust-lang.org:80", resolver.clone()).await { 9 | Ok(addrs) => println!("Socket addresses {:#?}", addrs), 10 | Err(err) => println!("Error resolve address {:?}", err), 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /examples/listener.rs: -------------------------------------------------------------------------------- 1 | use futures::prelude::*; 2 | use tokio_dns::TcpListener; 3 | 4 | #[tokio::main] 5 | async fn main() { 6 | // connect using the built-in resolver. 7 | match TcpListener::bind("localhost:3000").await { 8 | Ok(listener) => { 9 | println!("Ready to accept"); 10 | let mut s = listener.incoming(); 11 | while let Some(sock) = s.next().await { 12 | println!("Accepted connection from {:?}", sock.unwrap().peer_addr()); 13 | } 14 | } 15 | Err(err) => println!("Error binding socket {:?}", err), 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/endpoint.rs: -------------------------------------------------------------------------------- 1 | use std::io; 2 | use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6}; 3 | use std::str::FromStr; 4 | 5 | /// An Endpoint is a way of identifying the target of a connection. 6 | /// 7 | /// It can be a socket address or a host name which needs to be resolved 8 | /// into a list of IP addresses. 9 | #[derive(Clone, Copy, Debug, Eq, PartialEq)] 10 | pub enum Endpoint<'a> { 11 | /// Endpoint is a host. 12 | /// 13 | /// The `&str` is the name and the `u16` is the port. 14 | Host(&'a str, u16), 15 | /// Endpoint is a `SocketAddr`. 16 | SocketAddr(SocketAddr), 17 | } 18 | 19 | /// A trait for objects that can be converted into an Endpoint. 20 | /// 21 | /// This trait is implemented for the following types: 22 | /// 23 | /// * `SocketAddr`, `SocketAddrV4`, `SocketAddrV6` - a socket address. 24 | /// * `(IpAddr, u16)`, `(Ipv4Addr, u16)`, `(Ipv6Addr, u16)` - an IP address and a port 25 | /// * `(&str, u16)` - a `` and a port. 26 | /// * `&str` - a string formatted as `:port`. 27 | /// 28 | /// Where `` is a host name or an IP address. 29 | /// 30 | /// This trait is similar to the `ToSocketAddrs` trait, except 31 | /// that it does not perform host name resolution. 32 | pub trait ToEndpoint<'a> { 33 | /// Create an endpoint from this object. 34 | fn to_endpoint(self) -> io::Result>; 35 | } 36 | 37 | impl<'a> ToEndpoint<'a> for SocketAddr { 38 | fn to_endpoint(self) -> io::Result> { 39 | Ok(Endpoint::SocketAddr(self)) 40 | } 41 | } 42 | 43 | impl<'a, 'b> ToEndpoint<'a> for &'b SocketAddr { 44 | fn to_endpoint(self) -> io::Result> { 45 | Ok(Endpoint::SocketAddr(*self)) 46 | } 47 | } 48 | 49 | impl<'a> ToEndpoint<'a> for SocketAddrV4 { 50 | fn to_endpoint(self) -> io::Result> { 51 | Ok(Endpoint::SocketAddr(SocketAddr::V4(self))) 52 | } 53 | } 54 | 55 | impl<'a, 'b> ToEndpoint<'a> for &'b SocketAddrV4 { 56 | fn to_endpoint(self) -> io::Result> { 57 | Ok(Endpoint::SocketAddr(SocketAddr::V4(*self))) 58 | } 59 | } 60 | 61 | impl<'a> ToEndpoint<'a> for SocketAddrV6 { 62 | fn to_endpoint(self) -> io::Result> { 63 | Ok(Endpoint::SocketAddr(SocketAddr::V6(self))) 64 | } 65 | } 66 | 67 | impl<'a, 'b> ToEndpoint<'a> for &'b SocketAddrV6 { 68 | fn to_endpoint(self) -> io::Result> { 69 | Ok(Endpoint::SocketAddr(SocketAddr::V6(*self))) 70 | } 71 | } 72 | 73 | impl<'a> ToEndpoint<'a> for (IpAddr, u16) { 74 | fn to_endpoint(self) -> io::Result> { 75 | Ok(Endpoint::SocketAddr(SocketAddr::new(self.0, self.1))) 76 | } 77 | } 78 | 79 | impl<'a> ToEndpoint<'a> for (Ipv4Addr, u16) { 80 | fn to_endpoint(self) -> io::Result> { 81 | Ok(Endpoint::SocketAddr(SocketAddr::new( 82 | IpAddr::V4(self.0), 83 | self.1, 84 | ))) 85 | } 86 | } 87 | 88 | impl<'a> ToEndpoint<'a> for (Ipv6Addr, u16) { 89 | fn to_endpoint(self) -> io::Result> { 90 | Ok(Endpoint::SocketAddr(SocketAddr::new( 91 | IpAddr::V6(self.0), 92 | self.1, 93 | ))) 94 | } 95 | } 96 | 97 | impl<'a> ToEndpoint<'a> for (&'a str, u16) { 98 | fn to_endpoint(self) -> io::Result> { 99 | match IpAddr::from_str(self.0) { 100 | Ok(addr) => (addr, self.1).to_endpoint(), 101 | Err(_) => Ok(Endpoint::Host(self.0, self.1)), 102 | } 103 | } 104 | } 105 | 106 | impl<'a> ToEndpoint<'a> for &'a str { 107 | fn to_endpoint(self) -> io::Result> { 108 | // try to parse as a socket address first 109 | if let Ok(addr) = self.parse() { 110 | return Ok(Endpoint::SocketAddr(addr)); 111 | } 112 | 113 | fn parse_port(port: &str) -> io::Result { 114 | u16::from_str(port).map_err(|_| io::Error::new(io::ErrorKind::Other, "invalid port")) 115 | } 116 | 117 | match self.rfind(':') { 118 | Some(idx) => { 119 | let host = &self[..idx]; 120 | let port = parse_port(&self[idx + 1..])?; 121 | Ok(Endpoint::Host(host, port)) 122 | } 123 | None => Err(io::Error::new(io::ErrorKind::Other, "invalid endpoint")), 124 | } 125 | } 126 | } 127 | 128 | #[test] 129 | fn test_resolve_localhost() { 130 | use super::{CpuPoolResolver, Resolver}; 131 | 132 | let resolver = CpuPoolResolver::new(1); 133 | 134 | let fut = async move { 135 | let addrs = resolver.resolve("localhost").await.unwrap(); 136 | 137 | for addr in addrs { 138 | // TODO 1.12 addr.is_loopback() 139 | assert!(match addr { 140 | IpAddr::V4(a) => a.is_loopback(), 141 | IpAddr::V6(a) => a.is_loopback(), 142 | }); 143 | } 144 | }; 145 | 146 | let _ = futures::executor::block_on(fut); 147 | } 148 | 149 | #[test] 150 | fn test_endpoint_str_port() { 151 | use std::net::Ipv4Addr; 152 | 153 | let ep = ("0.0.0.0", 1227).to_endpoint().unwrap(); 154 | match ep { 155 | Endpoint::SocketAddr(addr) => { 156 | assert_eq!(addr.ip(), IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0))); 157 | assert_eq!(addr.port(), 1227); 158 | } 159 | _ => panic!(), 160 | } 161 | } 162 | 163 | #[test] 164 | fn test_endpoint_str() { 165 | let ep = "localhost:1227".to_endpoint().unwrap(); 166 | match ep { 167 | Endpoint::Host(host, port) => { 168 | assert_eq!(host, "localhost"); 169 | assert_eq!(port, 1227); 170 | } 171 | _ => panic!(), 172 | } 173 | } 174 | 175 | #[test] 176 | fn test_endpoint_str_ipv4() { 177 | use std::net::SocketAddrV4; 178 | 179 | let ep = "0.0.0.0:1227".to_endpoint().unwrap(); 180 | match ep { 181 | Endpoint::SocketAddr(SocketAddr::V4(addr)) => { 182 | assert_eq!(addr, SocketAddrV4::from_str("0.0.0.0:1227").unwrap()); 183 | } 184 | _ => panic!(), 185 | } 186 | } 187 | 188 | #[test] 189 | fn test_endpoint_str_ipv6() { 190 | use std::net::SocketAddrV6; 191 | 192 | let ep = "[::]:1227".to_endpoint().unwrap(); 193 | match ep { 194 | Endpoint::SocketAddr(SocketAddr::V6(addr)) => { 195 | assert_eq!(addr, SocketAddrV6::from_str("[::]:1227").unwrap()); 196 | } 197 | _ => panic!(), 198 | } 199 | } 200 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | //! This crate offers tools for asynchronous name resolution, and extensions to 2 | //! the `tokio_core` crate. 3 | //! 4 | //! First, `Endpoint` and `ToEndpoint` behave very much like `SocketAddr` and 5 | //! `ToSocketAddrs` from the standard library. The main difference is that the 6 | //! `ToEndpoint` trait does not perform any name resolution. If simply detect 7 | //! whether the given endpoint is a socket address or a host name. Then, it 8 | //! is up to a resolver to perform name resolution. 9 | //! 10 | //! The `Resolver` trait describes an abstract, asynchronous resolver. This crate 11 | //! provides one (for now) implementation of a resolver, the `CpuPoolResolver`. 12 | //! It uses a thread pool and the `ToSocketAddrs` trait to perform name resolution. 13 | //! 14 | //! [Git Repository](https://github.com/sbstp/tokio-dns) 15 | #![warn(missing_docs)] 16 | 17 | mod endpoint; 18 | mod net; 19 | mod resolver; 20 | 21 | pub use crate::endpoint::{Endpoint, ToEndpoint}; 22 | #[allow(deprecated)] 23 | pub use crate::net::{ 24 | resolve_ip_addr, resolve_ip_addr_with, resolve_sock_addr, resolve_sock_addr_with, TcpListener, 25 | TcpStream, UdpSocket, 26 | }; 27 | pub use crate::resolver::{CpuPoolResolver, Resolver}; 28 | -------------------------------------------------------------------------------- /src/net.rs: -------------------------------------------------------------------------------- 1 | use std::io; 2 | use std::net::{IpAddr, SocketAddr}; 3 | 4 | use futures::prelude::*; 5 | use tokio::net; 6 | 7 | use crate::endpoint::{Endpoint, ToEndpoint}; 8 | use crate::resolver::{CpuPoolResolver, Resolver}; 9 | 10 | lazy_static::lazy_static! { 11 | static ref POOL: CpuPoolResolver = CpuPoolResolver::new(5); 12 | } 13 | 14 | /// Resolve a hostname to a sequence of ip addresses using the default resolver. 15 | /// 16 | /// # Example 17 | /// ``` 18 | /// tokio_dns::resolve_ip_addr("rust-lang.org"); 19 | /// ``` 20 | pub async fn resolve_ip_addr(host: &str) -> io::Result> { 21 | POOL.resolve(host).await 22 | } 23 | 24 | /// Resolve a hostname to a sequence of ip addresses using a custom resolver. 25 | /// 26 | /// # Example 27 | /// ``` 28 | /// # use tokio_dns::CpuPoolResolver; 29 | /// let resolver = CpuPoolResolver::new(10); 30 | /// 31 | /// tokio_dns::resolve_ip_addr_with("rust-lang.org", resolver.clone()); 32 | /// ``` 33 | pub async fn resolve_ip_addr_with(host: &str, resolver: R) -> io::Result> 34 | where 35 | R: Resolver, 36 | { 37 | resolver.resolve(host).await 38 | } 39 | 40 | /// Resolve an endpoint to a sequence of socket addresses using the default resolver. 41 | /// 42 | /// # Example 43 | /// ``` 44 | /// tokio_dns::resolve_sock_addr(("rust-lang.org", 80)); 45 | /// ``` 46 | pub async fn resolve_sock_addr<'a, T>(endpoint: T) -> io::Result> 47 | where 48 | T: ToEndpoint<'a>, 49 | { 50 | resolve_endpoint(endpoint, POOL.clone()).await 51 | } 52 | 53 | /// Resolve an endpoint to a sequence of socket addresses using a custom resolver. 54 | /// 55 | /// # Example 56 | /// ``` 57 | /// # use tokio_dns::CpuPoolResolver; 58 | /// let resolver = CpuPoolResolver::new(10); 59 | /// 60 | /// tokio_dns::resolve_sock_addr_with(("rust-lang.org", 80), resolver.clone()); 61 | /// ``` 62 | pub async fn resolve_sock_addr_with<'a, T, R>( 63 | endpoint: T, 64 | resolver: R, 65 | ) -> io::Result> 66 | where 67 | T: ToEndpoint<'a>, 68 | R: Resolver, 69 | { 70 | resolve_endpoint(endpoint, resolver).await 71 | } 72 | 73 | /// Shim for tokio::net::TcpStream 74 | pub struct TcpStream; 75 | 76 | impl TcpStream { 77 | /// Connect to the endpoint using the default resolver. 78 | pub async fn connect<'a, T>(ep: T) -> io::Result 79 | where 80 | T: ToEndpoint<'a>, 81 | { 82 | TcpStream::connect_with(ep, POOL.clone()).await 83 | } 84 | 85 | /// Connect to the endpoint using a custom resolver. 86 | pub async fn connect_with<'a, T, R>(ep: T, resolver: R) -> io::Result 87 | where 88 | T: ToEndpoint<'a>, 89 | R: Resolver, 90 | { 91 | try_until_ok( 92 | resolve_endpoint(ep, resolver).await?, 93 | net::TcpStream::connect, 94 | ) 95 | .await 96 | } 97 | } 98 | 99 | /// Shim for tokio::net::TcpListener 100 | pub struct TcpListener; 101 | 102 | impl TcpListener { 103 | /// Bind to the endpoint using the default resolver. 104 | pub async fn bind<'a, T>(ep: T) -> io::Result 105 | where 106 | T: ToEndpoint<'a>, 107 | { 108 | TcpListener::bind_with(ep, POOL.clone()).await 109 | } 110 | 111 | /// Bind to the endpoint using a custom resolver. 112 | pub async fn bind_with<'a, T, R>(ep: T, resolver: R) -> io::Result 113 | where 114 | T: ToEndpoint<'a>, 115 | R: Resolver, 116 | { 117 | try_until_ok( 118 | resolve_endpoint(ep, resolver).await?, 119 | net::TcpListener::bind, 120 | ) 121 | .await 122 | } 123 | } 124 | 125 | /// Shim for tokio::net::UdpSocket 126 | pub struct UdpSocket; 127 | 128 | impl UdpSocket { 129 | /// Bind to the endpoint using the default resolver. 130 | pub async fn bind<'a, T>(ep: T) -> io::Result 131 | where 132 | T: ToEndpoint<'a>, 133 | { 134 | UdpSocket::bind_with(ep, POOL.clone()).await 135 | } 136 | 137 | /// Bind to the endpoint using a custom resolver. 138 | pub async fn bind_with<'a, T, R>(ep: T, resolver: R) -> io::Result 139 | where 140 | T: ToEndpoint<'a>, 141 | R: Resolver, 142 | { 143 | try_until_ok(resolve_endpoint(ep, resolver).await?, net::UdpSocket::bind).await 144 | } 145 | } 146 | 147 | /// Resolves endpoint into a vector of socket addresses. 148 | async fn resolve_endpoint<'a, T, R>(ep: T, resolver: R) -> io::Result> 149 | where 150 | R: Resolver, 151 | T: ToEndpoint<'a>, 152 | { 153 | let ep = match ep.to_endpoint() { 154 | Ok(ep) => ep, 155 | Err(e) => return Err(e), 156 | }; 157 | Ok({ 158 | match ep { 159 | Endpoint::Host(host, port) => resolver 160 | .resolve(host) 161 | .await? 162 | .into_iter() 163 | .map(|addr| SocketAddr::new(addr, port)) 164 | .collect(), 165 | Endpoint::SocketAddr(addr) => vec![addr], 166 | } 167 | }) 168 | } 169 | 170 | async fn try_until_ok(addrs: Vec, f: F) -> io::Result 171 | where 172 | F: Fn(SocketAddr) -> R + Send + 'static, 173 | R: Future> + Send + 'static, 174 | I: Send + 'static, 175 | { 176 | for addr in addrs { 177 | if let Ok(i) = f(addr).await { 178 | return Ok(i); 179 | } 180 | } 181 | 182 | Err(io::Error::new( 183 | io::ErrorKind::Other, 184 | "could not resolve to any address", 185 | )) 186 | } 187 | -------------------------------------------------------------------------------- /src/resolver.rs: -------------------------------------------------------------------------------- 1 | use std::io; 2 | use std::net::{IpAddr, ToSocketAddrs}; 3 | use std::pin::Pin; 4 | use std::str; 5 | 6 | use futures::prelude::*; 7 | 8 | /// The Resolver trait represents an object capable of 9 | /// resolving host names into IP addresses. 10 | pub trait Resolver { 11 | /// Given a host name, this function returns a Future which 12 | /// will eventually produce a list of IP addresses. 13 | fn resolve(&self, host: &str) -> Pin>> + Send>>; 14 | } 15 | 16 | /// A resolver based on a thread pool. 17 | /// 18 | /// This resolver uses the `ToSocketAddrs` trait inside 19 | /// a thread to provide non-blocking address resolving. 20 | #[derive(Clone)] 21 | pub struct CpuPoolResolver { 22 | pool: futures::executor::ThreadPool, 23 | } 24 | 25 | impl CpuPoolResolver { 26 | /// Create a new CpuPoolResolver with the given number of threads. 27 | pub fn new(num_threads: usize) -> Self { 28 | CpuPoolResolver { 29 | pool: futures::executor::ThreadPool::builder() 30 | .pool_size(num_threads) 31 | .create() 32 | .unwrap(), 33 | } 34 | } 35 | } 36 | 37 | impl Resolver for CpuPoolResolver { 38 | fn resolve(&self, host: &str) -> Pin>> + Send>> { 39 | let host = format!("{}:0", host); 40 | let pool = self.pool.clone(); 41 | 42 | async move { 43 | let (tx, rx) = futures::channel::oneshot::channel(); 44 | 45 | pool.spawn_obj_ok( 46 | async move { 47 | let _ = tx.send(match host[..].to_socket_addrs() { 48 | Ok(it) => Ok(it.map(|s| s.ip()).collect()), 49 | Err(e) => Err(e), 50 | }); 51 | } 52 | .boxed() 53 | .into(), 54 | ); 55 | 56 | rx.await.unwrap_or_else(|_| { 57 | Err(std::io::Error::new( 58 | std::io::ErrorKind::Interrupted, 59 | "Resolver future has been dropped", 60 | )) 61 | }) 62 | } 63 | .boxed() 64 | } 65 | } 66 | --------------------------------------------------------------------------------